qid
int64 1
74.7M
| question
stringlengths 0
58.3k
| date
stringlengths 10
10
| metadata
sequence | response_j
stringlengths 2
48.3k
| response_k
stringlengths 2
40.5k
|
---|---|---|---|---|---|
336,920 | I built this computer back in June and this has been an issue ever since I first built it. What happens is that my computer will POST just fine and then go to the black screen where it states "Loading Windows". Usually it sits there for a second and then it the pulsing Windows logo will appear, and after a few seconds, it brings me to the Windows login screen. However, about once a week at least, it will just sit there with a black screen and the "Loading Windows" text, but the logo will never appear. The hard drive indicator remains off and I don't hear any hard drive activity, which tells me that it's stuck. There's no error messages, but it never loads Windows. What I do here is just push the reset button and it will reboot. The "repair Windows" option never helps and is useless, so I just say "Load Windows normally", and it will load Windows fine 100% of the time, without fail. However, something must be wrong.
The computer started out with one 500GB hybrid SSD, and exhibited this behavior. I put in another and put it on RAID0 and it hasn't changed. It has 4 x 4GB of RAM, and a friend told me that perhaps the RAM is underpowered. So, every time this happens, I go into the BIOS and up the DRAM voltage one tick. I've been doing this for weeks and it hasn't done anything (first time I did it, I didn't see the issue for over a week, then it started happening again). I'm over 1.55V (I think 1.553V, if memory serves) but it's not even overclocked (they're 1333MHz) so I'm getting anxious that this won't solve the issue. I did both a full run of Memtest86+ and chkdsk and they both reported no errors. I've run several benchmarking suites (such as Heaven DX11 Benchmark, Crystal DiskMark, Furmark, 3DMark 11, and others, as well as playing games on high end settings and it never has given me any issues there, so it's not a hardware instability once Windows loads. I've even on one occasion had the computer up for a total of about 2 weeks straight and it didn't show any sign of glitching or malfunction.
This is the first computer I've built, and I am inexperienced with overclocking and dealing with power issues or other corner cases. Is my friend right that it's underpowered RAM? Or is there something else that could be afoot?
I have my computer specs below:
```
Computer: MSI MS-7640
CPU: AMD Phenom II X4 955 Black Edition (Deneb, RB-C3) @ 3200 MHz (16.00x200.0)
Motherboard: MSI 890FXA-GD65 (MS-7640)
Chipset: ATI RD890 + SB810/SB850
Memory: 16384 MBytes @ 666 MHz, 9.0-9-9-24
- 4096 MB PC10600 DDR3 SDRAM - Patriot Memory (PDP Systems) PSD34G13332
- 4096 MB PC10600 DDR3 SDRAM - Patriot Memory (PDP Systems) PSD34G13332
- 4096 MB PC10600 DDR3 SDRAM - Patriot Memory (PDP Systems) PSD34G13332
- 4096 MB PC10600 DDR3 SDRAM - Patriot Memory (PDP Systems) PSD34G13332
Graphics: MSI R6970 (MS-V237)
ATI RADEON HD 6970 (CAYMAN XT), 2048 MB GDDR5 SDRAM
Graphics: MSI R6970 (MS-V237)
ATI RADEON HD 6970 (CAYMAN XT), 0 MB
Drive: AMD 2+0 Stripe/RAID0, Disk drive
Drive: ATAPI iHBS212 2, BD-RE
Drive: ATAPI iHBS212 2, BD-RE
Drive: AMD RAID Console, Processor
Sound: ATI SB800/Hudson-1 - High Definition Audio Controller
Sound: ATI Cayman/Antilles - High Definition Audio Controller
Sound: ATI Cayman/Antilles - High Definition Audio Controller
Network: RealTek Semiconductor RTL8168/8111 PCI-E Gigabit Ethernet NIC
Network: Realtek PCIe GBE Family Controller
OS: Microsoft Windows 7 Professional (x64) Build 7601
```
As a note, I've been recommended in chat to enable boot logging and see if anything shows up. I've done that just now, and will post the results whenever this occurs again, if there's anything of interest.
**EDIT**
I've enabled verbose booting and boot logging, but so far have not seen the issue reappear within the past week or so. I will update when I do see it happen.
**EDIT #2 (11/25/2011)**
Since I've enabled the boot logging (and reverted back to stock DRAM voltages), I haven't seen the issue reappear. I feel it's worth noting that I also, during this time, installed Windows 8 Developer Preview as a second OS, and have it dual-boot using the Windows 7 boot loader. Would this extra delay (10 seconds, currently) before it attempts to load Windows 7 have any effect on its success in booting Windows? Does it make sense that it might have been getting to the "Loading Windows" step too quickly? Could this be an instability in the power supply?
By the way, the power supply is a [Thermaltake TPX-775M Toughpower XT 775W](http://www.tigerdirect.com/applications/SearchTools/item-details.asp?EdpNo=6624663).
**EDIT #3 (9/30/2011)**
I removed the Windows 8 Dev Preview partition so that it went back to the normal boot process. This morning, it hung at boot again. Since I was using verbose boot, it hung at the black screen before it started loading drivers. After I reset the computer and got into Windows, checking ntbtlog.txt didn't show anything logged for the failed boot session. So it apparently just sits there before it even starts loading drivers.
I think after work today I'm going to start the process of checking each stick of RAM. I've put that off long enough.
**EDIT #4 (10/21/2011)**
A little while ago, I found that one of my external USB hard drives had several bad sectors. Eventually it was unreadable. Since Windows likes to scan USB drives on startup, could this have caused the issue? I haven't seen the hang for quite some time now, after I ran `chkdsk` on the drive (currently it remains powered off, as I was able to recover the data on it). This drive has been hooked up since I built the computer. Perhaps Windows was finding bad sectors and didn't know how to proceed, even though it's an external HDD? | 2011/09/18 | [
"https://superuser.com/questions/336920",
"https://superuser.com",
"https://superuser.com/users/33595/"
] | You may have already tried this but, as no one else has suggested it...
Disable **ALL** overclocking features and next update **ALL** the drivers you can - never use the versions that come on disk and take a look at the AMD website and your motherboard company.
As it is happening at such an early stage, I believe the most likely cause is a bad I/O driver, but, it could be anything.
and finally if this doesn't solve it, we have to go the old fashioned way and disconnecting everything you can in case it is some sort of conflict/issue with third party hardware. | One of my external USB hard drives apparently was failing. Some weeks ago I found I couldn't access it anymore, so I had to run `chkdsk`, and about 1/3 of the drive was bad sectors. I believe that Windows may have been hanging because it was running into them while scanning the drive at boot. Since recovering the data off the drive and powering it off, I have not experienced any issues with booting. It has been a couple months now, so I believe this resolved the problem. |
4,615,401 | Consider the following statement:
>
> The king of France is bald.
>
>
>
We know that France does not currently have a king, so what is the truth value of this statement? If it is true, then its negation must be false, so the king of France is **not** bald is false, But when France does not have a king, does it make sense to determine the truth and falsity of this statement? What should be done with these types of statements? | 2023/01/10 | [
"https://math.stackexchange.com/questions/4615401",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/1010242/"
] | Insofar as this is not just a question about linguistics, the way this sort of issue is handled in mathematics is that to even use the word "the" to refer to a mathematical object is to make an implicit claim that that object both exists and is unique, e.g. when we speak of "*the* cyclic group of order $n$" and so forth. So there is an implicit existential quantifier there (one might render it more explicitly as "there exists a unique person who is king of France, and..."), and if the domain of discourse over which that quantifier ranges is empty (in this case, if France does not have a king) then the statement is false.
One needs to be a bit careful about this in mathematics, though, because sometimes the implicit quantifier is a universal quantifier and then if the domain of discourse being quantified over is empty such statements are [vacuously true](https://en.wikipedia.org/wiki/Vacuous_truth). | (Updated screenshot from proof checker)
[](https://i.stack.imgur.com/vUyI7.png)
[](https://i.stack.imgur.com/6FKEd.png) |
1,852,655 | I don't know when it is and when it is not okay to simply take the anti-derivative of a square root function when I'm trying to find the integral. Could someone explain to me when and when it is not appropriate? (Examples below of what I mean since my question sounds a bit unclear)
Example 1: $\int x^{1/2}~dx = \frac{2}{3} x^{3/2} + C$
Example 2: $\int (2x+1)^{1/2}~dx = \frac{1}{3} (2x+1)^{3/2} + C$
In cases 1 and 2, it was perfectly okay for me to simply take the anti-derivative of the square root function. My question is: why or why not can I apply this same logic to the following examples (ex.3 and 4)? How should I solve the following problems then, and what kinds of generalizations can I make about solving integrals of square root functions?
Example 3: $\int (2x^4+1)^{1/2}~dx = \frac{1}{12x^3} (2x^3+1)^{3/2} + C$
Example 4: $\int (1+e^{-2x})^{1/2}~dx = \frac{-1}{3e^{-2x}} (1+e^{-2x})^{3/2} + C$
Thank you so much for your help! *Also was hoping to apply the case to indefinite and definite integrals* | 2016/07/08 | [
"https://math.stackexchange.com/questions/1852655",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/352770/"
] | The main difference between your two groups of examples is that in the first two, the stuff under the square root is just a linear polynomial; in the second two, it has more complicated functions. When you have higher polynomials under the square roots, regular substitution won't suffice (even though it did in your second example), unless the square root is multiplied by something convenient on the outside, as in the case of $\int 2x\sqrt{x^2+1}dx$. Often you'll have to use trigonometric substitution, or even something with a bit more ingenuity. | If you think about these exercises in terms of substitutions, perhaps it will be clearer. For example 2, if you set $u = 2x+1$, then $du = 2\,dx$, or $dx = \frac{1}{2}\,du$, so that
$$\int (2x+1)^{1/2}\,dx = \frac{1}{2}\int u^{1/2}\,du = \frac{1}{3}u^{3/2}+C = \frac{1}{3}(2x+1)^{3/2}+C.$$
But try that with example 3: if $u = 2x^4+1$, then $du = 8x^3\,dx$, and there is no simple expression for the integral in terms of $u$.
So the only reason example 2 works is that $du$ is a constant multiple of $dx$. There are other situations where this substitution will work, but certainly it does not work in all cases. |
486,632 | Is inequality $$\Big (1+\frac{1}{k(k+1)}\Big )^k \geq 1+\frac{1}{k+1}$$ is true for all $k \in \mathbb{N}$ ? I am proving this using binomial theorem on the right side but I don't know what to do in the middle since there are many terms and there is an exponent of $k$. Is there a better way to prove this one? Thanks. I think of using $AM \geq GM$ inequality but I don't know how to apply it.Thanks Again. | 2013/09/07 | [
"https://math.stackexchange.com/questions/486632",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/20067/"
] | $$
\left(1+\frac{1}{k(k+1)}\right)^k=\sum\_{i=0}^k{k\choose i}\frac{1}{(k(k+1))^i}=1+\frac{1}{k+1}+\text{ something nonnegative} \ge 1+\frac{1}{k+1}.
$$ | **Hint** Bernoulli inequality and see Calvin`s comment......
You need the stronger version of Bernoulli, namely the one which says "*with equality if and only if...*" |
486,632 | Is inequality $$\Big (1+\frac{1}{k(k+1)}\Big )^k \geq 1+\frac{1}{k+1}$$ is true for all $k \in \mathbb{N}$ ? I am proving this using binomial theorem on the right side but I don't know what to do in the middle since there are many terms and there is an exponent of $k$. Is there a better way to prove this one? Thanks. I think of using $AM \geq GM$ inequality but I don't know how to apply it.Thanks Again. | 2013/09/07 | [
"https://math.stackexchange.com/questions/486632",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/20067/"
] | $$
\left(1+\frac{1}{k(k+1)}\right)^k=\sum\_{i=0}^k{k\choose i}\frac{1}{(k(k+1))^i}=1+\frac{1}{k+1}+\text{ something nonnegative} \ge 1+\frac{1}{k+1}.
$$ | First, note that $$f(x)=\left(1+\frac{1}{x}\right)^x$$ is a strictly increasing function on $(0,+\infty)$, by taking its derivative, which is $$\frac{(1+1/x)^x(-1+(1+x)\ln (1+1/x))}{1+x}$$
Hence, $f(k(k+1))>f(k+1)$. Now, take the $(k+1)$-th root of each side and you're done. |
4,549 | A few years ago, Peter Schiff and a few other Austrians (not all Austrians, as Mish was stating the opposite) were adamant about hyperinflation and Paul Krugman stated that it was like talking about fire problems during a flood, which made sense because of the credit crunch (the inverse problem). However, Schiff kept pointing to Zimbabwe and the Weimar Republic as examples of hyperinflation and even now, we're seeing it in Ukraine.
As far as Ukraine and Zimbabwe are concerned, neither appeared to have much gold before their hyperinflation. For instance, Ukraine has next to 0, if not 0 and Zimbabwe, from what I could find, had less than 5 metric tonnes. When I was looking online to see if anyone knew how much gold they estimate the Weimar Republic had, I couldn't find a figure and was curious if anyone knew, or could find a historic estimate?
The reason I ask this is because the United States owns the most gold in the world (and it's not a close competition), assuming we don't believe the people who think *it's not there*, and thus it's hard to believe that, unless the U.S. begins to liquidate its position, that it would face hyperinflation like these other countries even without a currency backed by gold because people know that in a really bad situation, it could trash the dollar, create a new currency backed by its gold (note that I'm not saying this would happen, but the US is hardly a country comparable to Zimbabwe when you consider its gold holdings). | 2015/02/26 | [
"https://economics.stackexchange.com/questions/4549",
"https://economics.stackexchange.com",
"https://economics.stackexchange.com/users/2746/"
] | To address the first part of your question:
>
> "By July 10, Germany's free gold reserve had fallen to the equivalent of £35 million pounds, and all the Bank was doing had produced precisely the effect it was hoped to avoid. Another loss of 50 million gold marks was suffered during the week which ended on July 14 — the direct result of supporting the paper mark by rationing supplies of foreign currencies and having to cover indispensable imports from the gold reserve. If intervention continued at the then level of 10 million gold marks daily, bankruptcy would come within 60 days: the reserves had already taken as much as they could stand. If intervention ceased, on the other hand, it was broadly expected that the dollar would go to a million marks, the pound to over 4 million — and by the end of July that expectation was fulfilled. Merchants were still said to be borrowing paper marks to the value of 80 per cent of their stock, and exchanging them at the Bank for dollar Treasury bills needed ostensibly for imports. These bills were sent abroad to the merchants' buying agencies, and in most cases stayed there with no countervalue returning to Germany."
>
>
>
-[A World of Possible Futures: German Weimar Republic in the early 1920s and the U.S. - Troubling similarities](http://www.nowandfutures.com/us_weimar.html)
The source itself appears to be of questionable value, but makes vague reference to:
["The Economics of Inflation (Routledge Library Editions-Economics, 84)" by Constantino Bresciani-Turroni (427 pages, Routledge, reprint edition, October 1, 2003, first published 1937](http://rads.stackoverflow.com/amzn/click/0415313929)
Judging from [historical gold prices](http://www.nma.org/pdf/gold/his_gold_prices.pdf) and [exchange rates](http://answers.google.com/answers/threadview/id/310722.html), we could estimate:
$$ 35M x 4.58 / 21.32 = 7.5M$$
So, 7.5 million troy ounces or 233 Metric Tonnes according to Google.
To address your second point, it seems to be exactly what the Weimar Republic tried.
I would not imagine the US would be keen to repeat something like that, though it seems far outside the scope of this SE to speculate on that. | It´s an historical side note at this point, but it´s not entirely clear that the Weimar authorities fully understood what they were kicking off.
The first public acknowledgement of the multiplier problem in the banking system - that is the way changes to reserve holdings could multiply the amount of money in deposit accounts - appears to be the 1931 MacMillan Report to the British Parliament. By contrast, von Mises book on capital in 1911 talks around various banking practices, including variations in cash money due to seasonal demands, but does not explicitly talk about the reserve issue.
So it´s entirely possible that when they tried to duck out of the Versailles Treaty requirements (which were impossible to meet in any case) by printing money, they didn´t envision a full on destruction of their monetary system.
It´s not as appreciated as it should be, the fundamental problem with the government printing money under reserve regulated systems, isn´t the money the government prints. It´s the second-order response of the banking system as it then creates a multiplier of the printed money as a result of its regulatory framework. F.ex. the government thinks its just doubling the money supply, resulting in an acceptable degree of mild inflation, but what happens is that the banking system multiplies that by 5x (reserve requirements back then were usually between 20-25%), and that then kicks off more government printing and a hyper-inflationary spiral, as the government is then forced to print more money to pay their civil servants. |
15,827,649 | 
```
<div id="div1">
<label class="someClass1">Price 1</label>
<label class="someClass1">Price 2</label>
<label class="someClass1">Price 3</label>
<label class="someClass1">Price 4</label>
</div>
<div id="div2">
<input type="text" class="someClass2"/>
<input type="text" class="someClass2"/>
<input type="text" class="someClass2"/>
<input type="text" class="someClass2"/>
</div>
```
I have two divs. One div contains `<label>` elements and another div contains `<input>` elements. The two divs are aligned horizontally. I need to align the labels and input elements vertically so that each label has it's input underneath.
I may achieve the above requirement by putting the `<label>` and `<input>` elements by placing them in `<table>` rows/columns. But I require them to use `<div>`.
Could someone help me out on this ? | 2013/04/05 | [
"https://Stackoverflow.com/questions/15827649",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1158189/"
] | **Short answer**, try this CSS
```
#div1 label.someClass1 { display: inline-block; margin: 0 5px; }
#div1 label.someClass1, #div2 input.someClass2 { width: 100px; }
#div2 input.someClass2 { margin: 0 0 0 10px; }
```
---
**Long answer**, to make the exact look you pictured in your question, use HTML5 placeholder attribute and CSS3 border-radius:
```
#div1 label {
display: inline-block;
font-weight: bold;
margin: 0 5px;
}
#div1 label, #div2 input {
width: 100px;
}
#div2 input {
border-radius: 5px; -webkit-border-radius: 5px;
border-width: 1px;
padding: 2px;
margin: 0 0 0 10px;
}
```
.
```
<div id="div1">
<label>Price 1</label>
<label>Price 2</label>
<label>Price 3</label>
<label>Price 4</label>
</div>
<div id="div2">
<input type="text" placeholder="Price"/>
<input type="text" placeholder="Price"/>
<input type="text" placeholder="Price"/>
<input type="text" placeholder="Price"/>
</div>
```
To finetune CSS3 effects, see [css3generator](http://css3generator.com/) | To get the divs on same row with inputs below them, use below css
```
#div1 label { display: inline-block; }
#div1 label, #div2 input { width: 100px; }
```
Check Demo here <http://jsfiddle.net/2wdUT/> |
15,827,649 | 
```
<div id="div1">
<label class="someClass1">Price 1</label>
<label class="someClass1">Price 2</label>
<label class="someClass1">Price 3</label>
<label class="someClass1">Price 4</label>
</div>
<div id="div2">
<input type="text" class="someClass2"/>
<input type="text" class="someClass2"/>
<input type="text" class="someClass2"/>
<input type="text" class="someClass2"/>
</div>
```
I have two divs. One div contains `<label>` elements and another div contains `<input>` elements. The two divs are aligned horizontally. I need to align the labels and input elements vertically so that each label has it's input underneath.
I may achieve the above requirement by putting the `<label>` and `<input>` elements by placing them in `<table>` rows/columns. But I require them to use `<div>`.
Could someone help me out on this ? | 2013/04/05 | [
"https://Stackoverflow.com/questions/15827649",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1158189/"
] | **Short answer**, try this CSS
```
#div1 label.someClass1 { display: inline-block; margin: 0 5px; }
#div1 label.someClass1, #div2 input.someClass2 { width: 100px; }
#div2 input.someClass2 { margin: 0 0 0 10px; }
```
---
**Long answer**, to make the exact look you pictured in your question, use HTML5 placeholder attribute and CSS3 border-radius:
```
#div1 label {
display: inline-block;
font-weight: bold;
margin: 0 5px;
}
#div1 label, #div2 input {
width: 100px;
}
#div2 input {
border-radius: 5px; -webkit-border-radius: 5px;
border-width: 1px;
padding: 2px;
margin: 0 0 0 10px;
}
```
.
```
<div id="div1">
<label>Price 1</label>
<label>Price 2</label>
<label>Price 3</label>
<label>Price 4</label>
</div>
<div id="div2">
<input type="text" placeholder="Price"/>
<input type="text" placeholder="Price"/>
<input type="text" placeholder="Price"/>
<input type="text" placeholder="Price"/>
</div>
```
To finetune CSS3 effects, see [css3generator](http://css3generator.com/) | Without css you can achieve it by using such an HTML structure -
```
<div id="div1">
<label class="someClass1">Price 1</label>
<div><input type="text" class="someClass2"/></div>
</div>
<div id="div2">
<label class="someClass1">Price 2</label>
<div><input type="text" class="someClass2"/></div>
</div>
<div id="div3">
<label class="someClass1">Price 3</label>
<div><input type="text" class="someClass2"/></div>
</div>
<div id="div4">
<label class="someClass1">Price 4</label>
<div><input type="text" class="someClass2"/></div>
</div>
``` |
15,827,649 | 
```
<div id="div1">
<label class="someClass1">Price 1</label>
<label class="someClass1">Price 2</label>
<label class="someClass1">Price 3</label>
<label class="someClass1">Price 4</label>
</div>
<div id="div2">
<input type="text" class="someClass2"/>
<input type="text" class="someClass2"/>
<input type="text" class="someClass2"/>
<input type="text" class="someClass2"/>
</div>
```
I have two divs. One div contains `<label>` elements and another div contains `<input>` elements. The two divs are aligned horizontally. I need to align the labels and input elements vertically so that each label has it's input underneath.
I may achieve the above requirement by putting the `<label>` and `<input>` elements by placing them in `<table>` rows/columns. But I require them to use `<div>`.
Could someone help me out on this ? | 2013/04/05 | [
"https://Stackoverflow.com/questions/15827649",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1158189/"
] | To get the divs on same row with inputs below them, use below css
```
#div1 label { display: inline-block; }
#div1 label, #div2 input { width: 100px; }
```
Check Demo here <http://jsfiddle.net/2wdUT/> | Without css you can achieve it by using such an HTML structure -
```
<div id="div1">
<label class="someClass1">Price 1</label>
<div><input type="text" class="someClass2"/></div>
</div>
<div id="div2">
<label class="someClass1">Price 2</label>
<div><input type="text" class="someClass2"/></div>
</div>
<div id="div3">
<label class="someClass1">Price 3</label>
<div><input type="text" class="someClass2"/></div>
</div>
<div id="div4">
<label class="someClass1">Price 4</label>
<div><input type="text" class="someClass2"/></div>
</div>
``` |
20,462,487 | I have been struggling with the scanner class. I just can't seem to rap my head around it's methods. I'm trying to run set of code which seems right to me. I've tried a few tweaks but still nothing. Any hints of why i am receiving this error
>
> "Exception in thread "main" java.util.InputMismatchException at
> java.util.Scanner.throwFor(Unknown Source) at
> java.util.Scanner.next(Unknown Source) at
> java.util.Scanner.nextInt(Unknown Source) at
> java.util.Scanner.nextInt(Unknown Source) at
> PolynomialTest.main(PolynomialTest.java:18)"
>
>
>
```
public class PolynomialTest {
public static void main(String[] args) throws IOException {
Scanner fileData = new Scanner(new File("operations.txt"));
Polynomial math = new Polynomial();
int coeff = fileData.nextInt();
int expo = fileData.nextInt();
while (fileData.hasNext()) {
Scanner nextTerm = new Scanner(fileData.nextLine());
if (nextTerm.next().equalsIgnoreCase("insert")) {
math.insert(coeff, expo);
System.out.println("The term (" + coeff + ", " + expo
+ ") has been added to the list in its proper place");
System.out.println("The list is now: " + math.toString());
} else if (nextTerm.next().equalsIgnoreCase("delete")) {
math.delete(coeff, expo);
System.out.println("The following term has been removed ("
+ coeff + ", " + expo + ")");
System.out.println("The list is now: " + math.toString());
} else if (nextTerm.next().equalsIgnoreCase("reverse")) {
math.reverse();
System.out
.println("The list was reversed in order and the list is now: "
+ math.toString());
} else if (nextTerm.next().equalsIgnoreCase("product")) {
System.out.println("The product of the polynomial is: "
+ math.product());
} else {
System.out.println("Not a recognized input method");
}
nextTerm.close();
}
PrintWriter save = new PrintWriter("operations.txt");
save.close();
fileData.close();
```
} | 2013/12/09 | [
"https://Stackoverflow.com/questions/20462487",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2628581/"
] | Why dont you you create a Class that holds the Statement, the count and handles all the addBatching plus other miscellaneous activities.
```
class BatchPreparedStatementHolder {
private int batchCount;
private PreparedStatement ps;
public BatchPreparedStatementHolder(PreparedStatement statement){
batchCount = 0;
ps = statment;
}
public void addBatch(){
ps.addBatch();
// increment how many times a batch has been added to the statement.
// execute batch if necessary.
if (++batchCount> 5000) {
ps.executeBatch();
batchCount = 0;
}
}
....
}
``` | The class suggestion is pretty good but a little heavy weight if you just need something simple. I would use something like a **HashMap**. (other languages call these "dictionaries"). I don't have time to read all your code, but it looks like you may be using Maps?
Anyways, you could make the key the auto-incremented value (as in databases) and the value could be, say a tuple or array of the other two values. See the following link for good advice on HashMaps:
<http://java67.blogspot.com/2013/02/10-examples-of-hashmap-in-java-programming-tutorial.html>
Or perhaps just make an array where the index refers to the auto-incremented function, and the content is another array?
Not sure exactly what you need but these might work! |
20,462,487 | I have been struggling with the scanner class. I just can't seem to rap my head around it's methods. I'm trying to run set of code which seems right to me. I've tried a few tweaks but still nothing. Any hints of why i am receiving this error
>
> "Exception in thread "main" java.util.InputMismatchException at
> java.util.Scanner.throwFor(Unknown Source) at
> java.util.Scanner.next(Unknown Source) at
> java.util.Scanner.nextInt(Unknown Source) at
> java.util.Scanner.nextInt(Unknown Source) at
> PolynomialTest.main(PolynomialTest.java:18)"
>
>
>
```
public class PolynomialTest {
public static void main(String[] args) throws IOException {
Scanner fileData = new Scanner(new File("operations.txt"));
Polynomial math = new Polynomial();
int coeff = fileData.nextInt();
int expo = fileData.nextInt();
while (fileData.hasNext()) {
Scanner nextTerm = new Scanner(fileData.nextLine());
if (nextTerm.next().equalsIgnoreCase("insert")) {
math.insert(coeff, expo);
System.out.println("The term (" + coeff + ", " + expo
+ ") has been added to the list in its proper place");
System.out.println("The list is now: " + math.toString());
} else if (nextTerm.next().equalsIgnoreCase("delete")) {
math.delete(coeff, expo);
System.out.println("The following term has been removed ("
+ coeff + ", " + expo + ")");
System.out.println("The list is now: " + math.toString());
} else if (nextTerm.next().equalsIgnoreCase("reverse")) {
math.reverse();
System.out
.println("The list was reversed in order and the list is now: "
+ math.toString());
} else if (nextTerm.next().equalsIgnoreCase("product")) {
System.out.println("The product of the polynomial is: "
+ math.product());
} else {
System.out.println("Not a recognized input method");
}
nextTerm.close();
}
PrintWriter save = new PrintWriter("operations.txt");
save.close();
fileData.close();
```
} | 2013/12/09 | [
"https://Stackoverflow.com/questions/20462487",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2628581/"
] | Why dont you you create a Class that holds the Statement, the count and handles all the addBatching plus other miscellaneous activities.
```
class BatchPreparedStatementHolder {
private int batchCount;
private PreparedStatement ps;
public BatchPreparedStatementHolder(PreparedStatement statement){
batchCount = 0;
ps = statment;
}
public void addBatch(){
ps.addBatch();
// increment how many times a batch has been added to the statement.
// execute batch if necessary.
if (++batchCount> 5000) {
ps.executeBatch();
batchCount = 0;
}
}
....
}
``` | Rather than keeping the Map.Entry in the map you can keep the nested class .. which will be easy to handle.. something like that ..
```
class Transaction implements AutoCloseable {
private final Connection conn;
class MapValue {
PreparedStatement p;
int index ;
public MapValue(){}
public MapValue(PreparedStatement p , int i)
{
index= i;
this.p=p;
}
}
private final Map<String, MapValue> sts = new HashMap<>();
Transaction(final Connection conn) throws SQLException {
conn.setAutoCommit(false);
this.conn = conn;
}
<T> void batch(final String st, final List<T> ts,
final BatchingInstructions<T> bi) throws SQLException {
final PreparedStatement stat;
int counter;
// if statement has already been created, retrieve statement and batch count
if (sts.containsKey(st)) {
MapValue m = sts.get(st);
stat = m.p;
counter = m.index;
} else {
// else create statement and batch count
stat = conn.prepareStatement(getInsert(st));
MapValue m = new MapValue(stat, 0);
sts.put(st, m);
}
for (final T t : ts) {
bi.batch(stat, t);
stat.addBatch();
// increment how many times a batch has been added to the statement.
// execute batch if necessary.
if (++counter > 5000) {
stat.executeBatch();
}
}
@Override
public void close() throws Exception {
for (final Map.Entry<PreparedStatement, Integer> m : sts.values()) {
if (m.getValue() > 0) {
m.getKey().executeBatch();
}
m.getKey().close();
}
conn.commit();
}
}
``` |
23,708,320 | In my project I have JSP pages that should print PDF documents | 2014/05/17 | [
"https://Stackoverflow.com/questions/23708320",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2293345/"
] | The method `add` should return boolean value, so all what you need to do is
```
public boolean add(MyObject newvalue) {
boolean retVal = super.add(newvalue);
Result = Double.NaN;
return retVal ;
}
``` | This is a good example as to when [composition over inheritance](http://en.wikipedia.org/wiki/Composition_over_inheritance) really makes sense for code design. Your class will become cluttered with unnecessary operations, when it only really needs to have an instance of a `List` of some kind floating around. It also means that you're not hard-dependent on the `ArrayList` implementation; for instance, what if your algorithms called for a `LinkedList` instead?
But, if you really want to fix what you have...
First and foremost, the reason you're getting the compiler error is because, as far as Java is concerned, you're *trying* to override the `add` method, but don't quite have the signature right.
The correct signature is specified as `boolean add(E)`, but you're overriding it with a signature of `void add(E)`. The types don't match, so you won't get a successful override, and Java will not compile the class, as you can see.
Next, creating more classes to accomplish the same thing as inheriting and properly overriding the `ArrayList` class will not gain you anything; if anything, it will be **more** of an overcomplication. |
14,496,615 | I have a test database with 1 table having some 50 million records. The table initially had 50 columns. The table has no indexes. When I execute the "sp\_spaceused" procedure I get "24733.88 MB" as result. Now to reduce the size of this database, I remove 15 columns (mostly int columns) and run the "sp\_spaceused", I still get "24733.88 MB" as result.
Why is the database size not reducing after removing so many columns? Am I missing anything here?
**Edit:** I have tried database shrinking but it didn't help either | 2013/01/24 | [
"https://Stackoverflow.com/questions/14496615",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/419556/"
] | Try running the following command:
```
DBCC CLEANTABLE ('dbname', 'yourTable', 0)
```
It will free space from dropped variable-length columns in tables or indexed views. More information here [DBCC CLEANTABLE](http://msdn.microsoft.com/en-us/library/ms174418.aspx) and here [Space used does not get changed after dropping a column](http://www.sqldbadiaries.com/2011/03/03/space-used-does-not-get-changed-after-dropping-a-column/)
Also, as correctly pointed out on the link posted on the first comment to this answer. After you've executed the DBCC CLEANTABLE command, you need to REBUILD your clustered index in case the table has one, in order to get back the space.
```
ALTER INDEX IndexName ON YourTable REBUILD
``` | The database size will not shrink simply because you have deleted objects. The database server usually holds the reclaimed space to be used for subsequent data inserts or new objects.
To reclaim the space freed, you have to shrink the database file. See [How do I shrink my SQL Server Database?](https://stackoverflow.com/questions/439071/how-do-i-shrink-my-sql-server-database) |
14,496,615 | I have a test database with 1 table having some 50 million records. The table initially had 50 columns. The table has no indexes. When I execute the "sp\_spaceused" procedure I get "24733.88 MB" as result. Now to reduce the size of this database, I remove 15 columns (mostly int columns) and run the "sp\_spaceused", I still get "24733.88 MB" as result.
Why is the database size not reducing after removing so many columns? Am I missing anything here?
**Edit:** I have tried database shrinking but it didn't help either | 2013/01/24 | [
"https://Stackoverflow.com/questions/14496615",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/419556/"
] | When any variable length column is dropped from table, it does not reduce the size of table. Table size stays the same till Indexes are reorganized or rebuild.
There is also DBCC command DBCC CLEANTABLE, which can be used to reclaim any space previously occupied with variable length columns. Here is the syntax:
```
DBCC CLEANTABLE ('MyDatabase','MySchema.MyTable', 0)WITH NO_INFOMSGS;
GO
```
Raj | The database size will not shrink simply because you have deleted objects. The database server usually holds the reclaimed space to be used for subsequent data inserts or new objects.
To reclaim the space freed, you have to shrink the database file. See [How do I shrink my SQL Server Database?](https://stackoverflow.com/questions/439071/how-do-i-shrink-my-sql-server-database) |
14,496,615 | I have a test database with 1 table having some 50 million records. The table initially had 50 columns. The table has no indexes. When I execute the "sp\_spaceused" procedure I get "24733.88 MB" as result. Now to reduce the size of this database, I remove 15 columns (mostly int columns) and run the "sp\_spaceused", I still get "24733.88 MB" as result.
Why is the database size not reducing after removing so many columns? Am I missing anything here?
**Edit:** I have tried database shrinking but it didn't help either | 2013/01/24 | [
"https://Stackoverflow.com/questions/14496615",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/419556/"
] | Try running the following command:
```
DBCC CLEANTABLE ('dbname', 'yourTable', 0)
```
It will free space from dropped variable-length columns in tables or indexed views. More information here [DBCC CLEANTABLE](http://msdn.microsoft.com/en-us/library/ms174418.aspx) and here [Space used does not get changed after dropping a column](http://www.sqldbadiaries.com/2011/03/03/space-used-does-not-get-changed-after-dropping-a-column/)
Also, as correctly pointed out on the link posted on the first comment to this answer. After you've executed the DBCC CLEANTABLE command, you need to REBUILD your clustered index in case the table has one, in order to get back the space.
```
ALTER INDEX IndexName ON YourTable REBUILD
``` | When any variable length column is dropped from table, it does not reduce the size of table. Table size stays the same till Indexes are reorganized or rebuild.
There is also DBCC command DBCC CLEANTABLE, which can be used to reclaim any space previously occupied with variable length columns. Here is the syntax:
```
DBCC CLEANTABLE ('MyDatabase','MySchema.MyTable', 0)WITH NO_INFOMSGS;
GO
```
Raj |
39,229,347 | So I used the default Registration Form Laravel.
Made copy of the Registration Form to make a slightly different one.
Basically there is two sign up forms
1. Starter - original
2. Bronze - Copy
**--My Routing List--**
```
Auth::routes();
Route::get('/register', function(){
return View::make('auth.register');
});
Route::get('/bronze', function(){
return View::make('auth.bronze');
});
Route::get('/login', function(){
return View::make('auth.login');
});
```
Now every time I submit the bronze sign up form, it redirects me to my home page.
I'm thinking maybe its my Action call in my view. which is identical to the Starter Form
```
<form class="form-horizontal" role="form" method="POST" action="{{ url('/register') }}">
```
if I'm correct what I just did is bad practice, but I'm a new-bie at this framework. | 2016/08/30 | [
"https://Stackoverflow.com/questions/39229347",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6099413/"
] | Change your routes like this:
```
const appRoutes: Routes = [
{ path: '', redirectTo: HomeComponent, pathMatch: 'full'}, //(redirectTo or component)
{path:'intro',component: IntroComponent},
{path:'login',component: LoginComponent},
{path:'register', component: RegisterComponent}
];
```
the default `pathMatch` strategy is `prefix` in routes so `path: ''` with `prefix` means practically everyroute. So everyroute was navigated to the `HomeComponent`. | This happens because initial navigation is not completed when calling `this.router.navigate(['/intro'])` from `ngOnInit`.
There are two ways to solve this:
**Solution #1**
In `app.module.ts` you disable initial navigation
```
RouterModule.forRoot(appRoutes, { initialNavigation: false })
```
Ref: [router.navigate failing silently on OnInit of component](https://github.com/angular/angular/issues/11748)
**Solution #2**
If you do not want to disable initial navigation then use `setTimeout` to allow the initial navigation to complete.
```
setTimeout(() => this.router.navigate(['/intro']), 1)
``` |
49,554,222 | Examples for implementing the directive's `link` method in typescript use as the fourth parameter instance of `ng.INgModelController`
```
public link($scope: ng.IScope, el: JQuery, attrs: ng.IAttributes, ngModel: ng.INgModelController)
```
but this does not compile for me (I have the latest angularjs.TypeScript.DefinitelyTyped 6.5.6 installed), because the interface `IDirectiveLinkFn` expects as the fourth parameter instance of `IController` and not `INgModelController`.
If the fourth parameter is modified to be of type `IController`, now it compiles, but the interfaces are very different. How is it possible after this change to access the model properties `ngModel.$viewValue` or `ngModel.$render` inside link function?
The packages.config contains these packages:
```
<package id="angularjs.TypeScript.DefinitelyTyped" version="6.5.6" targetFramework="net452" />
<package id="angular-material.TypeScript.DefinitelyTyped" version="1.6.4" targetFramework="net452" />
<package id="angular-ui.TypeScript.DefinitelyTyped" version="2.4.3" targetFramework="net452" />
``` | 2018/03/29 | [
"https://Stackoverflow.com/questions/49554222",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1882699/"
] | Since [INgModelController](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/628cbd69e1213d8b3f83950e2034e790b37d206a/types/angular/index.d.ts#L382) doesn't extend [IController](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/628cbd69e1213d8b3f83950e2034e790b37d206a/types/angular/index.d.ts#L1862) and isn't compatible with it (this is an oversight in AngularJS typing), the solution is to use union type:
```
public link($scope: ng.IScope, el: JQuery, attrs: ng.IAttributes,
ngModel: ng.INgController & ng.INgModelController) {...}
``` | Do you have @types declarations installed ?
For example, in `"@types/angular": "^1.6.43"`, in `IController` type you will find the next options:
```
// IController implementations frequently do not implement any of its methods.
// A string indexer indicates to TypeScript not to issue a weak type error in this case.
[s: string]: any;
```
If I correct, this means you can use any of properties from the `IController` type.
Another option is to use a type coercion, something like this:
```
let viewValue = (ngModel as ng.INgModelController).$viewValue;
``` |
46,038 | I want to be able to get a drop-down list of partial matches to Elisp function names (installed or those already defined in the buffer) as shown in the
screen-shot below from the YouTube video: <https://youtu.be/QaX3AaK3_Lk?t=332>
How do I achieve this? Is there a standard library for this?
[](https://i.stack.imgur.com/RUO2c.png) | 2018/11/16 | [
"https://emacs.stackexchange.com/questions/46038",
"https://emacs.stackexchange.com",
"https://emacs.stackexchange.com/users/10896/"
] | I'd like to recommend the package [company-mode](http://company-mode.github.io). I found it easier to setup and config. For beginners, using the following configuration will enable the autocomplete out of box.
```
(use-package company
:ensure t
:config
(progn
(add-hook 'after-init-hook 'global-company-mode)))
```
Moreover, there's a lot of backends you can use for specific programming languages. The following is how to config auto complete for python.
```
(use-package company-jedi
:ensure t
:config
(progn
(setq jedi:complete-on-dot t
jedi:use-shortcuts t)
(defun user/python-mode-hook ()
(add-to-list 'company-backends 'company-jedi))
(add-hook 'python-mode-hook 'user/python-mode-hook)))
``` | Without using external packages you can get autocompletion visible in minibuffer. Add this to config:
```
(setq tab-always-indent 'complete)
``` |
53,017,518 | Here is the simplified form of my intention: [Sketch](http://sketch.paperjs.org/#S/nZRNb9swDIb/CuFD4wCG4KbJxUAu63UFhnXADnEOik0namzJkOW0RZH/PsqWP1NsQwXkQyRFPXxJ+8OTvEAv8p7PaJKTF3iJSu3+wjW8wRYkvsIPbk7su5Dof8QSaGVaFRHs7sMwAPraB63ZKDKuZsbKaHXGR5UrHcFCY7qYOH6L1JwiWIWxvC5j+cZ4mj7jsUBp/N0D5aLPnhyxtESpMmOmR6GTvKdK6AzSJbu1RXgYEDRPRV3RJRtnyESed0RKc3nEDirlhkfgEjY1vZdIUaUSNvmidVxb2JaJCDjlSPDfZITPDqqWacVa0wxw/Qlg7B1ynpxjz7lUyRNh3iMI2eor0D0uK9QFv2GuXn3i6svhOeqJyD8xMSRRPu9+o/Jm2vz1Ztr8sdBHjSgXs4rvw07KrJaJEUqCkk+qrvCJ6Hy8kExLd6+lKzVeCM4KWapK2ANOg5GFApqDrBHAtaAvexR1m8becRK2/lKrF6qc0e4XVsYfxwZjsW2NERhdYwCDtZ3uT+ztbFe3HqNIeUs4mgO7Ck4PZgSdPj4BLUfX2yUysGYmDBZwdwfdf2Yn48bA7HjAdrul2XIjEnvzlE2T0NRaQsbzCqfe63TrAm1Fg8PF2O62jHPyZtJYPyKkefN6GAJmPbW9H5z/0VAHAEj88PeL2+HsHxT7Q4NJr8ODRn5uVKq8aLe//gE=).
I only want the alert box turn to red when the orange circle is close enough (when the gray circle touches) to the line:
[](https://i.stack.imgur.com/Kwr1k.png)
However, currently it may throw false alarms, ie. before close enough:
[](https://i.stack.imgur.com/7zJ3e.gif)
How can we correctly detect collisions? | 2018/10/26 | [
"https://Stackoverflow.com/questions/53017518",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1952991/"
] | I came up with "trial and error" approach: [Full example](https://github.com/ceremcem/paperjs-collision-test/blob/master/demo.js)
```js
// Returns item.position at the moment of collision
// and the collided object.
function collisionTest(item, curr){
var prev = item.position;
var point = curr.clone();
var hit = null;
var tolerance = 45;
var _error = 0.01;
var firstPass = true;
var _stopSearching = false;
var _step = ((curr - prev) / 2).clone();
var _acceptable_iter_count = 16;
var _max_iter_count = 100;
var i;
for (i = 0; i < _max_iter_count; i++){
var _hit = project.hitTest(point, {
fill: true,
stroke: true,
segments: true,
tolerance: tolerance,
match: function(hit){
if (hit.item && hit.item.data && hit.item.data.type === "pointer"){
return false
}
return true
}
})
if(_hit){
hit = _hit;
// hit has happened between prev and curr points
// step half way backward
point -= _step
if (_step.length < _error){
// step is too small, stop trials as soon
// as no hit can be found
_stopSearching = true;
}
} else {
if(firstPass || _stopSearching){
break;
} else {
// not hit found, but we should
// step forward to search for a more
// accurate collision point
point += _step
}
}
firstPass = false;
if(_step.length >= _error * 2 ) {
_step /= 2
} else {
// minimum step length must be error/2
// in order to save loop count
_step = _step.normalize(_error * 0.8)
}
}
if (i > _acceptable_iter_count){
console.log("found at " + i + ". iteration, step: ", _step.length)
}
return {point, hit}
}
```
### Algorithm
1. Perform a hit test.
2. If a hit is found, consider that the actual collision might happen anywhere between previous position and current position (on the `delta`).
3. Step backwards by `delta = delta / 2` and perform a hit test.
4. If still hits, repeat step 3.
5. If hit can not be found, step forward by `delta = delta / 2`
6. If still doesn't hit, repeat step 5.
7. If hits, repeat step 3 if step8 allows to do so.
8. If step size (`delta`) is too small or process exceeds max iteration limit, break and return the best possible collision point (the point for the item that provides best collision point)
Further Improvements
====================
This solution is based on the following problem: Detecting a hit is *not enough*, because it might be too late when the hit is detected and actual collision might be happened anywhere between previous and current points (on the `delta`) due to hit detection intervals.
This trial and error approach might be improved by starting the tries on a very accurate "guess" based on a proper calculation *after detecting the first hit*.
We can possibly calculate `1` (the actual collision point) in one shot by using `2`. It seems like it's the nearest point of `3` to `4`:
[](https://i.stack.imgur.com/RpayX.png)
If the calculation is correct, only 2 loops would be enough to detect a collision point: 1st is for detecting the hit (as shown by `#2`) and 2nd is for verification. If it's not correct, trial-and-error approach will take over. | You can use [`Path.getIntersections()`](http://paperjs.org/reference/path/#getintersections-path) or [`Path.intersects()`](http://paperjs.org/reference/path/#intersects-item). |
53,017,518 | Here is the simplified form of my intention: [Sketch](http://sketch.paperjs.org/#S/nZRNb9swDIb/CuFD4wCG4KbJxUAu63UFhnXADnEOik0namzJkOW0RZH/PsqWP1NsQwXkQyRFPXxJ+8OTvEAv8p7PaJKTF3iJSu3+wjW8wRYkvsIPbk7su5Dof8QSaGVaFRHs7sMwAPraB63ZKDKuZsbKaHXGR5UrHcFCY7qYOH6L1JwiWIWxvC5j+cZ4mj7jsUBp/N0D5aLPnhyxtESpMmOmR6GTvKdK6AzSJbu1RXgYEDRPRV3RJRtnyESed0RKc3nEDirlhkfgEjY1vZdIUaUSNvmidVxb2JaJCDjlSPDfZITPDqqWacVa0wxw/Qlg7B1ynpxjz7lUyRNh3iMI2eor0D0uK9QFv2GuXn3i6svhOeqJyD8xMSRRPu9+o/Jm2vz1Ztr8sdBHjSgXs4rvw07KrJaJEUqCkk+qrvCJ6Hy8kExLd6+lKzVeCM4KWapK2ANOg5GFApqDrBHAtaAvexR1m8becRK2/lKrF6qc0e4XVsYfxwZjsW2NERhdYwCDtZ3uT+ztbFe3HqNIeUs4mgO7Ck4PZgSdPj4BLUfX2yUysGYmDBZwdwfdf2Yn48bA7HjAdrul2XIjEnvzlE2T0NRaQsbzCqfe63TrAm1Fg8PF2O62jHPyZtJYPyKkefN6GAJmPbW9H5z/0VAHAEj88PeL2+HsHxT7Q4NJr8ODRn5uVKq8aLe//gE=).
I only want the alert box turn to red when the orange circle is close enough (when the gray circle touches) to the line:
[](https://i.stack.imgur.com/Kwr1k.png)
However, currently it may throw false alarms, ie. before close enough:
[](https://i.stack.imgur.com/7zJ3e.gif)
How can we correctly detect collisions? | 2018/10/26 | [
"https://Stackoverflow.com/questions/53017518",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1952991/"
] | You can use [`Path.getIntersections()`](http://paperjs.org/reference/path/#getintersections-path) or [`Path.intersects()`](http://paperjs.org/reference/path/#intersects-item). | Instead of attempting to find the direct intersections, you can instead find the [*nearest point*](http://paperjs.org/reference/path/#getnearestpoint-point) on the path from the position of the moving dot.
If the distance between the dot and that nearest point drops below a threshold (equal to the `strokeWidth` of the `Path` and the radius of the dot), then you can consider it a valid hit.
**There's a catch though**: The [`strokeJoin`](http://paperjs.org/reference/path/#strokejoin) & [`strokeCap`](http://paperjs.org/reference/path/#strokecap) properties of your path should be
set to `round`, since that results in a symmetrical stroke width around
corners and endings, hence avoiding false-negatives.
Here's an example:
```
var path = new Path({
segments: [
new Point(100, 200),
new Point(200, 100),
new Point(300, 300)
],
strokeWidth: 100,
// This is important.
strokeJoin: 'round',
// This is important.
strokeCap: 'round',
strokeColor: 'red',
selected: true,
position: view.center
})
var dot = new Path.Circle({
center: view.center,
radius: 10,
fillColor: 'red'
})
function onMouseMove(event) {
dot.position = event.point
var nearestPoint = path.getNearestPoint(dot.position)
var distance = dot.position.subtract(nearestPoint)
if (distance.length < (dot.bounds.width / 2) + (path.strokeWidth / 2)) {
path.strokeColor = 'blue'
} else {
path.strokeColor = 'red'
}
}
```
and the [Sketch](http://sketch.paperjs.org/#S/jVPBboMwDP0Vi0tBq1La3dB26m1Sp0mbtEPpIYBbotIEJYEeqv77nABrNm3aEELg957tPJtLJPkJoyx6PaIt62gelapy3z3X0HJbwyNIPMMLvcaXXAJdBg8nlNZksB0C7vIkJaSNl2k6h1WaJvOf0JVDl7+h9w6lRzKAu5FkrFZHfBeVrTMnHsOLBbzVwoC7T63SlkvLQsUTJc1gplUnq9l/RWvefteMgGqUdhDeAGywtFhlYHWHY7BVRlihqHIv8MxK8gp1Lq90qFw6XytlA1vZWuiywcndgf5FO+bVvBKdcQaMgb1omrCpqca+k6VrAJTcqM7gRvUYY0+5EhirUAts6pN68SAFaAYugWO4RiVyjcb62RDL7QM7oH0OwnGYKblJK2HI2RJJFjKY6QqreWnjMHcyFRV7iCcla1AeaAEfwNco3EAMO7slgAWsEriD2HcUbIcHPg/ph3FjeKuon1nRdDgbKFfAxuBfgsFczyePc0m/SaGRH71hJsq2u+sH).
---
That being said, the best way to go about it is to wait for (or implement yourself), [Path dilation/offsetting](https://github.com/paperjs/paper.js/issues/371) and find the intersection on the dilated path instead, since this will allow you to use any `strokeJoin`/`strokeCap` setting.
Ideally the dilation/offsetting would be done with the same `strokeJoin`/`strokeCap` properties of the `Path`.
There's a [JS library that reliably does polygon offsetting](https://sourceforge.net/projects/jsclipper/) which might be of use to you. |
53,017,518 | Here is the simplified form of my intention: [Sketch](http://sketch.paperjs.org/#S/nZRNb9swDIb/CuFD4wCG4KbJxUAu63UFhnXADnEOik0namzJkOW0RZH/PsqWP1NsQwXkQyRFPXxJ+8OTvEAv8p7PaJKTF3iJSu3+wjW8wRYkvsIPbk7su5Dof8QSaGVaFRHs7sMwAPraB63ZKDKuZsbKaHXGR5UrHcFCY7qYOH6L1JwiWIWxvC5j+cZ4mj7jsUBp/N0D5aLPnhyxtESpMmOmR6GTvKdK6AzSJbu1RXgYEDRPRV3RJRtnyESed0RKc3nEDirlhkfgEjY1vZdIUaUSNvmidVxb2JaJCDjlSPDfZITPDqqWacVa0wxw/Qlg7B1ynpxjz7lUyRNh3iMI2eor0D0uK9QFv2GuXn3i6svhOeqJyD8xMSRRPu9+o/Jm2vz1Ztr8sdBHjSgXs4rvw07KrJaJEUqCkk+qrvCJ6Hy8kExLd6+lKzVeCM4KWapK2ANOg5GFApqDrBHAtaAvexR1m8becRK2/lKrF6qc0e4XVsYfxwZjsW2NERhdYwCDtZ3uT+ztbFe3HqNIeUs4mgO7Ck4PZgSdPj4BLUfX2yUysGYmDBZwdwfdf2Yn48bA7HjAdrul2XIjEnvzlE2T0NRaQsbzCqfe63TrAm1Fg8PF2O62jHPyZtJYPyKkefN6GAJmPbW9H5z/0VAHAEj88PeL2+HsHxT7Q4NJr8ODRn5uVKq8aLe//gE=).
I only want the alert box turn to red when the orange circle is close enough (when the gray circle touches) to the line:
[](https://i.stack.imgur.com/Kwr1k.png)
However, currently it may throw false alarms, ie. before close enough:
[](https://i.stack.imgur.com/7zJ3e.gif)
How can we correctly detect collisions? | 2018/10/26 | [
"https://Stackoverflow.com/questions/53017518",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1952991/"
] | I came up with "trial and error" approach: [Full example](https://github.com/ceremcem/paperjs-collision-test/blob/master/demo.js)
```js
// Returns item.position at the moment of collision
// and the collided object.
function collisionTest(item, curr){
var prev = item.position;
var point = curr.clone();
var hit = null;
var tolerance = 45;
var _error = 0.01;
var firstPass = true;
var _stopSearching = false;
var _step = ((curr - prev) / 2).clone();
var _acceptable_iter_count = 16;
var _max_iter_count = 100;
var i;
for (i = 0; i < _max_iter_count; i++){
var _hit = project.hitTest(point, {
fill: true,
stroke: true,
segments: true,
tolerance: tolerance,
match: function(hit){
if (hit.item && hit.item.data && hit.item.data.type === "pointer"){
return false
}
return true
}
})
if(_hit){
hit = _hit;
// hit has happened between prev and curr points
// step half way backward
point -= _step
if (_step.length < _error){
// step is too small, stop trials as soon
// as no hit can be found
_stopSearching = true;
}
} else {
if(firstPass || _stopSearching){
break;
} else {
// not hit found, but we should
// step forward to search for a more
// accurate collision point
point += _step
}
}
firstPass = false;
if(_step.length >= _error * 2 ) {
_step /= 2
} else {
// minimum step length must be error/2
// in order to save loop count
_step = _step.normalize(_error * 0.8)
}
}
if (i > _acceptable_iter_count){
console.log("found at " + i + ". iteration, step: ", _step.length)
}
return {point, hit}
}
```
### Algorithm
1. Perform a hit test.
2. If a hit is found, consider that the actual collision might happen anywhere between previous position and current position (on the `delta`).
3. Step backwards by `delta = delta / 2` and perform a hit test.
4. If still hits, repeat step 3.
5. If hit can not be found, step forward by `delta = delta / 2`
6. If still doesn't hit, repeat step 5.
7. If hits, repeat step 3 if step8 allows to do so.
8. If step size (`delta`) is too small or process exceeds max iteration limit, break and return the best possible collision point (the point for the item that provides best collision point)
Further Improvements
====================
This solution is based on the following problem: Detecting a hit is *not enough*, because it might be too late when the hit is detected and actual collision might be happened anywhere between previous and current points (on the `delta`) due to hit detection intervals.
This trial and error approach might be improved by starting the tries on a very accurate "guess" based on a proper calculation *after detecting the first hit*.
We can possibly calculate `1` (the actual collision point) in one shot by using `2`. It seems like it's the nearest point of `3` to `4`:
[](https://i.stack.imgur.com/RpayX.png)
If the calculation is correct, only 2 loops would be enough to detect a collision point: 1st is for detecting the hit (as shown by `#2`) and 2nd is for verification. If it's not correct, trial-and-error approach will take over. | Instead of attempting to find the direct intersections, you can instead find the [*nearest point*](http://paperjs.org/reference/path/#getnearestpoint-point) on the path from the position of the moving dot.
If the distance between the dot and that nearest point drops below a threshold (equal to the `strokeWidth` of the `Path` and the radius of the dot), then you can consider it a valid hit.
**There's a catch though**: The [`strokeJoin`](http://paperjs.org/reference/path/#strokejoin) & [`strokeCap`](http://paperjs.org/reference/path/#strokecap) properties of your path should be
set to `round`, since that results in a symmetrical stroke width around
corners and endings, hence avoiding false-negatives.
Here's an example:
```
var path = new Path({
segments: [
new Point(100, 200),
new Point(200, 100),
new Point(300, 300)
],
strokeWidth: 100,
// This is important.
strokeJoin: 'round',
// This is important.
strokeCap: 'round',
strokeColor: 'red',
selected: true,
position: view.center
})
var dot = new Path.Circle({
center: view.center,
radius: 10,
fillColor: 'red'
})
function onMouseMove(event) {
dot.position = event.point
var nearestPoint = path.getNearestPoint(dot.position)
var distance = dot.position.subtract(nearestPoint)
if (distance.length < (dot.bounds.width / 2) + (path.strokeWidth / 2)) {
path.strokeColor = 'blue'
} else {
path.strokeColor = 'red'
}
}
```
and the [Sketch](http://sketch.paperjs.org/#S/jVPBboMwDP0Vi0tBq1La3dB26m1Sp0mbtEPpIYBbotIEJYEeqv77nABrNm3aEELg957tPJtLJPkJoyx6PaIt62gelapy3z3X0HJbwyNIPMMLvcaXXAJdBg8nlNZksB0C7vIkJaSNl2k6h1WaJvOf0JVDl7+h9w6lRzKAu5FkrFZHfBeVrTMnHsOLBbzVwoC7T63SlkvLQsUTJc1gplUnq9l/RWvefteMgGqUdhDeAGywtFhlYHWHY7BVRlihqHIv8MxK8gp1Lq90qFw6XytlA1vZWuiywcndgf5FO+bVvBKdcQaMgb1omrCpqca+k6VrAJTcqM7gRvUYY0+5EhirUAts6pN68SAFaAYugWO4RiVyjcb62RDL7QM7oH0OwnGYKblJK2HI2RJJFjKY6QqreWnjMHcyFRV7iCcla1AeaAEfwNco3EAMO7slgAWsEriD2HcUbIcHPg/ph3FjeKuon1nRdDgbKFfAxuBfgsFczyePc0m/SaGRH71hJsq2u+sH).
---
That being said, the best way to go about it is to wait for (or implement yourself), [Path dilation/offsetting](https://github.com/paperjs/paper.js/issues/371) and find the intersection on the dilated path instead, since this will allow you to use any `strokeJoin`/`strokeCap` setting.
Ideally the dilation/offsetting would be done with the same `strokeJoin`/`strokeCap` properties of the `Path`.
There's a [JS library that reliably does polygon offsetting](https://sourceforge.net/projects/jsclipper/) which might be of use to you. |
22,730,033 | I want to make the logo at the bottom of the picture so it will look like a watermarked picture with a logo.
Now the problem is that the absolute position is going outside the border and goes to the bottom of the page.
I'm quite sure that a small tweak can change the picture here (double meaning).
The jsFiddle :
<http://jsfiddle.net/PMc62/>
Here is my Code :
Html :
```
<section>
<ul>
<li>
<a href="">
<img src="http://www.reactive.com/Media/images/hero-ripcurl-01-2615749e-fba2-47da-abc7-d0ea3a9ecfbd-0-600x450.jpg" width=600 height=450>
<img src="https://puaction.com/img/logo.png" width=300 height=65>
</a>
<a href="">
<img src="http://img2.wikia.nocookie.net/__cb20120217141950/lego/images/6/67/Lego_lotr_2012_gollum-600x450.jpg" width=600 height=450>
<img src="https://puaction.com/img/logo.png" width=300 height=65>
</a>
</li>
</ul>
</section>
```
The css:
```
section ul:first-child li {
height: 450px;
overflow: hidden;
width: 600px;
}
section ul:first-child li a img:nth-child(2) {
bottom: 0;
height: 65px;
position: absolute;
left: 0;
width: 300px;
z-index: 9999;
}
```
Any Idea ? | 2014/03/29 | [
"https://Stackoverflow.com/questions/22730033",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3447293/"
] | If a GPIO isn't working on a PIC then it is often because one of the peripherals is using it. Many of the pins are multi purpose and if one of the peripherals is using it then it will not work as a GPIO.
The data sheet has this for the pin on the pinout diagram (for the PDIP20 package, double check for whichever package you are using):
PGC3/SOSCO/T1CK/U2CTS/CN0/RA4
This tells you which peripherals use the pin. It means you need to figure out what PGC3 is for, and turn that off. Then you have to work out what SOSCO is, and turn that off too. Also T1CK (timer 1 clock input maybe?), U2CTS and CN0 have to be off. | I just ran into this problem with a PIC24FV32KA301. The list of peripherals on this pin for my device is almost exactly the same as yours, namely: PGEC3/SOSCO/SCLKI/U2CTS/CN0/RA4
The problem was in the SOSCSRC fuse of the FOSCSEL configuration word, which switches between, according to the data sheet:
"analog crystal function" and "digital SCLKI function" on the SOSCO pin.
To get digital I/O on the SOCSO pin, the SOSCSRC fuse needed to be cleared. By default it is set (1). Here is the configuration line I used that did the trick:
```
_FOSCSEL( SOSCSRC_DIG );
```
The datasheet doesn't explicitly say this will permit digital I/O on the SOSCO pin, but I found in a [microchip forum post](http://picforum.ric323.com/viewtopic.php?f=32&t=71#p361) that the datasheet for a different device with a similar set of peripherals makes the situation more clear. |
22,730,033 | I want to make the logo at the bottom of the picture so it will look like a watermarked picture with a logo.
Now the problem is that the absolute position is going outside the border and goes to the bottom of the page.
I'm quite sure that a small tweak can change the picture here (double meaning).
The jsFiddle :
<http://jsfiddle.net/PMc62/>
Here is my Code :
Html :
```
<section>
<ul>
<li>
<a href="">
<img src="http://www.reactive.com/Media/images/hero-ripcurl-01-2615749e-fba2-47da-abc7-d0ea3a9ecfbd-0-600x450.jpg" width=600 height=450>
<img src="https://puaction.com/img/logo.png" width=300 height=65>
</a>
<a href="">
<img src="http://img2.wikia.nocookie.net/__cb20120217141950/lego/images/6/67/Lego_lotr_2012_gollum-600x450.jpg" width=600 height=450>
<img src="https://puaction.com/img/logo.png" width=300 height=65>
</a>
</li>
</ul>
</section>
```
The css:
```
section ul:first-child li {
height: 450px;
overflow: hidden;
width: 600px;
}
section ul:first-child li a img:nth-child(2) {
bottom: 0;
height: 65px;
position: absolute;
left: 0;
width: 300px;
z-index: 9999;
}
```
Any Idea ? | 2014/03/29 | [
"https://Stackoverflow.com/questions/22730033",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3447293/"
] | If a GPIO isn't working on a PIC then it is often because one of the peripherals is using it. Many of the pins are multi purpose and if one of the peripherals is using it then it will not work as a GPIO.
The data sheet has this for the pin on the pinout diagram (for the PDIP20 package, double check for whichever package you are using):
PGC3/SOSCO/T1CK/U2CTS/CN0/RA4
This tells you which peripherals use the pin. It means you need to figure out what PGC3 is for, and turn that off. Then you have to work out what SOSCO is, and turn that off too. Also T1CK (timer 1 clock input maybe?), U2CTS and CN0 have to be off. | This is because probably Second Oscillator (SOSC) is enabled, you can disable it from bit SOSCEN in OSCCON register; the code would be:
OSCCONbits.SOSCEN = 0;
Then you can configure your pin as output with TRIS register as usual... |
22,730,033 | I want to make the logo at the bottom of the picture so it will look like a watermarked picture with a logo.
Now the problem is that the absolute position is going outside the border and goes to the bottom of the page.
I'm quite sure that a small tweak can change the picture here (double meaning).
The jsFiddle :
<http://jsfiddle.net/PMc62/>
Here is my Code :
Html :
```
<section>
<ul>
<li>
<a href="">
<img src="http://www.reactive.com/Media/images/hero-ripcurl-01-2615749e-fba2-47da-abc7-d0ea3a9ecfbd-0-600x450.jpg" width=600 height=450>
<img src="https://puaction.com/img/logo.png" width=300 height=65>
</a>
<a href="">
<img src="http://img2.wikia.nocookie.net/__cb20120217141950/lego/images/6/67/Lego_lotr_2012_gollum-600x450.jpg" width=600 height=450>
<img src="https://puaction.com/img/logo.png" width=300 height=65>
</a>
</li>
</ul>
</section>
```
The css:
```
section ul:first-child li {
height: 450px;
overflow: hidden;
width: 600px;
}
section ul:first-child li a img:nth-child(2) {
bottom: 0;
height: 65px;
position: absolute;
left: 0;
width: 300px;
z-index: 9999;
}
```
Any Idea ? | 2014/03/29 | [
"https://Stackoverflow.com/questions/22730033",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3447293/"
] | If a GPIO isn't working on a PIC then it is often because one of the peripherals is using it. Many of the pins are multi purpose and if one of the peripherals is using it then it will not work as a GPIO.
The data sheet has this for the pin on the pinout diagram (for the PDIP20 package, double check for whichever package you are using):
PGC3/SOSCO/T1CK/U2CTS/CN0/RA4
This tells you which peripherals use the pin. It means you need to figure out what PGC3 is for, and turn that off. Then you have to work out what SOSCO is, and turn that off too. Also T1CK (timer 1 clock input maybe?), U2CTS and CN0 have to be off. | Note the SOSC pins might be general purpose input pins (if not used as secondary oscillator), so you might not be able to use it as output pin |
592,161 | My internet connection is working fine, but when I go to <http://www.google.com/> in Internet Explorer I get the following error:
```
No site configured at this address
```
Cutting and pasting the exact address into another browser gets to the site just fine. How can I get this working again in IE? | 2013/05/06 | [
"https://superuser.com/questions/592161",
"https://superuser.com",
"https://superuser.com/users/105147/"
] | Using IE's Developer Tools, delete the cache for the specific domain like so:
1. Open Internet Explorer 10
2. Press `F12` (or click the settings gear icon in the upper-right corner and click "F12 developer tools")
3. Press `Ctrl` + `D` (or in the menu bar that appears on the lower
portion of the screen, click Cache -> "Clear browser cache for this domain...")
4. Click Yes
5. Try going to the site again and you should be all set
Please note that before figuring this out, I had deleted the entire cache on the user's system, in which the google.com cache should be included. Deleting the entire cache did NOT fix the problem though, but deleting it for the specific domain did. | First off I'd try setting your internet's settings to default, that normally fixes these kind of problems.
If that doesn't work, try installing Firefox or Chrome then uninstalling IE then using Chrome or Firefox re-install IE.
If that doesn't work it might be as simple as clearing the browser cache or deleting cookies/history.
Alternatively try opening the page as cached or InPrivate. |
592,161 | My internet connection is working fine, but when I go to <http://www.google.com/> in Internet Explorer I get the following error:
```
No site configured at this address
```
Cutting and pasting the exact address into another browser gets to the site just fine. How can I get this working again in IE? | 2013/05/06 | [
"https://superuser.com/questions/592161",
"https://superuser.com",
"https://superuser.com/users/105147/"
] | Using IE's Developer Tools, delete the cache for the specific domain like so:
1. Open Internet Explorer 10
2. Press `F12` (or click the settings gear icon in the upper-right corner and click "F12 developer tools")
3. Press `Ctrl` + `D` (or in the menu bar that appears on the lower
portion of the screen, click Cache -> "Clear browser cache for this domain...")
4. Click Yes
5. Try going to the site again and you should be all set
Please note that before figuring this out, I had deleted the entire cache on the user's system, in which the google.com cache should be included. Deleting the entire cache did NOT fix the problem though, but deleting it for the specific domain did. | Try Settings ->Internet Options -> Advanced (TAB) -> Reset...(button)
And Settings ->Internet Options -> Advanced (TAB) -> Restore advanced settings |
592,161 | My internet connection is working fine, but when I go to <http://www.google.com/> in Internet Explorer I get the following error:
```
No site configured at this address
```
Cutting and pasting the exact address into another browser gets to the site just fine. How can I get this working again in IE? | 2013/05/06 | [
"https://superuser.com/questions/592161",
"https://superuser.com",
"https://superuser.com/users/105147/"
] | Using IE's Developer Tools, delete the cache for the specific domain like so:
1. Open Internet Explorer 10
2. Press `F12` (or click the settings gear icon in the upper-right corner and click "F12 developer tools")
3. Press `Ctrl` + `D` (or in the menu bar that appears on the lower
portion of the screen, click Cache -> "Clear browser cache for this domain...")
4. Click Yes
5. Try going to the site again and you should be all set
Please note that before figuring this out, I had deleted the entire cache on the user's system, in which the google.com cache should be included. Deleting the entire cache did NOT fix the problem though, but deleting it for the specific domain did. | I have experienced this issue.
Click `Tools` and click `Delete Browsing History`.
Then it should open. |
592,161 | My internet connection is working fine, but when I go to <http://www.google.com/> in Internet Explorer I get the following error:
```
No site configured at this address
```
Cutting and pasting the exact address into another browser gets to the site just fine. How can I get this working again in IE? | 2013/05/06 | [
"https://superuser.com/questions/592161",
"https://superuser.com",
"https://superuser.com/users/105147/"
] | Using IE's Developer Tools, delete the cache for the specific domain like so:
1. Open Internet Explorer 10
2. Press `F12` (or click the settings gear icon in the upper-right corner and click "F12 developer tools")
3. Press `Ctrl` + `D` (or in the menu bar that appears on the lower
portion of the screen, click Cache -> "Clear browser cache for this domain...")
4. Click Yes
5. Try going to the site again and you should be all set
Please note that before figuring this out, I had deleted the entire cache on the user's system, in which the google.com cache should be included. Deleting the entire cache did NOT fix the problem though, but deleting it for the specific domain did. | I had the same problem recently. The only change that occurred was that Microsoft had upgraded Windows Internet Explorer to version 10. My internet banking website was also affected. I tried clearing caches, deleting cookies and explorer history to no avail. In desperation I uninstalled Windows Internet Explorer 10 and now use Internet Explorer 9. Both problems have disappeared and Google is behaving itself. I am now averse to any further versions of the explorer Microsoft might supply unless I am assured that they will contain no problems. |
69,477 | I create PDF files from my Adobe Illustrator files by saving as. I would prefer it to create the pdf file and retain the AI file but sometimes it converts the ai file to a pdf. Not all the time, only sometimes. Why is this? Is there a way to create PDF files without having it convert your current artboard to a PDF file. | 2016/04/05 | [
"https://graphicdesign.stackexchange.com/questions/69477",
"https://graphicdesign.stackexchange.com",
"https://graphicdesign.stackexchange.com/users/64031/"
] | When you Save As, it may "replace" your file in Illustrator but your original file will still exist (and you can open it back up). So if your file is AI and you save as PDF the AI file will still exist.
You can always use "Save A Copy..." instead if you prefer to keep the original open while saving the other format.
Here's a recording I did showing the issue and then showing using "Save A Copy..."
[http://i.imgur.com/242rdFC.gifv](https://i.imgur.com/242rdFC.gifv) | You may need to save/name it in different format one for viewing .pdf type & another for editing .ai type. Hope this helps. Thanks |
73,143,890 | I have reviews ,users and airlines this is how to association is set up
```
class Airline < ApplicationRecord
has_many :reviews
has_many :users,through: :reviews
end
class Review < ApplicationRecord
belongs_to :user
belongs_to :airline
end
class User < ApplicationRecord
has_secure_password
has_many :reviews
has_many :airlines,through: :reviews
end
```
I want to do create method in my console... where I want to create a review by a particular user associated with a particular airline
I know i can grab my user like this
```
u1=User.find_by_name("Max")
r1=u1.reviews.create("")
```
but how can I associate the airline I know there is something "where". I don't no how to write that command. | 2022/07/27 | [
"https://Stackoverflow.com/questions/73143890",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | It seems you just need to create the review:
```
u = User.find_by(name: 'Max')
a = Airline.find_by(name: 'Poop Airlines')
r = Review.create(review: 'This airline smells.', user: u, airline: a)
``` | I think you are on the right track. Since a review is created by a user for an airline, a review needs both user\_id and airline\_id.
In your code you have grabbed the user, now get the airline for which you want to create a record and then create a review
```
u1=User.find_by_name("Max")
a1 = Airline.find_by_name("Airline name")
r1=u1.reviews.create(review_column_name: "", airline: a1) //<replace review_column_name> to whatever your column name in db
``` |
27,764,249 | Given a sample formula `'y=2x+1`' we can get y when we know x with a defined '`function`', for example in python
```
def y(x): return 2*x + 1
x : 1 2 3 4 5 ...
y : 3 5 7 9 11 ...
```
Can I do it reversed? Given data samples and get the approximate formula?
```
x : 1.001 2.12 3.1 4.001 5.021 ...
y : 3.002 5.23 7.2 9.002 11.32 . ..
```
Of course, it is easily to draw all points by coordinates and link those points to get approximate formula then guess the result when people to solve this, but how do it by programming?
Any keywords can search or libs can use?
Thank you.
=====
Many thanks for everyone. After searching a bit with information you shared, it is a BIGG...G area without a simple solution -\_-!.
Technically, I realized what I need should be "`polynomial fitting`" given the difference of `Polynomial regression/ Polynomial interpolation/ polynomial approximation`......
I will give the credit to Gerard, and again, thanks all for your help. | 2015/01/04 | [
"https://Stackoverflow.com/questions/27764249",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/353374/"
] | To make sure I understood your question, you want to retrieve the equation of the line that fits your data, right?
In case this is your question, you can use `polyfit` from the package `numpy`.
```
import numpy as np
x = [1.001, 2.12, 3.1, 4.001, 5.021]
y = [3.002, 5.23, 7.2, 9.002, 11.32]
np.polyfit(x, y, 1)
```
The returned values are:
```
array([ 2.05658156, 0.88110544])
```
This means that the equation of the line is:
```
y = 2.05658156x + 0.88110544
``` | Probably you need NumPy and SciPy packages. For example, see `Linear Regression` docs for SciPy: <http://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.stats.linregress.html> |
27,764,249 | Given a sample formula `'y=2x+1`' we can get y when we know x with a defined '`function`', for example in python
```
def y(x): return 2*x + 1
x : 1 2 3 4 5 ...
y : 3 5 7 9 11 ...
```
Can I do it reversed? Given data samples and get the approximate formula?
```
x : 1.001 2.12 3.1 4.001 5.021 ...
y : 3.002 5.23 7.2 9.002 11.32 . ..
```
Of course, it is easily to draw all points by coordinates and link those points to get approximate formula then guess the result when people to solve this, but how do it by programming?
Any keywords can search or libs can use?
Thank you.
=====
Many thanks for everyone. After searching a bit with information you shared, it is a BIGG...G area without a simple solution -\_-!.
Technically, I realized what I need should be "`polynomial fitting`" given the difference of `Polynomial regression/ Polynomial interpolation/ polynomial approximation`......
I will give the credit to Gerard, and again, thanks all for your help. | 2015/01/04 | [
"https://Stackoverflow.com/questions/27764249",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/353374/"
] | Here i would say the problem looks more like [polynomial interpolation](http://en.wikipedia.org/wiki/Polynomial_interpolation)
In python you have many libs dealing with that, for example high level [scipy.interpolate](http://docs.scipy.org/doc/scipy-0.14.0/reference/interpolate.html)
or you can do it "by hand" like [these examples](http://nbviewer.ipython.org/gist/rjleveque/8798427)
In any case, you will need some maths ! | Probably you need NumPy and SciPy packages. For example, see `Linear Regression` docs for SciPy: <http://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.stats.linregress.html> |
27,764,249 | Given a sample formula `'y=2x+1`' we can get y when we know x with a defined '`function`', for example in python
```
def y(x): return 2*x + 1
x : 1 2 3 4 5 ...
y : 3 5 7 9 11 ...
```
Can I do it reversed? Given data samples and get the approximate formula?
```
x : 1.001 2.12 3.1 4.001 5.021 ...
y : 3.002 5.23 7.2 9.002 11.32 . ..
```
Of course, it is easily to draw all points by coordinates and link those points to get approximate formula then guess the result when people to solve this, but how do it by programming?
Any keywords can search or libs can use?
Thank you.
=====
Many thanks for everyone. After searching a bit with information you shared, it is a BIGG...G area without a simple solution -\_-!.
Technically, I realized what I need should be "`polynomial fitting`" given the difference of `Polynomial regression/ Polynomial interpolation/ polynomial approximation`......
I will give the credit to Gerard, and again, thanks all for your help. | 2015/01/04 | [
"https://Stackoverflow.com/questions/27764249",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/353374/"
] | Here i would say the problem looks more like [polynomial interpolation](http://en.wikipedia.org/wiki/Polynomial_interpolation)
In python you have many libs dealing with that, for example high level [scipy.interpolate](http://docs.scipy.org/doc/scipy-0.14.0/reference/interpolate.html)
or you can do it "by hand" like [these examples](http://nbviewer.ipython.org/gist/rjleveque/8798427)
In any case, you will need some maths ! | To make sure I understood your question, you want to retrieve the equation of the line that fits your data, right?
In case this is your question, you can use `polyfit` from the package `numpy`.
```
import numpy as np
x = [1.001, 2.12, 3.1, 4.001, 5.021]
y = [3.002, 5.23, 7.2, 9.002, 11.32]
np.polyfit(x, y, 1)
```
The returned values are:
```
array([ 2.05658156, 0.88110544])
```
This means that the equation of the line is:
```
y = 2.05658156x + 0.88110544
``` |
1,168,905 | **Theorem:**
$$\lim\_{x \to a} f(x) = L$$
$$\lim\_{x \to a} g(x) = M$$
Then:
$$\lim\_{x \to a} f(x) g(x) = LM$$
Obviously,
$$|f(x) - L| < \epsilon$$
$$|g(x) - M| < \epsilon$$
But multiplying these together doesnt get the desired:
$$|f(x)g(x) - LM| < \epsilon$$
**Please, HINTS only!** | 2015/02/28 | [
"https://math.stackexchange.com/questions/1168905",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/178248/"
] | Hint:
$$\begin{align}|f(x)g(x)-LM|&=|f(x)g(x)-Lg(x)+Lg(x)-LM|\\&=|g(x)(f(x)-L)+L(g(x)-M)|\\&\le|g(x)||f(x)-L|+|L||g(x)-M|\end{align}$$ | Prove it for the special case where the two functions are infinitesimal as $x\to a$ that is $\lim\_{x\to a}f(x)=0$
Prove the theorem for such special functions then deduce the theorem. |
1,168,905 | **Theorem:**
$$\lim\_{x \to a} f(x) = L$$
$$\lim\_{x \to a} g(x) = M$$
Then:
$$\lim\_{x \to a} f(x) g(x) = LM$$
Obviously,
$$|f(x) - L| < \epsilon$$
$$|g(x) - M| < \epsilon$$
But multiplying these together doesnt get the desired:
$$|f(x)g(x) - LM| < \epsilon$$
**Please, HINTS only!** | 2015/02/28 | [
"https://math.stackexchange.com/questions/1168905",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/178248/"
] | Hint:
$$\begin{align}|f(x)g(x)-LM|&=|f(x)g(x)-Lg(x)+Lg(x)-LM|\\&=|g(x)(f(x)-L)+L(g(x)-M)|\\&\le|g(x)||f(x)-L|+|L||g(x)-M|\end{align}$$ | **Theorem 1:**
Denote $f(x)=L+\alpha(x)$.
$$\lim\_{x\to a}f(x)=L\iff \lim\_{x\to a}\alpha(x)=0$$
**Proof 1:**
Denote $f(x)=L+\alpha(x)$.
$$\lim\_{x\to a}f(x)=L\iff \forall\epsilon >0(\exists\delta>0(0<|x-a|<\delta\implies |f(x)-L|<\epsilon)$$
$$\iff \forall\epsilon >0(\exists\delta>0(0<|x-a|<\delta\implies |\alpha(x)|<\epsilon)\iff \lim\_{x\to a}\alpha(x)=0\ \ \ \square$$
$$f(x)g(x)=(L+\alpha(x))(M+\beta(x))=LM+\beta(x)L+M\alpha(x)+\alpha(x)\beta(x)$$
$\lim\_{x\to a}f(x)g(x)=LM$ holds iff $$\lim\_{x\to a}(\beta(x)L+M\alpha(x)+\alpha(x)\beta(x))=0$$
**Theorem 2:**
$$\lim\_{x\to a}\alpha(x)B(x)=0,$$
where $\lim\_{x\to a}\alpha(x)=0$ and $\exists m,M\in\mathbb R, m,M\neq 0(m\le B(x)\le M)$ (so that $|B|\le \max\{|m|,|M|\}$)
**Proof 2:**
$$\lim\_{x\to a}\alpha(x)B(x)=0\iff\forall\epsilon>0(\exists\delta>0(0<|x-a|<\delta\implies |\alpha(x)B(x)|<\epsilon))$$
We know that $$\lim\_{x\to a}\alpha(x)=0\iff \forall\epsilon>0(\exists\delta>0(0<|x-a|<\delta\implies |\alpha(x)|<\epsilon))$$
$$|\alpha(x)B(x)|=|\alpha(x)||B(x)|\le |\alpha(x)|\cdot\max\{|m|,|M|\}<\epsilon\cdot\max\{|m|,|M|\}$$
$\epsilon\cdot\max\{|m|,|M|\}$ can obtain any positive real value, because any real positive value $k$ is obtained when $\epsilon=\frac{k}{\max\{|m|,|M|\}}>0$. $\ \ \ \square$
**Theorem 3:**
$$\lim\_{x\to a}(\alpha(x)+\beta(x))=0,$$
where $\lim\_{x\to a}\alpha(x)=0, \lim\_{x\to a}\beta(x)=0$.
**Proof 3:**
$$\lim\_{x\to a}\alpha(x)=0\iff\forall\epsilon\_1>0(\exists\delta>0(0<|x-a|<\delta\implies |\alpha(x)|<\epsilon\_1))$$
$$\lim\_{x\to a}\beta(x)=0\iff\forall\epsilon\_2>0(\exists\delta>0(0<|x-a|<\delta\implies |\beta(x)|<\epsilon\_2))$$
Since they both hold for any $\epsilon\_1, \epsilon\_2>0$, take $\frac{\epsilon}{2}=\epsilon\_1=\epsilon\_2$.
Then
$$|\alpha(x)+\beta(x)|\le |\alpha(x)|+|\beta(x)|<\frac{\epsilon}{2}+\frac{\epsilon}{2}=\epsilon$$
So that
$$\forall\epsilon>0(\exists\delta>0(0<|x-a|<\delta\implies |\alpha(x)+\beta(x)|<\epsilon))\ \ \ \square$$
Our statement
$$\lim\_{x\to a}(\beta(x)L+M\alpha(x)+\alpha(x)\beta(x))=0$$
is trivial using Theorem 2 and Theorem 3. $\ \ \ \square$ |
11,529 | I would like to change the image next to the search box to a styled input button.
Do I need to create a new delegate control to do this? Can I do this with css, if so how?
This is the standard search UI

This is the desired css button look
 | 2011/04/20 | [
"https://sharepoint.stackexchange.com/questions/11529",
"https://sharepoint.stackexchange.com",
"https://sharepoint.stackexchange.com/users/3083/"
] | You can either replace the `DelegateControl` (if you have farm access)
<http://msdn.microsoft.com/en-us/library/ms463169.aspx>
```
<asp:ContentPlaceHolder id="PlaceHolderSearchArea" runat="server">
<SharePoint:DelegateControl runat="server" ControlId="SmallSearchInputBox" Version="4"/>
</asp:ContentPlaceHolder>
```
Or you can override the `PlaceHolderSearchArea` in your page layouts (if you can only have site access) | I don't think this quite answered the original question. The author asked how to change the OOB image and script click event, with a styled INPUT TYPE=BUTTON.
The options/suggestions given relied on simply changing the image and not the actual markup rendered by the SearchBoxEx control (which is the underlying SP server control rendered by the SmallSearchInputBox delegate control).
Ideally, you would want to completely remove the delegate control from the PlaceHolderSearchArea, and just include simple HTML markup for the INPUT text and INPUT button with the appropriate CSS classes. But if you did this, you would need to also provide the behavior for the button click/post.
You can just wrap these input elements with a form tag (NOT runat server), and set the action URL to the path of the search results page, and make sure that the name of the text box control is the name of the querystring parameter expected by the search results page.
WARNING: by doing this you will lose the builtin functionality that the SearchBoxEX control gets of "understanding" the configured search settings at the site collection (e.g. the search results page location, scopes, etc).
For public Internet site, this may not be as crucial since you want lean, controlled markup, and you likely already created a custom search results page, instead of the OOB experience, so you know the URL path users are taken for search results.
For Intranet/Portal sites, this might not be the desired approach since you might want the richer Search experience with the search controls being connected to SP search know-how. In this case, you might look into writing code to extend the SearchBoxEx control and override the OnRender event of the control to provide your own HTML while still leveraging the server-side properties and search functionality from SharePoint. Then you can deploy this as a feature that injects your custom control in the SmallSearchInputBox delegate, with a higher precedence number to replace the OOB SearchBoxEx.
HTH |
11,529 | I would like to change the image next to the search box to a styled input button.
Do I need to create a new delegate control to do this? Can I do this with css, if so how?
This is the standard search UI

This is the desired css button look
 | 2011/04/20 | [
"https://sharepoint.stackexchange.com/questions/11529",
"https://sharepoint.stackexchange.com",
"https://sharepoint.stackexchange.com/users/3083/"
] | ```
/*Search Box Styles*/
.s4-search input.ms-sbplain{margin-top:5px!important; background:url(../images/search_left.png) no-repeat; border:0 none !important; height:16px; padding:4px 2px 2px 9px; color:#666; font-size:.85em; font-style:normal;}
.s4-search .ms-sbgo{padding-top:5px;}
.s4-search .ms-sbgo a{margin-top:5px; background:url(../images/search_btn.png) no-repeat; width:27px; height:22px; display:block; }
.s4-search .srch-gosearchimg, .s4-search .ms-sbgo span{display:none; }
.adminBar .ms-sbrow a, .ms-sbcell{margin:0; padding:0;}
``` | Just throwing this into the discussion...
Erik Swenson did 2 great blog posts regarding how to change the way the OOTB search box looks like:
<http://erikswenson.blogspot.com/2011/02/sharepoint-2010-large-search-box-scopes.html>
and
<http://erikswenson.blogspot.com/2011/02/sharepoint-2010-large-search-box.html>
Seems to me that reusing the default control and changing the default image/ icon via css would be the easiest solution?
Greg |
11,529 | I would like to change the image next to the search box to a styled input button.
Do I need to create a new delegate control to do this? Can I do this with css, if so how?
This is the standard search UI

This is the desired css button look
 | 2011/04/20 | [
"https://sharepoint.stackexchange.com/questions/11529",
"https://sharepoint.stackexchange.com",
"https://sharepoint.stackexchange.com/users/3083/"
] | The image is rendered using an tag which you cannot modify using just CSS. You could either
* A - Use some jQuery to modify the HTML for the searchbox. You can target the srch-gosearchimg CSS class to modify the image tag and point it to another source image.
* B - Use a delegate control to replace the entire searchbox
My vote usually goes for option B since I don't like messing with a non-standardized HTML layout that jQuery uses. E.g. if a service pack is installed which changes the default searchbox then it'll blow your jquery out of the water. For option B you do need to have server access. For option A you do not since you can include jQuery using a content editor part or in the masterpage using SharePoint Designer. | You can either replace the `DelegateControl` (if you have farm access)
<http://msdn.microsoft.com/en-us/library/ms463169.aspx>
```
<asp:ContentPlaceHolder id="PlaceHolderSearchArea" runat="server">
<SharePoint:DelegateControl runat="server" ControlId="SmallSearchInputBox" Version="4"/>
</asp:ContentPlaceHolder>
```
Or you can override the `PlaceHolderSearchArea` in your page layouts (if you can only have site access) |
11,529 | I would like to change the image next to the search box to a styled input button.
Do I need to create a new delegate control to do this? Can I do this with css, if so how?
This is the standard search UI

This is the desired css button look
 | 2011/04/20 | [
"https://sharepoint.stackexchange.com/questions/11529",
"https://sharepoint.stackexchange.com",
"https://sharepoint.stackexchange.com/users/3083/"
] | You can either replace the `DelegateControl` (if you have farm access)
<http://msdn.microsoft.com/en-us/library/ms463169.aspx>
```
<asp:ContentPlaceHolder id="PlaceHolderSearchArea" runat="server">
<SharePoint:DelegateControl runat="server" ControlId="SmallSearchInputBox" Version="4"/>
</asp:ContentPlaceHolder>
```
Or you can override the `PlaceHolderSearchArea` in your page layouts (if you can only have site access) | Just throwing this into the discussion...
Erik Swenson did 2 great blog posts regarding how to change the way the OOTB search box looks like:
<http://erikswenson.blogspot.com/2011/02/sharepoint-2010-large-search-box-scopes.html>
and
<http://erikswenson.blogspot.com/2011/02/sharepoint-2010-large-search-box.html>
Seems to me that reusing the default control and changing the default image/ icon via css would be the easiest solution?
Greg |
11,529 | I would like to change the image next to the search box to a styled input button.
Do I need to create a new delegate control to do this? Can I do this with css, if so how?
This is the standard search UI

This is the desired css button look
 | 2011/04/20 | [
"https://sharepoint.stackexchange.com/questions/11529",
"https://sharepoint.stackexchange.com",
"https://sharepoint.stackexchange.com/users/3083/"
] | ```
/*Search Box Styles*/
.s4-search input.ms-sbplain{margin-top:5px!important; background:url(../images/search_left.png) no-repeat; border:0 none !important; height:16px; padding:4px 2px 2px 9px; color:#666; font-size:.85em; font-style:normal;}
.s4-search .ms-sbgo{padding-top:5px;}
.s4-search .ms-sbgo a{margin-top:5px; background:url(../images/search_btn.png) no-repeat; width:27px; height:22px; display:block; }
.s4-search .srch-gosearchimg, .s4-search .ms-sbgo span{display:none; }
.adminBar .ms-sbrow a, .ms-sbcell{margin:0; padding:0;}
``` | I don't think this quite answered the original question. The author asked how to change the OOB image and script click event, with a styled INPUT TYPE=BUTTON.
The options/suggestions given relied on simply changing the image and not the actual markup rendered by the SearchBoxEx control (which is the underlying SP server control rendered by the SmallSearchInputBox delegate control).
Ideally, you would want to completely remove the delegate control from the PlaceHolderSearchArea, and just include simple HTML markup for the INPUT text and INPUT button with the appropriate CSS classes. But if you did this, you would need to also provide the behavior for the button click/post.
You can just wrap these input elements with a form tag (NOT runat server), and set the action URL to the path of the search results page, and make sure that the name of the text box control is the name of the querystring parameter expected by the search results page.
WARNING: by doing this you will lose the builtin functionality that the SearchBoxEX control gets of "understanding" the configured search settings at the site collection (e.g. the search results page location, scopes, etc).
For public Internet site, this may not be as crucial since you want lean, controlled markup, and you likely already created a custom search results page, instead of the OOB experience, so you know the URL path users are taken for search results.
For Intranet/Portal sites, this might not be the desired approach since you might want the richer Search experience with the search controls being connected to SP search know-how. In this case, you might look into writing code to extend the SearchBoxEx control and override the OnRender event of the control to provide your own HTML while still leveraging the server-side properties and search functionality from SharePoint. Then you can deploy this as a feature that injects your custom control in the SmallSearchInputBox delegate, with a higher precedence number to replace the OOB SearchBoxEx.
HTH |
11,529 | I would like to change the image next to the search box to a styled input button.
Do I need to create a new delegate control to do this? Can I do this with css, if so how?
This is the standard search UI

This is the desired css button look
 | 2011/04/20 | [
"https://sharepoint.stackexchange.com/questions/11529",
"https://sharepoint.stackexchange.com",
"https://sharepoint.stackexchange.com/users/3083/"
] | The image is rendered using an tag which you cannot modify using just CSS. You could either
* A - Use some jQuery to modify the HTML for the searchbox. You can target the srch-gosearchimg CSS class to modify the image tag and point it to another source image.
* B - Use a delegate control to replace the entire searchbox
My vote usually goes for option B since I don't like messing with a non-standardized HTML layout that jQuery uses. E.g. if a service pack is installed which changes the default searchbox then it'll blow your jquery out of the water. For option B you do need to have server access. For option A you do not since you can include jQuery using a content editor part or in the masterpage using SharePoint Designer. | I don't think this quite answered the original question. The author asked how to change the OOB image and script click event, with a styled INPUT TYPE=BUTTON.
The options/suggestions given relied on simply changing the image and not the actual markup rendered by the SearchBoxEx control (which is the underlying SP server control rendered by the SmallSearchInputBox delegate control).
Ideally, you would want to completely remove the delegate control from the PlaceHolderSearchArea, and just include simple HTML markup for the INPUT text and INPUT button with the appropriate CSS classes. But if you did this, you would need to also provide the behavior for the button click/post.
You can just wrap these input elements with a form tag (NOT runat server), and set the action URL to the path of the search results page, and make sure that the name of the text box control is the name of the querystring parameter expected by the search results page.
WARNING: by doing this you will lose the builtin functionality that the SearchBoxEX control gets of "understanding" the configured search settings at the site collection (e.g. the search results page location, scopes, etc).
For public Internet site, this may not be as crucial since you want lean, controlled markup, and you likely already created a custom search results page, instead of the OOB experience, so you know the URL path users are taken for search results.
For Intranet/Portal sites, this might not be the desired approach since you might want the richer Search experience with the search controls being connected to SP search know-how. In this case, you might look into writing code to extend the SearchBoxEx control and override the OnRender event of the control to provide your own HTML while still leveraging the server-side properties and search functionality from SharePoint. Then you can deploy this as a feature that injects your custom control in the SmallSearchInputBox delegate, with a higher precedence number to replace the OOB SearchBoxEx.
HTH |
11,529 | I would like to change the image next to the search box to a styled input button.
Do I need to create a new delegate control to do this? Can I do this with css, if so how?
This is the standard search UI

This is the desired css button look
 | 2011/04/20 | [
"https://sharepoint.stackexchange.com/questions/11529",
"https://sharepoint.stackexchange.com",
"https://sharepoint.stackexchange.com/users/3083/"
] | The image is rendered using an tag which you cannot modify using just CSS. You could either
* A - Use some jQuery to modify the HTML for the searchbox. You can target the srch-gosearchimg CSS class to modify the image tag and point it to another source image.
* B - Use a delegate control to replace the entire searchbox
My vote usually goes for option B since I don't like messing with a non-standardized HTML layout that jQuery uses. E.g. if a service pack is installed which changes the default searchbox then it'll blow your jquery out of the water. For option B you do need to have server access. For option A you do not since you can include jQuery using a content editor part or in the masterpage using SharePoint Designer. | Just throwing this into the discussion...
Erik Swenson did 2 great blog posts regarding how to change the way the OOTB search box looks like:
<http://erikswenson.blogspot.com/2011/02/sharepoint-2010-large-search-box-scopes.html>
and
<http://erikswenson.blogspot.com/2011/02/sharepoint-2010-large-search-box.html>
Seems to me that reusing the default control and changing the default image/ icon via css would be the easiest solution?
Greg |
11,529 | I would like to change the image next to the search box to a styled input button.
Do I need to create a new delegate control to do this? Can I do this with css, if so how?
This is the standard search UI

This is the desired css button look
 | 2011/04/20 | [
"https://sharepoint.stackexchange.com/questions/11529",
"https://sharepoint.stackexchange.com",
"https://sharepoint.stackexchange.com/users/3083/"
] | ```
/*Search Box Styles*/
.s4-search input.ms-sbplain{margin-top:5px!important; background:url(../images/search_left.png) no-repeat; border:0 none !important; height:16px; padding:4px 2px 2px 9px; color:#666; font-size:.85em; font-style:normal;}
.s4-search .ms-sbgo{padding-top:5px;}
.s4-search .ms-sbgo a{margin-top:5px; background:url(../images/search_btn.png) no-repeat; width:27px; height:22px; display:block; }
.s4-search .srch-gosearchimg, .s4-search .ms-sbgo span{display:none; }
.adminBar .ms-sbrow a, .ms-sbcell{margin:0; padding:0;}
``` | You can simple modify these CSS class and IDs to bring changes to your SharePoint 2013 Search Textbox.
you can modify it according to your needs:
```
/*######################--Sharepoint 2013 Search Box--############################*/
#searchInputBox {
background: url('/_catalogs/masterpage/CSS/bg_search.png') no-repeat scroll 0 0;
background:#FFFFFF;
height: 27px; /*exact same height as image */
width: 325px; /*exact same width as image */
border-radius:7px;
margin-top:1%;
margin-right:70%;
}
#SearchBox > div {
border: 0;
border:thin #EEEEEE solid;
border-radius:7px;
background:#EDF5F9;
}
#SearchBox > div > input {
border: 0 none;
font-weight:bold;
/* adjust size and positioning of input box */
height: 23px;
padding: 2px 0 0 30px;
width: 220px;
background:#EDF5F9;
}
/* hide or show dropdown list button */
#SearchBox .ms-srch-sb {
display: block;
}
#SearchBox .ms-srch-sb-navLink{
margin-right:10px;
}
/*
#SearchBox .ms-srch-sb-searchLink{
float:right;
}
*/
/*
#SearchBox .ms-srch-sb > .ms-srch-sb-searchLink {
border: 0 none;
height: 34px;
margin-left: 0;
width: 62px;
}
*/
/* reset hover bg color */
#SearchBox .ms-srch-sb-searchLink:hover,
#SearchBox .ms-srch-sb-navLink:hover {
background-color: transparent;
}
/* hide search button image (magnifier) */
/*
#SearchBox .ms-srch-sb > .ms-srch-sb-searchLink img {
display: none;
}
*/
/*##################---End of Search box---##########################*/
``` |
11,529 | I would like to change the image next to the search box to a styled input button.
Do I need to create a new delegate control to do this? Can I do this with css, if so how?
This is the standard search UI

This is the desired css button look
 | 2011/04/20 | [
"https://sharepoint.stackexchange.com/questions/11529",
"https://sharepoint.stackexchange.com",
"https://sharepoint.stackexchange.com/users/3083/"
] | The image is rendered using an tag which you cannot modify using just CSS. You could either
* A - Use some jQuery to modify the HTML for the searchbox. You can target the srch-gosearchimg CSS class to modify the image tag and point it to another source image.
* B - Use a delegate control to replace the entire searchbox
My vote usually goes for option B since I don't like messing with a non-standardized HTML layout that jQuery uses. E.g. if a service pack is installed which changes the default searchbox then it'll blow your jquery out of the water. For option B you do need to have server access. For option A you do not since you can include jQuery using a content editor part or in the masterpage using SharePoint Designer. | You can simple modify these CSS class and IDs to bring changes to your SharePoint 2013 Search Textbox.
you can modify it according to your needs:
```
/*######################--Sharepoint 2013 Search Box--############################*/
#searchInputBox {
background: url('/_catalogs/masterpage/CSS/bg_search.png') no-repeat scroll 0 0;
background:#FFFFFF;
height: 27px; /*exact same height as image */
width: 325px; /*exact same width as image */
border-radius:7px;
margin-top:1%;
margin-right:70%;
}
#SearchBox > div {
border: 0;
border:thin #EEEEEE solid;
border-radius:7px;
background:#EDF5F9;
}
#SearchBox > div > input {
border: 0 none;
font-weight:bold;
/* adjust size and positioning of input box */
height: 23px;
padding: 2px 0 0 30px;
width: 220px;
background:#EDF5F9;
}
/* hide or show dropdown list button */
#SearchBox .ms-srch-sb {
display: block;
}
#SearchBox .ms-srch-sb-navLink{
margin-right:10px;
}
/*
#SearchBox .ms-srch-sb-searchLink{
float:right;
}
*/
/*
#SearchBox .ms-srch-sb > .ms-srch-sb-searchLink {
border: 0 none;
height: 34px;
margin-left: 0;
width: 62px;
}
*/
/* reset hover bg color */
#SearchBox .ms-srch-sb-searchLink:hover,
#SearchBox .ms-srch-sb-navLink:hover {
background-color: transparent;
}
/* hide search button image (magnifier) */
/*
#SearchBox .ms-srch-sb > .ms-srch-sb-searchLink img {
display: none;
}
*/
/*##################---End of Search box---##########################*/
``` |
11,529 | I would like to change the image next to the search box to a styled input button.
Do I need to create a new delegate control to do this? Can I do this with css, if so how?
This is the standard search UI

This is the desired css button look
 | 2011/04/20 | [
"https://sharepoint.stackexchange.com/questions/11529",
"https://sharepoint.stackexchange.com",
"https://sharepoint.stackexchange.com/users/3083/"
] | You can either replace the `DelegateControl` (if you have farm access)
<http://msdn.microsoft.com/en-us/library/ms463169.aspx>
```
<asp:ContentPlaceHolder id="PlaceHolderSearchArea" runat="server">
<SharePoint:DelegateControl runat="server" ControlId="SmallSearchInputBox" Version="4"/>
</asp:ContentPlaceHolder>
```
Or you can override the `PlaceHolderSearchArea` in your page layouts (if you can only have site access) | ```
/*Search Box Styles*/
.s4-search input.ms-sbplain{margin-top:5px!important; background:url(../images/search_left.png) no-repeat; border:0 none !important; height:16px; padding:4px 2px 2px 9px; color:#666; font-size:.85em; font-style:normal;}
.s4-search .ms-sbgo{padding-top:5px;}
.s4-search .ms-sbgo a{margin-top:5px; background:url(../images/search_btn.png) no-repeat; width:27px; height:22px; display:block; }
.s4-search .srch-gosearchimg, .s4-search .ms-sbgo span{display:none; }
.adminBar .ms-sbrow a, .ms-sbcell{margin:0; padding:0;}
``` |
2,388,772 | >
> Find the incentre of the triangle in the $xy-$plane whose sides are given
> by the lines $x = 0, y = 0$ and $x/3 + y/4 = 1$
>
>
>
I was trying this question many times but i could not get the solution. From my point of view, my incentre coordinate $(0+3+0/3 ,4+0+)/3) =(1,4/3)$
I don't know whether my answer is correct or not.
If anybody could help me, I would be very thankful to him. | 2017/08/10 | [
"https://math.stackexchange.com/questions/2388772",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/557708/"
] | Let $A(3,0)$, $B(0,4)$ and $O(0,0)$.
Now, let the incircle touches to $OA$, $OB$ and $AB$ in the points $K$, $M$ and $N$ respectively.
Also, let $r$ be a radius of the incircle and $D$ be a center of the the incircle.
Thus, easy to see that $DMOK$ is square with side-length $r$ and $AK=AN$, $BM=BN$.
Now, since $AB=\sqrt{3^2+4^2}=5$ and $AN+BN=AB$, we obtain:
$$4-r+3-r=5$$ or
$$r=1,$$
which gives $D(1,1)$. | It is well know that in triangle with some angle $90^{\circ}$ and sides $a,b,c$ and $r$ as radius of incircle we have $$r = {a+b-c\over 2}$$ if $c$ is hypotenuse. Thus $r = 1$ and so $(1,1)$ is the answer. |
2,388,772 | >
> Find the incentre of the triangle in the $xy-$plane whose sides are given
> by the lines $x = 0, y = 0$ and $x/3 + y/4 = 1$
>
>
>
I was trying this question many times but i could not get the solution. From my point of view, my incentre coordinate $(0+3+0/3 ,4+0+)/3) =(1,4/3)$
I don't know whether my answer is correct or not.
If anybody could help me, I would be very thankful to him. | 2017/08/10 | [
"https://math.stackexchange.com/questions/2388772",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/557708/"
] | It is well know that in triangle with some angle $90^{\circ}$ and sides $a,b,c$ and $r$ as radius of incircle we have $$r = {a+b-c\over 2}$$ if $c$ is hypotenuse. Thus $r = 1$ and so $(1,1)$ is the answer. | The inradius of a right triangle with side lengths $3,4,5$ clearly is $1$, from $(a+b+c)r=2\Delta$.
Since the incenter has to lie on the $x=y$ line, it is located at $\color{blue}{I\left(1,1\right)}$. |
2,388,772 | >
> Find the incentre of the triangle in the $xy-$plane whose sides are given
> by the lines $x = 0, y = 0$ and $x/3 + y/4 = 1$
>
>
>
I was trying this question many times but i could not get the solution. From my point of view, my incentre coordinate $(0+3+0/3 ,4+0+)/3) =(1,4/3)$
I don't know whether my answer is correct or not.
If anybody could help me, I would be very thankful to him. | 2017/08/10 | [
"https://math.stackexchange.com/questions/2388772",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/557708/"
] | Let $A(3,0)$, $B(0,4)$ and $O(0,0)$.
Now, let the incircle touches to $OA$, $OB$ and $AB$ in the points $K$, $M$ and $N$ respectively.
Also, let $r$ be a radius of the incircle and $D$ be a center of the the incircle.
Thus, easy to see that $DMOK$ is square with side-length $r$ and $AK=AN$, $BM=BN$.
Now, since $AB=\sqrt{3^2+4^2}=5$ and $AN+BN=AB$, we obtain:
$$4-r+3-r=5$$ or
$$r=1,$$
which gives $D(1,1)$. | Hint: with the vertices at $(0,0), (0,4), (3,0)$ the incentre must lie on the bisector of the angle at the origin i.e. $x=y$.
The inradius $r$ satisfies area of triangle $=rs$ where $s$ is half the sum of the sides. To see this connect the incentre to the three vertices, and drop perpendiculars to each of the sides. The lines to the vertices split the figure into three triangles each of height $r$ and base one of the sides of the triangle.
This is enough data to make solving quite easy. |
2,388,772 | >
> Find the incentre of the triangle in the $xy-$plane whose sides are given
> by the lines $x = 0, y = 0$ and $x/3 + y/4 = 1$
>
>
>
I was trying this question many times but i could not get the solution. From my point of view, my incentre coordinate $(0+3+0/3 ,4+0+)/3) =(1,4/3)$
I don't know whether my answer is correct or not.
If anybody could help me, I would be very thankful to him. | 2017/08/10 | [
"https://math.stackexchange.com/questions/2388772",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/557708/"
] | Hint: with the vertices at $(0,0), (0,4), (3,0)$ the incentre must lie on the bisector of the angle at the origin i.e. $x=y$.
The inradius $r$ satisfies area of triangle $=rs$ where $s$ is half the sum of the sides. To see this connect the incentre to the three vertices, and drop perpendiculars to each of the sides. The lines to the vertices split the figure into three triangles each of height $r$ and base one of the sides of the triangle.
This is enough data to make solving quite easy. | The inradius of a right triangle with side lengths $3,4,5$ clearly is $1$, from $(a+b+c)r=2\Delta$.
Since the incenter has to lie on the $x=y$ line, it is located at $\color{blue}{I\left(1,1\right)}$. |
2,388,772 | >
> Find the incentre of the triangle in the $xy-$plane whose sides are given
> by the lines $x = 0, y = 0$ and $x/3 + y/4 = 1$
>
>
>
I was trying this question many times but i could not get the solution. From my point of view, my incentre coordinate $(0+3+0/3 ,4+0+)/3) =(1,4/3)$
I don't know whether my answer is correct or not.
If anybody could help me, I would be very thankful to him. | 2017/08/10 | [
"https://math.stackexchange.com/questions/2388772",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/557708/"
] | Let $A(3,0)$, $B(0,4)$ and $O(0,0)$.
Now, let the incircle touches to $OA$, $OB$ and $AB$ in the points $K$, $M$ and $N$ respectively.
Also, let $r$ be a radius of the incircle and $D$ be a center of the the incircle.
Thus, easy to see that $DMOK$ is square with side-length $r$ and $AK=AN$, $BM=BN$.
Now, since $AB=\sqrt{3^2+4^2}=5$ and $AN+BN=AB$, we obtain:
$$4-r+3-r=5$$ or
$$r=1,$$
which gives $D(1,1)$. | The bisector of the right angle is $y=x$ A point of this bisector has coordinates $P(t;\;t)$ its distance from the angle sides is $|t|$
This distance must be equal to the distance from the line $x/3+y/4=1$
The formula of the distance $d$ from a point $(x\_P;\;y\_P)$ to a line $ax+by+c=0$ is
$$d=\dfrac{\left|ax\_p+by\_p+c\right|}{\sqrt{a^2+b^2}}$$
The equation of the line must be written as $4x+3y-12=0$
The point has coordinates $(t;\;t)$ and the distance must be $d=|t|$
$\dfrac{\left|3t +4t-12\right|}{\sqrt{3^3+4^2}}=|t|$
$\left|7t-12\right|=5|t|$
$7t-12=5t$ or $7t-12=-5t$
$t=6$ or $t=1$
The result is then $t=1$ and the incentre is $(1,\;1)$ |
2,388,772 | >
> Find the incentre of the triangle in the $xy-$plane whose sides are given
> by the lines $x = 0, y = 0$ and $x/3 + y/4 = 1$
>
>
>
I was trying this question many times but i could not get the solution. From my point of view, my incentre coordinate $(0+3+0/3 ,4+0+)/3) =(1,4/3)$
I don't know whether my answer is correct or not.
If anybody could help me, I would be very thankful to him. | 2017/08/10 | [
"https://math.stackexchange.com/questions/2388772",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/557708/"
] | The bisector of the right angle is $y=x$ A point of this bisector has coordinates $P(t;\;t)$ its distance from the angle sides is $|t|$
This distance must be equal to the distance from the line $x/3+y/4=1$
The formula of the distance $d$ from a point $(x\_P;\;y\_P)$ to a line $ax+by+c=0$ is
$$d=\dfrac{\left|ax\_p+by\_p+c\right|}{\sqrt{a^2+b^2}}$$
The equation of the line must be written as $4x+3y-12=0$
The point has coordinates $(t;\;t)$ and the distance must be $d=|t|$
$\dfrac{\left|3t +4t-12\right|}{\sqrt{3^3+4^2}}=|t|$
$\left|7t-12\right|=5|t|$
$7t-12=5t$ or $7t-12=-5t$
$t=6$ or $t=1$
The result is then $t=1$ and the incentre is $(1,\;1)$ | The inradius of a right triangle with side lengths $3,4,5$ clearly is $1$, from $(a+b+c)r=2\Delta$.
Since the incenter has to lie on the $x=y$ line, it is located at $\color{blue}{I\left(1,1\right)}$. |
2,388,772 | >
> Find the incentre of the triangle in the $xy-$plane whose sides are given
> by the lines $x = 0, y = 0$ and $x/3 + y/4 = 1$
>
>
>
I was trying this question many times but i could not get the solution. From my point of view, my incentre coordinate $(0+3+0/3 ,4+0+)/3) =(1,4/3)$
I don't know whether my answer is correct or not.
If anybody could help me, I would be very thankful to him. | 2017/08/10 | [
"https://math.stackexchange.com/questions/2388772",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/557708/"
] | Let $A(3,0)$, $B(0,4)$ and $O(0,0)$.
Now, let the incircle touches to $OA$, $OB$ and $AB$ in the points $K$, $M$ and $N$ respectively.
Also, let $r$ be a radius of the incircle and $D$ be a center of the the incircle.
Thus, easy to see that $DMOK$ is square with side-length $r$ and $AK=AN$, $BM=BN$.
Now, since $AB=\sqrt{3^2+4^2}=5$ and $AN+BN=AB$, we obtain:
$$4-r+3-r=5$$ or
$$r=1,$$
which gives $D(1,1)$. | The inradius of a right triangle with side lengths $3,4,5$ clearly is $1$, from $(a+b+c)r=2\Delta$.
Since the incenter has to lie on the $x=y$ line, it is located at $\color{blue}{I\left(1,1\right)}$. |
47,861,287 | I am trying to create a "add to string if condition" is met function, here's my actual code:
```
if ( ! function_exists( '_s_posted_on' ) ) :
function _s_posted_on( $params = array() ) {
$output = 's'; /** Holds the string of the code output by the arguments. */
if ( in_array('time', $params) ) : /** Begin main loop */
/**
Show the time of the post
*/
$time_string = '<time class="entry-date published" datetime="%1$s">%2$s</time>';
$time_string = sprintf( $time_string,
esc_attr( get_the_date( 'c' ) ),
esc_html( get_the_date() ),
esc_attr( get_the_modified_date( 'c' ) ),
esc_html( get_the_modified_date() )
);
$posted_on = sprintf(
/* translators: %s: post date. */
esc_html_x( 'Posted on %s', 'post date', '_s' ),
'<a href="' . esc_url( get_permalink() ) . '" rel="bookmark">' . $time_string . '</a>'
);
$output .= '<span class="posted-on">' . $posted_on . '</span>';
elseif ( in_array('author', $params) ) :
/**
Show the post's author
*/
$author = sprintf(
/* translators: %s: post author. */
esc_html_x( 'by %s', 'post author', '_s' ),
'<span class="author vcard"><a class="url fn n" href="' . esc_url( get_author_posts_url( get_the_author_meta( 'ID' ) ) ) . '">' . esc_html( get_the_author() ) . '</a></span>'
);
$output .= '<span class="author"> ' . $author . '</span>';
elseif ( in_array('category', $params) ) :
/**
Show the post's category.
*/
$categories = (array) wp_get_post_terms( get_the_ID(), 'category' );
$category_string = sprintf (
esc_html_x( 'in %s', 'post_category', '_s' ),
'<a class="category">' . $categories[0] -> name . '</a>'
);
$output .= '<span class="category">' . $category_string . '</span>';
else :
$output = 'No info about the post!';
endif; /** End main loop */
echo '<div class="post-meta-info"' . $output . '</div>';
}
endif;
```
Calling `_s_posted_on('time', 'category');` only outputs the code from `time`, yet it should output the code from `time`and `category` since both conditions are met.
The pseudo-code looks like this:
```
if (string_exists_in_params($string, $params)):
add_to_my_string --> $string2;
elseif (string_exists_in_params($string1, $params)):
add_to_string --> $string1;
elseif (string_exists_in_params($string2, $params)):
add_to_string --> $string2;
```
The problem is that the loop breaks every-time it hits a condition, so say I'd call my function `_s_posted_on` with `$string1, $string2`, my `output` should be the results of `$string1` and `$string2` but unfortunately, it stops at `$string1` and doesn't go further to check for `$string2`.
In short, I'm trying to add to a string, based on some conditions, where 2 conditions can be present, but the loop stops at the first condition met and breaks. | 2017/12/18 | [
"https://Stackoverflow.com/questions/47861287",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9111477/"
] | You can try multiple `ifs` with flag for `else`
```
$flag = false;
if (string_exists_in_params($string, $params)):
add_to_my_string --> $string2;
$flag = true;
if (string_exists_in_params($string1, $params)):
add_to_string --> $string1;
$flag = true;
if (string_exists_in_params($string2, $params)):
add_to_string --> $string2;
$flag = true;
if ($flag == false):
$output = 'No info about the post!';
``` | `elseif` means, if the previous condition did not pass, and this permission do pass, then do it. It sounds like you just want to have multiple `if` statements after one another, which is completely normal and fine to do.
So you can do
```
if($a == true) {
// Execute this if $a is true.
}
if($b == true) {
// Execute this if $b is true, no matter if the first if
// statement was executed or not.
}
``` |
47,861,287 | I am trying to create a "add to string if condition" is met function, here's my actual code:
```
if ( ! function_exists( '_s_posted_on' ) ) :
function _s_posted_on( $params = array() ) {
$output = 's'; /** Holds the string of the code output by the arguments. */
if ( in_array('time', $params) ) : /** Begin main loop */
/**
Show the time of the post
*/
$time_string = '<time class="entry-date published" datetime="%1$s">%2$s</time>';
$time_string = sprintf( $time_string,
esc_attr( get_the_date( 'c' ) ),
esc_html( get_the_date() ),
esc_attr( get_the_modified_date( 'c' ) ),
esc_html( get_the_modified_date() )
);
$posted_on = sprintf(
/* translators: %s: post date. */
esc_html_x( 'Posted on %s', 'post date', '_s' ),
'<a href="' . esc_url( get_permalink() ) . '" rel="bookmark">' . $time_string . '</a>'
);
$output .= '<span class="posted-on">' . $posted_on . '</span>';
elseif ( in_array('author', $params) ) :
/**
Show the post's author
*/
$author = sprintf(
/* translators: %s: post author. */
esc_html_x( 'by %s', 'post author', '_s' ),
'<span class="author vcard"><a class="url fn n" href="' . esc_url( get_author_posts_url( get_the_author_meta( 'ID' ) ) ) . '">' . esc_html( get_the_author() ) . '</a></span>'
);
$output .= '<span class="author"> ' . $author . '</span>';
elseif ( in_array('category', $params) ) :
/**
Show the post's category.
*/
$categories = (array) wp_get_post_terms( get_the_ID(), 'category' );
$category_string = sprintf (
esc_html_x( 'in %s', 'post_category', '_s' ),
'<a class="category">' . $categories[0] -> name . '</a>'
);
$output .= '<span class="category">' . $category_string . '</span>';
else :
$output = 'No info about the post!';
endif; /** End main loop */
echo '<div class="post-meta-info"' . $output . '</div>';
}
endif;
```
Calling `_s_posted_on('time', 'category');` only outputs the code from `time`, yet it should output the code from `time`and `category` since both conditions are met.
The pseudo-code looks like this:
```
if (string_exists_in_params($string, $params)):
add_to_my_string --> $string2;
elseif (string_exists_in_params($string1, $params)):
add_to_string --> $string1;
elseif (string_exists_in_params($string2, $params)):
add_to_string --> $string2;
```
The problem is that the loop breaks every-time it hits a condition, so say I'd call my function `_s_posted_on` with `$string1, $string2`, my `output` should be the results of `$string1` and `$string2` but unfortunately, it stops at `$string1` and doesn't go further to check for `$string2`.
In short, I'm trying to add to a string, based on some conditions, where 2 conditions can be present, but the loop stops at the first condition met and breaks. | 2017/12/18 | [
"https://Stackoverflow.com/questions/47861287",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9111477/"
] | `elseif` means, if the previous condition did not pass, and this permission do pass, then do it. It sounds like you just want to have multiple `if` statements after one another, which is completely normal and fine to do.
So you can do
```
if($a == true) {
// Execute this if $a is true.
}
if($b == true) {
// Execute this if $b is true, no matter if the first if
// statement was executed or not.
}
``` | Suggested Code:
```
if(!function_exists('_s_posted_on')){
function _s_posted_on($params=array()){
$params=array_intersect(array('time','author','category'),$params); // filter and sort
if(empty($params)){ // this provides a shortcut whereby NO additional conditions or function calls are required
$output = 'No info about the post!';
}else{
$output=''; // I don't understand why your string should start with `s` so I am omitting it
foreach($params as $param){ // iterate upto 3 times total
if($param=='time'){ // function-less conditional check
$time_string = '<time class="entry-date published" datetime="%1$s">%2$s</time>';
$time_string = sprintf( $time_string,
esc_attr(get_the_date('c')),
esc_html(get_the_date()),
esc_attr(get_the_modified_date('c')),
esc_html(get_the_modified_date())
);
$posted_on = sprintf(
/* translators: %s: post date. */
esc_html_x('Posted on %s','post date','_s'),
'<a href="'.esc_url(get_permalink()).'" rel="bookmark">'.$time_string.'</a>'
);
$output.='<span class="posted-on">'.$posted_on.'</span>';
}elseif($param=='author'){ // function-less conditional check
$author = sprintf(
/* translators: %s: post author. */
esc_html_x( 'by %s', 'post author', '_s' ),
'<span class="author vcard"><a class="url fn n" href="'.esc_url(get_author_posts_url(get_the_author_meta('ID'))).'">'.esc_html(get_the_author()).'</a></span>'
);
$output.='<span class="author"> '.$author.'</span>';
}else{ // can only be `category` due to filtration step and prior conditions
$categories=(array) wp_get_post_terms(get_the_ID(),'category');
$category_string=sprintf(
esc_html_x('in %s','post_category','_s'),
'<a class="category">'.$categories[0]->name.'</a>'
);
$output.='<span class="category">'.$category_string.'</span>';
} // end `param` conditional
} // end foreach
} // end `empty` conditional
echo '<div class="post-meta-info">'.$output.'</div>'; // (generally, return is used in functions instead of echoing)
// I added this greater than sign^ <-- it seems rather important!
}
}
```
Points / Explanations:
* Rather than colon-syntax condition blocks, I recommend curly brackets for improved readability.
* Because there is a finite number of eligible elements in `$params` AND because the order of the elements is important, I recommend using `array_intersect()` from the start. By putting your "actionable" elements in order all other processes down-script are simplified. (If you are generating these elements manually, you can omit this step -- assuming you are not adding "non-actionable" elements.) Here is a demo of what my filter/sort step does: [Demo](http://sandbox.onlinephpfunctions.com/code/bd355034356af7282b5e1bb0ba9b875c22b12063)
* Always try to write early exiting conditions in your condition blocks (and loops for that matter). If there are no actionable elements, then skip straight to the end -- don't check for `time` and then `author` and then `category` -- this is a matter of efficient / best practice.
* I don't know why your `$output` string starts with `s`, so I removed it.
* I was able to completely eliminate the `in_array()` calls. The `if-elseif-else` block inside of the `foreach()` now makes no function calls and, in fact, doesn't even need to check for `category` because it is guaranteed logically.
* I added the missing `>` to `<div class="post-meta-info"`.
* Generally, as a matter of best practice, functions are typically written to `return` something rather than `echo` something. If you want to echo `$output` more professionals will recommend `echo _s_posted_on($params=array());`. I don't have intimate knowledge of your project, so maybe you have a good reason to do it your way. |
47,861,287 | I am trying to create a "add to string if condition" is met function, here's my actual code:
```
if ( ! function_exists( '_s_posted_on' ) ) :
function _s_posted_on( $params = array() ) {
$output = 's'; /** Holds the string of the code output by the arguments. */
if ( in_array('time', $params) ) : /** Begin main loop */
/**
Show the time of the post
*/
$time_string = '<time class="entry-date published" datetime="%1$s">%2$s</time>';
$time_string = sprintf( $time_string,
esc_attr( get_the_date( 'c' ) ),
esc_html( get_the_date() ),
esc_attr( get_the_modified_date( 'c' ) ),
esc_html( get_the_modified_date() )
);
$posted_on = sprintf(
/* translators: %s: post date. */
esc_html_x( 'Posted on %s', 'post date', '_s' ),
'<a href="' . esc_url( get_permalink() ) . '" rel="bookmark">' . $time_string . '</a>'
);
$output .= '<span class="posted-on">' . $posted_on . '</span>';
elseif ( in_array('author', $params) ) :
/**
Show the post's author
*/
$author = sprintf(
/* translators: %s: post author. */
esc_html_x( 'by %s', 'post author', '_s' ),
'<span class="author vcard"><a class="url fn n" href="' . esc_url( get_author_posts_url( get_the_author_meta( 'ID' ) ) ) . '">' . esc_html( get_the_author() ) . '</a></span>'
);
$output .= '<span class="author"> ' . $author . '</span>';
elseif ( in_array('category', $params) ) :
/**
Show the post's category.
*/
$categories = (array) wp_get_post_terms( get_the_ID(), 'category' );
$category_string = sprintf (
esc_html_x( 'in %s', 'post_category', '_s' ),
'<a class="category">' . $categories[0] -> name . '</a>'
);
$output .= '<span class="category">' . $category_string . '</span>';
else :
$output = 'No info about the post!';
endif; /** End main loop */
echo '<div class="post-meta-info"' . $output . '</div>';
}
endif;
```
Calling `_s_posted_on('time', 'category');` only outputs the code from `time`, yet it should output the code from `time`and `category` since both conditions are met.
The pseudo-code looks like this:
```
if (string_exists_in_params($string, $params)):
add_to_my_string --> $string2;
elseif (string_exists_in_params($string1, $params)):
add_to_string --> $string1;
elseif (string_exists_in_params($string2, $params)):
add_to_string --> $string2;
```
The problem is that the loop breaks every-time it hits a condition, so say I'd call my function `_s_posted_on` with `$string1, $string2`, my `output` should be the results of `$string1` and `$string2` but unfortunately, it stops at `$string1` and doesn't go further to check for `$string2`.
In short, I'm trying to add to a string, based on some conditions, where 2 conditions can be present, but the loop stops at the first condition met and breaks. | 2017/12/18 | [
"https://Stackoverflow.com/questions/47861287",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9111477/"
] | You can try multiple `ifs` with flag for `else`
```
$flag = false;
if (string_exists_in_params($string, $params)):
add_to_my_string --> $string2;
$flag = true;
if (string_exists_in_params($string1, $params)):
add_to_string --> $string1;
$flag = true;
if (string_exists_in_params($string2, $params)):
add_to_string --> $string2;
$flag = true;
if ($flag == false):
$output = 'No info about the post!';
``` | Suggested Code:
```
if(!function_exists('_s_posted_on')){
function _s_posted_on($params=array()){
$params=array_intersect(array('time','author','category'),$params); // filter and sort
if(empty($params)){ // this provides a shortcut whereby NO additional conditions or function calls are required
$output = 'No info about the post!';
}else{
$output=''; // I don't understand why your string should start with `s` so I am omitting it
foreach($params as $param){ // iterate upto 3 times total
if($param=='time'){ // function-less conditional check
$time_string = '<time class="entry-date published" datetime="%1$s">%2$s</time>';
$time_string = sprintf( $time_string,
esc_attr(get_the_date('c')),
esc_html(get_the_date()),
esc_attr(get_the_modified_date('c')),
esc_html(get_the_modified_date())
);
$posted_on = sprintf(
/* translators: %s: post date. */
esc_html_x('Posted on %s','post date','_s'),
'<a href="'.esc_url(get_permalink()).'" rel="bookmark">'.$time_string.'</a>'
);
$output.='<span class="posted-on">'.$posted_on.'</span>';
}elseif($param=='author'){ // function-less conditional check
$author = sprintf(
/* translators: %s: post author. */
esc_html_x( 'by %s', 'post author', '_s' ),
'<span class="author vcard"><a class="url fn n" href="'.esc_url(get_author_posts_url(get_the_author_meta('ID'))).'">'.esc_html(get_the_author()).'</a></span>'
);
$output.='<span class="author"> '.$author.'</span>';
}else{ // can only be `category` due to filtration step and prior conditions
$categories=(array) wp_get_post_terms(get_the_ID(),'category');
$category_string=sprintf(
esc_html_x('in %s','post_category','_s'),
'<a class="category">'.$categories[0]->name.'</a>'
);
$output.='<span class="category">'.$category_string.'</span>';
} // end `param` conditional
} // end foreach
} // end `empty` conditional
echo '<div class="post-meta-info">'.$output.'</div>'; // (generally, return is used in functions instead of echoing)
// I added this greater than sign^ <-- it seems rather important!
}
}
```
Points / Explanations:
* Rather than colon-syntax condition blocks, I recommend curly brackets for improved readability.
* Because there is a finite number of eligible elements in `$params` AND because the order of the elements is important, I recommend using `array_intersect()` from the start. By putting your "actionable" elements in order all other processes down-script are simplified. (If you are generating these elements manually, you can omit this step -- assuming you are not adding "non-actionable" elements.) Here is a demo of what my filter/sort step does: [Demo](http://sandbox.onlinephpfunctions.com/code/bd355034356af7282b5e1bb0ba9b875c22b12063)
* Always try to write early exiting conditions in your condition blocks (and loops for that matter). If there are no actionable elements, then skip straight to the end -- don't check for `time` and then `author` and then `category` -- this is a matter of efficient / best practice.
* I don't know why your `$output` string starts with `s`, so I removed it.
* I was able to completely eliminate the `in_array()` calls. The `if-elseif-else` block inside of the `foreach()` now makes no function calls and, in fact, doesn't even need to check for `category` because it is guaranteed logically.
* I added the missing `>` to `<div class="post-meta-info"`.
* Generally, as a matter of best practice, functions are typically written to `return` something rather than `echo` something. If you want to echo `$output` more professionals will recommend `echo _s_posted_on($params=array());`. I don't have intimate knowledge of your project, so maybe you have a good reason to do it your way. |
378,109 | How do I check for remaining days of Remote Desktop Services grace period if the server is also a Domain Controller (so I cannot logon as local admin)? | 2012/04/10 | [
"https://serverfault.com/questions/378109",
"https://serverfault.com",
"https://serverfault.com/users/41450/"
] | I've discovered this is an error due to PLESK (and the user), and because there isn't much documentation on it, I think this post is worth keeping.
Because I had the vhost domain of the email address I was sending to established in PLESK, it tried to revert to a local Postfix search when it recognized the tail end of the email address as something it thought was hosted on the server itself.
There is documentation on how to fix this in the PostFix configuration file [here](http://www.luketarplin.com/blog/fixing-postfix-plesk-configuration-problem).
I appreciate everyone's efforts. | >
> Apr 10 10:26:29 ######### postfix-local[8331]: postfix-local:
> [email protected], [email protected],
> dirname=/var/qmail/mailnames Apr 10 10:26:29 #########
> postfix-local[8331]: cannot chdir to mailname dir name: No such file
> or directory Apr 10 10:26:29 ######### postfix-local[8331]: Unknown
> user: [email protected]
>
>
>
Contrary to what you may think, these are not postfix logs.
Postfix prefixes all log messages with `postfix/<servicename>` - never `postfix-<servicename>` |
378,109 | How do I check for remaining days of Remote Desktop Services grace period if the server is also a Domain Controller (so I cannot logon as local admin)? | 2012/04/10 | [
"https://serverfault.com/questions/378109",
"https://serverfault.com",
"https://serverfault.com/users/41450/"
] | I've discovered this is an error due to PLESK (and the user), and because there isn't much documentation on it, I think this post is worth keeping.
Because I had the vhost domain of the email address I was sending to established in PLESK, it tried to revert to a local Postfix search when it recognized the tail end of the email address as something it thought was hosted on the server itself.
There is documentation on how to fix this in the PostFix configuration file [here](http://www.luketarplin.com/blog/fixing-postfix-plesk-configuration-problem).
I appreciate everyone's efforts. | I had this issue too. Any email being sent to my company domain was being sent locally. This is (I believe) because in Plesk (yes it's a Plesk issue).
So basically it's going oh [email protected] is the registered user lets send any @company.com emails locally or something like that.
Anyway, I have had to fix this twice now and I did it by editing the /etc/postfix/main.cf file and commenting out the lines that started with "virtual".
See <http://www.rcneil.com/postfix-local-loop-in-plesk/> for instructions on how to fix the issue |
22,640 | Does anyone make a single fiber cwdm 10g sfp or xfp that will do 10g over a single fiber using a single 1510nm wavelength? | 2015/09/18 | [
"https://networkengineering.stackexchange.com/questions/22640",
"https://networkengineering.stackexchange.com",
"https://networkengineering.stackexchange.com/users/19145/"
] | Single fiber **and** single wavelength are **fundamentally incompatible.** You either need two fibers (send at each end connected to receive at the other end) and one wavelength is fine, or you need two different wavelengths so that data can travel both ways over the same fiber without conflict.
10Gb does not include a half-duplex option, which would be the only other way to get one fiber and one wavelength (and half the speed, or less than half the speed.)
"CWDM" means **C**oarse **W**avelength **D**ivision **M**ultiplexing" and is another way of saying "not one wavelength" and the "coarse" part also says "wavelengths that are not terribly close to each other" such as 1490/1510, 1310/1490, etc...
Dense WDM (DWDM) implies wavelengths that are much closer to each other. | As Ecnerwal states, you can't transmit signal with the same wavelength in both directions.
I'm pretty sure you know how one-eyed SFPs work, but here (<http://www.cisco.com/c/en/us/products/collateral/interfaces-modules/transceiver-modules/data_sheet_c78-455693.pdf>) you can find a diagram explaining it on page 3.
If you are planing yo use single fiber SFPs/XFPs, your CWDM muxes should support them. ( like this one <http://www.pandacomdirekt.com/en/products/wdm/passive-multiplexer/cwdm-multiplexer/48-channel-single-fiber.html>) |
22,640 | Does anyone make a single fiber cwdm 10g sfp or xfp that will do 10g over a single fiber using a single 1510nm wavelength? | 2015/09/18 | [
"https://networkengineering.stackexchange.com/questions/22640",
"https://networkengineering.stackexchange.com",
"https://networkengineering.stackexchange.com/users/19145/"
] | Single fiber **and** single wavelength are **fundamentally incompatible.** You either need two fibers (send at each end connected to receive at the other end) and one wavelength is fine, or you need two different wavelengths so that data can travel both ways over the same fiber without conflict.
10Gb does not include a half-duplex option, which would be the only other way to get one fiber and one wavelength (and half the speed, or less than half the speed.)
"CWDM" means **C**oarse **W**avelength **D**ivision **M**ultiplexing" and is another way of saying "not one wavelength" and the "coarse" part also says "wavelengths that are not terribly close to each other" such as 1490/1510, 1310/1490, etc...
Dense WDM (DWDM) implies wavelengths that are much closer to each other. | Single Fiber, Single Wavelength,CWDM Transceivers have been commercially available for years, some with built-in Micro-OTDR Fast Fiber Fault Finder technology, but so far only for 1 Gbps to 3 Gbps applications. |
22,640 | Does anyone make a single fiber cwdm 10g sfp or xfp that will do 10g over a single fiber using a single 1510nm wavelength? | 2015/09/18 | [
"https://networkengineering.stackexchange.com/questions/22640",
"https://networkengineering.stackexchange.com",
"https://networkengineering.stackexchange.com/users/19145/"
] | Single fiber **and** single wavelength are **fundamentally incompatible.** You either need two fibers (send at each end connected to receive at the other end) and one wavelength is fine, or you need two different wavelengths so that data can travel both ways over the same fiber without conflict.
10Gb does not include a half-duplex option, which would be the only other way to get one fiber and one wavelength (and half the speed, or less than half the speed.)
"CWDM" means **C**oarse **W**avelength **D**ivision **M**ultiplexing" and is another way of saying "not one wavelength" and the "coarse" part also says "wavelengths that are not terribly close to each other" such as 1490/1510, 1310/1490, etc...
Dense WDM (DWDM) implies wavelengths that are much closer to each other. | They're called BiDi optical transceivers. [I see some](http://connect.physicsworld.com/sfp-plus-10gsrlrmlrerzrcwdmdwdmbidi-transceivers/2003609.article) 1270nm / 1330nm Bi-Directional 40km Single Mode but I don't see any 1510nm.
### [Cisco SFP-10G-BX40D-I and SFP-10G-BX40U-I (for 40Km Single-Fiber Bidirectional Applications)](http://www.cisco.com/c/en/us/products/collateral/interfaces-modules/transceiver-modules/data_sheet_c78-455693.html)
[](https://i.stack.imgur.com/pRm7A.jpg)
The Cisco SFP-10G-BX40D-I and SFP-10G-BX40U-I SFPs operate on a single strand of standard SMF.
A SFP-10G-BX40D-I device is always connected to a SFP-10G-BX40U-I device with a single strand of standard SMF with an operating transmission range up to 40 km.
The communication over a single strand of fiber is achieved by separating the transmission wavelength of the two devices. SFP-10G-BX40D-I transmits a 1330-nm channel and receives a 1270-nm signal. The SFP-10G-BX40U-I transmits at a 1270-nm wavelength and receives a 1330-nm signal.
The SFP-10G-BX40D-I and SFP-10G-BX40U-I SFPs support digital optical monitoring (DOM) functions according to the industry-standard SFF-8472 multisource agreement (MSA). This feature gives the end user the ability to monitor real-time parameters of the SFP, such as optical output power, optical input power, temperature, laser bias current, and transceiver supply voltage. |
22,640 | Does anyone make a single fiber cwdm 10g sfp or xfp that will do 10g over a single fiber using a single 1510nm wavelength? | 2015/09/18 | [
"https://networkengineering.stackexchange.com/questions/22640",
"https://networkengineering.stackexchange.com",
"https://networkengineering.stackexchange.com/users/19145/"
] | They're called BiDi optical transceivers. [I see some](http://connect.physicsworld.com/sfp-plus-10gsrlrmlrerzrcwdmdwdmbidi-transceivers/2003609.article) 1270nm / 1330nm Bi-Directional 40km Single Mode but I don't see any 1510nm.
### [Cisco SFP-10G-BX40D-I and SFP-10G-BX40U-I (for 40Km Single-Fiber Bidirectional Applications)](http://www.cisco.com/c/en/us/products/collateral/interfaces-modules/transceiver-modules/data_sheet_c78-455693.html)
[](https://i.stack.imgur.com/pRm7A.jpg)
The Cisco SFP-10G-BX40D-I and SFP-10G-BX40U-I SFPs operate on a single strand of standard SMF.
A SFP-10G-BX40D-I device is always connected to a SFP-10G-BX40U-I device with a single strand of standard SMF with an operating transmission range up to 40 km.
The communication over a single strand of fiber is achieved by separating the transmission wavelength of the two devices. SFP-10G-BX40D-I transmits a 1330-nm channel and receives a 1270-nm signal. The SFP-10G-BX40U-I transmits at a 1270-nm wavelength and receives a 1330-nm signal.
The SFP-10G-BX40D-I and SFP-10G-BX40U-I SFPs support digital optical monitoring (DOM) functions according to the industry-standard SFF-8472 multisource agreement (MSA). This feature gives the end user the ability to monitor real-time parameters of the SFP, such as optical output power, optical input power, temperature, laser bias current, and transceiver supply voltage. | As Ecnerwal states, you can't transmit signal with the same wavelength in both directions.
I'm pretty sure you know how one-eyed SFPs work, but here (<http://www.cisco.com/c/en/us/products/collateral/interfaces-modules/transceiver-modules/data_sheet_c78-455693.pdf>) you can find a diagram explaining it on page 3.
If you are planing yo use single fiber SFPs/XFPs, your CWDM muxes should support them. ( like this one <http://www.pandacomdirekt.com/en/products/wdm/passive-multiplexer/cwdm-multiplexer/48-channel-single-fiber.html>) |
22,640 | Does anyone make a single fiber cwdm 10g sfp or xfp that will do 10g over a single fiber using a single 1510nm wavelength? | 2015/09/18 | [
"https://networkengineering.stackexchange.com/questions/22640",
"https://networkengineering.stackexchange.com",
"https://networkengineering.stackexchange.com/users/19145/"
] | They're called BiDi optical transceivers. [I see some](http://connect.physicsworld.com/sfp-plus-10gsrlrmlrerzrcwdmdwdmbidi-transceivers/2003609.article) 1270nm / 1330nm Bi-Directional 40km Single Mode but I don't see any 1510nm.
### [Cisco SFP-10G-BX40D-I and SFP-10G-BX40U-I (for 40Km Single-Fiber Bidirectional Applications)](http://www.cisco.com/c/en/us/products/collateral/interfaces-modules/transceiver-modules/data_sheet_c78-455693.html)
[](https://i.stack.imgur.com/pRm7A.jpg)
The Cisco SFP-10G-BX40D-I and SFP-10G-BX40U-I SFPs operate on a single strand of standard SMF.
A SFP-10G-BX40D-I device is always connected to a SFP-10G-BX40U-I device with a single strand of standard SMF with an operating transmission range up to 40 km.
The communication over a single strand of fiber is achieved by separating the transmission wavelength of the two devices. SFP-10G-BX40D-I transmits a 1330-nm channel and receives a 1270-nm signal. The SFP-10G-BX40U-I transmits at a 1270-nm wavelength and receives a 1330-nm signal.
The SFP-10G-BX40D-I and SFP-10G-BX40U-I SFPs support digital optical monitoring (DOM) functions according to the industry-standard SFF-8472 multisource agreement (MSA). This feature gives the end user the ability to monitor real-time parameters of the SFP, such as optical output power, optical input power, temperature, laser bias current, and transceiver supply voltage. | Single Fiber, Single Wavelength,CWDM Transceivers have been commercially available for years, some with built-in Micro-OTDR Fast Fiber Fault Finder technology, but so far only for 1 Gbps to 3 Gbps applications. |
5,230,747 | I have a jTable which currently displays and allows editing of a database table, I am now trying to sort adding tuples.
I am trying to get it to automatically add a row on downarrow at the bottom. So if I am at the bottom on the table and click my down arrow a new row will appear below. I just can't figure out how to do it.
Thanks
James | 2011/03/08 | [
"https://Stackoverflow.com/questions/5230747",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/513546/"
] | Action handling of `JTable` happens in `javax.swing.plaf.basic.BasicTableUI`. In your case, you probably need to register a new action for `SCROLL_DOWN_CHANGE_SELECTION`. In the action, check whether the current selection == last row of the table.
If that doesn't work, set a breakpoint in `javax.swing.plaf.basic.BasicTableUI.Actions.actionPerformed(ActionEvent)` to see which action is really executed. | You'll need to create a KeyListener and add this to your table:
```
public void keyReleased(KeyEvent e) {
int keyCode = e.getKeyCode();
if (keyCode == KeyEvent.VK_DOWN)
// check if selected table row = last row and if so: add new row to table model
}
```
greetz,
Stijn |
5,230,747 | I have a jTable which currently displays and allows editing of a database table, I am now trying to sort adding tuples.
I am trying to get it to automatically add a row on downarrow at the bottom. So if I am at the bottom on the table and click my down arrow a new row will appear below. I just can't figure out how to do it.
Thanks
James | 2011/03/08 | [
"https://Stackoverflow.com/questions/5230747",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/513546/"
] | JTable has a default Action for the down arrow key. If you want to change this behaviour then you need to create a custom Action. You can do this easily by using the [Wrapping Actions](http://tips4java.wordpress.com/2008/11/03/wrapping-actions/) concept to leverage the default code.
You can also look at [Table Tabbing](http://tips4java.wordpress.com/2008/11/04/table-tabbing/) for a working example of wrapping an Action. You code for the Action would be much simpler and would be something like:
```
if (last row is selected)
add a new row to the table
invoke the default down arrow action
``` | You'll need to create a KeyListener and add this to your table:
```
public void keyReleased(KeyEvent e) {
int keyCode = e.getKeyCode();
if (keyCode == KeyEvent.VK_DOWN)
// check if selected table row = last row and if so: add new row to table model
}
```
greetz,
Stijn |
5,230,747 | I have a jTable which currently displays and allows editing of a database table, I am now trying to sort adding tuples.
I am trying to get it to automatically add a row on downarrow at the bottom. So if I am at the bottom on the table and click my down arrow a new row will appear below. I just can't figure out how to do it.
Thanks
James | 2011/03/08 | [
"https://Stackoverflow.com/questions/5230747",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/513546/"
] | Action handling of `JTable` happens in `javax.swing.plaf.basic.BasicTableUI`. In your case, you probably need to register a new action for `SCROLL_DOWN_CHANGE_SELECTION`. In the action, check whether the current selection == last row of the table.
If that doesn't work, set a breakpoint in `javax.swing.plaf.basic.BasicTableUI.Actions.actionPerformed(ActionEvent)` to see which action is really executed. | JTable has a default Action for the down arrow key. If you want to change this behaviour then you need to create a custom Action. You can do this easily by using the [Wrapping Actions](http://tips4java.wordpress.com/2008/11/03/wrapping-actions/) concept to leverage the default code.
You can also look at [Table Tabbing](http://tips4java.wordpress.com/2008/11/04/table-tabbing/) for a working example of wrapping an Action. You code for the Action would be much simpler and would be something like:
```
if (last row is selected)
add a new row to the table
invoke the default down arrow action
``` |
308,928 | Simple use case for ApexMocks of a Service layer class, something I've done a 100 times
```
fflib_ApexMocks mocks = new fflib_ApexMocks();
OpportunitiesServiceImpl mockOpportunitiesService = (OpportunitiesServiceImpl) mocks.mock(OpportunitiesServiceImpl.class);
```
At runtime, I get this error:
```
Class.System.Test.createStub: line 93, column 1
Class.fflib_ApexMocks.mock: line 67, column 1
Class.MyTest.myTestMethod: line 28, column 1
System.TypeException: @Override specified for non-overriding method:
String OpportunitiesServiceImpl__sfdc_ApexStub.someMethod(Id)
```
The `OpportunitiesServiceImpl` class looks like this:
```
public virtual with sharing class OpportunitiesServiceImpl implements IOpportunitiesService {
public virtual void method1() {..}
public virtual void method2() {..}
private Id doStuff();
Id someMethod(Id oppoId);
public class SomeInner{..}
public virtual void method3() {..}
}
``` | 2020/06/09 | [
"https://salesforce.stackexchange.com/questions/308928",
"https://salesforce.stackexchange.com",
"https://salesforce.stackexchange.com/users/2602/"
] | Note the following:
* `OpportunitiesServiceImpl` is at V48.0
* `fflib_ApexMocks` is at V39 (this issues the call to `System.Test.createStub`)
So, I can't explain why this fixes the issue but it does:
The offending method indicated in the error message does not have an annotation of either `public` or `private`. Adding `private` and rerunning eliminates the error
```
public virtual with sharing class OpportunitiesServiceImpl implements IOpportunitiesService {
public virtual void method1() {..}
public virtual void method2() {..}
private Id doStuff();
private Id someMethod(Id oppoId); // added the access modifier "private"
public class SomeInner{..}
public virtual void method3() {..}
}
```
*Note that helper methods used by your mocked method must have an access modifier* | If you are trying to mock a method within a class, like calling some mock for `someMethod` instead of actual method `someMethod` in `OpportunitiesServiceImpl` implementation
```
OpportunitiesServiceImpl mockOpportunitiesService = (OpportunitiesServiceImpl) mocks.mock(OpportunitiesServiceImpl.class);
mockOpportunitiesService.someMethod('005000111222333');
```
you have to make that method public
```
public virtual with sharing class OpportunitiesServiceImpl implements IOpportunitiesService {
public virtual void method1() {..}
public virtual void method2() {..}
private Id doStuff();
public Id someMethod(Id oppoId); // added the access modifier "private"
public class SomeInner{..}
public virtual void method3() {..}
}
```
If this method lacks either annotation, then exception `System.TypeException: @Override specified for non-overriding method:` will be raised.
If this method has `private` annotation, the method will not be mocked, but the actual method from `OpportunitiesServiceImpl` will be called.
So to mock the method, it should have `public` or `global` annotation, in this case the mock will be called instead of the actual method from the underlying class. |
141,704 | One may find this question a duplicate, but my search through CrossValidated did not give satisfactory result. So I am posting this question and explaining what I want.
I need a book such that if one studies it - one knows he has no "white spots" in basic stats. On modern probability, in my opinion, the book of Olav Kallenberg (2nd edition) is such a book. It is also well composed and written. There are few other books getting close to it, but (in my opinion) they are worse.
There is huge number of books on stats and whenever I need to look up for something or recall something I never know which one to chose. So I just need one book in which I can look up for answers to basic (and "advanced") questions on any standard topic. | 2015/03/14 | [
"https://stats.stackexchange.com/questions/141704",
"https://stats.stackexchange.com",
"https://stats.stackexchange.com/users/71150/"
] | Presumably the person who asked this question is long gone, but for future reference I will mention a book here. Note: I have not read this book.
*Theoretical Statistics: Topics for a Core Course*, by Robert W. Keener. Amazon: [link.](https://rads.stackoverflow.com/amzn/click/com/B00DGER7WG)
I quote the last three lines of the review by Amazon user Der Boandlkramer:
>
> This book is in a class by itself!
>
>
> Its natural companion (and prerequisite, to some extent) textbook on
> probability is the monumental "Foundations of Modern Probability," by
> Olav Kallenberg.
>
>
>
For whatever it's worth, Keener's book is used at UCLA (STAT 200B). | Peter Bickel and Kjell Doksum wrote *Mathematical Statistics* [*Volume 1*](http://rads.stackoverflow.com/amzn/click/1498723802) and [*Volume 2.*](http://rads.stackoverflow.com/amzn/click/1498722687) The two books form a comprehensive guide to modern (frequentist) statistical methods at a level of mathematical sophistication similar to Kallenberg. |
33,369,206 | i want to get all the records in particular record type , but i got 1000 only.
This is the code I used.
```
function getRecords() {
return nlapiSearchRecord('contact', null, null, null);
}
```
I need two codes.
1) Get whole records at a single time
2) Get the records page wise by passing pageindex as an argument to the getRecords [1st =>0-1000 , 2nd =>1000 - 2000 , ...........]
```
function getRecords(pageIndex) {
.........
}
```
Thanks in advance | 2015/10/27 | [
"https://Stackoverflow.com/questions/33369206",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5040685/"
] | you can't get whole records at a time. However, you can sort results by internalid, and remember the last internalId of 1st search result and use an additional filter in your next search result.
```
var totalResults = [];
var res = nlapiSearchRecord('contact', null, null, new nlobjSearchColumn('internalid').setSort()) || [];
lastId = res[res.length - 1].getId();
copyAndPushToArray(totalResult, res);
while(res.length < 1000)
{
res = nlapiSearchRecord('contact', null, ['internalidnumber', 'greaterthan', lastId], new nlobjSearchColumn('internalid').setSort());
copyAndPushToArray(totalResult, res);
lastId = res[res.length - 1].getId();
}
```
Beware, if the number of records are high you may overuse governance limit in terms of time and usage points.
If you remember the lastId you can write a logic in RESTlet to take id as param and then use that as additional filter to return nextPage.
You can write a logic to get nth pageresult but, you might have to run search uselessly n-1 times.
Also, I would suggest to use `nlapiCreateSearch().runSearch()` as it can return up to 4000 records | Here is another way to get more than 1000 results on a search:
```
function getItems() {
var columns = ['internalid', 'itemid', 'salesdescription', 'baseprice', 'lastpurchaseprice', 'upccode', 'quantityonhand', 'vendorcode'];
var searchcolumns = [];
for(var col in columns) {
searchcolumns.push(new nlobjSearchColumn(columns[col]));
}
var search = nlapiCreateSearch('item', null, searchcolumns);
var results = search.runSearch();
var items = [], slice = [], i = 0;
do {
slice = results.getResults(i, i + 1000);
for (var itm in slice) {
var item = {};
for(var col in columns) { item[columns[col]] = slice[itm].getValue(columns[col]); } // convert nlobjSearchResult into simple js object
items.push(item);
i++;
}
} while (slice.length >= 1000);
return items;
}
``` |
171,843 | I have handed in my resignation to a Dutch company which I am currently working for, however, I misunderstood the contractual notice period. In the contract it says I must provide "one calendar month" of notice. I took this to mean that if I hand in my notice on the 20th of April, I would continue to work until the 20th of May. Unfortunately this is incorrect in the Netherlands. What it actually means is that I need to work a full month from start to finish after I give in my notice. Ie I need to work until the 31st of May.
This sort of still works with my next job but just barely. I had hoped to be able to fly back to my home country and spend some time with my family, who I have been separated from during covid, before starting my new job.
I have 15 days of holiday stored up and I want to leverage them to shorten my leaving period. Is the company allowed to deny my use of those holidays during the leaving period?
Typically the company does want to have a lot of notice from it's employees in regards to the use of their holidays in general, but I don't know in what capacity the company is allowed to outright deny holidays on short notice?
As another twist, June 1st will be the anniversary of when I joined the company. In the Netherlands, your accrued legal vacation days will expire 6 months after the last day of the year in which they were accrued. I'm not sure if that changes anything, but if the company didn't allow me to take those holidays, which I am entitled to, I would otherwise lose them. | 2021/04/26 | [
"https://workplace.stackexchange.com/questions/171843",
"https://workplace.stackexchange.com",
"https://workplace.stackexchange.com/users/125595/"
] | You won't lose your vacation days. You must take your required minimal number of yearly vacation days within 6 months (so, before *July* 1), which, for a 40 hour/week contract is 20 vacation days. (For vacation days above legal, it depends on the company; for the company I work for, that's 5 years). But that's irrelevant for your case, as you're leaving before that.
You can still take vacation days during your notification period -- in fact, it's extremely common for people to take their left over vacation days at the end of the notification period. You still need to follow the normal procedure at your work to take them. A company cannot deny your taking your vacation days purely because it's your notification period, but it can for the same reasons it can otherwise. If you have vacation days left over at the end of the contract, the normal procedure is that you get paid for them. (So, if you have 5 days of vacation not taken, you'd get paid for another 5 days (just less of a quarter of a monthly salary)). | >
> Is the company allowed to deny my use of those holidays during the leaving period?
>
>
>
No. See for example: <https://www.legalexpatdesk.nl/holidays/>
However that doesn't mean they won't try anyway and the key question for you is "What to do if they deny it ".
1. Read through your employee handbook and your corporate policies. Make sure you understand all the rules that governs that .
2. Read up on the legal framework in the Netherlands. Google is your friend. If you are not comfortable doing this, spend some money on an employment lawyer to understand the rules and what your options are.
3. Then have a "friendly" conversation with the company. State what you want and ask what their specific concerns are. Listen carefully and stay open-minded. Maybe it's something that can easily addressed with a mutual agreeable work around (documentation, shift coverage, project coverage, etc.)
4. If that doesn't help, you need to get more assertive. If applicable, bring up the corporate policies and state that you really don't want to violate those (which they can't argue with). State that it's very important to you to take this holiday and that a solution needs to be found.
5. Save the legal aspect as a means of last resort if anything else has failed and there is no way left to find collaborative solution. You can just go and take your vacation but I would put the details (dates and legal justification) into a certified letter and sent it up front to the company so you have your bases covered in case they fight back. A lawyer can help with this as well. |
33,854,058 | The following program isn't supposed to be executing sequentially but it is still doing so.
```
class A extends Thread
{
public void run()
{
for(int i=0; i<=5; i++)
{
System.out.println("Thread A : "+i);
}
System.out.println("exit from A");
}
}
class B extends Thread
{
public void run()
{
for(int j=0; j<=5; j++)
{
System.out.println("Thread B: "+j);
}
System.out.println("exit from B");
}
}
class C extends Thread
{
public void run()
{
for(int k=0; k<=5; k++)
{
System.out.println("Thread C : "+k);
}
System.out.println("exit from C");
}
}
class ThreadCounter
{
public static void main(String arg[])
{
new A().start();
new B().start();
new C().start();
}
}
```
The output I am getting is :
```
Thread A start
Thread A : 1
Thread A : 2
Thread A : 3
Thread A : 4
Thread A end
Thread B start
Thread B : 1
Thread B : 2
Thread B : 3
Thread B : 4
Thread B end
Thread C start
Thread C : 1
Thread C : 2
Thread C : 3
Thread C : 4
Thread C end
```
Can you please tell me why the execution is this way?
Isn't the execution supposed to be sequential only when run | 2015/11/22 | [
"https://Stackoverflow.com/questions/33854058",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5378299/"
] | Creating and starting a thread have a cost in performance, it is not a simple light operation. In consequence, it consumes some resources.
In your example, your run methods are very simple (a loop over 5 int for printing). This code is very light and execution is very quick.
I think that the execution of each loop exited before the next thread was created. Try to add a Thread.sleep() into the loop, increase the number of increments, or do some more complex stuff. | The threads do so little work that they finish before the switch to the next thread.
Try increasing the loops to 100000 or more. |
33,854,058 | The following program isn't supposed to be executing sequentially but it is still doing so.
```
class A extends Thread
{
public void run()
{
for(int i=0; i<=5; i++)
{
System.out.println("Thread A : "+i);
}
System.out.println("exit from A");
}
}
class B extends Thread
{
public void run()
{
for(int j=0; j<=5; j++)
{
System.out.println("Thread B: "+j);
}
System.out.println("exit from B");
}
}
class C extends Thread
{
public void run()
{
for(int k=0; k<=5; k++)
{
System.out.println("Thread C : "+k);
}
System.out.println("exit from C");
}
}
class ThreadCounter
{
public static void main(String arg[])
{
new A().start();
new B().start();
new C().start();
}
}
```
The output I am getting is :
```
Thread A start
Thread A : 1
Thread A : 2
Thread A : 3
Thread A : 4
Thread A end
Thread B start
Thread B : 1
Thread B : 2
Thread B : 3
Thread B : 4
Thread B end
Thread C start
Thread C : 1
Thread C : 2
Thread C : 3
Thread C : 4
Thread C end
```
Can you please tell me why the execution is this way?
Isn't the execution supposed to be sequential only when run | 2015/11/22 | [
"https://Stackoverflow.com/questions/33854058",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5378299/"
] | Creating and starting a thread have a cost in performance, it is not a simple light operation. In consequence, it consumes some resources.
In your example, your run methods are very simple (a loop over 5 int for printing). This code is very light and execution is very quick.
I think that the execution of each loop exited before the next thread was created. Try to add a Thread.sleep() into the loop, increase the number of increments, or do some more complex stuff. | When new A().start() is called, a new thread is created and starts execution. Then new A().start() returns. When new B().start() is called a thread is being created. Within this time thread A will finish up execution and return because new Thread creation is a costly and blocking call. The same thing happens to thread C because thread B already finish up before Thread C starts executing. So they are still executing in parallel. But one is finishing up before next one starts up. Try to start A, B and C in parallel not sequentially as you did above. Then you may be able to see different result. |
14,053,630 | I want to let the user choose and open multiple texts and perform a search for exact matches in the texts.
I want the encoding to be unicode.
If I search for "cat" I want it to find "cat", "cat,", ".cat" but not "catalogue".
I don't know how to let the user search for two words ("cat" OR "dog") in all of the texts at the same time??????
Maybe I can use RE?
So far I have just made it possible for the user to insert the path to the directory containing the text files to search in. Now I want to let the user (raw\_input) search for two words in all of the texts, and then print and save the results (e.g. "search\_word\_1" and "search\_word\_2" found in document1.txt, "search\_word\_2" found in document4.txt) in a separate document (search\_words).
```
import re, os
path = raw_input("insert path to directory :")
ex_library = os.listdir(path)
search_words = open("sword.txt", "w") # File or maybe list to put in the results
thelist = []
for texts in ex_library:
f = os.path.join(path, texts)
text = open(f, "r")
textname = os.path.basename(texts)
print textname
for line in text.read():
text.close()
``` | 2012/12/27 | [
"https://Stackoverflow.com/questions/14053630",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1921937/"
] | Regular expressions are appropriate tool in this case.
>
> I want it to find "cat", "cat,", ".cat" but not "catalogue".
>
>
>
Pattern: `r'\bcat\b'`
`\b` matches at a word boundary.
>
> how to let the user search for two words ("cat" OR "dog") in all of the texts at the same time
>
>
>
Pattern: `r'\bcat\b|\bdog\b'`
To print `"filename: <words that are found in it>"`:
```
#!/usr/bin/env python
import os
import re
import sys
def fgrep(words, filenames, encoding='utf-8', case_insensitive=False):
findwords = re.compile("|".join(r"\b%s\b" % re.escape(w) for w in words),
flags=re.I if case_insensitive else 0).findall
for name in filenames:
with open(name, 'rb') as file:
text = file.read().decode(encoding)
found_words = set(findwords(text))
yield name, found_words
def main():
words = [w.decode(sys.stdin.encoding) for w in sys.argv[1].split(",")]
filenames = sys.argv[2:] # the rest is filenames
for filename, found_words in fgrep(words, filenames):
print "%s: %s" % (os.path.basename(filename), ",".join(found_words))
main()
```
Example:
```
$ python findwords.py 'cat,dog' /path/to/*.txt
```
### Alternative solutions
To avoid reading the whole file in memory:
```
import codecs
...
with codecs.open(name, encoding=encoding) as file:
found_words = set(w for line in file for w in findwords(line))
```
You could also print found words in the context they are found e.g., print lines with highlighted words:
```
from colorama import init # pip install colorama
init(strip=not sys.stdout.isatty()) # strip colors if stdout is redirected
from termcolor import colored # pip install termcolor
highlight = lambda s: colored(s, on_color='on_red', attrs=['bold', 'reverse'])
...
regex = re.compile("|".join(r"\b%s\b" % re.escape(w) for w in words),
flags=re.I if case_insensitive else 0)
for line in file:
if regex.search(line): # line contains words
line = regex.sub(lambda m: highlight(m.group()), line)
yield line
``` | You need to split the text in each file on whitespace and punctuation. Once that's done you can simply look for the words you are searching for in the remaining list. You also need to convert everything to lowercase, unless you also want case sensitive search. |
14,053,630 | I want to let the user choose and open multiple texts and perform a search for exact matches in the texts.
I want the encoding to be unicode.
If I search for "cat" I want it to find "cat", "cat,", ".cat" but not "catalogue".
I don't know how to let the user search for two words ("cat" OR "dog") in all of the texts at the same time??????
Maybe I can use RE?
So far I have just made it possible for the user to insert the path to the directory containing the text files to search in. Now I want to let the user (raw\_input) search for two words in all of the texts, and then print and save the results (e.g. "search\_word\_1" and "search\_word\_2" found in document1.txt, "search\_word\_2" found in document4.txt) in a separate document (search\_words).
```
import re, os
path = raw_input("insert path to directory :")
ex_library = os.listdir(path)
search_words = open("sword.txt", "w") # File or maybe list to put in the results
thelist = []
for texts in ex_library:
f = os.path.join(path, texts)
text = open(f, "r")
textname = os.path.basename(texts)
print textname
for line in text.read():
text.close()
``` | 2012/12/27 | [
"https://Stackoverflow.com/questions/14053630",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1921937/"
] | Regular expressions are appropriate tool in this case.
>
> I want it to find "cat", "cat,", ".cat" but not "catalogue".
>
>
>
Pattern: `r'\bcat\b'`
`\b` matches at a word boundary.
>
> how to let the user search for two words ("cat" OR "dog") in all of the texts at the same time
>
>
>
Pattern: `r'\bcat\b|\bdog\b'`
To print `"filename: <words that are found in it>"`:
```
#!/usr/bin/env python
import os
import re
import sys
def fgrep(words, filenames, encoding='utf-8', case_insensitive=False):
findwords = re.compile("|".join(r"\b%s\b" % re.escape(w) for w in words),
flags=re.I if case_insensitive else 0).findall
for name in filenames:
with open(name, 'rb') as file:
text = file.read().decode(encoding)
found_words = set(findwords(text))
yield name, found_words
def main():
words = [w.decode(sys.stdin.encoding) for w in sys.argv[1].split(",")]
filenames = sys.argv[2:] # the rest is filenames
for filename, found_words in fgrep(words, filenames):
print "%s: %s" % (os.path.basename(filename), ",".join(found_words))
main()
```
Example:
```
$ python findwords.py 'cat,dog' /path/to/*.txt
```
### Alternative solutions
To avoid reading the whole file in memory:
```
import codecs
...
with codecs.open(name, encoding=encoding) as file:
found_words = set(w for line in file for w in findwords(line))
```
You could also print found words in the context they are found e.g., print lines with highlighted words:
```
from colorama import init # pip install colorama
init(strip=not sys.stdout.isatty()) # strip colors if stdout is redirected
from termcolor import colored # pip install termcolor
highlight = lambda s: colored(s, on_color='on_red', attrs=['bold', 'reverse'])
...
regex = re.compile("|".join(r"\b%s\b" % re.escape(w) for w in words),
flags=re.I if case_insensitive else 0)
for line in file:
if regex.search(line): # line contains words
line = regex.sub(lambda m: highlight(m.group()), line)
yield line
``` | Some (maybe useful) information in addition to the existing answers:
You should be aware that what the user means when he thinks of a "character" (=grapheme) is not always the same as a Unicode character, and some graphemes can be represented by Unicode characters in more than one unique way (e.g. composite character vs. base character + combining mark).
To do a search based on graphemes (=what the user expects in most cases) and not on specific Unicode character sequences, you need to [normalize](http://en.wikipedia.org/wiki/Unicode_normalization) your strings before you search. |
37,575,274 | I have a container that is 100vh (minus the fixed nav height).
```
<section class="container">
```
Inside this container I have some text:
```
<div class="text">
<p>title</p>
</div>
```
Which can be of any length as the content is dynamic.
Below this text I have an image:
```
<div class="image">
<img src="https://s-media-cache-ak0.pinimg.com/736x/d1/a6/64/d1a664bca214bf785a293cbc87950fc4.jpg">
</div>
```
The image needs to fill the rest of the 100vh (- nav height) container.
I use:
```
.container{
display:flex;
flex-flow: column nowrap;
....
```
[Fiddle](https://jsfiddle.net/20pspusz/)
The issue I am having is that I need the image to be the height of the rest of the space.
How can I do this? In my fiddle, if your screen is small it is being cut off and if your screen is large it does not fill the space. Height: 100% fails to work, making it too large.
Flex solutions only please, no table tricks - thanks! | 2016/06/01 | [
"https://Stackoverflow.com/questions/37575274",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1013512/"
] | Make the image container (`.image`) a flex container with `height: 100%`.
You can then fine-tune the image's aspect ratio and alignment with `object-fit` / `object-position`.
```css
nav {
position:fixed;
background:grey;
width:100%;
height: 100px;
}
main {
padding-top: 100px;
}
.container {
display:flex;
flex-flow: column nowrap;
height: calc(100vh - 100px);
background: green;
border: 3px solid brown;
}
.text { background: yellow; }
/* ***** NEW ***** */
.image {
display: flex;
justify-content: center;
height: 100%;
}
img {
width: 100%;
object-fit: contain;
}
```
```html
<nav>Nav</nav>
<main>
<section class="container">
<div class="text"><p>title</p></div>
<div class="image">
<img src="https://s-media-cache-ak0.pinimg.com/736x/d1/a6/64/d1a664bca214bf785a293cbc87950fc4.jpg">
</div>
</section>
<section class="container">
<div class="text"><p>hello</p></div>
<div class="image">
<img src="https://s-media-cache-ak0.pinimg.com/736x/d1/a6/64/d1a664bca214bf785a293cbc87950fc4.jpg">
</div>
</section>
</main>
```
[**Revised Fiddle**](https://jsfiddle.net/20pspusz/2/)
Note that the `object-fit` property is not supported by IE. For more details and a workaround see: <https://stackoverflow.com/a/37127590/3597276> | Maybe not exactly what you wanted, but if you move the image to a div and use it as a background, you can get the desired effect.
[Fiddle](https://jsfiddle.net/7a5trtrz/1/)
HTML:
Nav
title
```
<section class="container">
<div class="text">
<p>hello</p>
</div>
<div class="imageWrap">
<div class="image"></div>
</div>
</section>
</main>
```
CSS:
```
nav {
background: grey;
width: 100%;
height: 100px;
position: fixed;
}
main{
padding-top: 100px;
}
.container{
display: flex;
flex-flow: column nowrap;
height: calc(100vh - 100px);
background: green;
border: 3px solid brown;
}
.imageWrap {
flex: 1;
display: flex;
}
.image {
flex: 1;
background-size: contain;
background-repeat: no-repeat;
background-image: url(https://s-media-cache-ak0.pinimg.com/736x/d1/a6/64/d1a664bca214bf785a293cbc87950fc4.jpg)
}
.text{
background: yellow;
}
``` |
10,178 | [I asked this question here](https://gaming.stackexchange.com/questions/197833/find-recommended-system-requirements-for-all-owned-games) about trying to locate a summary of hardware requirements for all of my steam games. It eventually got closed as a recommendation question. I don't feel that I'm looking for any hardware or software recommendations and I attempted to edit it to clarify that. I also tried to reach out to the close voters for their reasoning as well with no feedback.
I'm new to this stack site but not to SE so I knew to go over the help center a few times before and after posting. Did I miss something that would make the question off topic? | 2015/01/01 | [
"https://gaming.meta.stackexchange.com/questions/10178",
"https://gaming.meta.stackexchange.com",
"https://gaming.meta.stackexchange.com/users/39471/"
] | IMO, No - It shouldn't have been closed. (It's not off-topic)
-------------------------------------------------------------
*I have no idea why it was voted to be closed for "recommendations", even though it's a question about finding information; basically what the developer recommends using.*
Your question was (in my words):
>
> **How do I find the recommended computer specifications for all the games I own?**
>
> *And then compile all of them into a single file for me to read to just to make sure it was compatable with my laptop.*
>
>
>
---
Following the FAQ:
>
> ... If your question generally covers things such as …
>
>
> * Gameplay strategies and tactics **No**
> * Puzzle solving or obstacle clearing **No**
> * Game mechanics and terminology **No**
> * Plot and characters in games **No**
> * Game-specific hardware and utilities **Yes!**
>
>
>
So, that's allowed. And the second bit:
>
> Please note, however, that site policies *prohibit* questions of the following types:
>
>
> * Game and Mod Development ([try the Game Development Stack Exchange](https://gamedev.stackexchange.com/) instead) **No**
> * Requests for game identification based on personal recollection alone **No**
> * Catalogues (listing games that fit specific criteria or are like an existing game) **No**
> * Shopping advice and recommendations **No**
> * Speculation of the future of the industry and of upcoming releases **No**
> * Piracy, and support with pirated games. **No**
>
>
>
Also in the clear. | It was completely on-topic. Your question was not a recommendation, it was:
>
> Can Steam do this thing? If so, how?
>
>
>
Questions about using Steam are completely on-topic here (it's gaming related).
Unfortunately, casually skimming the question and the title does give the impression that you're looking for a list online. Once one person doesn't bother reading the question before voting to close, it ends up on the close review queue, where people are even less likely to read it. |
266,839 | A few minutes ago, a [question about *"double compilation"*](https://stackoverflow.com/q/24965167/2344584) was posted. The OP read an article claiming that passing an already compiled executable through GCC for a second time results in a 2x speed boost and asked how that was possible.
Double compilation is clearly impossible and the article is likely to be a hoax. But I realize that it might not be obvious to newbies, so I am uncertain whether:
1. I should vote to close the question as off-topic for SO
2. the question should be left open for people to learn about the hoax.
So, should I vote to close the question or leave it open? | 2014/07/25 | [
"https://meta.stackoverflow.com/questions/266839",
"https://meta.stackoverflow.com",
"https://meta.stackoverflow.com/users/2344584/"
] | If such an article actually *exists*, then you should probably answer the question and point out why it's bunk (assuming it is).
If the article *doesn't* exist, then it's not a real question. Either close it as unclear and note that such an article should be linked to / cited so that folks can effectively answer the question, or close it as off-topic and write in something about pulling the one with bells on it. | Whether or not the article exists the hoax/mistake is circulating. Otherwise the person asking the question would not have heard it.
It's worth debunking such obviously false claims, whether backed by an article or not...as we don't know how far the false information may have spread.
(Obviously something as ludicrous as that would not spread far as anyone who knows anything about how compilers work would be able to immediately spot it as false but other invalid claims are far more reasonable on the surface). |
266,839 | A few minutes ago, a [question about *"double compilation"*](https://stackoverflow.com/q/24965167/2344584) was posted. The OP read an article claiming that passing an already compiled executable through GCC for a second time results in a 2x speed boost and asked how that was possible.
Double compilation is clearly impossible and the article is likely to be a hoax. But I realize that it might not be obvious to newbies, so I am uncertain whether:
1. I should vote to close the question as off-topic for SO
2. the question should be left open for people to learn about the hoax.
So, should I vote to close the question or leave it open? | 2014/07/25 | [
"https://meta.stackoverflow.com/questions/266839",
"https://meta.stackoverflow.com",
"https://meta.stackoverflow.com/users/2344584/"
] | If such an article actually *exists*, then you should probably answer the question and point out why it's bunk (assuming it is).
If the article *doesn't* exist, then it's not a real question. Either close it as unclear and note that such an article should be linked to / cited so that folks can effectively answer the question, or close it as off-topic and write in something about pulling the one with bells on it. | It's a similar case to [Which is faster: while(1) or while(2)?](https://stackoverflow.com/questions/24848359/which-is-faster-while1-or-while2)
Such questions should exist on SO, just to provide the reference to the future visitors that it's a hoax. A hoax must be demented publicly, because otherwise anyone googling for that hoax would find only the sites that "prove" it.
It's not hard to believe, even for an advanced programmer, that some tool may give better result when run second time. Unfortunately, the tools that give the other output each time they are run, or even are unable to run correctly at the first time, are getting more and more the normality. |
266,839 | A few minutes ago, a [question about *"double compilation"*](https://stackoverflow.com/q/24965167/2344584) was posted. The OP read an article claiming that passing an already compiled executable through GCC for a second time results in a 2x speed boost and asked how that was possible.
Double compilation is clearly impossible and the article is likely to be a hoax. But I realize that it might not be obvious to newbies, so I am uncertain whether:
1. I should vote to close the question as off-topic for SO
2. the question should be left open for people to learn about the hoax.
So, should I vote to close the question or leave it open? | 2014/07/25 | [
"https://meta.stackoverflow.com/questions/266839",
"https://meta.stackoverflow.com",
"https://meta.stackoverflow.com/users/2344584/"
] | Whether or not the article exists the hoax/mistake is circulating. Otherwise the person asking the question would not have heard it.
It's worth debunking such obviously false claims, whether backed by an article or not...as we don't know how far the false information may have spread.
(Obviously something as ludicrous as that would not spread far as anyone who knows anything about how compilers work would be able to immediately spot it as false but other invalid claims are far more reasonable on the surface). | It's a similar case to [Which is faster: while(1) or while(2)?](https://stackoverflow.com/questions/24848359/which-is-faster-while1-or-while2)
Such questions should exist on SO, just to provide the reference to the future visitors that it's a hoax. A hoax must be demented publicly, because otherwise anyone googling for that hoax would find only the sites that "prove" it.
It's not hard to believe, even for an advanced programmer, that some tool may give better result when run second time. Unfortunately, the tools that give the other output each time they are run, or even are unable to run correctly at the first time, are getting more and more the normality. |
74,400 | **Edit:** In response to the comments, the question has been edited to include the MWE. The accepted answer (by Gonzalo) is still valid.
Here's my code:
```
\documentclass{article}
% *** MISC UTILITY PACKAGES ***
\usepackage{graphicx}
\usepackage[caption=false]{subfig}%The caption option has been disabled
%to avoid conflict with the IEEEtran class file.
\usepackage{tikz}
% *** MATH PACKAGES ***
\usepackage[cmex10]{amsmath}
\usepackage{amssymb}
\begin{document}
\begin{figure}[!t]
\centering
\begin{tikzpicture}
\node[anchor=south west, inner sep = 0] (image) at (0,0)
{\includegraphics[width=8cm]{Tulips.jpg}};
\begin {scope}[x={(image.south east)},y={(image.north west)}]
\fill [white] (0,0) rectangle (1,1);
\foreach \y in {0,1,...,8} { \node [anchor=east] at (0.09,0.07+0.88*\y/8) {\small {-5+5*\y}}; }
\end {scope}
\end{tikzpicture}
\caption{Nothing}
\label{nothing}
\end{figure}
\end{document}
```
Here's the result:

I wanted the series to appear as {-5,0,5,...35}. What's being shown is {-5+5\*0,-5+5\*1,-5+5\*2,...-5+5\*8}.
How to evaluate the series before it gets printed as text? | 2012/09/27 | [
"https://tex.stackexchange.com/questions/74400",
"https://tex.stackexchange.com",
"https://tex.stackexchange.com/users/8303/"
] | You can use the `evaluate=<variable> as <macro> using <formula>` syntax:
```
\documentclass{scrartcl}
\usepackage{tikz,pgf}
\usepackage{graphicx}
\begin{document}
\begin{tikzpicture}
\node[anchor=south west, inner sep = 0] (image) at (0,0)
{\includegraphics[width=8cm]{cat}};
\begin {scope}[x={(image.south east)},y={(image.north west)}]
\draw [help lines,lime,xstep=.01,ystep=.01] (0,0) grid (1,1);
\draw [help lines,orange,xstep=.05,ystep=.05] (0,0) grid (1,1);
\draw [help lines,red,xstep=.1,ystep=.1] (0,0) grid (1,1);
\foreach \x in {0,1,...,9} { \node [anchor=north] at (\x/10,0) {0.\x}; }
\foreach \y in {0,1,...,9} { \node [anchor=east] at (0,\y/10) {0.\y}; }
\fill [white] (0,0) rectangle (1,1);
\foreach \y [evaluate=\y as \yeval using -5+5*\y] in {0,...,8} { \node [anchor=east,font=\tiny] at (0.09,0.07+0.88*\y/8) {\pgfmathtruncatemacro{\yet}{\yeval}\yet}; }
\end {scope}
\end{tikzpicture}
\end{document}
```
 | Answer to the modified question:
```
\documentclass{article}
% *** MISC UTILITY PACKAGES ***
\usepackage{graphicx}
\usepackage[caption=false]{subfig}%The caption option has been disabled
%to avoid conflict with the IEEEtran class file.
\usepackage{tikz}
% *** MATH PACKAGES ***
\usepackage[cmex10]{amsmath}
\usepackage{amssymb}
\begin{document}
\begin{figure}[!t]
\centering
\begin{tikzpicture}
\node[anchor=south west, inner sep = 0] (image) at (0,0)
{\includegraphics[width=8cm]{Tulips.jpg}};
\begin {scope}[x={(image.south east)},y={(image.north west)}]
\fill [white] (0,0) rectangle (1,1);
% \foreach \y in {0,1,...,8} { \node [anchor=east] at (0.09,0.07+0.88*\y/8) {\small {-5+5*\y}}; }
\foreach \y [evaluate=\y as \yeval using -5+5*\y] in {0,...,8} { \node [anchor=east,font=\small] at (0.09,0.07+0.88*\y/8) {\yeval}; }
\end {scope}
\end{tikzpicture}
\caption{Nothing}
\label{nothing}
\end{figure}
\end{document}
```
The output looks like this:
 |
49,341 | I'm wondering why some people release software as freeware, yet they don't release the source code. Why is that? I can think of some reasons, yet most of them don't make very much sense. Why would you want to keep the source closed but let the program be freely available (free of charge, not free as in freedom)? | 2011/02/18 | [
"https://softwareengineering.stackexchange.com/questions/49341",
"https://softwareengineering.stackexchange.com",
"https://softwareengineering.stackexchange.com/users/12750/"
] | One I don't see here yet - because the source code has value in itself, separate from the application as a whole.
If you have useful libraries that you've written, you're likely to use them even in projects that you intend to give away. That doesn't mean you're willing to give that library source code away. And without those libraries, the rest of the source code is probably worthless.
If you give away library source code that you've developed over a period of years, you're giving a competitive advantage away - very likely to your competitors.
One thing that I think is often relevant, though - that code probably includes libraries that have had time, effort and even emotions invested in them over a period of years. It would be like inviting thousands of people to read our diaries. | Despite the general bad idea that security-through-obscurity is, in the malware removal field, its a constant cat and mouse game between those of us who write analysis/removal tools, and those writing cleverer and cleverer malware. Sometimes we release a tool freely to users to use, but try to obfuscate the tool's operation in order to make it more difficult for malware authors to defeat the defeat tool :)
This is obviously atypical for most software, but it's something I see all the time. |
49,341 | I'm wondering why some people release software as freeware, yet they don't release the source code. Why is that? I can think of some reasons, yet most of them don't make very much sense. Why would you want to keep the source closed but let the program be freely available (free of charge, not free as in freedom)? | 2011/02/18 | [
"https://softwareengineering.stackexchange.com/questions/49341",
"https://softwareengineering.stackexchange.com",
"https://softwareengineering.stackexchange.com/users/12750/"
] | One of my favorite productivity tools is freeware. I asked the author about the source one time, and he said he couldn't release it because it contains a lot of proprietary code that belongs to his employer. So I suppose that his employer doesn't mind it being used in a free tool, but that it's also being used in their commercial products and they don't want to give away the code to it. | One I don't see here yet - because the source code has value in itself, separate from the application as a whole.
If you have useful libraries that you've written, you're likely to use them even in projects that you intend to give away. That doesn't mean you're willing to give that library source code away. And without those libraries, the rest of the source code is probably worthless.
If you give away library source code that you've developed over a period of years, you're giving a competitive advantage away - very likely to your competitors.
One thing that I think is often relevant, though - that code probably includes libraries that have had time, effort and even emotions invested in them over a period of years. It would be like inviting thousands of people to read our diaries. |
49,341 | I'm wondering why some people release software as freeware, yet they don't release the source code. Why is that? I can think of some reasons, yet most of them don't make very much sense. Why would you want to keep the source closed but let the program be freely available (free of charge, not free as in freedom)? | 2011/02/18 | [
"https://softwareengineering.stackexchange.com/questions/49341",
"https://softwareengineering.stackexchange.com",
"https://softwareengineering.stackexchange.com/users/12750/"
] | One of my favorite productivity tools is freeware. I asked the author about the source one time, and he said he couldn't release it because it contains a lot of proprietary code that belongs to his employer. So I suppose that his employer doesn't mind it being used in a free tool, but that it's also being used in their commercial products and they don't want to give away the code to it. | I have several freeware apps for which I wont provide source code. The main reason is because they share large amounts of code with commercial applications. Consider something like a document viewer... that still needs the rendering system of its commercial cousin, a document creator. Another reason is some of the apps also use non-open sourced 3rd party components. |
49,341 | I'm wondering why some people release software as freeware, yet they don't release the source code. Why is that? I can think of some reasons, yet most of them don't make very much sense. Why would you want to keep the source closed but let the program be freely available (free of charge, not free as in freedom)? | 2011/02/18 | [
"https://softwareengineering.stackexchange.com/questions/49341",
"https://softwareengineering.stackexchange.com",
"https://softwareengineering.stackexchange.com/users/12750/"
] | There have been 2 great answers so far but here are my reasons that I can see:
1. It is more trouble than it is worth.
2. They use the freemium model
3. Don't feel they should
For #1, if the product is free and the person isn't seeing any profits from it, they may not feel like having to deal with hosting the source code and making sure that they update it whenever they make changes. Now, I know that it isn't that big of a hassel but who knows, it may be big enough to discourage some
For #2, if they use a freemium model, then releasing source will basically allow people to add in the features that they charge for and cost the developer money.
For #3, I think that it has been a tradition (of sorts) for Windows programs not to be open source (no facts to back me up so I could be wrong). Windows has been a closed-source platform so it isn't expected to release source for something that is free. The original question doesn't specifically mention Windows, but that is where I see the majority of free but not open source software. | Despite the general bad idea that security-through-obscurity is, in the malware removal field, its a constant cat and mouse game between those of us who write analysis/removal tools, and those writing cleverer and cleverer malware. Sometimes we release a tool freely to users to use, but try to obfuscate the tool's operation in order to make it more difficult for malware authors to defeat the defeat tool :)
This is obviously atypical for most software, but it's something I see all the time. |
49,341 | I'm wondering why some people release software as freeware, yet they don't release the source code. Why is that? I can think of some reasons, yet most of them don't make very much sense. Why would you want to keep the source closed but let the program be freely available (free of charge, not free as in freedom)? | 2011/02/18 | [
"https://softwareengineering.stackexchange.com/questions/49341",
"https://softwareengineering.stackexchange.com",
"https://softwareengineering.stackexchange.com/users/12750/"
] | Hmm, what comes to my mind is
* Because you want to retain some measure of control over the product
* Because you want to reserve the possibility / right to charge for the product in the future
* Because you're ashamed of your source code
* Because you want to make sure you are credited for the product, and it doesn't get stolen and re-used in other projects (of which there is always a risk when you publish the code) | I provide open source code as sort of a community service idea, and as a portfolio idea.
If I was selling software directly - I don't, I'm employed in a position where the company sells the product, not me - I would *more* than happy to sell my software as closed source. Allowing competitors to look over my code and reduce my competitive advantage is not in my best interest, as a rule.
Put another way, I do not consider releasing software as open source to be a moral imperative. |
49,341 | I'm wondering why some people release software as freeware, yet they don't release the source code. Why is that? I can think of some reasons, yet most of them don't make very much sense. Why would you want to keep the source closed but let the program be freely available (free of charge, not free as in freedom)? | 2011/02/18 | [
"https://softwareengineering.stackexchange.com/questions/49341",
"https://softwareengineering.stackexchange.com",
"https://softwareengineering.stackexchange.com/users/12750/"
] | I have several freeware apps for which I wont provide source code. The main reason is because they share large amounts of code with commercial applications. Consider something like a document viewer... that still needs the rendering system of its commercial cousin, a document creator. Another reason is some of the apps also use non-open sourced 3rd party components. | Despite the general bad idea that security-through-obscurity is, in the malware removal field, its a constant cat and mouse game between those of us who write analysis/removal tools, and those writing cleverer and cleverer malware. Sometimes we release a tool freely to users to use, but try to obfuscate the tool's operation in order to make it more difficult for malware authors to defeat the defeat tool :)
This is obviously atypical for most software, but it's something I see all the time. |
49,341 | I'm wondering why some people release software as freeware, yet they don't release the source code. Why is that? I can think of some reasons, yet most of them don't make very much sense. Why would you want to keep the source closed but let the program be freely available (free of charge, not free as in freedom)? | 2011/02/18 | [
"https://softwareengineering.stackexchange.com/questions/49341",
"https://softwareengineering.stackexchange.com",
"https://softwareengineering.stackexchange.com/users/12750/"
] | One I don't see here yet - because the source code has value in itself, separate from the application as a whole.
If you have useful libraries that you've written, you're likely to use them even in projects that you intend to give away. That doesn't mean you're willing to give that library source code away. And without those libraries, the rest of the source code is probably worthless.
If you give away library source code that you've developed over a period of years, you're giving a competitive advantage away - very likely to your competitors.
One thing that I think is often relevant, though - that code probably includes libraries that have had time, effort and even emotions invested in them over a period of years. It would be like inviting thousands of people to read our diaries. | I have several freeware apps for which I wont provide source code. The main reason is because they share large amounts of code with commercial applications. Consider something like a document viewer... that still needs the rendering system of its commercial cousin, a document creator. Another reason is some of the apps also use non-open sourced 3rd party components. |
49,341 | I'm wondering why some people release software as freeware, yet they don't release the source code. Why is that? I can think of some reasons, yet most of them don't make very much sense. Why would you want to keep the source closed but let the program be freely available (free of charge, not free as in freedom)? | 2011/02/18 | [
"https://softwareengineering.stackexchange.com/questions/49341",
"https://softwareengineering.stackexchange.com",
"https://softwareengineering.stackexchange.com/users/12750/"
] | One of my favorite productivity tools is freeware. I asked the author about the source one time, and he said he couldn't release it because it contains a lot of proprietary code that belongs to his employer. So I suppose that his employer doesn't mind it being used in a free tool, but that it's also being used in their commercial products and they don't want to give away the code to it. | There have been 2 great answers so far but here are my reasons that I can see:
1. It is more trouble than it is worth.
2. They use the freemium model
3. Don't feel they should
For #1, if the product is free and the person isn't seeing any profits from it, they may not feel like having to deal with hosting the source code and making sure that they update it whenever they make changes. Now, I know that it isn't that big of a hassel but who knows, it may be big enough to discourage some
For #2, if they use a freemium model, then releasing source will basically allow people to add in the features that they charge for and cost the developer money.
For #3, I think that it has been a tradition (of sorts) for Windows programs not to be open source (no facts to back me up so I could be wrong). Windows has been a closed-source platform so it isn't expected to release source for something that is free. The original question doesn't specifically mention Windows, but that is where I see the majority of free but not open source software. |
49,341 | I'm wondering why some people release software as freeware, yet they don't release the source code. Why is that? I can think of some reasons, yet most of them don't make very much sense. Why would you want to keep the source closed but let the program be freely available (free of charge, not free as in freedom)? | 2011/02/18 | [
"https://softwareengineering.stackexchange.com/questions/49341",
"https://softwareengineering.stackexchange.com",
"https://softwareengineering.stackexchange.com/users/12750/"
] | One I don't see here yet - because the source code has value in itself, separate from the application as a whole.
If you have useful libraries that you've written, you're likely to use them even in projects that you intend to give away. That doesn't mean you're willing to give that library source code away. And without those libraries, the rest of the source code is probably worthless.
If you give away library source code that you've developed over a period of years, you're giving a competitive advantage away - very likely to your competitors.
One thing that I think is often relevant, though - that code probably includes libraries that have had time, effort and even emotions invested in them over a period of years. It would be like inviting thousands of people to read our diaries. | I provide open source code as sort of a community service idea, and as a portfolio idea.
If I was selling software directly - I don't, I'm employed in a position where the company sells the product, not me - I would *more* than happy to sell my software as closed source. Allowing competitors to look over my code and reduce my competitive advantage is not in my best interest, as a rule.
Put another way, I do not consider releasing software as open source to be a moral imperative. |
49,341 | I'm wondering why some people release software as freeware, yet they don't release the source code. Why is that? I can think of some reasons, yet most of them don't make very much sense. Why would you want to keep the source closed but let the program be freely available (free of charge, not free as in freedom)? | 2011/02/18 | [
"https://softwareengineering.stackexchange.com/questions/49341",
"https://softwareengineering.stackexchange.com",
"https://softwareengineering.stackexchange.com/users/12750/"
] | I provide open source code as sort of a community service idea, and as a portfolio idea.
If I was selling software directly - I don't, I'm employed in a position where the company sells the product, not me - I would *more* than happy to sell my software as closed source. Allowing competitors to look over my code and reduce my competitive advantage is not in my best interest, as a rule.
Put another way, I do not consider releasing software as open source to be a moral imperative. | Despite the general bad idea that security-through-obscurity is, in the malware removal field, its a constant cat and mouse game between those of us who write analysis/removal tools, and those writing cleverer and cleverer malware. Sometimes we release a tool freely to users to use, but try to obfuscate the tool's operation in order to make it more difficult for malware authors to defeat the defeat tool :)
This is obviously atypical for most software, but it's something I see all the time. |
55,317,727 | This implementation seems to be working fine ([Stackblitz](https://stackblitz.com/edit/typescript-distinct)):
```
/**
* Returns all the elements that are distinct by the
* `property` value. Note that the implementation uses a `Map<string, E>` to
* index the entities by key. Therefore the more recent occurences
* matching a key instance will overwrite the previous ones.
*
* @param property The name of the property to check for distinct values by.
* @param entities The entities in the array.
*
* @example
* ```
* let todos:Todo = [{ id: 1, "Lets do it!" }, {id: 2, "All done!"}];
* let dtodos:Todo[] = distinct<Todo>(todos, 'id');
*/
export function distinct<E>(entities:E[], property:string):E[] {
let map:Map<string, E> = new Map();
entities.forEach((e:E)=>{
map.set(e[property], e);
});
return Array.from(map.values());
}
```
The only thing is that VSCode draws a red squiggly under the `e[property]` part and the error message is:
>
> Element implicitly has an 'any' type because type '{}' has no index signature.ts(7017)
>
>
>
Is there a way to get rid of that?
Library Holding Implementation
------------------------------
I added the latest suggested implementation to this light weight state manager for objects and entities:
<https://www.npmjs.com/package/@fireflysemantics/slice>
```
npm i @fireflysemantics/slice
...
import {distinct} from '@fireflysemantics/slice/utilities';
```
Demo
----
<https://stackblitz.com/edit/typescript-slice-distinct> | 2019/03/23 | [
"https://Stackoverflow.com/questions/55317727",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1684269/"
] | The Error message is a bit misleading. His problem is, that it can not ensure that `e[property]` is of type `string` as you've defined the `Map`.
Make the key in the Map of type `any` as with so much flexibility you can not determine the type of the value either.
Additionally I'd type the `property` parameter as `keyof E` so TS ensures that I can only paste in valid property names for the type.
```
function distinct<E>(entities:E[], property:keyof E):E[] {
let map:Map<any, E> = new Map();
entities.forEach((e:E)=>{
map.set(e[property], e);
});
return Array.from(map.values());
}
``` | Based on [Thomas](https://stackoverflow.com/users/6567275/thomas)' answer, we can simplify both:
* JavaScript code: constructing the `Map` at once;
* TypeScript typing: adding the `K extends keyof E`, we can cast the tuples (`[E[K], E]`) used as `Map` constructor input parameter and remove the `any` type use.
Here the code:
```
function distinct<E, K extends keyof E>(entities: E[], property: K): E[] {
const entitiesByProperty = new Map(entities.map(e => [e[property], e] as [E[K], E]));
return Array.from(entitiesByProperty.values());
}
```
When calling `distinct()`, there's no need to specify the generic types since they can be inferred. Here's a working example:
```
enum Status { Pending = 0, Done = 1 }
interface Todo { id: number, label: string, status: Status, date?: Date }
const todos: Todo[] = [
{ id: 1, label: 'Task 1', status: Status.Pending },
{ id: 2, label: 'Task 2', status: Status.Pending },
{ id: 1, label: 'Task 1', status: Status.Done },
];
distinct(todos, 'id'); // [{ id: 1, ... status: 1 }, { id: 2, ... status: 0 }]
``` |
17,354 | I am making a donation page in wordpress using civicrm (latest version for wordpress). For someone who comes to the page for the first time I would like to give them the option of signing up for a newsletter.
The issue is that at this stage they have not signed up yet so they are not in the database. I have a profile attached to the bottom of the donation page to allow them to put in their details. Another issue with the search bar is it allow you to find anyones email address just by searching for their name which is also not what I want.
I was wondering how to remove this search bar asking to select someone else. I would prefer for it to go to an anonymous form that doesn't let you search for contacts. See picture below of the yellow bar containing the form.
[](https://i.stack.imgur.com/EEKMJ.png) | 2017/02/22 | [
"https://civicrm.stackexchange.com/questions/17354",
"https://civicrm.stackexchange.com",
"https://civicrm.stackexchange.com/users/4344/"
] | I have a fully working donation page set up in civicrm where:
* there is a Financial Type "Donations" set up in
Administer/civicontribute/financial type.
* Financial Type is set up in the relevant Contribution Page as "Donations".
* A Profile is attached to the contribution page that collects
information in fields such as first name, last name and email
address
The settings in the profile are set to 'Used For' standalone form or directory. 'Search views' are switched off. Advance settings include "Wordpress User account required".
I assume that you have a log in facility set up in the CMS Wordpress and that you have switched on 'Anyone can register' in Wordpress/Settings/General. When a user completes your form, they should then get registered in both Wordpress and CiviCRM.
You may be seeing the Search Bar only because you are personally logged in as Admin. Try looking at the contribution page when not logged in and see what shows.
Hope this helps! | The answer peterb gives is correct. One other possible reason you're seeing this is because the URL you're using has "&cid=0" at the end, which is a special parameter meant to cause the behavior you're seeing. Try removing that parameter if it exists AND accessing the page while not logged in; that should fix you up. |
81,014 | For example:
[](https://i.imgur.com/YnInEl3.gif)
My explanation of what's happening in the gif: When a title has been hovered for a short amount of time, that title expands, pushing other content off the screen and grabbing the user's attention.
I've read that taking actions on hover is not desirable, rather only take action when the user takes explicit action (such as a click). Is that a principle and would it apply in this case? | 2015/07/05 | [
"https://ux.stackexchange.com/questions/81014",
"https://ux.stackexchange.com",
"https://ux.stackexchange.com/users/68212/"
] | As always it depends. The reason it's not a best practice is because a hover state can be attained in multiple unintended ways, including scrolling as in the example you listed.
In the case of Netflix, they undoubtedly knew the consequences. That's likely why the hover state has such a short timer before activating, as well as why each tile only expands slightly. That way users get additional information on hover without significantly increasing the error rate (through bad accidental clicks).
Furthermore, I'd postulate that Netflix wouldn't mind if users made an error too much. They might find a show/movie they want to watch. The company's model already has users paying before using the service and no one will seriously leave because they accidentally started playing the wrong content. Is it an intended "happy accident"? Probably not, but I wouldn't doubt that if Netflix were to attempt to do so, they would have a mechanism to track how often that happens, along with the rate of continued viewing. | Dark patterns FTW?
==================
The problem with moving things around on hover is that the targets jump. This isn't really a problem for the item being expanded. As Jamezrp pointed out, that may be intentional. Maybe Netflix is using a dark pattern to try to increase engagement. I say *dark* because it's not an ideal interaction, but Netflix may have found the "negative" side effect to work in their or their users' favor.
Rule of thumb
=============
In general, you don't want to do this kind of expansion because it creates a certain amount of disorientation. If the thing being expanded (intentionally or not) is just one option among many in the user's consideration set, then they'll have to stumble a bit if they decide to try another option before committing to the click.
A better option
===============
If you're tempted to use a hover pattern (or it's tap equivalent in a touch UI) to provide expanded info, there is a better way. Rather than distorting the whole environment, just change the state of the item in question. In the Netflix example, the additional info could simply be layered over the cover image without any expansion. The cover attracted attention and now it becomes simply a backdrop.
So this ...
[](https://i.stack.imgur.com/0npk6.png)
Becomes this ...
[](https://i.stack.imgur.com/hJmmb.png) |
81,014 | For example:
[](https://i.imgur.com/YnInEl3.gif)
My explanation of what's happening in the gif: When a title has been hovered for a short amount of time, that title expands, pushing other content off the screen and grabbing the user's attention.
I've read that taking actions on hover is not desirable, rather only take action when the user takes explicit action (such as a click). Is that a principle and would it apply in this case? | 2015/07/05 | [
"https://ux.stackexchange.com/questions/81014",
"https://ux.stackexchange.com",
"https://ux.stackexchange.com/users/68212/"
] | Is hover the *only* way you can find out that information? Would someone on a tablet, or someone using keyboard without a mouse be able to find that full information without having to select that item fully?
If hover is just one way to display it - an enhancement, so to speak - then it is OK. But if you *have* to use your mouse and hover over the item in order to find out the details, or you have to actually select and start watching the film before you get those details, then no, it isn't OK.
Never penalise people who can't / don't use a mouse. Use hover for enhancements, but never for *the way*. | Dark patterns FTW?
==================
The problem with moving things around on hover is that the targets jump. This isn't really a problem for the item being expanded. As Jamezrp pointed out, that may be intentional. Maybe Netflix is using a dark pattern to try to increase engagement. I say *dark* because it's not an ideal interaction, but Netflix may have found the "negative" side effect to work in their or their users' favor.
Rule of thumb
=============
In general, you don't want to do this kind of expansion because it creates a certain amount of disorientation. If the thing being expanded (intentionally or not) is just one option among many in the user's consideration set, then they'll have to stumble a bit if they decide to try another option before committing to the click.
A better option
===============
If you're tempted to use a hover pattern (or it's tap equivalent in a touch UI) to provide expanded info, there is a better way. Rather than distorting the whole environment, just change the state of the item in question. In the Netflix example, the additional info could simply be layered over the cover image without any expansion. The cover attracted attention and now it becomes simply a backdrop.
So this ...
[](https://i.stack.imgur.com/0npk6.png)
Becomes this ...
[](https://i.stack.imgur.com/hJmmb.png) |
10,986,968 | We are doing UI screens for WPF application on Laptop But we are planing to give demo on 22"inch Monitor. Here Dimensions are getting changed when we see UI screens on 22"inch Monitor. How can I make same UI screen apperance on both Laptop and 22" inch Monitor? please help me here.... | 2012/06/11 | [
"https://Stackoverflow.com/questions/10986968",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1420601/"
] | Are you using an absolute layout, where specific X/Y/Height/Width is being defined for every control? If you use other types of layouts, they are more relative to window height/width and automatically handle these issues. | Wrap your entire application in the [Viewbox](http://msdn.microsoft.com/en-us/library/system.windows.controls.viewbox.aspx) control. As long as you don't have rasterized images, nothing will look stretched. |
4,103,432 | I am a bit confused on how to create a overloaded constructor.
Below is my assignment:
>
> Include the following:
>
> i) A default constructor and an overloaded constructor.
>
> ii) Accessor and mutator methods for each attribute.
>
>
>
Below is my pseudocode. From what I created so far I assume a OVERLOADED constructor is a constructor that has parameters but I am not absolutely sure about that.
```
public class Employee
// declarations
private employeeid : integer
private employeesalary : integer
public Employee ()
employeeid = 0
employeesalary = 0
return
public Employee (id : integer, salary : integer)
employeeid = id
employeesalary = salary
return
public num getemployeeid ( )
return employeeid
public num getemployeesalary ( )
return employeesalary
public String getnumberofaccidents ( )
return numberofaccidents
public void setCustomeraget(integer id)
employeeid = id
return
public void setEmployeesalary (integer salary)
employeesalary = salary
return
End Class
```
Example:
```
public policy holder (nr : num, age : num, nracct : num)
set policynumber (nr : num)
set customerage (age : num)
set NumberAccident (nrAcct)
``` | 2010/11/05 | [
"https://Stackoverflow.com/questions/4103432",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/485217/"
] | I always hated psudocode *in classroom settings* for this very reason. How much do you write? What am I allowed to leave off, or in other words, what are we taking for granted here?
As far as the overloaded function, it looks as though you understand it just fine.
Here is your default constructor that doesn't take any arguments:
```
public Employee ()
```
And here is your other constructor that does take arguments.
```
public Employee (id : integer, salary : integer)
```
So, to answer your original question, you are correct. An overloaded constructor is simply having multiple constructors that take different arguments. In your case, I can create the class by calling the constructor two different ways:
```
Employee myEmployee = new Employee();
```
OR
```
Employee myEmployee = new Employee(12, 64500);
```
In programmer speak you have an overloaded constructor.
As for the **rest** of your code:
One thing you are doing wrong is that you have not declared "numberofaccidents". Like so:
```
private employeeid : integer
private employeesalary : integer
private numberofaccidents : integer
```
Think of accessors and mutators as "getters" and "setters". You might want to change "setCustomeraget" to "setCustomerId" though. Also, there is no "setnumberofaccidents". Try and pair up your getters and setters so that you can always tell if you are missing one. Something like this:
```
public num getSalary()
return employeesalary
public void setSalary(integer salary)
employeesalary = salary
``` | Yes. You code looks like its on the right lines. However shouldn't the methods/functions be part of the class?
* An overload X is an X with different set of parameters.
* An Accessor is a function (sometimes called a property) that gets something from the object.
* A mutator is a function (sometimes called a property) that changes some aspect of the object. |
35,920,448 | `$table->text('company_logo')->nullable();`
I'm trying to create a migration to store Base 64 Encoded image in my My SQL database. I'm not if what I have is good enough.
Is what I have good enough ? How do I know it ? | 2016/03/10 | [
"https://Stackoverflow.com/questions/35920448",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4480164/"
] | You can also use the `dplyr` package to aggregate the data:
```
library(dplyr)
mean_data <- group_by(data, gender, week) %>%
summarise(motivation = mean(motivation, na.rm = TRUE))
```
You can use `na.omit()` to get rid of the `NA` values as follows:
```
library(ggplot2)
ggplot(na.omit(mean_data), aes(x = week, y = motivation, colour = gender)) +
geom_point() + geom_line()
```
[](https://i.stack.imgur.com/F7IHh.png)
There is no need here to explicitly use the `group` aesthetic because `ggplot` will automatically group the lines by the categorical variables in your plot. And the only categorical variable you have is `gender`. (See [this answer](https://stackoverflow.com/a/10358388/4303162) for more information). | You almost certainly have to make sure those grouping variables are factors.
I'm not quite sure what you want, but here's a shot...
```
library("ggplot2")
df <- read.table(textConnection("ID gender week class motivation
1 male 0 1 100
1 male 6 1 120
1 male 10 1 130
2 female 0 1 90
2 female 6 1 NA
2 female 10 1 117
3 male 0 2 89
3 male 6 2 112
3 male 10 2 NA"), header=TRUE, stringsAsFactors=FALSE)
df2 <- aggregate(df$motivation, by=list(df$gender, df$week),
function(x)mean(x, na.rm=TRUE))
names(df2) <- c("gender", "week", "avg")
df2$gender <- factor(df2$gender)
ggplot(data = df2[!is.na(df2$avg), ],
aes(x = week, y = avg, group=gender, color=gender)) +
geom_point()+geom_line()
```
[](https://i.stack.imgur.com/YF0B2.png) |
35,920,448 | `$table->text('company_logo')->nullable();`
I'm trying to create a migration to store Base 64 Encoded image in my My SQL database. I'm not if what I have is good enough.
Is what I have good enough ? How do I know it ? | 2016/03/10 | [
"https://Stackoverflow.com/questions/35920448",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4480164/"
] | You can also use the `dplyr` package to aggregate the data:
```
library(dplyr)
mean_data <- group_by(data, gender, week) %>%
summarise(motivation = mean(motivation, na.rm = TRUE))
```
You can use `na.omit()` to get rid of the `NA` values as follows:
```
library(ggplot2)
ggplot(na.omit(mean_data), aes(x = week, y = motivation, colour = gender)) +
geom_point() + geom_line()
```
[](https://i.stack.imgur.com/F7IHh.png)
There is no need here to explicitly use the `group` aesthetic because `ggplot` will automatically group the lines by the categorical variables in your plot. And the only categorical variable you have is `gender`. (See [this answer](https://stackoverflow.com/a/10358388/4303162) for more information). | Another possibility is using `stat_summary`, so you can do it only with **ggplot**.
```
ggplot(data = DataRlong, aes(x = week, y = motivation, group = gender)) +
stat_summary(geom = "line", fun.y = mean)
``` |
13,279,303 | Spent quite some time on this forum looking at answers similar to my problem but couldn't find the one that matched my case.
I have an HTML form that I am submitting via javascript to my aspx page.
```
function Submit()
{
document.MyFormName.action = 'StreamPDF.aspx'
document.MyFormName.submit();
}
```
The StreamPDF.aspx returns application/pdf which presents the user with the open/save dialog. The PDF generation takes quite a while and the user needs to be presented with the 'wait' cursor. This is a simple aspx page (No MVC, no other plugins).
So my only option is to use javascript to post the data.The closest answer was [this](http://johnculviner.com/post/2012/03/22/Ajax-like-feature-rich-file-downloads-with-jQuery-File-Download.aspx).
I took the idea from this link and just before I submit the iframe, I am setting the wait cursor. But I have no way of knowing whether the PDF came back since I can't have cookies sent to the browser. It's my limitation. So I am still at square 1. Any help would be greatly appreciated. | 2012/11/07 | [
"https://Stackoverflow.com/questions/13279303",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1040648/"
] | can you give a try with `blockui`
<http://forums.asp.net/p/1620326/4457438.aspx/1?Re+Show+wait+message+on+submit> | After several attempts to get this working, I realized that the only non-intrusive approach to fix this is the suggestion in the link I posted. Have the server notify the client that the file is streamed by setting a cookie which is deleted by the client script.
Thanks for all your responses. |
2,376,430 | My application is raising an unauthorized access error. While running my application, I try to access a directory in the following location: Application.UserAppDataPath.
The Problem: It says I do not have permission to access the Application.UserAppDataPath directory
Is there a way to set permissions within my application source code?
Something like:
```
Application.UserAppDataPath.SetPermissions()
``` | 2010/03/04 | [
"https://Stackoverflow.com/questions/2376430",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/210200/"
] | Looking at your comment, you say this is your code:
```
StreamReader sr = new StreamReader(Application.UserAppDataPath);
```
`Application.UserAppDataPath` is a **directory**, not a *file*. If you try to open that directly, it's the same as trying to open a file one level *below* the AppData folder, which you really don't have permission to do.
Use `Path.Combine` to construct a path to a *file inside* the AppData folder, i.e.
```
string fileName = Path.Combine(Application.UserAppDataPath, "settings.xml");
StreamReader sr = new StreamReader(fileName);
```
Of course this is just an example - in reality you should probably be using a sub-folder inside AppData specific to your application. | Its probably a UAC issue, Try running your application as an elevated process, and see if the error persists |
112,464 | I have SharePoint list with more than 1000 items(ID's).
I'm dumping list with *BASH* script to my server with *curl*:
`curl --ntlm -u $curl_account $SITE -o $output_file 2>/dev/null`
and I get only 1000 ID's to my *$output\_file*. Is there are some limits or smth to do, that I could get all items?
Thanks for any info :) | 2014/08/20 | [
"https://sharepoint.stackexchange.com/questions/112464",
"https://sharepoint.stackexchange.com",
"https://sharepoint.stackexchange.com/users/31504/"
] | I dont see any limitation on data retrieving using curl. is it get only 1st 1000 items only?
Do you have any filter on your default view in list.
also check this blog, he used curl to print the list data.
<http://blog.vgrem.com/tag/curl/>
<http://justinlee.sg/2011/01/05/crud-operations-on-microsoft-sharepoint-2010-odata-lists-with-curl/> | Try and do it in a loop, record the last id retrieved after each 1000, then add a filter to the call i.e. where ID > lastid. do this until the number of items retrieved is < 1000 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.