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
|
---|---|---|---|---|---|
31,173,307 | What are the differences between this:
```
if(a && b)
{
//code
}
```
and this:
```
if(a)
{
if(b)
{
//code
}
}
```
From what I know `b` will only get evaluated in the first code block if `a` is true, and the second code block would be the same thing.
Are there any benefits of using one over the other? Code execution time? memory? etc. | 2015/07/01 | [
"https://Stackoverflow.com/questions/31173307",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4714970/"
] | It makes a difference if you have an **else** associated with each **if**.
```
if(a && b)
{
//do something if both a and b evaluate to true
} else {
//do something if either of a or b is false
}
```
and this:
```
if(a)
{
if(b)
{
//do something if both a and b are true
} else {
//do something if only a is true
}
} else {
if(b)
{
//do something if only b is true
} else {
//do something if both a and b are false
}
}
``` | there shouldn't be a difference, but in readability I would prefer the first one, because it is less verbose and less indented. |
31,173,307 | What are the differences between this:
```
if(a && b)
{
//code
}
```
and this:
```
if(a)
{
if(b)
{
//code
}
}
```
From what I know `b` will only get evaluated in the first code block if `a` is true, and the second code block would be the same thing.
Are there any benefits of using one over the other? Code execution time? memory? etc. | 2015/07/01 | [
"https://Stackoverflow.com/questions/31173307",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4714970/"
] | They get compiled to the same bytecode. No performance difference.
Readability is the only difference. As a huge generalization, short-circuiting looks better but nesting is slightly clearer. It really boils down to the specific use case. I'd typically short-circuit.
---
I tried this out. Here's the code:
```
public class Test {
public static void main(String[] args) {
boolean a = 1>0;
boolean b = 0>1;
if (a && b)
System.out.println(5);
if (a)
if (b)
System.out.println(5);
}
}
```
This compiles to:
```
0: iconst_1
1: istore_1
2: iconst_0
3: istore_2
4: iload_1
5: ifeq 19
8: iload_2
9: ifeq 19
12: getstatic #2
15: iconst_5
16: invokevirtual #3
19: iload_1
20: ifeq 34
23: iload_2
24: ifeq 34
27: getstatic #2
30: iconst_5
31: invokevirtual #3
34: return
```
Note how this block repeats twice:
```
4: iload_1
5: ifeq 19
8: iload_2
9: ifeq 19
12: getstatic #2
15: iconst_5
16: invokevirtual #3
```
Same bytecode both times. | It makes a difference if you have an **else** associated with each **if**.
```
if(a && b)
{
//do something if both a and b evaluate to true
} else {
//do something if either of a or b is false
}
```
and this:
```
if(a)
{
if(b)
{
//do something if both a and b are true
} else {
//do something if only a is true
}
} else {
if(b)
{
//do something if only b is true
} else {
//do something if both a and b are false
}
}
``` |
403,709 | I have a map $f(t,g,h)$ where $f:[0,1]\times C^1 \times C^1 \to \mathbb{R}.$
I want to define $$F(t,g,h) = \frac{d}{dt}f(t,g,h)$$
where $g$ and $h$ have no $t$-dependence in them. So $g(x) = t^2x$ would not be admissible if you want to calculate what $F$ is. How do I write this properly? Is it correct to write instead
>
> Define $F$ by $F(t,\cdot,\cdot) = \frac{d}{dt}f(t,\cdot,\cdot)$.
>
>
>
But there is some ambiguity in the arguments. What is the best way to write it? | 2013/05/27 | [
"https://math.stackexchange.com/questions/403709",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/61615/"
] | Without words... Well, nearly without words...
 | For $0\leq\phi\leq{\pi\over2}$ consider the two points $(\cos \phi,\pm\sin \phi)$ on the unit circle. Their distance is $2\sin \phi$, while the length of the circular arc between them is $2\phi$. Therefore we have
$$2\sin\phi\leq 2\phi\qquad(0\leq\phi\leq{\pi\over2})\ .$$
Putting $\phi:=|x|$ we obtain
$$|\sin x|\leq |x|\qquad(0\leq|x|\leq{\pi\over2})\ ,$$
and for $|x|\geq{\pi\over2}$ one obviously has $|x|\geq{\pi\over2}>1\geq|\sin x|$. |
403,709 | I have a map $f(t,g,h)$ where $f:[0,1]\times C^1 \times C^1 \to \mathbb{R}.$
I want to define $$F(t,g,h) = \frac{d}{dt}f(t,g,h)$$
where $g$ and $h$ have no $t$-dependence in them. So $g(x) = t^2x$ would not be admissible if you want to calculate what $F$ is. How do I write this properly? Is it correct to write instead
>
> Define $F$ by $F(t,\cdot,\cdot) = \frac{d}{dt}f(t,\cdot,\cdot)$.
>
>
>
But there is some ambiguity in the arguments. What is the best way to write it? | 2013/05/27 | [
"https://math.stackexchange.com/questions/403709",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/61615/"
] | For $0\leq\phi\leq{\pi\over2}$ consider the two points $(\cos \phi,\pm\sin \phi)$ on the unit circle. Their distance is $2\sin \phi$, while the length of the circular arc between them is $2\phi$. Therefore we have
$$2\sin\phi\leq 2\phi\qquad(0\leq\phi\leq{\pi\over2})\ .$$
Putting $\phi:=|x|$ we obtain
$$|\sin x|\leq |x|\qquad(0\leq|x|\leq{\pi\over2})\ ,$$
and for $|x|\geq{\pi\over2}$ one obviously has $|x|\geq{\pi\over2}>1\geq|\sin x|$. | The sine function is an odd function, so it suffices to prove the inequality for nonnegative $x$.
For $0\le x\le 1$, rewrite $\sin x$ in two different ways:
\begin{align\*}
\sin x &=\sum\_{n=0}^\infty\left(\frac{x^{4n+1}}{(4n+1)!} - \frac{x^{4n+3}}{(4n+3)!}\right)\tag{1}\\
&=x - \sum\_{n=0}^\infty\left(\frac{x^{4n+3}}{(4n+3)!} - \frac{x^{4n+5}}{(4n+5)!}\right).\tag{2}
\end{align\*}
Since each bracket term in the two infinite series is nonnegative, $(1)$ implies that $\sin x\ge0$ and $(2)$ implies that $\sin x\le x$. Therefore $|\sin x|\le |x|$.
For $x>1$, note that $\sin x = |\operatorname{imag}(e^{ix})| \le |e^{ix}|$. If we can show that $|e^{ix}|\le1$, we are done. One way to prove this is to show that $\overline{e^{ix}}=e^{-ix}$ (easy) and $e^{ix}e^{-ix}=1$ (theorems about multiplication of absolutely convergent power series, i.e. convergence of Cauchy product, is needed here). |
403,709 | I have a map $f(t,g,h)$ where $f:[0,1]\times C^1 \times C^1 \to \mathbb{R}.$
I want to define $$F(t,g,h) = \frac{d}{dt}f(t,g,h)$$
where $g$ and $h$ have no $t$-dependence in them. So $g(x) = t^2x$ would not be admissible if you want to calculate what $F$ is. How do I write this properly? Is it correct to write instead
>
> Define $F$ by $F(t,\cdot,\cdot) = \frac{d}{dt}f(t,\cdot,\cdot)$.
>
>
>
But there is some ambiguity in the arguments. What is the best way to write it? | 2013/05/27 | [
"https://math.stackexchange.com/questions/403709",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/61615/"
] | Without words... Well, nearly without words...
 | The sine function is an odd function, so it suffices to prove the inequality for nonnegative $x$.
For $0\le x\le 1$, rewrite $\sin x$ in two different ways:
\begin{align\*}
\sin x &=\sum\_{n=0}^\infty\left(\frac{x^{4n+1}}{(4n+1)!} - \frac{x^{4n+3}}{(4n+3)!}\right)\tag{1}\\
&=x - \sum\_{n=0}^\infty\left(\frac{x^{4n+3}}{(4n+3)!} - \frac{x^{4n+5}}{(4n+5)!}\right).\tag{2}
\end{align\*}
Since each bracket term in the two infinite series is nonnegative, $(1)$ implies that $\sin x\ge0$ and $(2)$ implies that $\sin x\le x$. Therefore $|\sin x|\le |x|$.
For $x>1$, note that $\sin x = |\operatorname{imag}(e^{ix})| \le |e^{ix}|$. If we can show that $|e^{ix}|\le1$, we are done. One way to prove this is to show that $\overline{e^{ix}}=e^{-ix}$ (easy) and $e^{ix}e^{-ix}=1$ (theorems about multiplication of absolutely convergent power series, i.e. convergence of Cauchy product, is needed here). |
65,618,221 | Why isn't C/C++ called platform independent like java when the same source code written in C/C++ can be made to run on different operating systems by different compilers, just like JVM is used in java.
Isn't different compilers and JVM doing same thing and achieving platform independence. | 2021/01/07 | [
"https://Stackoverflow.com/questions/65618221",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11815436/"
] | >
> Isn't different compilers and JVM doing same thing and achieving platform independence.
>
>
>
The JVM per se is the platform. It is abstracting away, whether it is ARM/AMD64/...
C/C++ is getting compiled. It may only run on the processor(family) that it was compiled for.
You can't just take a binary for MIPS and execute it on ARM.
Compare it:
```
[C(++)]
|
v
[Processor]
```
vs
```
[Java (Classfiles)]
|
v
[JVM] #Abstraction layer
|
v
[Processor]
``` | C++ language itself doesn't assume any specific platform, so in that sense it is platform independent. |
65,618,221 | Why isn't C/C++ called platform independent like java when the same source code written in C/C++ can be made to run on different operating systems by different compilers, just like JVM is used in java.
Isn't different compilers and JVM doing same thing and achieving platform independence. | 2021/01/07 | [
"https://Stackoverflow.com/questions/65618221",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11815436/"
] | >
> Isn't different compilers and JVM doing same thing and achieving platform independence.
>
>
>
Not really. Your Java program is running *within* the JVM, which acts as a translation layer between the Java byte code and the native machine code. It *hides* the platform-specific details from the Java application code.
This is not the case with C. C code (typically) runs natively, so there is no translation layer isolating it from platform-specific details. Your C code can be directly affected by platform-specific differences (word sizes, type representations, byte order, etc.).
A *strictly conforming* C program, which uses nothing outside of the standard library and makes no assumptions about type sizes or representation beyond the minimums guaranteed by the language standard, should exhibit the same behavior on any platform for which it is compiled. All you need to do is recompile it for the target platform.
The problem is that most useful real-world C and C++ code *isn't* strictly conforming; to do almost anything interesting you have to rely on third-party and system-specific libraries and utilities, and as soon as you do you lose that platform independence. I *could* write a command-line tool manipulates files in the local file system that would run on Windows and MacOS and Linux and VMS and MPE; all I would need to do is recompile it for the different targets. However, if I wanted to write something GUI-driven, or something that communicated over a network, or something that had to navigate the file system, or anything like that, then I'm reliant on system-specific tools and I *can't* just rebuild the code on different platforms. | In case of C or C++ (language that are not platform independent), the compiler generates an .exe file which is OS dependent. When we try to run this .exe file on another OS it does not run, since it is OS dependent and hence is not compatible with the other OS. |
65,618,221 | Why isn't C/C++ called platform independent like java when the same source code written in C/C++ can be made to run on different operating systems by different compilers, just like JVM is used in java.
Isn't different compilers and JVM doing same thing and achieving platform independence. | 2021/01/07 | [
"https://Stackoverflow.com/questions/65618221",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11815436/"
] | >
> Isn't different compilers and JVM doing same thing and achieving platform independence.
>
>
>
Not really. Your Java program is running *within* the JVM, which acts as a translation layer between the Java byte code and the native machine code. It *hides* the platform-specific details from the Java application code.
This is not the case with C. C code (typically) runs natively, so there is no translation layer isolating it from platform-specific details. Your C code can be directly affected by platform-specific differences (word sizes, type representations, byte order, etc.).
A *strictly conforming* C program, which uses nothing outside of the standard library and makes no assumptions about type sizes or representation beyond the minimums guaranteed by the language standard, should exhibit the same behavior on any platform for which it is compiled. All you need to do is recompile it for the target platform.
The problem is that most useful real-world C and C++ code *isn't* strictly conforming; to do almost anything interesting you have to rely on third-party and system-specific libraries and utilities, and as soon as you do you lose that platform independence. I *could* write a command-line tool manipulates files in the local file system that would run on Windows and MacOS and Linux and VMS and MPE; all I would need to do is recompile it for the different targets. However, if I wanted to write something GUI-driven, or something that communicated over a network, or something that had to navigate the file system, or anything like that, then I'm reliant on system-specific tools and I *can't* just rebuild the code on different platforms. | C++ language itself doesn't assume any specific platform, so in that sense it is platform independent. |
65,618,221 | Why isn't C/C++ called platform independent like java when the same source code written in C/C++ can be made to run on different operating systems by different compilers, just like JVM is used in java.
Isn't different compilers and JVM doing same thing and achieving platform independence. | 2021/01/07 | [
"https://Stackoverflow.com/questions/65618221",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11815436/"
] | >
> Isn't different compilers and JVM doing same thing and achieving platform independence.
>
>
>
Not really. Your Java program is running *within* the JVM, which acts as a translation layer between the Java byte code and the native machine code. It *hides* the platform-specific details from the Java application code.
This is not the case with C. C code (typically) runs natively, so there is no translation layer isolating it from platform-specific details. Your C code can be directly affected by platform-specific differences (word sizes, type representations, byte order, etc.).
A *strictly conforming* C program, which uses nothing outside of the standard library and makes no assumptions about type sizes or representation beyond the minimums guaranteed by the language standard, should exhibit the same behavior on any platform for which it is compiled. All you need to do is recompile it for the target platform.
The problem is that most useful real-world C and C++ code *isn't* strictly conforming; to do almost anything interesting you have to rely on third-party and system-specific libraries and utilities, and as soon as you do you lose that platform independence. I *could* write a command-line tool manipulates files in the local file system that would run on Windows and MacOS and Linux and VMS and MPE; all I would need to do is recompile it for the different targets. However, if I wanted to write something GUI-driven, or something that communicated over a network, or something that had to navigate the file system, or anything like that, then I'm reliant on system-specific tools and I *can't* just rebuild the code on different platforms. | >
> Isn't different compilers and JVM doing same thing and achieving platform independence.
>
>
>
The JVM per se is the platform. It is abstracting away, whether it is ARM/AMD64/...
C/C++ is getting compiled. It may only run on the processor(family) that it was compiled for.
You can't just take a binary for MIPS and execute it on ARM.
Compare it:
```
[C(++)]
|
v
[Processor]
```
vs
```
[Java (Classfiles)]
|
v
[JVM] #Abstraction layer
|
v
[Processor]
``` |
65,618,221 | Why isn't C/C++ called platform independent like java when the same source code written in C/C++ can be made to run on different operating systems by different compilers, just like JVM is used in java.
Isn't different compilers and JVM doing same thing and achieving platform independence. | 2021/01/07 | [
"https://Stackoverflow.com/questions/65618221",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11815436/"
] | It's not the language itself that is platform dependent. It's possible to compile both C and C++ for JVM, but it's not very common to do so. [Compiling C++ for the JVM](https://stackoverflow.com/q/4221605/6699433)
In the same way, it is possible to compile Java for a specific target instead of JVM. [Compiling java source code to native exe](https://stackoverflow.com/q/28249838/6699433)
But Java and JVM are both designed to work together, so that combination is very natural to use.
C is designed to be very close to the hardware. There's not really a reason to use C if your target is JVM. Then use Java instead.
In theory, you can compile ANY language for ANY target, as long as the target is turing complete.
Sidenote: Don't write "C/C++". They are completely different languages. | In case of C or C++ (language that are not platform independent), the compiler generates an .exe file which is OS dependent. When we try to run this .exe file on another OS it does not run, since it is OS dependent and hence is not compatible with the other OS. |
65,618,221 | Why isn't C/C++ called platform independent like java when the same source code written in C/C++ can be made to run on different operating systems by different compilers, just like JVM is used in java.
Isn't different compilers and JVM doing same thing and achieving platform independence. | 2021/01/07 | [
"https://Stackoverflow.com/questions/65618221",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11815436/"
] | It's not the language itself that is platform dependent. It's possible to compile both C and C++ for JVM, but it's not very common to do so. [Compiling C++ for the JVM](https://stackoverflow.com/q/4221605/6699433)
In the same way, it is possible to compile Java for a specific target instead of JVM. [Compiling java source code to native exe](https://stackoverflow.com/q/28249838/6699433)
But Java and JVM are both designed to work together, so that combination is very natural to use.
C is designed to be very close to the hardware. There's not really a reason to use C if your target is JVM. Then use Java instead.
In theory, you can compile ANY language for ANY target, as long as the target is turing complete.
Sidenote: Don't write "C/C++". They are completely different languages. | C++ language itself doesn't assume any specific platform, so in that sense it is platform independent. |
65,618,221 | Why isn't C/C++ called platform independent like java when the same source code written in C/C++ can be made to run on different operating systems by different compilers, just like JVM is used in java.
Isn't different compilers and JVM doing same thing and achieving platform independence. | 2021/01/07 | [
"https://Stackoverflow.com/questions/65618221",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11815436/"
] | >
> Isn't different compilers and JVM doing same thing and achieving platform independence.
>
>
>
Not really. Your Java program is running *within* the JVM, which acts as a translation layer between the Java byte code and the native machine code. It *hides* the platform-specific details from the Java application code.
This is not the case with C. C code (typically) runs natively, so there is no translation layer isolating it from platform-specific details. Your C code can be directly affected by platform-specific differences (word sizes, type representations, byte order, etc.).
A *strictly conforming* C program, which uses nothing outside of the standard library and makes no assumptions about type sizes or representation beyond the minimums guaranteed by the language standard, should exhibit the same behavior on any platform for which it is compiled. All you need to do is recompile it for the target platform.
The problem is that most useful real-world C and C++ code *isn't* strictly conforming; to do almost anything interesting you have to rely on third-party and system-specific libraries and utilities, and as soon as you do you lose that platform independence. I *could* write a command-line tool manipulates files in the local file system that would run on Windows and MacOS and Linux and VMS and MPE; all I would need to do is recompile it for the different targets. However, if I wanted to write something GUI-driven, or something that communicated over a network, or something that had to navigate the file system, or anything like that, then I'm reliant on system-specific tools and I *can't* just rebuild the code on different platforms. | The role of JVM in the independent platform is that it acts as a virtual processor. when we used c/c++ to compiler different processor converts the source code into a different binary pattern that's why there are not platform-independent. |
65,618,221 | Why isn't C/C++ called platform independent like java when the same source code written in C/C++ can be made to run on different operating systems by different compilers, just like JVM is used in java.
Isn't different compilers and JVM doing same thing and achieving platform independence. | 2021/01/07 | [
"https://Stackoverflow.com/questions/65618221",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11815436/"
] | In case of C or C++ (language that are not platform independent), the compiler generates an .exe file which is OS dependent. When we try to run this .exe file on another OS it does not run, since it is OS dependent and hence is not compatible with the other OS. | The role of JVM in the independent platform is that it acts as a virtual processor. when we used c/c++ to compiler different processor converts the source code into a different binary pattern that's why there are not platform-independent. |
65,618,221 | Why isn't C/C++ called platform independent like java when the same source code written in C/C++ can be made to run on different operating systems by different compilers, just like JVM is used in java.
Isn't different compilers and JVM doing same thing and achieving platform independence. | 2021/01/07 | [
"https://Stackoverflow.com/questions/65618221",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11815436/"
] | >
> Isn't different compilers and JVM doing same thing and achieving platform independence.
>
>
>
Not really. Your Java program is running *within* the JVM, which acts as a translation layer between the Java byte code and the native machine code. It *hides* the platform-specific details from the Java application code.
This is not the case with C. C code (typically) runs natively, so there is no translation layer isolating it from platform-specific details. Your C code can be directly affected by platform-specific differences (word sizes, type representations, byte order, etc.).
A *strictly conforming* C program, which uses nothing outside of the standard library and makes no assumptions about type sizes or representation beyond the minimums guaranteed by the language standard, should exhibit the same behavior on any platform for which it is compiled. All you need to do is recompile it for the target platform.
The problem is that most useful real-world C and C++ code *isn't* strictly conforming; to do almost anything interesting you have to rely on third-party and system-specific libraries and utilities, and as soon as you do you lose that platform independence. I *could* write a command-line tool manipulates files in the local file system that would run on Windows and MacOS and Linux and VMS and MPE; all I would need to do is recompile it for the different targets. However, if I wanted to write something GUI-driven, or something that communicated over a network, or something that had to navigate the file system, or anything like that, then I'm reliant on system-specific tools and I *can't* just rebuild the code on different platforms. | It's not the language itself that is platform dependent. It's possible to compile both C and C++ for JVM, but it's not very common to do so. [Compiling C++ for the JVM](https://stackoverflow.com/q/4221605/6699433)
In the same way, it is possible to compile Java for a specific target instead of JVM. [Compiling java source code to native exe](https://stackoverflow.com/q/28249838/6699433)
But Java and JVM are both designed to work together, so that combination is very natural to use.
C is designed to be very close to the hardware. There's not really a reason to use C if your target is JVM. Then use Java instead.
In theory, you can compile ANY language for ANY target, as long as the target is turing complete.
Sidenote: Don't write "C/C++". They are completely different languages. |
65,618,221 | Why isn't C/C++ called platform independent like java when the same source code written in C/C++ can be made to run on different operating systems by different compilers, just like JVM is used in java.
Isn't different compilers and JVM doing same thing and achieving platform independence. | 2021/01/07 | [
"https://Stackoverflow.com/questions/65618221",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11815436/"
] | It's not the language itself that is platform dependent. It's possible to compile both C and C++ for JVM, but it's not very common to do so. [Compiling C++ for the JVM](https://stackoverflow.com/q/4221605/6699433)
In the same way, it is possible to compile Java for a specific target instead of JVM. [Compiling java source code to native exe](https://stackoverflow.com/q/28249838/6699433)
But Java and JVM are both designed to work together, so that combination is very natural to use.
C is designed to be very close to the hardware. There's not really a reason to use C if your target is JVM. Then use Java instead.
In theory, you can compile ANY language for ANY target, as long as the target is turing complete.
Sidenote: Don't write "C/C++". They are completely different languages. | The role of JVM in the independent platform is that it acts as a virtual processor. when we used c/c++ to compiler different processor converts the source code into a different binary pattern that's why there are not platform-independent. |
3,816,331 | I have 3 ways I want to filter:
1. by name
2. by list
3. and show all
I'm using ASP.NET 3.5 and SQL Server 2008. Using ADO.NET and stored procs.
I'm passing my list as a table valued parameter (but I'm testing with a table variable) and the name as a nvarchar. I have "show all" as ISNULL(@var, column) = column. Obviously the way I'm querying this is not taking advantage of short circuiting or my understanding of how WHERE clauses work is lacking. What's happening is if I make @var = 'some string' and insert a null to the table variable, then it filters correctly. If I make @var = null and insert 'some string' to the table variable, then I get every record, where I should be getting 'some string'.
The code:
```
declare @resp1 nvarchar(32)
set @resp1 = null
declare @usersTable table
(responsible nvarchar(32))
--insert into @usersTable (responsible) values (null)
insert into @usersTable (responsible) values ('ssimpson')
insert into @usersTable (responsible) values ('kwilcox')
select uT.responsible, jsq.jobnumber, jsq.qid, aq.question, aq.section, aq.seq, answers.*
from answers
inner join jobno_specific_questions as jsq on answers.jqid = jsq.jqid
inner join apqp_questions as aq on jsq.qid = aq.qid
left join @usersTable as uT on uT.responsible = answers.responsible
where answers.taskAction = 1 and (uT.responsible is not null or ISNULL(@resp1, Answers.responsible) = Answers.responsible)
order by aq.section, jsq.jobnumber, answers.priority, aq.seq
```
This is what I've come up with. It's ugly though....
```
declare @resp1 nvarchar(32)
set @resp1 = 'rrox'
declare @filterPick int
declare @usersTable table
(responsible nvarchar(32))
insert into @usersTable (responsible) values (null)
--insert into @usersTable (responsible) values ('ssimpson')
--insert into @usersTable (responsible) values ('kwilcox')
if @resp1 is null
begin
set @filterPick = 2
end
else
begin
set @filterPick = 1
end
select uT.responsible, jsq.jobnumber, jsq.qid, aq.question, aq.section, aq.seq, answers.*
from answers
inner join jobno_specific_questions as jsq on answers.jqid = jsq.jqid
inner join apqp_questions as aq on jsq.qid = aq.qid
left join @usersTable as uT on uT.responsible = answers.responsible
where answers.taskAction = 1 and
(case
when uT.responsible is not null then 2
when ISNULL(@resp1, Answers.responsible) = Answers.responsible then 1
end = @filterPick )
order by aq.section, jsq.jobnumber, answers.priority, aq.seq
```
Ok. I think I've got it. I've removed @resp1 because it wasn't necessary and am just using the table valued parameter @usersTable (but here I'm using a table variable for testing). I've added a flag @filterPick so I can show only values in @usersTable or every record where answers.taskAction = 1.
The code:
```
declare @filterPick bit
declare @usersTable table
(responsible nvarchar(32))
insert into @usersTable (responsible) values (null)
--insert into @usersTable (responsible) values ('ssimpson')
--insert into @usersTable (responsible) values ('kwilcox')
if exists (select * from @usersTable where responsible is not null)
begin
set @filterPick = 1
end
else
begin
set @filterPick = 0
end
select *
from answers
inner join jobno_specific_questions as jsq on answers.jqid = jsq.jqid
inner join apqp_questions as aq on jsq.qid = aq.qid
left join @usersTable as uT on answers.responsible = uT.responsible
where answers.taskAction = 1 and (uT.responsible is not null or (isnull(uT.responsible, answers.responsible) = answers.responsible and @filterPick = 0))
order by aq.section, jsq.jobnumber, answers.priority, aq.seq
``` | 2010/09/28 | [
"https://Stackoverflow.com/questions/3816331",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/428757/"
] | I'm a bit confused by your question but I'll give it a shot.
First off i suspect your issues with the incorrect records being returned have to do with your comparison of a null value. To demonstrate what I am talking about query any table you want and add this to the end:
```
WHERE null = null
```
no records will be returned. In your code I would change:
```
where answers.taskAction = 1 and (uT.responsible is not null or ISNULL(@resp1, Answers.responsible) = Answers.responsible)
```
to
```
where answers.taskAction = 1 and (uT.responsible is not null or @resp1 is null)
```
And see if that returns the desired result. | Have you considered changing the WHERE clause to something like:
```
WHERE Answers.taskAction = 1
AND(ISNULL(@resp1, Answers.responsible) = Answers.responsible
OR Answers.responsible IN (SELECT responsible FROM uT))
```
Instead of JOINing on the table-valued parameter? |
49,815,229 | i've been trying to authenticate user input using the mysqli\_fetch\_assoc function, though it works i.e redirects user to the home page when the username and password is correct, but it doesn't display the error message(s) when the inputs are incorrect however it displays the username error message when the username is incorrect case wise. pls how do i fix it? here is the code
```
$username = $password = "";
$username_err = $password_err = "";
//testing input values
if ($_SERVER["REQUEST_METHOD"] == "POST") {
//processing username input
if (empty($_POST['username'])) {
$username_err = " *username is required!";
}else{ //if field is not empty
$username = test_input($_POST['username']);
}
//processing password input
if (empty($_POST['password'])) {
$password_err = " *password is required!";
}elseif (strlen($_POST['password']) < 8) {
$password_err = " *password must not be less than 8 characters!";
}else{ //if field is not empty
$password = md5($_POST['password']);
}
//comparing user input with stored details
$sql = "SELECT * FROM users_log WHERE Username = '$username' AND Password = '$password'";
$result = mysqli_query($dbconn, $sql);
$row = mysqli_fetch_assoc($result);
if ($row) {
if ($row['Username'] != $username ) {
$username_err = "Incorrect Username";
}elseif ($row['Password'] != $password ) {
$password_err = "Incorrect Password";
}else{
header("location:../home/homeIndex.php");
}
}
}
function test_input($input){
$input = trim($input);
$input = stripslashes($input);
$input = htmlspecialchars($input);
return $input;
}
```
the html output
```
<span><?php echo "$username_err<br>"; ?></span>
<input type="text" name="username" class="form-control" placeholder="Username" size="30">
</div><br>
<?php echo "$password_err<br>"; ?></span>
<input type="password" name="password" class="form-control" placeholder="Password" size="30" >
</div><br>
``` | 2018/04/13 | [
"https://Stackoverflow.com/questions/49815229",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9602904/"
] | ```
if ($row) {
if ($row['Username'] != $username ) {
$username_err = "Incorrect Username";
}elseif ($row['Password'] != $password ) {
$password_err = "Incorrect Password";
}else{
header("location:../home/homeIndex.php");
}
}
```
data inside the $row will execute when condition is true. So use if condition like this,
```
if ($row) {
header("location:../home/homeIndex.php");
}else{
$username_err = "Incorrect Username Or Password";
}
```
Hope this will resolve your issue | You are wrapping the incorrect username conditions inside `if($row)` , this is not going to work as inside query , you are checking for username and password both , but incase any of these is wrong , query is going to return 0 results so that means `if($row)` is negative and anything inside it will not work ... try below :
```
if ($row) {
header("location:../home/homeIndex.php");
} else {
$error = "Incorrect Username or password";
}
```
Why this and `$error = "incorrect username or password` , it's cause you are not actually checking username and password individually to say , if username is incorrect or password is incorrect. you are checking them both together which makes `if($row)` not to work as you want , so you better try above one. |
49,815,229 | i've been trying to authenticate user input using the mysqli\_fetch\_assoc function, though it works i.e redirects user to the home page when the username and password is correct, but it doesn't display the error message(s) when the inputs are incorrect however it displays the username error message when the username is incorrect case wise. pls how do i fix it? here is the code
```
$username = $password = "";
$username_err = $password_err = "";
//testing input values
if ($_SERVER["REQUEST_METHOD"] == "POST") {
//processing username input
if (empty($_POST['username'])) {
$username_err = " *username is required!";
}else{ //if field is not empty
$username = test_input($_POST['username']);
}
//processing password input
if (empty($_POST['password'])) {
$password_err = " *password is required!";
}elseif (strlen($_POST['password']) < 8) {
$password_err = " *password must not be less than 8 characters!";
}else{ //if field is not empty
$password = md5($_POST['password']);
}
//comparing user input with stored details
$sql = "SELECT * FROM users_log WHERE Username = '$username' AND Password = '$password'";
$result = mysqli_query($dbconn, $sql);
$row = mysqli_fetch_assoc($result);
if ($row) {
if ($row['Username'] != $username ) {
$username_err = "Incorrect Username";
}elseif ($row['Password'] != $password ) {
$password_err = "Incorrect Password";
}else{
header("location:../home/homeIndex.php");
}
}
}
function test_input($input){
$input = trim($input);
$input = stripslashes($input);
$input = htmlspecialchars($input);
return $input;
}
```
the html output
```
<span><?php echo "$username_err<br>"; ?></span>
<input type="text" name="username" class="form-control" placeholder="Username" size="30">
</div><br>
<?php echo "$password_err<br>"; ?></span>
<input type="password" name="password" class="form-control" placeholder="Password" size="30" >
</div><br>
``` | 2018/04/13 | [
"https://Stackoverflow.com/questions/49815229",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9602904/"
] | ```
if ($row) {
if ($row['Username'] != $username ) {
$username_err = "Incorrect Username";
}elseif ($row['Password'] != $password ) {
$password_err = "Incorrect Password";
}else{
header("location:../home/homeIndex.php");
}
}
```
data inside the $row will execute when condition is true. So use if condition like this,
```
if ($row) {
header("location:../home/homeIndex.php");
}else{
$username_err = "Incorrect Username Or Password";
}
```
Hope this will resolve your issue | If Username or password are incorrect the $result must be empty. Check if !empty($result). |
68,146,659 | Is it possible to achive authentication with email and password in flutter without using firebase? I have searched around Stackoverflow and internet in general and found nothing about this.
I am creating a simple authentication class this is what I have done at the moment:
```
class User {
bool isAuthenticated = false;
late String userid;
late String username;
late String email;
late DateTime expireDate; // this variable is used to make the user re-authenticate when today is expireDate
User(bool isAuthenticated, String userid, String username, String email) {
this.isAuthenticated = isAuthenticated;
this.userid = userid;
this.username = username;
this.email = email;
this.expireDate = new DateTime.now().add(new Duration(days: 30));
}
}
class Authentication {
Future<User> signin(String email, String password) {}
void signup(String username, String email, String password) {}
}
```
EDIT #1: I know how to setup a cookie/token based authentication server I have my own repos on that topic: [cookie authentication](https://github.com/datteroandrea/cookieauth), [token authentication](https://github.com/datteroandrea/jwtauth) but I don't know how to handle the tokens/cookies in flutter. | 2021/06/26 | [
"https://Stackoverflow.com/questions/68146659",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10457357/"
] | You can use Nodejs & express to create your own API and MongoDB or any other DB to act as a persistent DB. I am attaching my github repo link which has minimum code required to setup a email/password auth in mongodb
[Github](https://github.com/AshutoshPatole/backends)
EDIT :
I have little to no idea about sessions but for tokens there are packages in pub.dev which lets you decode the tokens. [jwt-decoder](https://pub.dev/packages/jwt_decoder).
You can check the expiry time of the token using this package and for storing them you can use [secure\_storage](https://pub.dev/packages/flutter_secure_storage)
I had a look at your token authentication repo. I would suggest you to verify the token when you get them and not just blindly trust them. | Yes it is Totally possible to create Authentication without Firebase, but it becomes a-lot more difficult and there are multiple solutions.
What firebase provides:
-----------------------
1. Server space with no down time
2. Complete set of Api's including authentication with various methods
3. Strong security(built by google)
4. Ease of use and setup with great documentation
The reason I bring these up is cause the alternative ur looking for is very difficult for a programer who's relatively new and can feel like you are building multiple applications at a time. It's definitely a learning curve. Also I'm assuming u don't just want local authentication cause thats kinda pointless.
Creating ur own backend involves:
---------------------------------
1. Setting up a server(usually ubuntu)(and either on a raspi or a host like amazon, digital ocean, etc)
2. Setting up a database with tables(mysql, sql, mongoDB)
3. Creating communication API's (php, Node.js)
So here's what i'd recommend for getting into backend dev,
use LAMP architecture : Linux, Apache, MySQL, PHP
Setting up Lamp isn't too hard heres a link i followed:
<https://www.digitalocean.com/community/tutorials/how-to-install-linux-apache-mysql-php-lamp-stack-on-ubuntu-16-04>
After u set up ur back end, then u have to create api calls from flutter.
The call (if u created an auth.php where people can login) would look something like:
```
http://ip:8080/auth.php?email="[email protected]"&pass="123456"
```
I understand why you feel like you didn't find solutions, i was there too but there are tons,LAMP is one of the more easier ones. If u are still interested i'd recommend checking out System Design courses. |
68,146,659 | Is it possible to achive authentication with email and password in flutter without using firebase? I have searched around Stackoverflow and internet in general and found nothing about this.
I am creating a simple authentication class this is what I have done at the moment:
```
class User {
bool isAuthenticated = false;
late String userid;
late String username;
late String email;
late DateTime expireDate; // this variable is used to make the user re-authenticate when today is expireDate
User(bool isAuthenticated, String userid, String username, String email) {
this.isAuthenticated = isAuthenticated;
this.userid = userid;
this.username = username;
this.email = email;
this.expireDate = new DateTime.now().add(new Duration(days: 30));
}
}
class Authentication {
Future<User> signin(String email, String password) {}
void signup(String username, String email, String password) {}
}
```
EDIT #1: I know how to setup a cookie/token based authentication server I have my own repos on that topic: [cookie authentication](https://github.com/datteroandrea/cookieauth), [token authentication](https://github.com/datteroandrea/jwtauth) but I don't know how to handle the tokens/cookies in flutter. | 2021/06/26 | [
"https://Stackoverflow.com/questions/68146659",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10457357/"
] | This answer is based of #edit1. Since you mentioned that you already know how to set up tokens on the server side you're half way done. Here's a few assumptions I'm making, you already know js/php and worked with JSON output, The database already has a column and table that keeps track of sessions and user\_id.
Since you know how Cookies are built this should be relatively easy cause i built it around similar architecture. We has to use the local memory that app's provide access to. There are two packages in flutter that allow u to do this, you can use either:
* shared\_preferences [package link](https://pub.dev/packages/shared_preferences)
* flutter\_secure\_storage [package link](https://pub.dev/packages/flutter_secure_storage)
The main difference is if you want to store 'tokens' or data you want secure you would obviously use flutter\_secure\_storage. I'm going to use this for code example. And yes the data is saved even after the app is closed.
Setting up Tokens(flutter):
---------------------------
1. Setting up User Class
When using firebase we generally take for granted the user class that comes with flutter\_auth but that is basically what we have to build. A user class with all the data u want to store and then a function called authenticate.
```
class AppUser{
final _storage = new FlutterSecureStorage();
//below class is mentioned in the next part
AuthApi api = new AuthApi();
//constructor
AppUser(){
//ur data;
};
Future<bool> authenticate(email, password) async {
//this is the api mentioned in next part
http.Response res = await api.login(email, password);
Map<String, dynamic> jsonRes = jsonDecode(res.body);
if (jsonRes["error"]) {
return false;
}
_setToken(jsonRes["token"]);
_setUID(jsonRes["user-id"].toString());
_setAuthState(true);
return true;
}
Future<void> _setToken(String val) async {
//how to write to safe_storage
await _storage.write(key: 'token', value: val);
}
Future<void> _setUID(String val) async {
await _storage.write(key: 'user_id', value: val);
}
//you can stream this or use it in a wrapper to help navigate
Future<bool> isAuthenticated() async {
bool authState = await _getAuthState();
return authState;
}
Future<void> _getAuthState() async {
//how to read from safe_storage u can use the same to read token later just replace 'state' with 'token'
String myState = (await _storage.read(key: 'state')).toString();
//returns boolean true or false
return myState.toLowerCase() == 'true';
}
Future<void> _setAuthState(bool liveAuthState) async {
await _storage.write(key: 'state', value: liveAuthState.toString());
}
}
```
and assuming ur going to authenticate on a button press so it would look like
```
onPressed(){
AuthUser user = new AuthUser();
if(user.authenticate(email, password)){
//if logged in. Prolly call Navigator.
}else{
//handle error
}
}
```
2. Setting up api calls
Oka so this is calling a Node express API, and the json output looks like
```
//if successful
{"status":200, "error": false, "token": "sha256token", "user-id": "uid"}
```
we need to create a class that will give us an output for making this call hence the AuthApi class
```
class AuthApi {
//this is the login api and it returns the above JSON
Future<http.Response> login(String email, String password){
return http.post(
Uri.parse(ip + '/api/auth/login'),
headers: <String, String>{
'Content-Type': 'application/json',
},
body: jsonEncode(<String, String>{
"email": email,
"password": password,
}),
);
}
}
```
Thank you for clarifying what u needed, it helped answer better. | Yes it is Totally possible to create Authentication without Firebase, but it becomes a-lot more difficult and there are multiple solutions.
What firebase provides:
-----------------------
1. Server space with no down time
2. Complete set of Api's including authentication with various methods
3. Strong security(built by google)
4. Ease of use and setup with great documentation
The reason I bring these up is cause the alternative ur looking for is very difficult for a programer who's relatively new and can feel like you are building multiple applications at a time. It's definitely a learning curve. Also I'm assuming u don't just want local authentication cause thats kinda pointless.
Creating ur own backend involves:
---------------------------------
1. Setting up a server(usually ubuntu)(and either on a raspi or a host like amazon, digital ocean, etc)
2. Setting up a database with tables(mysql, sql, mongoDB)
3. Creating communication API's (php, Node.js)
So here's what i'd recommend for getting into backend dev,
use LAMP architecture : Linux, Apache, MySQL, PHP
Setting up Lamp isn't too hard heres a link i followed:
<https://www.digitalocean.com/community/tutorials/how-to-install-linux-apache-mysql-php-lamp-stack-on-ubuntu-16-04>
After u set up ur back end, then u have to create api calls from flutter.
The call (if u created an auth.php where people can login) would look something like:
```
http://ip:8080/auth.php?email="[email protected]"&pass="123456"
```
I understand why you feel like you didn't find solutions, i was there too but there are tons,LAMP is one of the more easier ones. If u are still interested i'd recommend checking out System Design courses. |
68,146,659 | Is it possible to achive authentication with email and password in flutter without using firebase? I have searched around Stackoverflow and internet in general and found nothing about this.
I am creating a simple authentication class this is what I have done at the moment:
```
class User {
bool isAuthenticated = false;
late String userid;
late String username;
late String email;
late DateTime expireDate; // this variable is used to make the user re-authenticate when today is expireDate
User(bool isAuthenticated, String userid, String username, String email) {
this.isAuthenticated = isAuthenticated;
this.userid = userid;
this.username = username;
this.email = email;
this.expireDate = new DateTime.now().add(new Duration(days: 30));
}
}
class Authentication {
Future<User> signin(String email, String password) {}
void signup(String username, String email, String password) {}
}
```
EDIT #1: I know how to setup a cookie/token based authentication server I have my own repos on that topic: [cookie authentication](https://github.com/datteroandrea/cookieauth), [token authentication](https://github.com/datteroandrea/jwtauth) but I don't know how to handle the tokens/cookies in flutter. | 2021/06/26 | [
"https://Stackoverflow.com/questions/68146659",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10457357/"
] | This answer is based of #edit1. Since you mentioned that you already know how to set up tokens on the server side you're half way done. Here's a few assumptions I'm making, you already know js/php and worked with JSON output, The database already has a column and table that keeps track of sessions and user\_id.
Since you know how Cookies are built this should be relatively easy cause i built it around similar architecture. We has to use the local memory that app's provide access to. There are two packages in flutter that allow u to do this, you can use either:
* shared\_preferences [package link](https://pub.dev/packages/shared_preferences)
* flutter\_secure\_storage [package link](https://pub.dev/packages/flutter_secure_storage)
The main difference is if you want to store 'tokens' or data you want secure you would obviously use flutter\_secure\_storage. I'm going to use this for code example. And yes the data is saved even after the app is closed.
Setting up Tokens(flutter):
---------------------------
1. Setting up User Class
When using firebase we generally take for granted the user class that comes with flutter\_auth but that is basically what we have to build. A user class with all the data u want to store and then a function called authenticate.
```
class AppUser{
final _storage = new FlutterSecureStorage();
//below class is mentioned in the next part
AuthApi api = new AuthApi();
//constructor
AppUser(){
//ur data;
};
Future<bool> authenticate(email, password) async {
//this is the api mentioned in next part
http.Response res = await api.login(email, password);
Map<String, dynamic> jsonRes = jsonDecode(res.body);
if (jsonRes["error"]) {
return false;
}
_setToken(jsonRes["token"]);
_setUID(jsonRes["user-id"].toString());
_setAuthState(true);
return true;
}
Future<void> _setToken(String val) async {
//how to write to safe_storage
await _storage.write(key: 'token', value: val);
}
Future<void> _setUID(String val) async {
await _storage.write(key: 'user_id', value: val);
}
//you can stream this or use it in a wrapper to help navigate
Future<bool> isAuthenticated() async {
bool authState = await _getAuthState();
return authState;
}
Future<void> _getAuthState() async {
//how to read from safe_storage u can use the same to read token later just replace 'state' with 'token'
String myState = (await _storage.read(key: 'state')).toString();
//returns boolean true or false
return myState.toLowerCase() == 'true';
}
Future<void> _setAuthState(bool liveAuthState) async {
await _storage.write(key: 'state', value: liveAuthState.toString());
}
}
```
and assuming ur going to authenticate on a button press so it would look like
```
onPressed(){
AuthUser user = new AuthUser();
if(user.authenticate(email, password)){
//if logged in. Prolly call Navigator.
}else{
//handle error
}
}
```
2. Setting up api calls
Oka so this is calling a Node express API, and the json output looks like
```
//if successful
{"status":200, "error": false, "token": "sha256token", "user-id": "uid"}
```
we need to create a class that will give us an output for making this call hence the AuthApi class
```
class AuthApi {
//this is the login api and it returns the above JSON
Future<http.Response> login(String email, String password){
return http.post(
Uri.parse(ip + '/api/auth/login'),
headers: <String, String>{
'Content-Type': 'application/json',
},
body: jsonEncode(<String, String>{
"email": email,
"password": password,
}),
);
}
}
```
Thank you for clarifying what u needed, it helped answer better. | You can use Nodejs & express to create your own API and MongoDB or any other DB to act as a persistent DB. I am attaching my github repo link which has minimum code required to setup a email/password auth in mongodb
[Github](https://github.com/AshutoshPatole/backends)
EDIT :
I have little to no idea about sessions but for tokens there are packages in pub.dev which lets you decode the tokens. [jwt-decoder](https://pub.dev/packages/jwt_decoder).
You can check the expiry time of the token using this package and for storing them you can use [secure\_storage](https://pub.dev/packages/flutter_secure_storage)
I had a look at your token authentication repo. I would suggest you to verify the token when you get them and not just blindly trust them. |
8,713 | another user recommend to me in another post [this page](http://www.bricklink.com/) to buy miniatures for my growing collection of minifigures of LEGO Star Wars.
My question regarding the page is simple, there is a large assortment of minifigures of all the years, but why no one includes their accessories? For example, laser sheets or blasters ...
Can the originals be obtained in any way within the page or is there any other method to obtain them?
I've been looking at Amazon, but the prices are very high ... But they do include the minifigures accessories.
Any ideas? | 2017/03/15 | [
"https://bricks.stackexchange.com/questions/8713",
"https://bricks.stackexchange.com",
"https://bricks.stackexchange.com/users/8450/"
] | As you've noticed, the [Starwars Minifigs](https://www.bricklink.com/catalogList.asp?catType=M&catString=65) don't come with accessories - this probably makes it easier for the sellers and buyers in terms of sorting: for example the battle packs often came with 3 or 4 different characters along with 2 different weapon styles - there's no definitive "this character has this style of weapon".
The weapons can be found using the [Parts - Minifig, Weapon](https://www.bricklink.com/catalogList.asp?pg=2&catLike=W&sortBy=N&sortAsc=A&catType=P&catID=19) category - there are (at present) 4 guns tagged with `(SW)`, as well as the various different lightsaber hilts (listed as `Weapon Lightsaber Hilt`), various generic weapons (pikes/spears) and the newer "Shooter Mini with [...] Trigger" that is appearing for more play value over authentic weapon styles (another reason why you might want to buy the weapons separately).
In terms of lightsabers, the beams themselves are listed as `Bar 4L (Lightsaber Blade / Wand)` under the [Bars category](https://www.bricklink.com/catalogList.asp?catType=P&catString=46) (there's also Kylo Ren's `Bar 4L / 2L Crossed`).
If you're after more "realistic" weapons, then third party producers may be what you're after. BrickArms do a nice line in [Sci-Fi weapons](http://www.brickarms.com/scifi.php) that include Han's DL-44 and the Imperial issued EL-11, DC-15, DC-15S and D9-AR. | Since you are asking 'why' accessories are not included in listings for minifigures, I will give you a short and simple answer to directly answer that part of your question.
It is not nearly as efficient to try and have figures with their accessories be listed as it would be for them to be alone. Accessories are different from a minifig's hat, persay, because we do not see a character bald in universe, so the hat is a necessity for their character, but a weapon or accessory does not have that same necessity.
In addition to this, proneness to discrepancies in listings from seller to seller would be much higher when accessories are involved. This is especially true if a figure comes in more than one set, but has different accessories in each set. By keeping accessories and minifigures separate, there will be fewer catalog entries in the database. The goal is always to keep the database as simplistic and easy to use as possible.
I hope that sheds some light on why BL does not list its figures with their accessories (nor does any other third-party-lego-selling website). |
8,585,380 | My code gives me segfault error: which I don't understand,the debugger says error comes from printing the value from stored\_
```
char *stored_ = NULL;
char testMessage[15];
//strcpy(stored_, testMessage);
for (int a = 0;a < 10; a++)
{
sprintf(testMessage,"Message::%i\n",a);
printf("string is:%s;length is %i\n",testMessage,strlen(testMessage));
stored_ = (char*) realloc (stored_, sizeof(char) * (strlen(testMessage) * (a+1) ));
strcpy(&stored_[a], testMessage);
}
for (int b = 0;b < 10; b++)
{
printf("inside:|%s|\n",stored_[b]);
}
``` | 2011/12/21 | [
"https://Stackoverflow.com/questions/8585380",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1051003/"
] | Fist up, `sizeof(char)` is *always* 1, you don't need to multiply by it.
Secondly, when you're allocating room for a string, you have to use:
```
malloc (strlen (string) + 1);
```
In other words, you need room for the null byte at the end.
Thirdly, you appear to be confused between character pointers and character *pointer* pointers. `stored_` is a single block of characters and `stored_[1]` is only one byte beyond `stored_[0]`, meaning you won't have enough room to store the string.
```
stored_[n], n=: 0 1 2 3
+---+---+---+---+
| | | | |...
+---+---+---+---+
each of these cells is a single byte.
```
You'll either have to manage the single block of characters yourself, leaving enough room for each element (by using sparse indexes), or have a block of character pointers with indexes 0, 1, 2 and so on, but you'll then have to manage the string allocations separately.
The following code shows how to do this latter one:
```
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main (void) {
// An array of char pointers (C strings).
char **stored_ = NULL;
char testMessage[15];
int i;
// Populate them.
for (i = 0; i < 10; i++) {
sprintf (testMessage,"Message::%i",i);
printf ("string is:%s;length is %i\n",testMessage,strlen(testMessage));
// Reallocate array of char *, allocate room for string, then store it.
stored_ = realloc (stored_,sizeof (char*) * (i + 1));
stored_[i] = malloc (strlen (testMessage) + 1);
strcpy (stored_[i], testMessage);
}
```
That's the meat of it, the allocation of the array of character pointers *separate* from the actual arrays of characters forming the C strings.
Then the code below prints them and cleans up.
```
// Print them.
for (i = 0; i < 10; i++) {
printf("inside:|%s|\n",stored_[i]);
}
// Free all memory and return.
for (i = 0; i < 10; i++) {
free (stored_[i]);
}
free (stored_);
return 0;
}
```
The output being, as expected:
```
string is:Message::0;length is 10
string is:Message::1;length is 10
string is:Message::2;length is 10
string is:Message::3;length is 10
string is:Message::4;length is 10
string is:Message::5;length is 10
string is:Message::6;length is 10
string is:Message::7;length is 10
string is:Message::8;length is 10
string is:Message::9;length is 10
inside:|Message::0|
inside:|Message::1|
inside:|Message::2|
inside:|Message::3|
inside:|Message::4|
inside:|Message::5|
inside:|Message::6|
inside:|Message::7|
inside:|Message::8|
inside:|Message::9|
```
With this method, each cell is a pointer to an array of characters, separately allocated (which holds the C string):
```
stored_[n], n=: 0 1 2 3
+---+---+---+---+
| | | | |...
+---+---+---+---+
| | | | +----------------------+
| | | +---> | character array here |
| | | +----------------------+
| | | +----------------------+
| | +-------> | character array here |
| | +----------------------+
| | +----------------------+
| +-----------> | character array here |
| +----------------------+
| +----------------------+
+---------------> | character array here |
+----------------------+
``` | You don't appear to be calculating the string length of `stored_` correctly.
Every loop you assign `testMessage` to `&stored_[loopindex]`. I'm not sure if this is intended behaviour, but it's what you're doing, so I'd expect your 10th iteration to give the string `"MMMMMMMMMessage::9\n"`.
Anyway, `testMessage` is always the same number of characters, so the storage space required by `stored_` could be calculated as:
```
strlen(testMessage) // length of str to place at &stored_[a]
+ a // the loop index, where you're inserting testMessage
+ 1 // important! extra char to hold the null terminator
```
Don't ever forget the +1, every string in C must have space for the [null terminator](http://en.wikipedia.org/wiki/Null-terminated_string). |
17,787,603 | This is code to perform the delete operation. The four images appear, but the alert box for delete operation is not appearing by giving the onload functionality. Please guide me...here is the code.
```
// script for deletedelete operation
$(document).ready(function(){
$('a.delete').on('click',function(e){
e.preventDefault();
imageID = $(this).closest('.image')[0].id;
alert('Now deleting "'+imageID+'"');
$(this).closest('.image')
.fadeTo(300,0,function(){
$(this)
.animate({width:0},200,function(){
$(this)
.remove();
});
});
});
});
```
HTML
```
//four images being given with delete link
<div id="container">
<div class="image" id="image1" style="background-image:url(http://lorempixel.com/100/100/abstract);">
<a href="#" class="delete">Delete</a>
</div>
<div class="image" id="image2" style="background-image:url(http://lorempixel.com/100/100/food);">
<a href="#" class="delete">Delete</a>
</div>
<div class="image" id="image3" style="background-image:url(http://lorempixel.com/100/100/people);">
<a href="#" class="delete">Delete</a>
</div>
<div class="image" id="image4" style="background-image:url(http://lorempixel.com/100/100/technics);">
<a href="#" class="delete">Delete</a>
</div>
</div>
``` | 2013/07/22 | [
"https://Stackoverflow.com/questions/17787603",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2605662/"
] | You can use jQuery's build in filter() function, and write a filter with the condition you described.
First, you should hide all the items with any price.
```
$(".price").parent().hide();
```
Then, you can filter all the items with in-range prices and show them:
```
$(".price").filter(function(){
var $this = $(this);
var value = $this.val();
return (value >= minNumber && value <= maxNumber); // returns boolean - true will keep this item in the filtered collection
}).parent().show();
``` | I would go by something like:
1. Get all the divs that have prices.
2. Iterate through all:
1. Transform the strings (minus the pound symbol) to float numbers and compare with an IF statement if they are inside the provided range.
2. If they are just go to the next (use continue maybe)
3. Else (not in the range) add a class like *.hide* so it can be blended through css (or just use the blend function from jquery) |
17,787,603 | This is code to perform the delete operation. The four images appear, but the alert box for delete operation is not appearing by giving the onload functionality. Please guide me...here is the code.
```
// script for deletedelete operation
$(document).ready(function(){
$('a.delete').on('click',function(e){
e.preventDefault();
imageID = $(this).closest('.image')[0].id;
alert('Now deleting "'+imageID+'"');
$(this).closest('.image')
.fadeTo(300,0,function(){
$(this)
.animate({width:0},200,function(){
$(this)
.remove();
});
});
});
});
```
HTML
```
//four images being given with delete link
<div id="container">
<div class="image" id="image1" style="background-image:url(http://lorempixel.com/100/100/abstract);">
<a href="#" class="delete">Delete</a>
</div>
<div class="image" id="image2" style="background-image:url(http://lorempixel.com/100/100/food);">
<a href="#" class="delete">Delete</a>
</div>
<div class="image" id="image3" style="background-image:url(http://lorempixel.com/100/100/people);">
<a href="#" class="delete">Delete</a>
</div>
<div class="image" id="image4" style="background-image:url(http://lorempixel.com/100/100/technics);">
<a href="#" class="delete">Delete</a>
</div>
</div>
``` | 2013/07/22 | [
"https://Stackoverflow.com/questions/17787603",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2605662/"
] | I'd use a function like this one, where `range` is the string you gave
```
function highlightDivs(range) {
var lower = range.split(" ")[0].slice(1);
var upper = range.split(" ")[2].slice(1);
$('.section-link').hide();
$('.section-link').children('.price').each(function() {
if (lower <= $(this).val() && upper >= $(this).val()){
$(this).parent().show();
}
});
}
``` | You can use jQuery's build in filter() function, and write a filter with the condition you described.
First, you should hide all the items with any price.
```
$(".price").parent().hide();
```
Then, you can filter all the items with in-range prices and show them:
```
$(".price").filter(function(){
var $this = $(this);
var value = $this.val();
return (value >= minNumber && value <= maxNumber); // returns boolean - true will keep this item in the filtered collection
}).parent().show();
``` |
17,787,603 | This is code to perform the delete operation. The four images appear, but the alert box for delete operation is not appearing by giving the onload functionality. Please guide me...here is the code.
```
// script for deletedelete operation
$(document).ready(function(){
$('a.delete').on('click',function(e){
e.preventDefault();
imageID = $(this).closest('.image')[0].id;
alert('Now deleting "'+imageID+'"');
$(this).closest('.image')
.fadeTo(300,0,function(){
$(this)
.animate({width:0},200,function(){
$(this)
.remove();
});
});
});
});
```
HTML
```
//four images being given with delete link
<div id="container">
<div class="image" id="image1" style="background-image:url(http://lorempixel.com/100/100/abstract);">
<a href="#" class="delete">Delete</a>
</div>
<div class="image" id="image2" style="background-image:url(http://lorempixel.com/100/100/food);">
<a href="#" class="delete">Delete</a>
</div>
<div class="image" id="image3" style="background-image:url(http://lorempixel.com/100/100/people);">
<a href="#" class="delete">Delete</a>
</div>
<div class="image" id="image4" style="background-image:url(http://lorempixel.com/100/100/technics);">
<a href="#" class="delete">Delete</a>
</div>
</div>
``` | 2013/07/22 | [
"https://Stackoverflow.com/questions/17787603",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2605662/"
] | I'd use a function like this one, where `range` is the string you gave
```
function highlightDivs(range) {
var lower = range.split(" ")[0].slice(1);
var upper = range.split(" ")[2].slice(1);
$('.section-link').hide();
$('.section-link').children('.price').each(function() {
if (lower <= $(this).val() && upper >= $(this).val()){
$(this).parent().show();
}
});
}
``` | I would go by something like:
1. Get all the divs that have prices.
2. Iterate through all:
1. Transform the strings (minus the pound symbol) to float numbers and compare with an IF statement if they are inside the provided range.
2. If they are just go to the next (use continue maybe)
3. Else (not in the range) add a class like *.hide* so it can be blended through css (or just use the blend function from jquery) |
17,787,603 | This is code to perform the delete operation. The four images appear, but the alert box for delete operation is not appearing by giving the onload functionality. Please guide me...here is the code.
```
// script for deletedelete operation
$(document).ready(function(){
$('a.delete').on('click',function(e){
e.preventDefault();
imageID = $(this).closest('.image')[0].id;
alert('Now deleting "'+imageID+'"');
$(this).closest('.image')
.fadeTo(300,0,function(){
$(this)
.animate({width:0},200,function(){
$(this)
.remove();
});
});
});
});
```
HTML
```
//four images being given with delete link
<div id="container">
<div class="image" id="image1" style="background-image:url(http://lorempixel.com/100/100/abstract);">
<a href="#" class="delete">Delete</a>
</div>
<div class="image" id="image2" style="background-image:url(http://lorempixel.com/100/100/food);">
<a href="#" class="delete">Delete</a>
</div>
<div class="image" id="image3" style="background-image:url(http://lorempixel.com/100/100/people);">
<a href="#" class="delete">Delete</a>
</div>
<div class="image" id="image4" style="background-image:url(http://lorempixel.com/100/100/technics);">
<a href="#" class="delete">Delete</a>
</div>
</div>
``` | 2013/07/22 | [
"https://Stackoverflow.com/questions/17787603",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2605662/"
] | Use jQuery's filter()
An example -> <http://jsfiddle.net/H6mtY/1/>
```
var minValue = 0.01,
maxValue = 100.01;
var filterFn = function(i){
var $this = $(this);
if($this.hasClass('amount')){
// assume that text is always a symbol with a number
var value = +$this.text().match(/\d+.?\d*/)[0];
if(value > minValue && value < maxValue){
return true;
}
}
return false;
};
// apply your filter to body for example
$('#target span')
.filter(filterFn)
.each(function(i,ele){
// do something with the selected ones
$(this).css('color','red');
});
``` | I would go by something like:
1. Get all the divs that have prices.
2. Iterate through all:
1. Transform the strings (minus the pound symbol) to float numbers and compare with an IF statement if they are inside the provided range.
2. If they are just go to the next (use continue maybe)
3. Else (not in the range) add a class like *.hide* so it can be blended through css (or just use the blend function from jquery) |
17,787,603 | This is code to perform the delete operation. The four images appear, but the alert box for delete operation is not appearing by giving the onload functionality. Please guide me...here is the code.
```
// script for deletedelete operation
$(document).ready(function(){
$('a.delete').on('click',function(e){
e.preventDefault();
imageID = $(this).closest('.image')[0].id;
alert('Now deleting "'+imageID+'"');
$(this).closest('.image')
.fadeTo(300,0,function(){
$(this)
.animate({width:0},200,function(){
$(this)
.remove();
});
});
});
});
```
HTML
```
//four images being given with delete link
<div id="container">
<div class="image" id="image1" style="background-image:url(http://lorempixel.com/100/100/abstract);">
<a href="#" class="delete">Delete</a>
</div>
<div class="image" id="image2" style="background-image:url(http://lorempixel.com/100/100/food);">
<a href="#" class="delete">Delete</a>
</div>
<div class="image" id="image3" style="background-image:url(http://lorempixel.com/100/100/people);">
<a href="#" class="delete">Delete</a>
</div>
<div class="image" id="image4" style="background-image:url(http://lorempixel.com/100/100/technics);">
<a href="#" class="delete">Delete</a>
</div>
</div>
``` | 2013/07/22 | [
"https://Stackoverflow.com/questions/17787603",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2605662/"
] | I'd use a function like this one, where `range` is the string you gave
```
function highlightDivs(range) {
var lower = range.split(" ")[0].slice(1);
var upper = range.split(" ")[2].slice(1);
$('.section-link').hide();
$('.section-link').children('.price').each(function() {
if (lower <= $(this).val() && upper >= $(this).val()){
$(this).parent().show();
}
});
}
``` | Use jQuery's filter()
An example -> <http://jsfiddle.net/H6mtY/1/>
```
var minValue = 0.01,
maxValue = 100.01;
var filterFn = function(i){
var $this = $(this);
if($this.hasClass('amount')){
// assume that text is always a symbol with a number
var value = +$this.text().match(/\d+.?\d*/)[0];
if(value > minValue && value < maxValue){
return true;
}
}
return false;
};
// apply your filter to body for example
$('#target span')
.filter(filterFn)
.each(function(i,ele){
// do something with the selected ones
$(this).css('color','red');
});
``` |
122,741 | We are traveling from Tbilisi to Ataturk airport and then with a transit to Antalya; both legs were sold under a single ticket by Turkish Airlines.
* Do they automatically put luggage for transit?
* How far is the second terminal, and where we should go for passport control? | 2018/09/23 | [
"https://travel.stackexchange.com/questions/122741",
"https://travel.stackexchange.com",
"https://travel.stackexchange.com/users/84484/"
] | For International to Domestic connections on Turkish Airlines, your bags will be automatically transferred to the domestic flight IF (and only if!) the domestic destination you are travelling to has customs facilities at the airport.
In the case of Antalya, they DO have such facilities, so your bags will be automatically transferred to your domestic flight.
Shortly before landing into Istanbul an announcement will be made on the flight, and they will direct you to the back of the in-flight SkyLife magazine to confirm which locations do and do not have customs facilities, so you can use this to confirm what I've said above.
Upon landing in Istanbul you will need to proceed through Passport Control (just follow the signs), through baggage claim and customs (WITHOUT collecting your bags), and then make an immediate LEFT turn and follow the signs to the domestic terminal which is a 5-10 minute walk away. | * I just always ask about luggage at the check-in when I drop it off to be extra sure. I expect that it would be transferred automatically in your case.
* There is no way that you will miss the passport control (just follow the signs), and Ataturk is a single large building so different places in it can't be very far. |
34,666,777 | I am creating a simple program that takes some input and turns it into an output to .txt file.
I have been trying to use if-else statements to make it so that after it has received a name ;
```
//user enters name and then moves to next line
System.out.println("Enter Your Name");
gamerName = Scan.nextLine();
```
it will either move onto the next part (if a name is entered) or break.
How and where will i properly add and format these if-else statements? thanks you
```
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
import java.nio.file.*;
public class JavaProject {
private static char[] input;
public static void main(String[] args) {
for(int b = 1; b < 100; b++ ) {
//this is making the code loop 100 times
//variables
int[] minutesPlayed = new int [100];
String gamerName, gamerReport;
//Main data storage arrays
String[] gameNames = new String[100];
int[] highScores = new int[100];
@SuppressWarnings("resource")
Scanner Scan = new Scanner(System.in);
//formatting for output and input
System.out.println("////// Game Score Report Generator \\\\\\\\\\\\");
System.out.println(" ");
//user enters name and then moves to next line
System.out.println("Enter Your Name");
gamerName = Scan.nextLine();
//user is given an example of input format
System.out.println("FALSE DATA FORMAT WILL CAUSE ERROR - Input Gamer Information " + "Using Format --> Game : Achievement Score : Minutes Played");
System.out.println(" ");
//another data input guide which is just above where data input is in console
System.out.println("Game : Achievement Score : Minutes Played");
gamerReport = Scan.nextLine();
String[] splitUpReport; // an array of string
splitUpReport = gamerReport.split(":"); // split the text up on the colon
int i = 0;
//copy data from split text into main data storage arrays
gameNames[i] = splitUpReport[0];
highScores[i] = Integer.parseInt(splitUpReport[1].trim() );
minutesPlayed[i] = Integer.parseInt(splitUpReport[2].trim());
//output to file using a PrintWriter using a FileOutPutStream with append set to true within the printwriter constructor
//
try
{
PrintWriter writer = new PrintWriter(new FileOutputStream("Gaming Report Data", true));
writer.println("Player : " + gamerName);
writer.println();
writer.println("--------------------------------");
writer.println();
String[] report = gamerReport.split(":");
writer.println("Game: " + report[0] + ", score= " +report[1] + ", minutes played= " +report[2]);
writer.println();
writer.close();
} catch (IOException e)
{
System.err.println("File does not exist!");
}
}
}
public static char[] getInput() {
return input;
}
public static void setInput(char[] input) {
JavaProject.input = input;
}
}
``` | 2016/01/07 | [
"https://Stackoverflow.com/questions/34666777",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5517288/"
] | In this case, the problem turned out to be because my project in Eclipse depended on downstream project. When I went into my project's build path and removed the downstream project, my test went from red to green.
The difference was spotted by contrasting output from the correct Maven CLI execution and the incorrect Eclipse execution. By diff'ing command line output between Maven CLI and Eclipse I spotted the following line in the Maven CLI console output:
```
<org.springframework.core.io.support.PathMatchingResourcePatternResolver><main><org.springframework.core.io.support.PathMatchingResourcePatternResolver.doFindPathMatchingJarResources(?:?):Looking for matching resources in jar file [file:/Users/jthoms/.m2/repository/com/acme/teamnamespace/downstream-project/0.0.2/downstream-project-0.0.2.jar]>
```
This corresponded to a line in Eclipse's console output:
```
<org.springframework.core.io.support.PathMatchingResourcePatternResolver><main><org.springframework.core.io.support.PathMatchingResourcePatternResolver.doFindMatchingFileSystemResources(?:?):Looking for matching resources in directory tree [/git/cloned/downstream-project/target/classes/com/acme/teamnamespace]>
```
In the Maven CLI output the source from a JAR file but in Eclipse it was in a project directory tree. After that line, all logged output started to become very different until the exception occurred. | Check that the class name ends with "Test", otherwise maven will just skip the tests in that class and that's confusing you. Eclipse JUnit doesn't care about the class name and runs it anyway |
23,936 | I have the following setup:
There is a collection of items I and a collection of partial rankings V. That is, an element of V is a total ordering on a subset of I. There is no expectation of consistency among the elements of V: it may be that x < y for one element and y < x for another.
I would like to assign a score $s : I \to \mathbb{R}$ which in some sense captures these rankings. That is, I would like s(x) < s(y) to mean "x tends to be less than y for elements of V which have both in their domain". I'm not sure of what a good way to do this is.
[Arrow's impossibility theorem](http://en.wikipedia.org/wiki/Arrow%27s_impossibility_theorem) puts some constraints on what can be achieved here, because given a set of votes and a scoring function like this we could use the scoring function to define a total order on the items, which is then constrained by the theorem.
I suppose I'm really looking for references rather than an answer to this question (although both would be appreciated): I'm sure there's a body of theory around this, but I have no idea what it is like or what it's called, so I'm at a bit of a loss as to where to start looking for a solution. | 2010/05/08 | [
"https://mathoverflow.net/questions/23936",
"https://mathoverflow.net",
"https://mathoverflow.net/users/4959/"
] | Here is a list biased towards what is remarkable in the complex case. (To the potential peeved real manifold: I love you too.) By "complex" I mean holomorphic manifolds and holomorphic maps; by "real" I mean $\mathcal{C}^{\infty}$ manifolds and $\mathcal{C}^{\infty}$ maps.
* Consider a map $f$ between manifolds of *equal* dimension.
In the complex case: if $f$ is injective then it is an isomorphism onto its image. In the real case, $x\mapsto x^3$ is not invertible.
* Consider a holomorphic $f: U-K \rightarrow \mathbb{C}$, where $U\subset \mathbb{C}^n$ is open and $K$ is a compact s.t. $U-K$ is connected. When $n\geq 2$, $f$ extends to $U$. This so-called Hartogs phenomenon has no counterpart in the real case.
* If a complex manifold is compact or is a bounded open subset of $\mathbb{C}^n$, then its group of automorphisms is a Lie group. In the smooth case it is always infinite dimensional.
* The space of sections of a vector bundle over a compact complex manifold is finite dimensional. In the real case it is always infinite dimensional.
* To expand on Charles Staats's excellent answer: few smooth atlases happen to be holomorphic, but even fewer diffeomorphisms happen to be holomorphic. Considering manifolds up to isomorphism, the net result is that many complex manifolds come in continuous families, whereas real manifolds rarely do (in dimension other than $4$: a compact topological manifold has at most finitely many smooth structures; $\mathbb{R}^n$ has exactly one).
On the theme of *zero subsets* (i.e., subsets defined locally by the vanishing of one or several functions):
* *One* equation always defines a *codimension one* subset in the complex case, but
{$x\_1^2+\dots+x\_n^2=0$} is reduced to one point in $\mathbb{R}^n$.
* In the complex case, a zero subset isn't necessarily a submanifold, but
is amenable to manifold theory by Hironaka desingularization. In the real case, *any* closed subset is a zero set.
* The image of a proper map between two complex manifolds is a zero subset, so isn't too bad by the previous point. Such a direct image is hard to deal with in the real case. | Some embedding statements.
A compact complex subvariety of ${\mathbb{C}}^n$ is a point. However, every compact real manifold of dimension $n$ can be realized as a submanifold of some ${\mathbb{R}}^{2n}$.
There are compact complex manifolds that cannot be embedded into complex projective space. An example most often quoted in textbooks is the Hopf manifold, which is not even Kahler. On the other hand, I heard that embedding into real projective space is not often considered in differential geometry. |
23,936 | I have the following setup:
There is a collection of items I and a collection of partial rankings V. That is, an element of V is a total ordering on a subset of I. There is no expectation of consistency among the elements of V: it may be that x < y for one element and y < x for another.
I would like to assign a score $s : I \to \mathbb{R}$ which in some sense captures these rankings. That is, I would like s(x) < s(y) to mean "x tends to be less than y for elements of V which have both in their domain". I'm not sure of what a good way to do this is.
[Arrow's impossibility theorem](http://en.wikipedia.org/wiki/Arrow%27s_impossibility_theorem) puts some constraints on what can be achieved here, because given a set of votes and a scoring function like this we could use the scoring function to define a total order on the items, which is then constrained by the theorem.
I suppose I'm really looking for references rather than an answer to this question (although both would be appreciated): I'm sure there's a body of theory around this, but I have no idea what it is like or what it's called, so I'm at a bit of a loss as to where to start looking for a solution. | 2010/05/08 | [
"https://mathoverflow.net/questions/23936",
"https://mathoverflow.net",
"https://mathoverflow.net/users/4959/"
] | Any two compact surfaces (without boundary) of the same genus are diffeomorphic. However, if S is a surface of genus g > 0, there are uncountably many non-isomorphic complex (or, equivalently, algebraic) structures on S. | For a closed analytic subset Z ⊂ S of a (say compact) complex manifold
with complement U=S-Z one has additivity of the (topological) Euler characteristic:
Χ(S)=Χ(Z)+Χ(U).
This is wrong for if S and Z are topological spaces or smooth manifolds.
Indeed, take for Z a point on a circle S.
This (surprising) difference was recently pointed out to me by Manfred Lehn.
Of course there is also no additivity of Poincare-Polynomials or other
"motivic" invariants of complex varieties. |
23,936 | I have the following setup:
There is a collection of items I and a collection of partial rankings V. That is, an element of V is a total ordering on a subset of I. There is no expectation of consistency among the elements of V: it may be that x < y for one element and y < x for another.
I would like to assign a score $s : I \to \mathbb{R}$ which in some sense captures these rankings. That is, I would like s(x) < s(y) to mean "x tends to be less than y for elements of V which have both in their domain". I'm not sure of what a good way to do this is.
[Arrow's impossibility theorem](http://en.wikipedia.org/wiki/Arrow%27s_impossibility_theorem) puts some constraints on what can be achieved here, because given a set of votes and a scoring function like this we could use the scoring function to define a total order on the items, which is then constrained by the theorem.
I suppose I'm really looking for references rather than an answer to this question (although both would be appreciated): I'm sure there's a body of theory around this, but I have no idea what it is like or what it's called, so I'm at a bit of a loss as to where to start looking for a solution. | 2010/05/08 | [
"https://mathoverflow.net/questions/23936",
"https://mathoverflow.net",
"https://mathoverflow.net/users/4959/"
] | Here is a list biased towards what is remarkable in the complex case. (To the potential peeved real manifold: I love you too.) By "complex" I mean holomorphic manifolds and holomorphic maps; by "real" I mean $\mathcal{C}^{\infty}$ manifolds and $\mathcal{C}^{\infty}$ maps.
* Consider a map $f$ between manifolds of *equal* dimension.
In the complex case: if $f$ is injective then it is an isomorphism onto its image. In the real case, $x\mapsto x^3$ is not invertible.
* Consider a holomorphic $f: U-K \rightarrow \mathbb{C}$, where $U\subset \mathbb{C}^n$ is open and $K$ is a compact s.t. $U-K$ is connected. When $n\geq 2$, $f$ extends to $U$. This so-called Hartogs phenomenon has no counterpart in the real case.
* If a complex manifold is compact or is a bounded open subset of $\mathbb{C}^n$, then its group of automorphisms is a Lie group. In the smooth case it is always infinite dimensional.
* The space of sections of a vector bundle over a compact complex manifold is finite dimensional. In the real case it is always infinite dimensional.
* To expand on Charles Staats's excellent answer: few smooth atlases happen to be holomorphic, but even fewer diffeomorphisms happen to be holomorphic. Considering manifolds up to isomorphism, the net result is that many complex manifolds come in continuous families, whereas real manifolds rarely do (in dimension other than $4$: a compact topological manifold has at most finitely many smooth structures; $\mathbb{R}^n$ has exactly one).
On the theme of *zero subsets* (i.e., subsets defined locally by the vanishing of one or several functions):
* *One* equation always defines a *codimension one* subset in the complex case, but
{$x\_1^2+\dots+x\_n^2=0$} is reduced to one point in $\mathbb{R}^n$.
* In the complex case, a zero subset isn't necessarily a submanifold, but
is amenable to manifold theory by Hironaka desingularization. In the real case, *any* closed subset is a zero set.
* The image of a proper map between two complex manifolds is a zero subset, so isn't too bad by the previous point. Such a direct image is hard to deal with in the real case. | Some of these properties are local, and distinguish analytic and algebraic functions, from smooth functions.
Others are global and distinguish compact manifolds from projective manifolds by their difference in containment of many subvarieties.
some are as simple as contrasting the dimension, and homology of say projective Real space from that of projective Complex space, as noted.
As a deep contrast between smooth and analytic structure I like the answer pointing out that analytic riemann surfaces can have many non isomorphic structures on the same smooth manifold. this is interesting already for genus one manifolds. and it is not trivial to show that the sphere has only one complex analytic structure.
that might be a fun challenge to a class, to show two Riemann surfaces both diffeomorphic to the 2-sphere, are holomorphically isomorphic.
You might also be interested in some of the articles by Kolla'r on the Nash conjecture contrasting real varieties and real manifolds. such as "What are the simplest varieties?", Bulletin, vol 38. I like the pair of theorems 54, 51, subtitled respectively: "the Nash conjecture is true in dim 3", and "The Nash conjecture is false in dim 3". |
23,936 | I have the following setup:
There is a collection of items I and a collection of partial rankings V. That is, an element of V is a total ordering on a subset of I. There is no expectation of consistency among the elements of V: it may be that x < y for one element and y < x for another.
I would like to assign a score $s : I \to \mathbb{R}$ which in some sense captures these rankings. That is, I would like s(x) < s(y) to mean "x tends to be less than y for elements of V which have both in their domain". I'm not sure of what a good way to do this is.
[Arrow's impossibility theorem](http://en.wikipedia.org/wiki/Arrow%27s_impossibility_theorem) puts some constraints on what can be achieved here, because given a set of votes and a scoring function like this we could use the scoring function to define a total order on the items, which is then constrained by the theorem.
I suppose I'm really looking for references rather than an answer to this question (although both would be appreciated): I'm sure there's a body of theory around this, but I have no idea what it is like or what it's called, so I'm at a bit of a loss as to where to start looking for a solution. | 2010/05/08 | [
"https://mathoverflow.net/questions/23936",
"https://mathoverflow.net",
"https://mathoverflow.net/users/4959/"
] | Some of these properties are local, and distinguish analytic and algebraic functions, from smooth functions.
Others are global and distinguish compact manifolds from projective manifolds by their difference in containment of many subvarieties.
some are as simple as contrasting the dimension, and homology of say projective Real space from that of projective Complex space, as noted.
As a deep contrast between smooth and analytic structure I like the answer pointing out that analytic riemann surfaces can have many non isomorphic structures on the same smooth manifold. this is interesting already for genus one manifolds. and it is not trivial to show that the sphere has only one complex analytic structure.
that might be a fun challenge to a class, to show two Riemann surfaces both diffeomorphic to the 2-sphere, are holomorphically isomorphic.
You might also be interested in some of the articles by Kolla'r on the Nash conjecture contrasting real varieties and real manifolds. such as "What are the simplest varieties?", Bulletin, vol 38. I like the pair of theorems 54, 51, subtitled respectively: "the Nash conjecture is true in dim 3", and "The Nash conjecture is false in dim 3". | A connected real manifold can be disconnected by the removal of a submanifold but the complement of a subvariety on an irreducible variety is still connected. |
23,936 | I have the following setup:
There is a collection of items I and a collection of partial rankings V. That is, an element of V is a total ordering on a subset of I. There is no expectation of consistency among the elements of V: it may be that x < y for one element and y < x for another.
I would like to assign a score $s : I \to \mathbb{R}$ which in some sense captures these rankings. That is, I would like s(x) < s(y) to mean "x tends to be less than y for elements of V which have both in their domain". I'm not sure of what a good way to do this is.
[Arrow's impossibility theorem](http://en.wikipedia.org/wiki/Arrow%27s_impossibility_theorem) puts some constraints on what can be achieved here, because given a set of votes and a scoring function like this we could use the scoring function to define a total order on the items, which is then constrained by the theorem.
I suppose I'm really looking for references rather than an answer to this question (although both would be appreciated): I'm sure there's a body of theory around this, but I have no idea what it is like or what it's called, so I'm at a bit of a loss as to where to start looking for a solution. | 2010/05/08 | [
"https://mathoverflow.net/questions/23936",
"https://mathoverflow.net",
"https://mathoverflow.net/users/4959/"
] | Some of these properties are local, and distinguish analytic and algebraic functions, from smooth functions.
Others are global and distinguish compact manifolds from projective manifolds by their difference in containment of many subvarieties.
some are as simple as contrasting the dimension, and homology of say projective Real space from that of projective Complex space, as noted.
As a deep contrast between smooth and analytic structure I like the answer pointing out that analytic riemann surfaces can have many non isomorphic structures on the same smooth manifold. this is interesting already for genus one manifolds. and it is not trivial to show that the sphere has only one complex analytic structure.
that might be a fun challenge to a class, to show two Riemann surfaces both diffeomorphic to the 2-sphere, are holomorphically isomorphic.
You might also be interested in some of the articles by Kolla'r on the Nash conjecture contrasting real varieties and real manifolds. such as "What are the simplest varieties?", Bulletin, vol 38. I like the pair of theorems 54, 51, subtitled respectively: "the Nash conjecture is true in dim 3", and "The Nash conjecture is false in dim 3". | For a closed analytic subset Z ⊂ S of a (say compact) complex manifold
with complement U=S-Z one has additivity of the (topological) Euler characteristic:
Χ(S)=Χ(Z)+Χ(U).
This is wrong for if S and Z are topological spaces or smooth manifolds.
Indeed, take for Z a point on a circle S.
This (surprising) difference was recently pointed out to me by Manfred Lehn.
Of course there is also no additivity of Poincare-Polynomials or other
"motivic" invariants of complex varieties. |
23,936 | I have the following setup:
There is a collection of items I and a collection of partial rankings V. That is, an element of V is a total ordering on a subset of I. There is no expectation of consistency among the elements of V: it may be that x < y for one element and y < x for another.
I would like to assign a score $s : I \to \mathbb{R}$ which in some sense captures these rankings. That is, I would like s(x) < s(y) to mean "x tends to be less than y for elements of V which have both in their domain". I'm not sure of what a good way to do this is.
[Arrow's impossibility theorem](http://en.wikipedia.org/wiki/Arrow%27s_impossibility_theorem) puts some constraints on what can be achieved here, because given a set of votes and a scoring function like this we could use the scoring function to define a total order on the items, which is then constrained by the theorem.
I suppose I'm really looking for references rather than an answer to this question (although both would be appreciated): I'm sure there's a body of theory around this, but I have no idea what it is like or what it's called, so I'm at a bit of a loss as to where to start looking for a solution. | 2010/05/08 | [
"https://mathoverflow.net/questions/23936",
"https://mathoverflow.net",
"https://mathoverflow.net/users/4959/"
] | Here is a list biased towards what is remarkable in the complex case. (To the potential peeved real manifold: I love you too.) By "complex" I mean holomorphic manifolds and holomorphic maps; by "real" I mean $\mathcal{C}^{\infty}$ manifolds and $\mathcal{C}^{\infty}$ maps.
* Consider a map $f$ between manifolds of *equal* dimension.
In the complex case: if $f$ is injective then it is an isomorphism onto its image. In the real case, $x\mapsto x^3$ is not invertible.
* Consider a holomorphic $f: U-K \rightarrow \mathbb{C}$, where $U\subset \mathbb{C}^n$ is open and $K$ is a compact s.t. $U-K$ is connected. When $n\geq 2$, $f$ extends to $U$. This so-called Hartogs phenomenon has no counterpart in the real case.
* If a complex manifold is compact or is a bounded open subset of $\mathbb{C}^n$, then its group of automorphisms is a Lie group. In the smooth case it is always infinite dimensional.
* The space of sections of a vector bundle over a compact complex manifold is finite dimensional. In the real case it is always infinite dimensional.
* To expand on Charles Staats's excellent answer: few smooth atlases happen to be holomorphic, but even fewer diffeomorphisms happen to be holomorphic. Considering manifolds up to isomorphism, the net result is that many complex manifolds come in continuous families, whereas real manifolds rarely do (in dimension other than $4$: a compact topological manifold has at most finitely many smooth structures; $\mathbb{R}^n$ has exactly one).
On the theme of *zero subsets* (i.e., subsets defined locally by the vanishing of one or several functions):
* *One* equation always defines a *codimension one* subset in the complex case, but
{$x\_1^2+\dots+x\_n^2=0$} is reduced to one point in $\mathbb{R}^n$.
* In the complex case, a zero subset isn't necessarily a submanifold, but
is amenable to manifold theory by Hironaka desingularization. In the real case, *any* closed subset is a zero set.
* The image of a proper map between two complex manifolds is a zero subset, so isn't too bad by the previous point. Such a direct image is hard to deal with in the real case. | A proper variety doesn't have (non-constant) global sections. A real manifold, compact or not, has lots of global sections.
There are lots of maps between real manifolds. Maps between varieties are much more restricted (e.g. by Riemann-Hurwitz in the case of curves). |
23,936 | I have the following setup:
There is a collection of items I and a collection of partial rankings V. That is, an element of V is a total ordering on a subset of I. There is no expectation of consistency among the elements of V: it may be that x < y for one element and y < x for another.
I would like to assign a score $s : I \to \mathbb{R}$ which in some sense captures these rankings. That is, I would like s(x) < s(y) to mean "x tends to be less than y for elements of V which have both in their domain". I'm not sure of what a good way to do this is.
[Arrow's impossibility theorem](http://en.wikipedia.org/wiki/Arrow%27s_impossibility_theorem) puts some constraints on what can be achieved here, because given a set of votes and a scoring function like this we could use the scoring function to define a total order on the items, which is then constrained by the theorem.
I suppose I'm really looking for references rather than an answer to this question (although both would be appreciated): I'm sure there's a body of theory around this, but I have no idea what it is like or what it's called, so I'm at a bit of a loss as to where to start looking for a solution. | 2010/05/08 | [
"https://mathoverflow.net/questions/23936",
"https://mathoverflow.net",
"https://mathoverflow.net/users/4959/"
] | Some embedding statements.
A compact complex subvariety of ${\mathbb{C}}^n$ is a point. However, every compact real manifold of dimension $n$ can be realized as a submanifold of some ${\mathbb{R}}^{2n}$.
There are compact complex manifolds that cannot be embedded into complex projective space. An example most often quoted in textbooks is the Hopf manifold, which is not even Kahler. On the other hand, I heard that embedding into real projective space is not often considered in differential geometry. | For a closed analytic subset Z ⊂ S of a (say compact) complex manifold
with complement U=S-Z one has additivity of the (topological) Euler characteristic:
Χ(S)=Χ(Z)+Χ(U).
This is wrong for if S and Z are topological spaces or smooth manifolds.
Indeed, take for Z a point on a circle S.
This (surprising) difference was recently pointed out to me by Manfred Lehn.
Of course there is also no additivity of Poincare-Polynomials or other
"motivic" invariants of complex varieties. |
23,936 | I have the following setup:
There is a collection of items I and a collection of partial rankings V. That is, an element of V is a total ordering on a subset of I. There is no expectation of consistency among the elements of V: it may be that x < y for one element and y < x for another.
I would like to assign a score $s : I \to \mathbb{R}$ which in some sense captures these rankings. That is, I would like s(x) < s(y) to mean "x tends to be less than y for elements of V which have both in their domain". I'm not sure of what a good way to do this is.
[Arrow's impossibility theorem](http://en.wikipedia.org/wiki/Arrow%27s_impossibility_theorem) puts some constraints on what can be achieved here, because given a set of votes and a scoring function like this we could use the scoring function to define a total order on the items, which is then constrained by the theorem.
I suppose I'm really looking for references rather than an answer to this question (although both would be appreciated): I'm sure there's a body of theory around this, but I have no idea what it is like or what it's called, so I'm at a bit of a loss as to where to start looking for a solution. | 2010/05/08 | [
"https://mathoverflow.net/questions/23936",
"https://mathoverflow.net",
"https://mathoverflow.net/users/4959/"
] | Here is a list biased towards what is remarkable in the complex case. (To the potential peeved real manifold: I love you too.) By "complex" I mean holomorphic manifolds and holomorphic maps; by "real" I mean $\mathcal{C}^{\infty}$ manifolds and $\mathcal{C}^{\infty}$ maps.
* Consider a map $f$ between manifolds of *equal* dimension.
In the complex case: if $f$ is injective then it is an isomorphism onto its image. In the real case, $x\mapsto x^3$ is not invertible.
* Consider a holomorphic $f: U-K \rightarrow \mathbb{C}$, where $U\subset \mathbb{C}^n$ is open and $K$ is a compact s.t. $U-K$ is connected. When $n\geq 2$, $f$ extends to $U$. This so-called Hartogs phenomenon has no counterpart in the real case.
* If a complex manifold is compact or is a bounded open subset of $\mathbb{C}^n$, then its group of automorphisms is a Lie group. In the smooth case it is always infinite dimensional.
* The space of sections of a vector bundle over a compact complex manifold is finite dimensional. In the real case it is always infinite dimensional.
* To expand on Charles Staats's excellent answer: few smooth atlases happen to be holomorphic, but even fewer diffeomorphisms happen to be holomorphic. Considering manifolds up to isomorphism, the net result is that many complex manifolds come in continuous families, whereas real manifolds rarely do (in dimension other than $4$: a compact topological manifold has at most finitely many smooth structures; $\mathbb{R}^n$ has exactly one).
On the theme of *zero subsets* (i.e., subsets defined locally by the vanishing of one or several functions):
* *One* equation always defines a *codimension one* subset in the complex case, but
{$x\_1^2+\dots+x\_n^2=0$} is reduced to one point in $\mathbb{R}^n$.
* In the complex case, a zero subset isn't necessarily a submanifold, but
is amenable to manifold theory by Hironaka desingularization. In the real case, *any* closed subset is a zero set.
* The image of a proper map between two complex manifolds is a zero subset, so isn't too bad by the previous point. Such a direct image is hard to deal with in the real case. | A connected real manifold can be disconnected by the removal of a submanifold but the complement of a subvariety on an irreducible variety is still connected. |
23,936 | I have the following setup:
There is a collection of items I and a collection of partial rankings V. That is, an element of V is a total ordering on a subset of I. There is no expectation of consistency among the elements of V: it may be that x < y for one element and y < x for another.
I would like to assign a score $s : I \to \mathbb{R}$ which in some sense captures these rankings. That is, I would like s(x) < s(y) to mean "x tends to be less than y for elements of V which have both in their domain". I'm not sure of what a good way to do this is.
[Arrow's impossibility theorem](http://en.wikipedia.org/wiki/Arrow%27s_impossibility_theorem) puts some constraints on what can be achieved here, because given a set of votes and a scoring function like this we could use the scoring function to define a total order on the items, which is then constrained by the theorem.
I suppose I'm really looking for references rather than an answer to this question (although both would be appreciated): I'm sure there's a body of theory around this, but I have no idea what it is like or what it's called, so I'm at a bit of a loss as to where to start looking for a solution. | 2010/05/08 | [
"https://mathoverflow.net/questions/23936",
"https://mathoverflow.net",
"https://mathoverflow.net/users/4959/"
] | Some embedding statements.
A compact complex subvariety of ${\mathbb{C}}^n$ is a point. However, every compact real manifold of dimension $n$ can be realized as a submanifold of some ${\mathbb{R}}^{2n}$.
There are compact complex manifolds that cannot be embedded into complex projective space. An example most often quoted in textbooks is the Hopf manifold, which is not even Kahler. On the other hand, I heard that embedding into real projective space is not often considered in differential geometry. | I think there's some big difference concerning the metric approach too.
In fact, the Gram-Schmidt process (which is real analytic) enables us -in real differential geometry- to find some local orthonormal frames (for any hermitian bundle, and in particular for the tangent bundle), whereas in the holomorphic case, very subtle differences may occur there.
For example, in the Kähler case, we can find "orthonormal" frames for the tangent bundle at order 2, which is the key for the Kähler identities, leading to fundamental results like the equality of all Laplacians and thus the Hodge decomposition theorem in the compact case. |
23,936 | I have the following setup:
There is a collection of items I and a collection of partial rankings V. That is, an element of V is a total ordering on a subset of I. There is no expectation of consistency among the elements of V: it may be that x < y for one element and y < x for another.
I would like to assign a score $s : I \to \mathbb{R}$ which in some sense captures these rankings. That is, I would like s(x) < s(y) to mean "x tends to be less than y for elements of V which have both in their domain". I'm not sure of what a good way to do this is.
[Arrow's impossibility theorem](http://en.wikipedia.org/wiki/Arrow%27s_impossibility_theorem) puts some constraints on what can be achieved here, because given a set of votes and a scoring function like this we could use the scoring function to define a total order on the items, which is then constrained by the theorem.
I suppose I'm really looking for references rather than an answer to this question (although both would be appreciated): I'm sure there's a body of theory around this, but I have no idea what it is like or what it's called, so I'm at a bit of a loss as to where to start looking for a solution. | 2010/05/08 | [
"https://mathoverflow.net/questions/23936",
"https://mathoverflow.net",
"https://mathoverflow.net/users/4959/"
] | Some of these properties are local, and distinguish analytic and algebraic functions, from smooth functions.
Others are global and distinguish compact manifolds from projective manifolds by their difference in containment of many subvarieties.
some are as simple as contrasting the dimension, and homology of say projective Real space from that of projective Complex space, as noted.
As a deep contrast between smooth and analytic structure I like the answer pointing out that analytic riemann surfaces can have many non isomorphic structures on the same smooth manifold. this is interesting already for genus one manifolds. and it is not trivial to show that the sphere has only one complex analytic structure.
that might be a fun challenge to a class, to show two Riemann surfaces both diffeomorphic to the 2-sphere, are holomorphically isomorphic.
You might also be interested in some of the articles by Kolla'r on the Nash conjecture contrasting real varieties and real manifolds. such as "What are the simplest varieties?", Bulletin, vol 38. I like the pair of theorems 54, 51, subtitled respectively: "the Nash conjecture is true in dim 3", and "The Nash conjecture is false in dim 3". | I think there's some big difference concerning the metric approach too.
In fact, the Gram-Schmidt process (which is real analytic) enables us -in real differential geometry- to find some local orthonormal frames (for any hermitian bundle, and in particular for the tangent bundle), whereas in the holomorphic case, very subtle differences may occur there.
For example, in the Kähler case, we can find "orthonormal" frames for the tangent bundle at order 2, which is the key for the Kähler identities, leading to fundamental results like the equality of all Laplacians and thus the Hodge decomposition theorem in the compact case. |
11,289,905 | I can't understand what is happening in my code:
```
for (NSMutableDictionary *dict in jsonResponse) {
NSString *days = [dict objectForKey:@"dayOfTheWeek"];
NSArray *arrayDays = [days componentsSeparatedByString:@" "];
NSLog(@"la var %@ size %lu", days, sizeof(arrayDays));
for(int i = 0; i<sizeof(arrayDays); i++){
NSLog(@"el dia %@",[arrayDays objectAtIndex:i]);
}
}
```
What I get in log:
```
2012-07-02 10:06:57.191 usualBike[1342:f803] var M T W T F size 4
2012-07-02 10:06:57.191 usualBike[1342:f803] day M
2012-07-02 10:06:57.192 usualBike[1342:f803] day T
2012-07-02 10:06:57.192 usualBike[1342:f803] day W
2012-07-02 10:06:57.193 usualBike[1342:f803] day T
2012-07-02 10:06:57.193 usualBike[1342:f803] var S S size 4
2012-07-02 10:06:57.194 usualBike[1342:f803] day S
2012-07-02 10:06:57.194 usualBike[1342:f803] day S
```
And crashes, because position 3 doesn't exist.
Why the size is not changing the second time? it should be 1.
Thank you in advance | 2012/07/02 | [
"https://Stackoverflow.com/questions/11289905",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1256477/"
] | Regex!
```
re.sub('[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}','CENSORED_IP',data)
```
Worthy of note, this also matches things like 999.999.999.999. If that's a problem, you will have to get a regex that is a little more complicated. Furthermore, this only works on IPv4 Addresses.
On only valid IP's:
```
re.sub('(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)','CENSORED_IP',data)
```
Source: [Regex Source](https://stackoverflow.com/questions/4011855/regexp-to-check-if-an-ip-is-valid) | For IPv4 Addresses you can use the Regex provided by [Regular-Expression.info](http://www.regular-expressions.info/examples.html). This will ensure that your IP Address is actually valid.
>
> Matching an IP address is another good example of a trade-off between regex complexity and exactness. \b\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}\b will match any IP address just fine, but will also match 999.999.999.999 as if it were a valid IP address. Whether this is a problem depends on the files or data you intend to apply the regex to. To restrict all 4 numbers in the IP address to 0..255, you can use this complex beast: \b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b Analyze this regular expression with RegexBuddy (everything on a single line). The long regex stores each of the 4 numbers of the IP address into a capturing group. You can use these groups to further process the IP number.
>
>
> If you don't need access to the individual numbers, you can shorten the regex with a quantifier to: \b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b Analyze this regular expression with RegexBuddy. Similarly, you can shorten the quick regex to \b(?:\d{1,3}.){3}\d{1,3}\b Analyze this regular expression with RegexBuddy
>
>
> |
394,250 | Here's a snippet of code:
An inlined function:
```
inline void rayStep(const glm::vec3 &ray, float &rayLength, const glm::vec3 &distanceFactor, glm::ivec3 ¤tVoxelCoordinates, const glm::ivec3 &raySign, const glm::ivec3 &rayPositive, glm::vec3 &positionInVoxel, const int smallestIndex) {
rayLength += distanceFactor[smallestIndex];
currentVoxelCoordinates[smallestIndex] += raySign[smallestIndex];
positionInVoxel += ray * glm::vec3(distanceFactor[smallestIndex]);
positionInVoxel[smallestIndex] = 1 - rayPositive[smallestIndex];
}
```
It's usage:
```
glm::ivec3 distanceFactor = (glm::vec3(rayPositive) - positionInVoxel) / ray;
if (distanceFactor.x < distanceFactor.y)
{
if (distanceFactor.x < distanceFactor.z)
{
rayStep(ray, rayLength, distanceFactor, currentVoxelCoordinates, raySign, rayPositive, positionInVoxel, 0);
}
else
{
rayStep(ray, rayLength, distanceFactor, currentVoxelCoordinates, raySign, rayPositive, positionInVoxel, 2);
}
}
else
{
if (distanceFactor.y < distanceFactor.z)
{
rayStep(ray, rayLength, distanceFactor, currentVoxelCoordinates, raySign, rayPositive, positionInVoxel, 1);
}
else
{
rayStep(ray, rayLength, distanceFactor, currentVoxelCoordinates, raySign, rayPositive, positionInVoxel, 2);
}
}
```
I really dislike the way the usage of the function looks like.
One way I could fix it is to calculate the index of the smallest component
and then just use the body of the function directly in the code:
```
int smallestIndex = (distanceFactor.x < distanceFactor.y) ? (distanceFactor.x < distanceFactor.z ? 0 : 2) : (distanceFactor.y < distanceFactor.z ? 1 : 2);
rayLength += distanceFactor[smallestIndex];
currentVoxelCoordinates[smallestIndex] += raySign[smallestIndex];
positionInVoxel += ray * glm::vec3(distanceFactor[smallestIndex]);
positionInVoxel[smallestIndex] = 1 - rayPositive[smallestIndex];
```
This looks much cleaner to me.
So why haven't I done that, if it bothers me so much?
The benefit of the above code is that value of the `smallestComponentIndex` of the function is know at compile time - the value is given as a constant and the function is inlined. This enables the compiler to do some optimizations which it wouldn't be able to do if the value were unknown during the compile time - which is what happens in the example with double ternary operator.
The performance hit in my example is not small, the code goes from 30ms to about 45ms of execution time - that's 50% increase.
This seems negligible, but this is a part of a simple ray tracer - if I want to scale it to do more complex calculations, I need this part to be as fast as possible, since it's done once per ray intersection. This was run on low resolution with a single ray per pixel, with no light sources taken into account. A simple ray cast, really, hence the runtime of 30ish ms.
Is there any way I can have both the code expression and speed? Some nicer way to express what I want to do, while making sure that value of the `smallestComponentIndex` is known at compile time? | 2019/07/04 | [
"https://softwareengineering.stackexchange.com/questions/394250",
"https://softwareengineering.stackexchange.com",
"https://softwareengineering.stackexchange.com/users/247488/"
] | This is going to be a frame challenge answer.
>
> It is possible to design base class in a way that I have to pass connection string only once and not for each of the 4 concrete classes?
>
>
>
You *shouldn't* try to achieve what you want to with a base class.
Why not?
========
Basically, if you use a base class for this, it might work fine now. Over time, your code will get more and more complex. The older code is, the more difficult it is to change it. And then when at some point one of your repos needs a different connection string, you will have to untangle everything and it. will. be. PAIN.
So having to provide the connection string to each repo is actually *a good thing*. In the end. At the moment it seems like just more work, but it's worth it going forward.
What instead?
=============
This is a situation where [favoring composition over inheritance](https://en.wikipedia.org/wiki/Composition_over_inheritance) is actually easier then messing around with inheritance in a way it isn't really supposed to be used. "Switching over" won't actually be a lot of work for you, because you already have the common functionality in your base class. In order to adjust it just
* give it a more fitting name, `RepoConnector` or something like that
* make it non-abstract
* make the constructor public or internal
Then you can *inject* it into your repos, store it in a field and use it from there. For example, your `RegionRepo` would look something like this:
```
internal class RegionRepo
{
private readonly RepoConnector _repoConnector ;
public RegionRepo(RepoConnector repoConnector, int variantId)
{
_repoConnector = repoConnector;
VariantId = variantId;
}
public int GetRegionIdByVariantId()
{
string query = "";
List<SqlParameter> parameters = new List<SqlParameter>();
parameters.Add(new SqlParameter("@id", VariantId));
return _repoConnector.ExecuteScalar(query, parameters);
}
}
```
Admittedly, this isn't exactly what you wanted. Now the connection string is only provided once, but instead the `RepoConnector` is being passed to all the repos.
However, passing the info to each repo is the "proper" way to do it that won't give you headaches later on. Also, you do still get "the best of both worlds": If you want to change the connection string, there's only one place to change now, PLUS you won't have to rewrite common functionality for each repo.
"Dirty logic"?
==============
The same advice does not really apply for this bit:
```
List<SqlParameter> parameters = new List<SqlParameter>();
parameters.Add(new SqlParameter("@TestId", TestId));
parameters.Add(new SqlParameter("@VariantId", VariantId));
```
It's not *that* dirty. However, you say "*I have to do this at so many places*". If it's really bad enough, you *might* want to add a little helper method to the `RepoConnector`, something like this:
```
internal void ExecuteQuery(string query, string name1, int value1,
string name2, int value2)
{
List<SqlParameter> parameters = new List<SqlParameter>();
parameters.Add(new SqlParameter(name1, value1));
parameters.Add(new SqlParameter(name2, value2));
ExecuteQuery(query, parameters);
}
```
As is probably obvious, this only helps if you're really doing the same thing (as in the example, "calling ExecuteQuery with 2 int parameters") multiple times. Another alternative might be using `params`:
```
void ExecuteQuery(string query, params SqlParameter[] parameters)
{
// Everything else can stay the same here because foreach still works on arrays
}
// You can now call it this way:
ExecuteQuery(query, new SqlParameter("@TestId", TestId), new SqlParameter("@VariantId", VariantId));
// You can put as many "new SqlParameter()" as you want, or even without any:
ExecuteQuery(query);
```
But again, this doesn't give you *a lot*, so it's only worth it in some cases. If you're always doing slightly different things, it's probably easier to do that by writing slightly different code for each. | >
> It is possible to design base class in a way that I have to pass connection string only once and not for each of the 4 concrete classes?
>
>
>
Short answer - No.
If you're going to use inheritance and work with [instances of] subclasses, then you have to use the proper plumbing to allow the derived classes to work with the base class.
When you instantiate instances of the subclasses, .Net implicitly constructs the base class *for you* and, given the constructors you've got defined, that construction process requires the connection string, so you *have* to pass it from subclass to base class.
This is perfectly normal and nothing to be concerned about.
>
> I want to hide this below dirty logic ...
>
>
>
I wouldn't say it was particularly "dirty".
It's clear, explicit in what it's doing, can be understood at a glance and is probably specific to each, individual, execution. Personally, I'm not seeing a problem with it.
Sure, you *could* replace it with some sort of "parameter builder", like this:
```
List<SqlParameter> parameters = new CustomSqlParameterBuilder()
.AddNameValue( "@TestId", TestId )
.AddNameTypeValue( "@VariantId", GetType( System.Int32 ), VariantId )
.Build();
```
... but is it that really any clearer / quicker / better?
YMMV. |
1,271,166 | I am looking for help to achieve the following
The Diagram represents a car, users can add engine and colour
when I view the XML it looks like this:
```
<Car>
<Engine>BigEngine</Engine>
<Colour>Pink</Colour>
</Car>
```
What I would like to do is to wrap the car inside 'vehicle', i.e
```
<Vehicle>
<Car>
<Engine>BigEngine</Engine>
<Colour>Pink</Colour>
</Car>
</Vehicle>
```
I am not sure of the best way to achieve this. I want the model explorer and the generated XML to be wrapped in 'vehicle' but for all other intents and purposes the user is working with a car only
Info: Visual Studio 2010, C# and DSL SDK for 2010 | 2009/08/13 | [
"https://Stackoverflow.com/questions/1271166",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/76581/"
] | not sure how to do it in Jquery
```
window.onbeforeunload = function (e) {
var e = e || window.event;
// For IE and Firefox
if (e) {
e.returnValue = 'Any string';
}
// For Safari
return 'Any string';
};
```
<https://developer.mozilla.org/en/DOM/window.onbeforeunload> | The event you're looking for is beforeunload, you can stop a page refresh like this:
```
$(window).bind('beforeunload', function(){
return '';
});
``` |
1,271,166 | I am looking for help to achieve the following
The Diagram represents a car, users can add engine and colour
when I view the XML it looks like this:
```
<Car>
<Engine>BigEngine</Engine>
<Colour>Pink</Colour>
</Car>
```
What I would like to do is to wrap the car inside 'vehicle', i.e
```
<Vehicle>
<Car>
<Engine>BigEngine</Engine>
<Colour>Pink</Colour>
</Car>
</Vehicle>
```
I am not sure of the best way to achieve this. I want the model explorer and the generated XML to be wrapped in 'vehicle' but for all other intents and purposes the user is working with a car only
Info: Visual Studio 2010, C# and DSL SDK for 2010 | 2009/08/13 | [
"https://Stackoverflow.com/questions/1271166",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/76581/"
] | On $(document).load()
* read a var current\_page from cookie
* if it's the same as your current page, you have a refresh
* write current page to var current\_page in cookie | The event you're looking for is beforeunload, you can stop a page refresh like this:
```
$(window).bind('beforeunload', function(){
return '';
});
``` |
23,600 | Any idea how to write this code better."the html is nested tabs"
Two selectors and two similar events, in a function would be better or a pattern to reduce lines. [eg .jsbin](http://jsbin.com/utaxot/3/edit)
```
$(function() {
var $items = $('#vtab>ul>li'),
$items2 = $('#vtab2>ul>li');
$items.mouseover(function() {
var index = $items.index($(this));
$items.removeClass('selected');
$(this).addClass('selected');
$('#vtab>div').hide().eq(index).show();
}).eq(1).mouseover();
$items2.mouseover(function() {
var index = $items2.index($(this));
$items2.removeClass('selected');
$(this).addClass('selected');
$('#vtab2>div').hide().eq(index).show();
}).eq(1).mouseover();
});
``` | 2013/03/08 | [
"https://codereview.stackexchange.com/questions/23600",
"https://codereview.stackexchange.com",
"https://codereview.stackexchange.com/users/22919/"
] | First of all, your code has a bug: You did not follow the [rule of three](http://en.wikipedia.org/wiki/Rule_of_three_%28C++_programming%29).
Code such as `myStack1 = myStack2;` will cause the pointer to be deleted twice - which is undefined behavior.
---
```
int storedElements;
```
This seems kind of misleading. This variable doesn't hold the *stored elements*. It holds the *number of stored elements*. Perhaps `storedElementsCount` or something like that would be better?
---
```
myStaticIntStack( int aNumber );
```
Why did you call the variable `aNumber` here? `aNumber` is a *terrible* name. It tells me essentially *nothing*. Later you used `stackSize` which is a **FAR** better name. Why didn't you use it here too?
And, by the way, consider using `size_t` to store sizes and capacities instead of ints. This would apply to `stackSize` and `storedElements`.
---
```
myStaticIntStack::myStaticIntStack()
{
this->stackSize = 1;
this->elements = new int(0);
this->storedElements = 0;
}
```
Seriously? The default behavior for the stack is to create a stack with maximum size 1? That is kind of... worthless. It's OK to allow this in the myStaticIntStack(int) constructor, but as a *default* it just seems odd.
Consider not even allowing a default constructor.
---
```
myStaticIntStack::myStaticIntStack( int stackSize )
{
this->stackSize = stackSize;
this->elements = new int[ stackSize ];
this->storedElements = 0;
}
```
Can the stackSize be zero? Can it be negative? Consider adding an assertion.
By the way, if you make stackSize be a size\_t, the negative case becomes impossible, since size\_t is unsigned. But you'll still need to handle the "stackSize == 0" case.
A size of 0 might be acceptable. If that is the case, add a comment stating that and why it is so.
Consider declaring this constructor `explicit`.
---
```
myStaticIntStack::~myStaticIntStack()
{
if( this->elements != NULL )
{
if( stackSize > 1 )
delete[] this->elements;
else
delete this->elements;
}
}
```
Why do you need a NULL check? Are you expecting the destructor to be called with `elements == NULL`? If this merely defensive programming and this case is never supposed to happen, then leave it as an assertion.
Also, that whole `delete` vs `delete[]` is weird. What if I use the constructor `myStaticIntStack(1)`? Then you'll be `delete`ing something created with `new[]`.
I'd change the code (from the constructors) so that `new[]` - not `new` - is always used and, therefore, `delete[]` is always the right thing to do in the destructor.
---
```
void myStaticIntStack::push( int newElement )
{
if( this->storedElements == this->stackSize )
cout << "Stack is full, you must POP an element before PUSHing a new one!" << endl;
else
{
this->elements[ (this->stackSize - 1) - this->storedElements ] = newElement;
this->storedElements++;
}
}
```
This is improper error handling that violates the single responsibility principle.
Your function should either throw an exception, merely assert the condition or return an error code. Printing to the command line should be done elsewhere - probably *outside* this class.
---
```
this->elements[ (this->stackSize - 1) - this->storedElements ] = newElement;
```
I'm pretty sure you could simplify this. For a stackSize=16, the first position is at index 15. Why 15? Why not 0? That'd simplify the code to just `elements[storedElements] = newElement;`. Just remember to also fix the pop/peek code.
Just because the stack is Last-in-first-out doesn't mean you have to fill the last indexes in the internal array first. That's an implementation detail.
---
>
> it's confusing that pop() returns a value even if Stack is empty.
>
>
>
Then *don't* return a value if the Stack is empty. Throw an exception or abort with an assertion. Problem solved. Next.
As I stated before, your `cout`s are in the wrong place. If you fix that the "Pop return" problem might just naturally go away.
If you decide to keep it like that (return -1), then consider making `-1` a named constant since [magic numbers](https://stackoverflow.com/questions/47882/what-is-a-magic-number-and-why-is-it-bad) are bad.
```
return ERROR_STACK_IS_EMPTY;
```
---
```
int myStaticIntStack::peek()
```
Same thing about `cout`.
Also, `peek()` doesn't change anything, does it? Then consider making it `const`.
```
int myStaticIntStack::peek() const
```
---
Consider splitting your myStaticIntStack in two files: `myStaticIntStack.hpp` and `myStaticIntStack.cpp`.
Your main function would be in a third file.
---
Some extra thoughts:
* I suspect the "better way" might be to just use a vector internally. This would painlessly solve your "rule of three" problem. Bonus points since it'd make it easier to "resize" the stack after being created if you ever wanted to add that feature.
* Personally, I'd uppercase the first letter of the class name, but that's just personal preference. Nothing wrong with your particular style.
* Consider adding a `bool empty()` function, that checks if the stack is empty.
* Consider adding a `bool full()` function, that checks if the stack is full.
* Those two functions above could make your error detection code easier to understand. If your assignment forbids adding extra functions, consider adding them as private functions.
* Consider adding a `int size()` function, that returns storedElements.
* Consider adding a `int capacity()` function, that returns stackSize
* Normally, a class like this would be implemented as a template since it's useful to have stacks for more than just integers. Not sure if you've learned about templates yet.
If you follow QuentinUK's suggestion of removing the `this->`, beware. There is one case that might cause you trouble.
In the constructor, `this->stackSize = stackSize;` is correct, but `stackSize = stackSize;` would not be.
To work around this issue, you could use something like this:
```
/*optionally add "explicit" here*/ myStaticIntStack::myStaticIntStack( int stackSize ) :
stackSize(stackSize)
{
elements = new int[ stackSize ];
storedElements = 0;
}
```
This is all I can think of right now. Hope this helps. | `this` is not always needed in member functions, you can remove all the
```
this->
```
The compiler knows this from the context.
And move brackets, e.g.:
```
int myStaticIntStack::peek() {
if( 0 == storedElements ){
cout << "Stack is empty, you must PUSH an element before PEEKing one!" << endl;
return -1;
}
else{
return elements[stackSize - storedElements ];
}
}
```
In comparisons, the `const` is safer on the left. This avoids a possible `=`, which is a common error.
You could improve it by making a vector class. You may have to do this from scratch if it is homework. It would be better than old C arrays. |
23,600 | Any idea how to write this code better."the html is nested tabs"
Two selectors and two similar events, in a function would be better or a pattern to reduce lines. [eg .jsbin](http://jsbin.com/utaxot/3/edit)
```
$(function() {
var $items = $('#vtab>ul>li'),
$items2 = $('#vtab2>ul>li');
$items.mouseover(function() {
var index = $items.index($(this));
$items.removeClass('selected');
$(this).addClass('selected');
$('#vtab>div').hide().eq(index).show();
}).eq(1).mouseover();
$items2.mouseover(function() {
var index = $items2.index($(this));
$items2.removeClass('selected');
$(this).addClass('selected');
$('#vtab2>div').hide().eq(index).show();
}).eq(1).mouseover();
});
``` | 2013/03/08 | [
"https://codereview.stackexchange.com/questions/23600",
"https://codereview.stackexchange.com",
"https://codereview.stackexchange.com/users/22919/"
] | First of all, your code has a bug: You did not follow the [rule of three](http://en.wikipedia.org/wiki/Rule_of_three_%28C++_programming%29).
Code such as `myStack1 = myStack2;` will cause the pointer to be deleted twice - which is undefined behavior.
---
```
int storedElements;
```
This seems kind of misleading. This variable doesn't hold the *stored elements*. It holds the *number of stored elements*. Perhaps `storedElementsCount` or something like that would be better?
---
```
myStaticIntStack( int aNumber );
```
Why did you call the variable `aNumber` here? `aNumber` is a *terrible* name. It tells me essentially *nothing*. Later you used `stackSize` which is a **FAR** better name. Why didn't you use it here too?
And, by the way, consider using `size_t` to store sizes and capacities instead of ints. This would apply to `stackSize` and `storedElements`.
---
```
myStaticIntStack::myStaticIntStack()
{
this->stackSize = 1;
this->elements = new int(0);
this->storedElements = 0;
}
```
Seriously? The default behavior for the stack is to create a stack with maximum size 1? That is kind of... worthless. It's OK to allow this in the myStaticIntStack(int) constructor, but as a *default* it just seems odd.
Consider not even allowing a default constructor.
---
```
myStaticIntStack::myStaticIntStack( int stackSize )
{
this->stackSize = stackSize;
this->elements = new int[ stackSize ];
this->storedElements = 0;
}
```
Can the stackSize be zero? Can it be negative? Consider adding an assertion.
By the way, if you make stackSize be a size\_t, the negative case becomes impossible, since size\_t is unsigned. But you'll still need to handle the "stackSize == 0" case.
A size of 0 might be acceptable. If that is the case, add a comment stating that and why it is so.
Consider declaring this constructor `explicit`.
---
```
myStaticIntStack::~myStaticIntStack()
{
if( this->elements != NULL )
{
if( stackSize > 1 )
delete[] this->elements;
else
delete this->elements;
}
}
```
Why do you need a NULL check? Are you expecting the destructor to be called with `elements == NULL`? If this merely defensive programming and this case is never supposed to happen, then leave it as an assertion.
Also, that whole `delete` vs `delete[]` is weird. What if I use the constructor `myStaticIntStack(1)`? Then you'll be `delete`ing something created with `new[]`.
I'd change the code (from the constructors) so that `new[]` - not `new` - is always used and, therefore, `delete[]` is always the right thing to do in the destructor.
---
```
void myStaticIntStack::push( int newElement )
{
if( this->storedElements == this->stackSize )
cout << "Stack is full, you must POP an element before PUSHing a new one!" << endl;
else
{
this->elements[ (this->stackSize - 1) - this->storedElements ] = newElement;
this->storedElements++;
}
}
```
This is improper error handling that violates the single responsibility principle.
Your function should either throw an exception, merely assert the condition or return an error code. Printing to the command line should be done elsewhere - probably *outside* this class.
---
```
this->elements[ (this->stackSize - 1) - this->storedElements ] = newElement;
```
I'm pretty sure you could simplify this. For a stackSize=16, the first position is at index 15. Why 15? Why not 0? That'd simplify the code to just `elements[storedElements] = newElement;`. Just remember to also fix the pop/peek code.
Just because the stack is Last-in-first-out doesn't mean you have to fill the last indexes in the internal array first. That's an implementation detail.
---
>
> it's confusing that pop() returns a value even if Stack is empty.
>
>
>
Then *don't* return a value if the Stack is empty. Throw an exception or abort with an assertion. Problem solved. Next.
As I stated before, your `cout`s are in the wrong place. If you fix that the "Pop return" problem might just naturally go away.
If you decide to keep it like that (return -1), then consider making `-1` a named constant since [magic numbers](https://stackoverflow.com/questions/47882/what-is-a-magic-number-and-why-is-it-bad) are bad.
```
return ERROR_STACK_IS_EMPTY;
```
---
```
int myStaticIntStack::peek()
```
Same thing about `cout`.
Also, `peek()` doesn't change anything, does it? Then consider making it `const`.
```
int myStaticIntStack::peek() const
```
---
Consider splitting your myStaticIntStack in two files: `myStaticIntStack.hpp` and `myStaticIntStack.cpp`.
Your main function would be in a third file.
---
Some extra thoughts:
* I suspect the "better way" might be to just use a vector internally. This would painlessly solve your "rule of three" problem. Bonus points since it'd make it easier to "resize" the stack after being created if you ever wanted to add that feature.
* Personally, I'd uppercase the first letter of the class name, but that's just personal preference. Nothing wrong with your particular style.
* Consider adding a `bool empty()` function, that checks if the stack is empty.
* Consider adding a `bool full()` function, that checks if the stack is full.
* Those two functions above could make your error detection code easier to understand. If your assignment forbids adding extra functions, consider adding them as private functions.
* Consider adding a `int size()` function, that returns storedElements.
* Consider adding a `int capacity()` function, that returns stackSize
* Normally, a class like this would be implemented as a template since it's useful to have stacks for more than just integers. Not sure if you've learned about templates yet.
If you follow QuentinUK's suggestion of removing the `this->`, beware. There is one case that might cause you trouble.
In the constructor, `this->stackSize = stackSize;` is correct, but `stackSize = stackSize;` would not be.
To work around this issue, you could use something like this:
```
/*optionally add "explicit" here*/ myStaticIntStack::myStaticIntStack( int stackSize ) :
stackSize(stackSize)
{
elements = new int[ stackSize ];
storedElements = 0;
}
```
This is all I can think of right now. Hope this helps. | If you have to implement a stack backwards, ok. :) It's a common thought pattern; i used to do it all the time too. But the truth is, it makes a lot of things easier if you consider the stack to grow upward.
```
void myStaticIntStack::push( int newElement )
{
if( storedElements == stackSize ) {
cout << "Stack is full, you must POP an element before PUSHing a new one!" << endl;
}
else {
// note the lack of index math :P
elements[ storedElements ] = newElement;
storedElements++;
// you could even do this all in one line like:
// elements[storedElements++] = newElement;
// but i assume you're just learning c++, so. :)
}
}
int myStaticIntStack::pop()
{
if( storedElements == 0 )
{
// For future reference, you should be throwing exceptions here, rather than
// returning an int. You're forgiven this time, cause you're new. :)
// But what if i wanted to store -1 in this thing? I can't reliably do that,
// now that you've used -1 as an error code.
cout << "Stack is empty, you must PUSH an element before POPping one!" << endl;
return -1;
}
else
{
storedElements--;
// again, note the indexing is much simpler
return elements[storedElements];
// You could likewise make this a one-liner...
// return elements[--storedElements];
}
}
``` |
23,600 | Any idea how to write this code better."the html is nested tabs"
Two selectors and two similar events, in a function would be better or a pattern to reduce lines. [eg .jsbin](http://jsbin.com/utaxot/3/edit)
```
$(function() {
var $items = $('#vtab>ul>li'),
$items2 = $('#vtab2>ul>li');
$items.mouseover(function() {
var index = $items.index($(this));
$items.removeClass('selected');
$(this).addClass('selected');
$('#vtab>div').hide().eq(index).show();
}).eq(1).mouseover();
$items2.mouseover(function() {
var index = $items2.index($(this));
$items2.removeClass('selected');
$(this).addClass('selected');
$('#vtab2>div').hide().eq(index).show();
}).eq(1).mouseover();
});
``` | 2013/03/08 | [
"https://codereview.stackexchange.com/questions/23600",
"https://codereview.stackexchange.com",
"https://codereview.stackexchange.com/users/22919/"
] | First of all, your code has a bug: You did not follow the [rule of three](http://en.wikipedia.org/wiki/Rule_of_three_%28C++_programming%29).
Code such as `myStack1 = myStack2;` will cause the pointer to be deleted twice - which is undefined behavior.
---
```
int storedElements;
```
This seems kind of misleading. This variable doesn't hold the *stored elements*. It holds the *number of stored elements*. Perhaps `storedElementsCount` or something like that would be better?
---
```
myStaticIntStack( int aNumber );
```
Why did you call the variable `aNumber` here? `aNumber` is a *terrible* name. It tells me essentially *nothing*. Later you used `stackSize` which is a **FAR** better name. Why didn't you use it here too?
And, by the way, consider using `size_t` to store sizes and capacities instead of ints. This would apply to `stackSize` and `storedElements`.
---
```
myStaticIntStack::myStaticIntStack()
{
this->stackSize = 1;
this->elements = new int(0);
this->storedElements = 0;
}
```
Seriously? The default behavior for the stack is to create a stack with maximum size 1? That is kind of... worthless. It's OK to allow this in the myStaticIntStack(int) constructor, but as a *default* it just seems odd.
Consider not even allowing a default constructor.
---
```
myStaticIntStack::myStaticIntStack( int stackSize )
{
this->stackSize = stackSize;
this->elements = new int[ stackSize ];
this->storedElements = 0;
}
```
Can the stackSize be zero? Can it be negative? Consider adding an assertion.
By the way, if you make stackSize be a size\_t, the negative case becomes impossible, since size\_t is unsigned. But you'll still need to handle the "stackSize == 0" case.
A size of 0 might be acceptable. If that is the case, add a comment stating that and why it is so.
Consider declaring this constructor `explicit`.
---
```
myStaticIntStack::~myStaticIntStack()
{
if( this->elements != NULL )
{
if( stackSize > 1 )
delete[] this->elements;
else
delete this->elements;
}
}
```
Why do you need a NULL check? Are you expecting the destructor to be called with `elements == NULL`? If this merely defensive programming and this case is never supposed to happen, then leave it as an assertion.
Also, that whole `delete` vs `delete[]` is weird. What if I use the constructor `myStaticIntStack(1)`? Then you'll be `delete`ing something created with `new[]`.
I'd change the code (from the constructors) so that `new[]` - not `new` - is always used and, therefore, `delete[]` is always the right thing to do in the destructor.
---
```
void myStaticIntStack::push( int newElement )
{
if( this->storedElements == this->stackSize )
cout << "Stack is full, you must POP an element before PUSHing a new one!" << endl;
else
{
this->elements[ (this->stackSize - 1) - this->storedElements ] = newElement;
this->storedElements++;
}
}
```
This is improper error handling that violates the single responsibility principle.
Your function should either throw an exception, merely assert the condition or return an error code. Printing to the command line should be done elsewhere - probably *outside* this class.
---
```
this->elements[ (this->stackSize - 1) - this->storedElements ] = newElement;
```
I'm pretty sure you could simplify this. For a stackSize=16, the first position is at index 15. Why 15? Why not 0? That'd simplify the code to just `elements[storedElements] = newElement;`. Just remember to also fix the pop/peek code.
Just because the stack is Last-in-first-out doesn't mean you have to fill the last indexes in the internal array first. That's an implementation detail.
---
>
> it's confusing that pop() returns a value even if Stack is empty.
>
>
>
Then *don't* return a value if the Stack is empty. Throw an exception or abort with an assertion. Problem solved. Next.
As I stated before, your `cout`s are in the wrong place. If you fix that the "Pop return" problem might just naturally go away.
If you decide to keep it like that (return -1), then consider making `-1` a named constant since [magic numbers](https://stackoverflow.com/questions/47882/what-is-a-magic-number-and-why-is-it-bad) are bad.
```
return ERROR_STACK_IS_EMPTY;
```
---
```
int myStaticIntStack::peek()
```
Same thing about `cout`.
Also, `peek()` doesn't change anything, does it? Then consider making it `const`.
```
int myStaticIntStack::peek() const
```
---
Consider splitting your myStaticIntStack in two files: `myStaticIntStack.hpp` and `myStaticIntStack.cpp`.
Your main function would be in a third file.
---
Some extra thoughts:
* I suspect the "better way" might be to just use a vector internally. This would painlessly solve your "rule of three" problem. Bonus points since it'd make it easier to "resize" the stack after being created if you ever wanted to add that feature.
* Personally, I'd uppercase the first letter of the class name, but that's just personal preference. Nothing wrong with your particular style.
* Consider adding a `bool empty()` function, that checks if the stack is empty.
* Consider adding a `bool full()` function, that checks if the stack is full.
* Those two functions above could make your error detection code easier to understand. If your assignment forbids adding extra functions, consider adding them as private functions.
* Consider adding a `int size()` function, that returns storedElements.
* Consider adding a `int capacity()` function, that returns stackSize
* Normally, a class like this would be implemented as a template since it's useful to have stacks for more than just integers. Not sure if you've learned about templates yet.
If you follow QuentinUK's suggestion of removing the `this->`, beware. There is one case that might cause you trouble.
In the constructor, `this->stackSize = stackSize;` is correct, but `stackSize = stackSize;` would not be.
To work around this issue, you could use something like this:
```
/*optionally add "explicit" here*/ myStaticIntStack::myStaticIntStack( int stackSize ) :
stackSize(stackSize)
{
elements = new int[ stackSize ];
storedElements = 0;
}
```
This is all I can think of right now. Hope this helps. | Ok, a few comments:
1. If you are going to support a stack with no capacity, I don't know why you need to allocate memory at all. You could simply have the pointer as `NULL`.
2. Using `cout` for error handling is not appropriate. You could either give "undefined behaviour" however may I suggest you throw an exception. You can handle your exceptions and use `cout` in your exception handler.
3. Implement a deep copy constructor and implement `swap()`. Then implement assignment in terms of both of these. To swap you would do:
```
void MyStaticIntStack::swap( MyStaticIntStack & other )
{
// swap each member
}
```
If you don't like using `std::swap`, write your own. I am not sure you have to avoid all STL, you probably cannot use STL containers for this because the exercise is to write your own container, but utilities like swap may be permitted (plus you can throw std exceptions).
I don't see why `-1` shouldn't be a valid number in your stack. If someone does not know whether your stack is empty and tries a `peek()` from code, they would get -1 (plus some `cout` that they cannot handle). Perhaps have a method
```
bool empty() const;
```
which tells you if the stack is empty or not. You could also have `size()` and `capacity()` access methods.
You might want to be able to resize the capacity of your stack. If you find that difficult, have a private constructor that takes a new capacity plus a reference to an existing stack. That constructor can create the data with the relevant size and copy the data into it.
Your internal method would call this constructor to create a new bigger capacity stack, then invoke the `swap()` method. The temporary one would now disappear. (Do not create it with new).
On a style issue:
1. Initialize your members in the constructor initialization list, not the body of your constructor.
2. Do not use `this->` all over the code. |
93,285 | I apologize if this is a duplicate, I can't find anything up-to-date that really helps answer my question.
I know this is nitpicky, but it's been a long battle and I am losing it.
For some time, I have been annoyed with the fact that you can't customize the android camera app's naming convention. My workaround, since the dawn of Dropbox camera upload, has been to use dropbox to upload and rename my photos (yyyy-mm-dd HH.nn.ss.jpg) and then use dropsync to overwrite the original file in my camera photo.
The problem I'm facing at the moment is that the camera in the hangouts app does not follow the same rules as the default camera app for my phone (Sony Xperia z3) so I end up with duplicates in my gallery of any image I happened to capture using hangouts instead of the camera. I could use the camera to take a picture and then share it using hangouts, but I decided instead to play around with Tasker and try to automate consolidating my images. (Another gripe I have is that Dropbox won't let me exclude folders, so I'd like to get rid of Camera Upload altogether and not have every screenshot I've ever taken backed up forever).
The directory for the default camera is [internal storage]/DCIM/100ANDRO and for hangouts it is [internal storage]/DCIM/Camera
I have a profile (below) triggered by the "file modified" event that will move the new file in the "Camera" folder into the "DCIM" folder. However, there is often a race condition, so Dropbox will upload the image before it is moved and again after. So my problem of duplicate images is not yet solved.
[
(click for larger version)](https://i.stack.imgur.com/Ur5vO.png)
I'd like to forgo the Dropbox/Dropsync combo and instead use Tasker to rename a file as it is added to either of the camera folders. I'd like to use the same naming convention that Dropbox uses, but I can't figure out how Tasker can access the EXIF data from the image to rename the photo to something like "2014-12-30 10.23.56.jpg".
So, as a tl;dr: I am using Tasker to move images captured from different apps into a common folder. Can anyone help me add a step to rename the file I am moving based on the date and time the image was captured? | 2014/12/30 | [
"https://android.stackexchange.com/questions/93285",
"https://android.stackexchange.com",
"https://android.stackexchange.com/users/87069/"
] | Use Tasker's native Java calls
==============================
Java code
---------
Use [ExifInterface.getAttribute](http://developer.android.com/reference/android/media/ExifInterface.html#getAttribute(java.lang.String)) to solve this problem.
```
exif = new ExifInterface( %filename )
%datetime = exif.getAttribute(exif.TAG_DATETIME)
```
Implementation overview
-----------------------
1. Getting path of a .JPG from `%filename` Tasker variable
2. Construct a new `ExifInterface` class instance into `exif` Java variable
3. Get date & time by `exif.getAttribute` Java function, and store results into `%datetime` Tasker variable
4. Free `exif` Java variable
5. Check `%datetime` is set *(this is not set when .JPG is not contains EXIF info)*
[](https://i.stack.imgur.com/0DRB7.png)
Step by step solution in Tasker
-------------------------------
1. Add a new **Code > Java Function** action
a. Set `ExifInterface` to **Class Or Object** *(or select by magnifying glass button)*
b. Write `new \\ {ExifInterface} (String)` to **Function** *(or select by magnifying glass button)*
c. Write `%filename` to **Param (String)**
d. Write `exif` to **Return {ExifInterface}**
[](https://i.stack.imgur.com/JQwNs.png)
2. Add a new **Code > Java Function** action
a. Write `exif` to **Class Or Object** *(or select by coffee button)*
b. Write `getAttribute \\ {String} (String)` to **Function** *(or select by magnifying glass button)*
c. Write `exif.TAG_DATETIME` to **Param (String)**
d. Write `%datetime` to **Return {String}**
[](https://i.stack.imgur.com/8WSGb.png)
3. Add a new **Code > Java Object** action
a. Left **Mode** on `Delete`
b. and write `exif` to **Name**
[](https://i.stack.imgur.com/DrHrr.png)
4. Check `%datetime` is set *- I added a conditional Flash for show `%datetime`*
**Done!** | Since you are using the "file modified" trigger (which should be instant at the moment the file is written,) you can use the current date and time instead of trying to extract the EXIF data from the images.
Tasker's [getFormattedDate](http://tasker.wikidot.com/getformatteddate) function will help with parsing the date/time and constructing the new file name. The only issue you might have is if the source folder contains more than one image. You can use a counter variable within your loop and append it to the end of the file name to mitigate that. |
50,179,858 | I've been having issues regarding this narrowing conversion error
>
> Overload resolution failed because no accessible 'Show' can be called without a narrowing conversion:
>
>
> 'Public Shared Function Show(owner As System.Windows.Forms.IWin32Window, text As String, caption As String, buttons As System.Windows.Forms.MessageBoxButtons) As System.Windows.Forms.DialogResult': Argument matching parameter 'owner' narrows from 'String' to 'System.Windows.Forms.IWin32Window'.
>
>
> 'Public Shared Function Show(owner As System.Windows.Forms.IWin32Window, text As String, caption As String, buttons As System.Windows.Forms.MessageBoxButtons) As System.Windows.Forms.DialogResult': Argument matching parameter 'caption' narrows from 'Microsoft.VisualBasic.MsgBoxStyle' to 'String'.
>
>
> 'Public Shared Function Show(owner As System.Windows.Forms.IWin32Window, text As String, caption As String, buttons As System.Windows.Forms.MessageBoxButtons) As System.Windows.Forms.DialogResult': Argument matching parameter 'buttons' narrows from 'System.Windows.Forms.MessageBoxIcon' to 'System.Windows.Forms.MessageBoxButtons'.
>
>
> 'Public Shared Function Show(text As String, caption As String, buttons As System.Windows.Forms.MessageBoxButtons, icon As System.Windows.Forms.MessageBoxIcon) As System.Windows.Forms.DialogResult': Argument matching parameter 'buttons' narrows from 'Microsoft.VisualBasic.MsgBoxStyle' to 'System.Windows.Forms.MessageBoxButtons'.
>
>
>
I did some research and the generic solution for "Overload resolution failed because no accessible '' can be called without a narrowing conversion: " errors is to Specify Option Strict Off according to Microsoft. I tried changing this manually in the Project Properties but it didn't seem to work.
This is the code where the error is occurring:
```
If MessageBox.Show("Please Enter a value for ESD (rad)", "ESD (rad) Value", MsgBoxStyle.OkCancel, MessageBoxIcon.Information) = DialogResult.OK Then
txtCal_USE_Radio.Focus()
```
I've also checked several other forums where they talk about this error but specifically related to the 'New' function and they don't seem to help.
Any help on this would be great! | 2018/05/04 | [
"https://Stackoverflow.com/questions/50179858",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9742443/"
] | You've invoking `Show({string}, {MsgBoxStyle}, {MessageBoxIcon})`, so the last overload in the error message is the closest:
>
> 'Public Shared Function Show(text As String, caption As String, buttons As System.Windows.Forms.MessageBoxButtons, icon As System.Windows.Forms.MessageBoxIcon) As System.Windows.Forms.DialogResult': Argument matching parameter 'buttons' narrows from 'Microsoft.VisualBasic.MsgBoxStyle' to 'System.Windows.Forms.MessageBoxButtons'.
>
>
>
That's `Show({String}, {String}, {MessageBoxButtons}, {MessageBoxIcon})` - you're missing a `caption` argument, and instead of `MsgBoxStyle` you should use the `MessageBoxButtons` enum.
Sounds like you have `Option Strict On` - that's ~~good~~ excellent - but it seems you also have `Imports Microsoft.VisualBasic`, which is essentially polluting your *IntelliSense* with VB6 back-compatibility stuff, which `MsgBoxStyle` is part of; that enum means to work with the legacy `MsgBox` function, which `MessageBox` is a more .NET-idiomatic replacement for.
Switching off `Option Strict` would be the single worst thing to do - you're passing a bad parameter and the compiler is telling you "I can't convert the supplied type to the expected one"; last thing to do is to make it say "hey don't worry, just implicitly convert all the things and blow up at run-time instead".
*IntelliSense*/autocomplete should be telling you what to do *as you type the arguments into the function call*; re-type the opening parenthese `(` and watch *IntelliSense* highlight the parameters and their respective types as you use the arrow keys to move the caret across the arguments you're supplying. | You are mixing your MesssageBox with MsgBox Change MsgBoxStyle.OkCancel to the MessageBox syntax.
```
If MessageBox.Show("Please Enter a value for ESD (rad)", "ESD (rad) Value", MessageBoxButtons.OKCancel, MessageBoxIcon.Information) = DialogResult.OK Then
``` |
28,235,744 | I am trying to start an external executable file via Groovy but got some problems with it! I just want to start the `rs.exe` with several parameters to create a PDF-file using the SSRS.
But as soon as I try to get the return value/exit-code it doesn't work anymore! But I want to grab the generated file and add it to a database, so I need a return value to know when its generated. This works totally fine for generating:
```
def id = 1
def cmd = """ C://Program Files (x86)//...//rs.exe
-i C:\\export.rss
-s http://localhost/ReportServer_SQLEXPRESS
-v ID=${id}
-e Exec2005 """
def proc = cmd.execute()
```
But I don't get any return value/exit-code. I already tried different way, e.g.
```
proc.waitFor()
```
but I or
```
cmd.execute().value
```
but nothing worked. When I start the `rs.exe` with all my provided data in Windows I get the return "Process succesfully ended". Any Groovy-specialists here that can help me out? | 2015/01/30 | [
"https://Stackoverflow.com/questions/28235744",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4511347/"
] | Try executing command when it's defined in the following way:
```
def cmd = ['cmd', '/c', 'C://Program Files (x86)//...//rs.exe', '-i', 'C:\\export.rss', '-s', 'http://localhost/ReportServer_SQLEXPRESS', '-v', "ID=${id}", '-e', 'Exec2005']
def proc = cmd.execute()
``` | I was able to run it now and get the exit-code. But without those escape forward-slashes I wasn't able to let it run. To get the exit-codes I just used "proc.text" and it works perfectly now.
It was working before but I didn't know how to get the exit-codes, ".text" solved it completely. Thanks for your help! |
31,758,853 | I'm currently working on a Node.js stack application used by over 25000 people, we're using Sails.js framework in particular and we got MongoDB
Application is running at a EC2 instance with 30GB of RAM, databse is running on a Mongolab AWS based cluster in same zone the EC2 is. We even got an Elastic Cache Redis instance with 1.5GB for storage.
So the main and huge problem we're facing is **LATENCY**. When we reach a peak of concurrent users requesting application we're getting multiple timeouts and sails application reaching over 7.5GB of RAM, HTTP requests to API take longer than 15 seconds (which is unacceptable) and when even get 502 and 504 responses sent by nginx.
I can notice Mongo write operations as our main latency issue, however even GET requests take long when a demand peak is present. I can't access production servers, I only got a keymetrics monitoring tool by pm2 (which is actually great) and New Relic alerts.
So, I'd like to know some roadmap to cope these issues, maybe more detailed information should be offered, so far I can say application seems stable when not much users are present.
What are main factors and setup to consider?
So far I know *what I should do*, but I'm not sure about details or the *hows*.
IMHO:
1. Cache as much as possible.
2. Delay MongoDB write operations.
3. Separate Mongo databases with higher write demand.
4. Virtualize?
5. Tune up node setups.
On optimising code, I've posted another stackoverflow question with one example of [code patterns I'm following](https://codereview.stackexchange.com/questions/98815/).
**What are your advise and opinion for production applications?** | 2015/08/01 | [
"https://Stackoverflow.com/questions/31758853",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/742560/"
] | Basically most of main points are already present in answers. I'll just summarise them.
To optimize your application you could do several main things.
1. Try to move form `node.js` to `io.js` it still have a bit better performance and latest cutting edge updated. (But read carefully about experimental features). Or at least from `node.js` `v10` to `v12`. There was lot of performance optimisations.
2. Avoid using synchronous functions that uses I/O operations or operating with big amount of data.
3. Switch from one node process to [clustering](https://nodejs.org/api/cluster.html) system.
4. Check your application to memory leaks. I'm using [memwatch-next](https://github.com/marcominetti/node-memwatch) for `node.js v12` and [memwatch](https://github.com/lloyd/node-memwatch) for `node.js v10`
5. Try to avoid saving data to global variables
6. Use caching. For data that should be accessible globally you could use `Redis` or `Memcached` is also a great store.
7. Avoid of using `async` with `Promises`. Both libs are doing same things. So no need to use both of them. (I saw that in your code example).
8. Combine `async.waterfall` with `async.parallel` methods where it could be done.
For example if you need to fetch some data from mongo that is related only to user, you could fetch user and then in parallel fetch all other data you need.
9. If you are using `sails.js` make sure that it's in `production` mode. (I assume you already did this)
10. Disable all hooks that you don't need. In most cases `grunt` hook is useless.And if you don't need `Socket.io` in your application - disable it using `.sailsrc` file. Something like:
{
"generators": {
"modules": {}
},
"hooks": {
"grunt": false,
"sockets": false
}
}
Another hooks that could be disabled are: `i18n`, `csrf`, `cors`. BUT only if you don't use them in your system.
11. Disable useless globalisation. In `config/globals.js`. I assume `_`, `async`, `services` could be disabled by default. Just because `Sails.js` uses old version of `lodash` and `async` libraries and new versions has much better performance.
12. Manually install `lodash` and `async` into `Sails.js` project and use new versions. (look point 11)
13. Some "write to mongo" operations could be made after returning result to user. For example: you can call `res.view()` method that will send response to user before `Model.save()` BUT code will continue running with all variables, so you could save data to mongo DB. So user wouldn't see delay during write operation.
14. You could use queues like [RabbitMQ](https://www.rabbitmq.com/) to perform operations that require lot of resources. For example: If you need to store big data collection you could send it to `RabbitMQ` and return response to user. Then handle this message in "background" process ad store data. It will also can help you with scaling your application. | Firstly, ensure that you are not using synchronous I/O. If you can run on `io.js`, there is `--trace-sync-io` flag (`iojs --trace-sync-io server.js`) that will warn you if you use synchronous code with the following console warning: `WARNING: Detected use of sync API`.
Secondly, find out why your RAM usage goes so high. If it's because of lots of data loaded into memory (XML parsing, large amount of data returned from MongoDB, etc), you should consider using `streams`. V8 garbage collection (Google's JavaScript VM used in `Node.js` / `io.js`) may cause slowdown if your memory usage goes very high. More here: [Node.js Performance Tip of the Week: Managing Garbage Collection](http://Node.js%20Performance%20Tip%20of%20the%20Week:%20Managing%20Garbage%20Collection) and [Node.js Performance Tip of the Week: Heap Profiling](https://strongloop.com/strongblog/node-js-performance-heap-profiling-tip/)
Thirdly, experiment with [Node.js clustering](https://strongloop.com/strongblog/node-js-performance-scaling-proxies-clusters/) and [MongoDB sharding](http://docs.mongodb.org/manual/core/sharding-introduction/).
Lastly, check if you using or can switch to `MongoDB` 3.x. We've observed some significant performance gains just by upgrading from 2.x to 3.x. |
31,758,853 | I'm currently working on a Node.js stack application used by over 25000 people, we're using Sails.js framework in particular and we got MongoDB
Application is running at a EC2 instance with 30GB of RAM, databse is running on a Mongolab AWS based cluster in same zone the EC2 is. We even got an Elastic Cache Redis instance with 1.5GB for storage.
So the main and huge problem we're facing is **LATENCY**. When we reach a peak of concurrent users requesting application we're getting multiple timeouts and sails application reaching over 7.5GB of RAM, HTTP requests to API take longer than 15 seconds (which is unacceptable) and when even get 502 and 504 responses sent by nginx.
I can notice Mongo write operations as our main latency issue, however even GET requests take long when a demand peak is present. I can't access production servers, I only got a keymetrics monitoring tool by pm2 (which is actually great) and New Relic alerts.
So, I'd like to know some roadmap to cope these issues, maybe more detailed information should be offered, so far I can say application seems stable when not much users are present.
What are main factors and setup to consider?
So far I know *what I should do*, but I'm not sure about details or the *hows*.
IMHO:
1. Cache as much as possible.
2. Delay MongoDB write operations.
3. Separate Mongo databases with higher write demand.
4. Virtualize?
5. Tune up node setups.
On optimising code, I've posted another stackoverflow question with one example of [code patterns I'm following](https://codereview.stackexchange.com/questions/98815/).
**What are your advise and opinion for production applications?** | 2015/08/01 | [
"https://Stackoverflow.com/questions/31758853",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/742560/"
] | Basically most of main points are already present in answers. I'll just summarise them.
To optimize your application you could do several main things.
1. Try to move form `node.js` to `io.js` it still have a bit better performance and latest cutting edge updated. (But read carefully about experimental features). Or at least from `node.js` `v10` to `v12`. There was lot of performance optimisations.
2. Avoid using synchronous functions that uses I/O operations or operating with big amount of data.
3. Switch from one node process to [clustering](https://nodejs.org/api/cluster.html) system.
4. Check your application to memory leaks. I'm using [memwatch-next](https://github.com/marcominetti/node-memwatch) for `node.js v12` and [memwatch](https://github.com/lloyd/node-memwatch) for `node.js v10`
5. Try to avoid saving data to global variables
6. Use caching. For data that should be accessible globally you could use `Redis` or `Memcached` is also a great store.
7. Avoid of using `async` with `Promises`. Both libs are doing same things. So no need to use both of them. (I saw that in your code example).
8. Combine `async.waterfall` with `async.parallel` methods where it could be done.
For example if you need to fetch some data from mongo that is related only to user, you could fetch user and then in parallel fetch all other data you need.
9. If you are using `sails.js` make sure that it's in `production` mode. (I assume you already did this)
10. Disable all hooks that you don't need. In most cases `grunt` hook is useless.And if you don't need `Socket.io` in your application - disable it using `.sailsrc` file. Something like:
{
"generators": {
"modules": {}
},
"hooks": {
"grunt": false,
"sockets": false
}
}
Another hooks that could be disabled are: `i18n`, `csrf`, `cors`. BUT only if you don't use them in your system.
11. Disable useless globalisation. In `config/globals.js`. I assume `_`, `async`, `services` could be disabled by default. Just because `Sails.js` uses old version of `lodash` and `async` libraries and new versions has much better performance.
12. Manually install `lodash` and `async` into `Sails.js` project and use new versions. (look point 11)
13. Some "write to mongo" operations could be made after returning result to user. For example: you can call `res.view()` method that will send response to user before `Model.save()` BUT code will continue running with all variables, so you could save data to mongo DB. So user wouldn't see delay during write operation.
14. You could use queues like [RabbitMQ](https://www.rabbitmq.com/) to perform operations that require lot of resources. For example: If you need to store big data collection you could send it to `RabbitMQ` and return response to user. Then handle this message in "background" process ad store data. It will also can help you with scaling your application. | For Mongodb you can use [mongtop](http://docs.mongodb.org/manual/reference/program/mongotop/) to see which databases are contested, 2.2+ uses per database locks, if database has write heavy workload reads will be affected as mongodb is using [writer greedy locks](http://docs.mongodb.org/v2.6/faq/concurrency/#what-type-of-locking-does-mongodb-use)
And for node.js you could check if there are any sort of event loop delays which could explain API request delays
```
(function getEventLoopDelay() {
var startTime = Date.now();
setTimeout(function() {
console.log(Math.max(Date.now() - startTime - 1000, 0));
getEventLoopDelay();
}, 100);
})();
``` |
42,850,428 | We are currently use the oob page types for Blog, News and Event. We have one page for each of these types that includes a repeater to show a list of the pages of that type. We would also like to have a page that includes a repeater that shows all blog, news and event pages in one spot, sorted by their created date.
I have seen some old comments ([here](https://devnet.kentico.com/questions/using-two-page-types-in-a-repeater), [here](https://devnet.kentico.com/questions/columns-content-filter-over-multiple-page-types)) on devnet saying that although a repeater can render multiple page types, the fields rendered must be identical across each of those page types. The workarounds suggested are either to create the same fields in each page type, or to create a custom SQL query and use a query repeater to render the data. I've done this and it works just fine, but it was pretty cumbersome to create and will be difficult to maintain. (If we want to add other page types, for example.) Can anyone suggest a more out-of-the-box method available in Kentico 10?
**Update:**
I'm trying to accomplish this as Brenden described, but am running into trouble.
My page structure is as follows:
```
Root
.RollupPage (CMS.MenuItem)
..BlogPosts (CMS.Blog)
...January 2017 (CMS.BlogMonth)
....blog post 1 (CMS.BlogPost)
...February 2017 (CMS.BlogMonth)
....blog post 2 (CMS.BlogPost)
..Events (CMS.MenuItem)
...Event1 (CMS.BookingEvent)
...Event2 (CMS.BookingEvent)
```
I've attempted to use a universal viewer, but failed to get it to return any data.
I configured it with:
```
Path: /RollupPage/%
Page types: CMS.BlogPost;CMS.BookingEvent
Hierarchical Transformation: CMS.MenuItem.HierTrans1
```
HierTrans1 has the following transformations:
```
CMS.BlogPost.Default (Item transformation for type CMS.BlogPost)
CMS.BookingEvent.EventCalendarItem (Item transformation for type CMS.BookingEvent)
```
These aren't customized at all; they are standard OOB transformations just so I can see it work.
When I view the RollupPage, the universal viewer displays nothing.
I attempted to use a Hierarchical Viewer with the same settings as I did with the Universal Viewer. It kind-of worked. It displayed my booking events but did not display any blog posts. Yet using the same blog post transformation (CMS.BlogPost.default) with hierarchical viewer whose `Path` was set to `/RollupPage/BlogPosts/%` displayed my blog posts correctly but, obviously, did not display my booking events.
The results I've gotten so far makes me think a) something about the way I've created my pages is stopping the universal viewer from traversing the whole tree and/or b) the hierarchical viewer either only goes a couple of levels deep, or maybe it is being blocked from traversing the tree too... No events are recorded when I edit or view these web parts.
Any idea what I may be doing wrong? | 2017/03/17 | [
"https://Stackoverflow.com/questions/42850428",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6683608/"
] | For this scenario use a universal viewer. Reason being is you can create a hierarchical transformation which will have different transformations for each of your unique page types. You most likely won't use the hierarchy at all but you can simply add 3 different item transformations for the different page types. | The other ways are this
1. Evaluate right `fieldname` by check object `classname` inside the transformation and assign appropriate value.
2. Dynamically assign transformation by checking the object classname |
42,850,428 | We are currently use the oob page types for Blog, News and Event. We have one page for each of these types that includes a repeater to show a list of the pages of that type. We would also like to have a page that includes a repeater that shows all blog, news and event pages in one spot, sorted by their created date.
I have seen some old comments ([here](https://devnet.kentico.com/questions/using-two-page-types-in-a-repeater), [here](https://devnet.kentico.com/questions/columns-content-filter-over-multiple-page-types)) on devnet saying that although a repeater can render multiple page types, the fields rendered must be identical across each of those page types. The workarounds suggested are either to create the same fields in each page type, or to create a custom SQL query and use a query repeater to render the data. I've done this and it works just fine, but it was pretty cumbersome to create and will be difficult to maintain. (If we want to add other page types, for example.) Can anyone suggest a more out-of-the-box method available in Kentico 10?
**Update:**
I'm trying to accomplish this as Brenden described, but am running into trouble.
My page structure is as follows:
```
Root
.RollupPage (CMS.MenuItem)
..BlogPosts (CMS.Blog)
...January 2017 (CMS.BlogMonth)
....blog post 1 (CMS.BlogPost)
...February 2017 (CMS.BlogMonth)
....blog post 2 (CMS.BlogPost)
..Events (CMS.MenuItem)
...Event1 (CMS.BookingEvent)
...Event2 (CMS.BookingEvent)
```
I've attempted to use a universal viewer, but failed to get it to return any data.
I configured it with:
```
Path: /RollupPage/%
Page types: CMS.BlogPost;CMS.BookingEvent
Hierarchical Transformation: CMS.MenuItem.HierTrans1
```
HierTrans1 has the following transformations:
```
CMS.BlogPost.Default (Item transformation for type CMS.BlogPost)
CMS.BookingEvent.EventCalendarItem (Item transformation for type CMS.BookingEvent)
```
These aren't customized at all; they are standard OOB transformations just so I can see it work.
When I view the RollupPage, the universal viewer displays nothing.
I attempted to use a Hierarchical Viewer with the same settings as I did with the Universal Viewer. It kind-of worked. It displayed my booking events but did not display any blog posts. Yet using the same blog post transformation (CMS.BlogPost.default) with hierarchical viewer whose `Path` was set to `/RollupPage/BlogPosts/%` displayed my blog posts correctly but, obviously, did not display my booking events.
The results I've gotten so far makes me think a) something about the way I've created my pages is stopping the universal viewer from traversing the whole tree and/or b) the hierarchical viewer either only goes a couple of levels deep, or maybe it is being blocked from traversing the tree too... No events are recorded when I edit or view these web parts.
Any idea what I may be doing wrong? | 2017/03/17 | [
"https://Stackoverflow.com/questions/42850428",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6683608/"
] | You can use the **Hierarchical viewer** or the **Universal viewer**, as Brenden Kehren mentioned, to achieve the goal you are describing.
When configuring the web part you must select all the **Page types** that are included in the hierarchy, in your case: **CMS.MenuItem, CMS.Blog, CMS.BlogMonth, CMS.BlogPost** and **CMSBookingEvent**.
Create a **Hierarchical transformation** to be used with your viewer and add an **Item transformation** for each of the items you wish to display. Also make sure the **Level** setting for each transformation is configured properly (-1 applies the transformation to all levels).
For **Universal viewer** it is necessary to check the property **Load hierarchical data** in the section **Extended settings** of the configuration.
As an additional note, you can leave the path property empty in case you are viewing the child documents of the current page.
For reference there is also an example on the **Corporate Site** example site in the content tree path **Examples > Web Parts > Listings and viewers > Pages > Hierarchical viewer** (or **Universal viewer**).
Hope this helps! | For this scenario use a universal viewer. Reason being is you can create a hierarchical transformation which will have different transformations for each of your unique page types. You most likely won't use the hierarchy at all but you can simply add 3 different item transformations for the different page types. |
42,850,428 | We are currently use the oob page types for Blog, News and Event. We have one page for each of these types that includes a repeater to show a list of the pages of that type. We would also like to have a page that includes a repeater that shows all blog, news and event pages in one spot, sorted by their created date.
I have seen some old comments ([here](https://devnet.kentico.com/questions/using-two-page-types-in-a-repeater), [here](https://devnet.kentico.com/questions/columns-content-filter-over-multiple-page-types)) on devnet saying that although a repeater can render multiple page types, the fields rendered must be identical across each of those page types. The workarounds suggested are either to create the same fields in each page type, or to create a custom SQL query and use a query repeater to render the data. I've done this and it works just fine, but it was pretty cumbersome to create and will be difficult to maintain. (If we want to add other page types, for example.) Can anyone suggest a more out-of-the-box method available in Kentico 10?
**Update:**
I'm trying to accomplish this as Brenden described, but am running into trouble.
My page structure is as follows:
```
Root
.RollupPage (CMS.MenuItem)
..BlogPosts (CMS.Blog)
...January 2017 (CMS.BlogMonth)
....blog post 1 (CMS.BlogPost)
...February 2017 (CMS.BlogMonth)
....blog post 2 (CMS.BlogPost)
..Events (CMS.MenuItem)
...Event1 (CMS.BookingEvent)
...Event2 (CMS.BookingEvent)
```
I've attempted to use a universal viewer, but failed to get it to return any data.
I configured it with:
```
Path: /RollupPage/%
Page types: CMS.BlogPost;CMS.BookingEvent
Hierarchical Transformation: CMS.MenuItem.HierTrans1
```
HierTrans1 has the following transformations:
```
CMS.BlogPost.Default (Item transformation for type CMS.BlogPost)
CMS.BookingEvent.EventCalendarItem (Item transformation for type CMS.BookingEvent)
```
These aren't customized at all; they are standard OOB transformations just so I can see it work.
When I view the RollupPage, the universal viewer displays nothing.
I attempted to use a Hierarchical Viewer with the same settings as I did with the Universal Viewer. It kind-of worked. It displayed my booking events but did not display any blog posts. Yet using the same blog post transformation (CMS.BlogPost.default) with hierarchical viewer whose `Path` was set to `/RollupPage/BlogPosts/%` displayed my blog posts correctly but, obviously, did not display my booking events.
The results I've gotten so far makes me think a) something about the way I've created my pages is stopping the universal viewer from traversing the whole tree and/or b) the hierarchical viewer either only goes a couple of levels deep, or maybe it is being blocked from traversing the tree too... No events are recorded when I edit or view these web parts.
Any idea what I may be doing wrong? | 2017/03/17 | [
"https://Stackoverflow.com/questions/42850428",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6683608/"
] | You can use the **Hierarchical viewer** or the **Universal viewer**, as Brenden Kehren mentioned, to achieve the goal you are describing.
When configuring the web part you must select all the **Page types** that are included in the hierarchy, in your case: **CMS.MenuItem, CMS.Blog, CMS.BlogMonth, CMS.BlogPost** and **CMSBookingEvent**.
Create a **Hierarchical transformation** to be used with your viewer and add an **Item transformation** for each of the items you wish to display. Also make sure the **Level** setting for each transformation is configured properly (-1 applies the transformation to all levels).
For **Universal viewer** it is necessary to check the property **Load hierarchical data** in the section **Extended settings** of the configuration.
As an additional note, you can leave the path property empty in case you are viewing the child documents of the current page.
For reference there is also an example on the **Corporate Site** example site in the content tree path **Examples > Web Parts > Listings and viewers > Pages > Hierarchical viewer** (or **Universal viewer**).
Hope this helps! | The other ways are this
1. Evaluate right `fieldname` by check object `classname` inside the transformation and assign appropriate value.
2. Dynamically assign transformation by checking the object classname |
1,617,855 | The question is basically it but here's the background of the story if curious:
My eyes woulld ache since I spend 12+ hours a day looking at a computer screen, so I decided to give night light a try and turned it to 70% strength. The colors were uglier than normal but I used it for about a year (always on) and now when I turn it off it looks like I'm looking at the sun when I look at my computer screen.
Anyway, my concern is, is leaving night light on long periods of time bad for my computer?
And a follow-up question if someoone knows: is always using night light bad for the eyes? | 2021/01/15 | [
"https://superuser.com/questions/1617855",
"https://superuser.com",
"https://superuser.com/users/1233850/"
] | >
> is leaving night light on long periods of time bad for my computer?
>
>
>
What night light setting does is just to decrease light of display, and maybe not equally all colours, but blue is reduced a bit more then the others.
So the answer for your question is **NO**, using night light will not cause any negative effect for your display (it could even be a little beneficial for it, but I don't think that would be measurable).
>
> is always using night light bad for the eyes?
>
>
>
Having less eye strain with night light settings is definitely a good sign, that's the feedback from your eyes that it prefers those settings. | Well, it depends on the strength of the Night Light. If it's Normal then It's Beneficial for your Health but if you set it to Extreme Kinda Ultra Instinct then you need to check whether you are color blind for red because it's bad for your display as it uses the red color at its max then all time. So Just Consider the Level of Night Light and Everything is OKAY. Except for your Color accuracy If you gonna use Photoshop or Some other $h!t. |
774,809 | I'd like to make a tool bar with icons that get's bigger when you mouse over them. I don't mind reinventing the wheel, but if anyone can suggest a good:
1. Image Format (not sure bitmaps'll work here and not sure how to do Vectors)
2. Existing Control (pay or free, so long as I can use it in a close source app)
3. Container class (is TPanel sufficient?) | 2009/04/21 | [
"https://Stackoverflow.com/questions/774809",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1765/"
] | I've not used it yet personally, but maybe check out TMS TAdvSmoothDock rather than reinventing wheel..?
<http://www.tmssoftware.com/site/advsmoothdock.asp> | There is some sample code doing exactly this on the delphi.about.com website.
The link below shows the code as well as an example image of the dock while running.
<http://delphi.about.com/od/fullcodeprojects/a/mac-doc-launch.htm>
I don't know if the code is D2009 compatible or not, but even if it isn't the code shouldn't be that hard to bring forward. I would think anyways.
HTH,
Ryan. |
15,430,684 | I have searched on this subject and am just getting more confused.
We have a Forms Authentication web application. I have changed the old FormsAuthentication.SetCookie statement to instead create a GenericPrincipal containing a FormsIdentity, then I have added a couple of custom claims, then I write a sessionsecuritytokentocookie using SessionAuthenticationModule. I am getting slightly confused with FederatedAuthentication - I am using FederatedAuthentication.SessionAuthenticationModule to write the token but I think this is the same as just using Modules("SessionAuthenticationModule") in my case?
Anyway, the authentication works fine but my custom claims are not being recreated. I am not using membership providers or role providers - does that matter?
I have read about SessionAuthenticationModules, ClaimsAuthenticationManagers, ClaimsTransformationModules but I am no longer certain which of these I should be using or how? Currently I just add my claims where the old login code was (I haven't got time to rewrite the whole login process) and I was expecting these claims to be recreated automatically on each request.
What do I need to do - obviously I do not want to have to go to the database every time to rebuild them - I thought they were being stored in the cookie and recreated automatically. | 2013/03/15 | [
"https://Stackoverflow.com/questions/15430684",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2047485/"
] | Your approach is fine - you create a ClaimsPrincipal with all the claims you need and write out the session cookie. No need for a claims authentication manager.
possible gotchas:
* make sure you set the authentication type when creating the ClaimsIdentity - otherwise the client will not be authenticated
* by default session cookies require SSL (the browser won't resend the cookie over plain text). This can be changed but is not recommended. | You need custom ClaimsAuthenticationManager, it will be called once and add claims. Don't forget to register this custom class in your application:
```
public override ClaimsPrincipal Authenticate(string resourceName, ClaimsPrincipal incomingPrincipal)
{
//works only with one default identity
//In contra to a a default implementation modify incomingPrincipal by adding claims)
if (incomingPrincipal != null && incomingPrincipal.Identity.IsAuthenticated == true)
{
ClaimsIdentity claimsIdentity = incomingPrincipal.Identity as ClaimsIdentity;
if (claimsIdentity != null)
{
IEnumerable<Claim> claims = new Claim[] { };
claims = claims.Concat(CreateIdsClaims(incomingPrincipal.Identity.Name));
claims = claims.Concat<Claim>(CreateRoleClaims(GetRolesByName(incomingPrincipal.Identity.Name)));
claimsIdentity.AddClaims(claims);
}
return incomingPrincipal;
}
return null;
}
``` |
34,517,581 | >
> Note: I already went through the below SO Question and 7 Answers (as of now) about [Symbols](https://github.com/zenparsing/es-private-fields), WeekMaps and Maps, Please read the full question before you vote: [Private properties in JavaScript ES6 classes](https://stackoverflow.com/questions/22156326/private-properties-in-javascript-es6-classes)
>
> Article: <https://esdiscuss.org/topic/es7-property-initializers>
>
>
>
Below is my `Simple Class` which contains Private, Public and Protected Properties and Methods.
```js
'use strict';
class MyClass {
constructor () {
this.publicVar = 'This is Public Variable';
this.privateVar = 'This is Private Variable';
this.protectedVar = 'This is Protected Variable';
} // Public Constructor Method.
publicMethod () {
console.log(' Accessing this.publicVar: ', this.publicVar);
console.log(' Accessing this.privateVar: ', this.privateVar);
console.log(' Accessing this.protectedVar: ', this.protectedVar);
return 'Its Public Method'
} // Public Method.
privateMethod () {return 'Its Private Method'} // Private Method.
protectedMethod () {return 'Its Protected Method'} // Protected Method.
foo () {
this.publicMethod();
this.privateMethod();
this.protectedMethod();
} // Public Method
} // end class
```
I'm instantiating the Object and calling the public method which is working as expected.
```
let MyObject = new MyClass;
MyObject.foo(); // Works fine.
console.log( MyObject.publicVar ); // Works
console.log( MyObject.publicMethod() ); // Works
```
>
> Working as expected.
>
>
>
Now my question. I'm aware few things like Symbol are in the ES6 specification, what is the current workaround to get protected and private variables/methods working on ES6 classes.
```
console.log( MyObject.privateVar ); // Works
console.log( MyObject.privateMethod() ); // Works
```
>
> I want this property and method to be visible only in its own class.
>
>
>
```
console.log( MyObject.protectedVar ); // Works
console.log( MyObject.protectedMethod() ); // Works
```
>
> I want this property and method to be visible in its own class and inside classes extending it.
>
>
>
Workaround / better solution to achieve this behavior is appreciated | 2015/12/29 | [
"https://Stackoverflow.com/questions/34517581",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5696335/"
] | **Private properties**
In ES6 (and before), all private property implementations rely on [closure](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures).
People [have been doing it](http://javascript.crockford.com/private.html) even before JavaScript has versions.
WeakMap is just a variation that removes the need of new scope and new functions for each new object, at cost of access speed.
Symbol is a ES6 variation that hides the attribute from common operations, such as simple property access or `for in`.
```js
var MyClass;
( () => {
// Define a scoped symbol for private property A.
const PropA = Symbol( 'A' );
// Define the class once we have all symbols
MyClass = class {
someFunction () {
return "I can read " + this[ PropA ]; // Access private property
}
}
MyClass.prototype[ PropA ] = 'Private property or method';
})();
// function in the closure can access the private property.
var myObject = new MyClass();
alert( myObject.someFunction() );
// But we cannot "recreate" the Symbol externally.
alert( myObject[ Symbol( 'A' ) ] ); // undefined
// However if someone *really* must access it...
var symbols = Object.getOwnPropertySymbols( myObject.__proto__ );
alert( myObject[ symbols[ 0 ] ] );
```
As seen above, it can be worked around by [Object.getOwnPropertySymbols()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertySymbols).
Despite its existence, I always choice symbol over WeakMap.
The code is cleaner, simpler, less gc work, and (I think) more efficient.
>
> I personally avoid `class`, too. `Object.create` is much simpler. But that is out of scope.
>
>
>
---
**Protected properties**
Protected properties, by its nature, requires executing function to know the object of the calling code, to judge whether it should be granted access.
This is impossible in JS, not because ES6 has [no real class](https://www.quora.com/Are-ES6-classes-bad-for-JavaScript), but because caller *context* is [simply unavailable](https://stackoverflow.com/questions/28260389/can-you-get-the-property-name-through-which-a-function-was-called/28314301#28314301).
Due to [various](https://en.wikipedia.org/wiki/Prototype-based_programming) [special](https://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work) [natures](https://en.wikipedia.org/wiki/First-class_function) of JavaScript, for the foreseeable future protected properties shall remain impossible.
[ Update ]
Three years later, thanks to widespread support of module, it is possible to emulate most benefits of protected properties, see the answer below by Twifty.
They are still public, but you need to go extra to access them, which means it is difficult to accidentally access or override them.
[ /Update ]
Alternatively...
---
**Package properties**
Some languages have semi-protected properties, sometimes called "package private", where the method / property is accessible to members in the same module / package.
ES6 can implement it with closure.
It is exactly the same as the private property code above - just share the scope and its symbols with multiple prototypes.
But this is impractical, since this requires that the whole module be defined under same closed scope, i.e. in a single file.
But it is an option nonetheless. | I'm late to answer this, but it is possible to emulate private AND protected methods in javascript.
**Private methods/properties**
Uses the well known Symbol approach
```
const someMethod = Symbol()
const someProperty = Symbol()
export default class Parent {
constructor () {
this[someProperty] = 'and a private property'
}
[someMethod] () {
console.log('this is a private method')
console.log(this[someProperty])
}
callPrivateMethod () {
this[someMethod]()
}
}
```
**Protected methods/properties**
By their nature, protected members are visible to derived classes. They must also mimic the `super.method` pattern.
symbols.js
```
export default {
protectedMethod: Symbol()
}
```
parent.js
```
import symbols from './symbols'
const someMethod = Symbol()
const someProperty = Symbol()
export default class Parent {
constructor () {
this[someProperty] = 'and a private property'
}
[someMethod] () {
console.log('this is a private method')
console.log(this[someProperty])
}
[symbols.protectedMethod] () {
console.log('I am the parent')
}
callPrivateMethod () {
this[someMethod]()
}
}
```
child.js
```
import Parent from './parent'
import symbols from './symbols'
export default class Child {
[symbols.protectedMethod] () {
console.log('I am the child')
super[symbols.protectedMethod]()
}
callProtectedMethod () {
this[symbols.protectedMethod]()
}
}
``` |
34,517,581 | >
> Note: I already went through the below SO Question and 7 Answers (as of now) about [Symbols](https://github.com/zenparsing/es-private-fields), WeekMaps and Maps, Please read the full question before you vote: [Private properties in JavaScript ES6 classes](https://stackoverflow.com/questions/22156326/private-properties-in-javascript-es6-classes)
>
> Article: <https://esdiscuss.org/topic/es7-property-initializers>
>
>
>
Below is my `Simple Class` which contains Private, Public and Protected Properties and Methods.
```js
'use strict';
class MyClass {
constructor () {
this.publicVar = 'This is Public Variable';
this.privateVar = 'This is Private Variable';
this.protectedVar = 'This is Protected Variable';
} // Public Constructor Method.
publicMethod () {
console.log(' Accessing this.publicVar: ', this.publicVar);
console.log(' Accessing this.privateVar: ', this.privateVar);
console.log(' Accessing this.protectedVar: ', this.protectedVar);
return 'Its Public Method'
} // Public Method.
privateMethod () {return 'Its Private Method'} // Private Method.
protectedMethod () {return 'Its Protected Method'} // Protected Method.
foo () {
this.publicMethod();
this.privateMethod();
this.protectedMethod();
} // Public Method
} // end class
```
I'm instantiating the Object and calling the public method which is working as expected.
```
let MyObject = new MyClass;
MyObject.foo(); // Works fine.
console.log( MyObject.publicVar ); // Works
console.log( MyObject.publicMethod() ); // Works
```
>
> Working as expected.
>
>
>
Now my question. I'm aware few things like Symbol are in the ES6 specification, what is the current workaround to get protected and private variables/methods working on ES6 classes.
```
console.log( MyObject.privateVar ); // Works
console.log( MyObject.privateMethod() ); // Works
```
>
> I want this property and method to be visible only in its own class.
>
>
>
```
console.log( MyObject.protectedVar ); // Works
console.log( MyObject.protectedMethod() ); // Works
```
>
> I want this property and method to be visible in its own class and inside classes extending it.
>
>
>
Workaround / better solution to achieve this behavior is appreciated | 2015/12/29 | [
"https://Stackoverflow.com/questions/34517581",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5696335/"
] | **Private properties**
In ES6 (and before), all private property implementations rely on [closure](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures).
People [have been doing it](http://javascript.crockford.com/private.html) even before JavaScript has versions.
WeakMap is just a variation that removes the need of new scope and new functions for each new object, at cost of access speed.
Symbol is a ES6 variation that hides the attribute from common operations, such as simple property access or `for in`.
```js
var MyClass;
( () => {
// Define a scoped symbol for private property A.
const PropA = Symbol( 'A' );
// Define the class once we have all symbols
MyClass = class {
someFunction () {
return "I can read " + this[ PropA ]; // Access private property
}
}
MyClass.prototype[ PropA ] = 'Private property or method';
})();
// function in the closure can access the private property.
var myObject = new MyClass();
alert( myObject.someFunction() );
// But we cannot "recreate" the Symbol externally.
alert( myObject[ Symbol( 'A' ) ] ); // undefined
// However if someone *really* must access it...
var symbols = Object.getOwnPropertySymbols( myObject.__proto__ );
alert( myObject[ symbols[ 0 ] ] );
```
As seen above, it can be worked around by [Object.getOwnPropertySymbols()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertySymbols).
Despite its existence, I always choice symbol over WeakMap.
The code is cleaner, simpler, less gc work, and (I think) more efficient.
>
> I personally avoid `class`, too. `Object.create` is much simpler. But that is out of scope.
>
>
>
---
**Protected properties**
Protected properties, by its nature, requires executing function to know the object of the calling code, to judge whether it should be granted access.
This is impossible in JS, not because ES6 has [no real class](https://www.quora.com/Are-ES6-classes-bad-for-JavaScript), but because caller *context* is [simply unavailable](https://stackoverflow.com/questions/28260389/can-you-get-the-property-name-through-which-a-function-was-called/28314301#28314301).
Due to [various](https://en.wikipedia.org/wiki/Prototype-based_programming) [special](https://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work) [natures](https://en.wikipedia.org/wiki/First-class_function) of JavaScript, for the foreseeable future protected properties shall remain impossible.
[ Update ]
Three years later, thanks to widespread support of module, it is possible to emulate most benefits of protected properties, see the answer below by Twifty.
They are still public, but you need to go extra to access them, which means it is difficult to accidentally access or override them.
[ /Update ]
Alternatively...
---
**Package properties**
Some languages have semi-protected properties, sometimes called "package private", where the method / property is accessible to members in the same module / package.
ES6 can implement it with closure.
It is exactly the same as the private property code above - just share the scope and its symbols with multiple prototypes.
But this is impractical, since this requires that the whole module be defined under same closed scope, i.e. in a single file.
But it is an option nonetheless. | Also can use a symbol as a "key" for enabling a version of a class with protected inheritance via gatekeepers and conditional behavior.
eg in this BST `root` is private and `add`/`insert` returns true. Did not want any direct node access.
However, an AVL subclass could use both, as well as some utility functions.
The key allows opinionated expressions of the class as either a standalone or a base. Could be done even DRY-er with decorators, or a protected access map (rather than pass through gatekeeper getters).
```
class BinarySearchTree {
#root;
constructor(sym) {
this.#root = null;
this.#access = sym;
}
#protectionCheck = () =>
this.#access === PROTECTED ||
(() => {
throw new Error("Ah, ah, ah. You didn't say the magic word.");
})();
__root() {
this.#protectionCheck();
return this.#root;
}
add(val) {
...
return this.#access === PROTECTED ? node : true;
}
}
class AVL extends BinarySearchTree {
constructor() {
super(PROTECTED);
}
get #root() {
return super.__root();
}
add = (value) => {
const node = super.add(value);
this.#balanceUpstream(node);
return true;
};
}
``` |
34,517,581 | >
> Note: I already went through the below SO Question and 7 Answers (as of now) about [Symbols](https://github.com/zenparsing/es-private-fields), WeekMaps and Maps, Please read the full question before you vote: [Private properties in JavaScript ES6 classes](https://stackoverflow.com/questions/22156326/private-properties-in-javascript-es6-classes)
>
> Article: <https://esdiscuss.org/topic/es7-property-initializers>
>
>
>
Below is my `Simple Class` which contains Private, Public and Protected Properties and Methods.
```js
'use strict';
class MyClass {
constructor () {
this.publicVar = 'This is Public Variable';
this.privateVar = 'This is Private Variable';
this.protectedVar = 'This is Protected Variable';
} // Public Constructor Method.
publicMethod () {
console.log(' Accessing this.publicVar: ', this.publicVar);
console.log(' Accessing this.privateVar: ', this.privateVar);
console.log(' Accessing this.protectedVar: ', this.protectedVar);
return 'Its Public Method'
} // Public Method.
privateMethod () {return 'Its Private Method'} // Private Method.
protectedMethod () {return 'Its Protected Method'} // Protected Method.
foo () {
this.publicMethod();
this.privateMethod();
this.protectedMethod();
} // Public Method
} // end class
```
I'm instantiating the Object and calling the public method which is working as expected.
```
let MyObject = new MyClass;
MyObject.foo(); // Works fine.
console.log( MyObject.publicVar ); // Works
console.log( MyObject.publicMethod() ); // Works
```
>
> Working as expected.
>
>
>
Now my question. I'm aware few things like Symbol are in the ES6 specification, what is the current workaround to get protected and private variables/methods working on ES6 classes.
```
console.log( MyObject.privateVar ); // Works
console.log( MyObject.privateMethod() ); // Works
```
>
> I want this property and method to be visible only in its own class.
>
>
>
```
console.log( MyObject.protectedVar ); // Works
console.log( MyObject.protectedMethod() ); // Works
```
>
> I want this property and method to be visible in its own class and inside classes extending it.
>
>
>
Workaround / better solution to achieve this behavior is appreciated | 2015/12/29 | [
"https://Stackoverflow.com/questions/34517581",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5696335/"
] | I'm late to answer this, but it is possible to emulate private AND protected methods in javascript.
**Private methods/properties**
Uses the well known Symbol approach
```
const someMethod = Symbol()
const someProperty = Symbol()
export default class Parent {
constructor () {
this[someProperty] = 'and a private property'
}
[someMethod] () {
console.log('this is a private method')
console.log(this[someProperty])
}
callPrivateMethod () {
this[someMethod]()
}
}
```
**Protected methods/properties**
By their nature, protected members are visible to derived classes. They must also mimic the `super.method` pattern.
symbols.js
```
export default {
protectedMethod: Symbol()
}
```
parent.js
```
import symbols from './symbols'
const someMethod = Symbol()
const someProperty = Symbol()
export default class Parent {
constructor () {
this[someProperty] = 'and a private property'
}
[someMethod] () {
console.log('this is a private method')
console.log(this[someProperty])
}
[symbols.protectedMethod] () {
console.log('I am the parent')
}
callPrivateMethod () {
this[someMethod]()
}
}
```
child.js
```
import Parent from './parent'
import symbols from './symbols'
export default class Child {
[symbols.protectedMethod] () {
console.log('I am the child')
super[symbols.protectedMethod]()
}
callProtectedMethod () {
this[symbols.protectedMethod]()
}
}
``` | Also can use a symbol as a "key" for enabling a version of a class with protected inheritance via gatekeepers and conditional behavior.
eg in this BST `root` is private and `add`/`insert` returns true. Did not want any direct node access.
However, an AVL subclass could use both, as well as some utility functions.
The key allows opinionated expressions of the class as either a standalone or a base. Could be done even DRY-er with decorators, or a protected access map (rather than pass through gatekeeper getters).
```
class BinarySearchTree {
#root;
constructor(sym) {
this.#root = null;
this.#access = sym;
}
#protectionCheck = () =>
this.#access === PROTECTED ||
(() => {
throw new Error("Ah, ah, ah. You didn't say the magic word.");
})();
__root() {
this.#protectionCheck();
return this.#root;
}
add(val) {
...
return this.#access === PROTECTED ? node : true;
}
}
class AVL extends BinarySearchTree {
constructor() {
super(PROTECTED);
}
get #root() {
return super.__root();
}
add = (value) => {
const node = super.add(value);
this.#balanceUpstream(node);
return true;
};
}
``` |
155,882 | I have a simple echo server program running on CentOS 7. If I run both the client and the server in the VM, I can connect to the server.
I'm using VirtualBox with the "bridged" network configuration. Using the IP of my Linux VM (found using ifconfig), I can successfully ssh into the Linux VM from Cygwin in Windows.
However when I try to connect to the server using putty from my Windows 7 host PC the connection won't work. I don't understand why the server doesn't see a connection request from the host PC. What could be causing this? The windows Firewall is disabled. | 2014/09/16 | [
"https://unix.stackexchange.com/questions/155882",
"https://unix.stackexchange.com",
"https://unix.stackexchange.com/users/84370/"
] | I suggest you capture the packets and write them to a file with the `<file>.pcap` extension, and then open with `wireshark`.
For example, in CentOS, to capture the packets:
```
$ tcpdump -i eth0 -s 1500 -w /root/<filename.pcap>
``` | Something else must be up. The following test works fine for me. I'm using `socat` as both the client and server and I'm running `tcpdump` on my local system that I'm sitting at.
### 1. Setup socat server (listener)
```
$ socat - TCP-LISTEN:2222,crlf
```
### 2. Setup socat client
```
$ socat - TCP:192.168.1.80:2222
```
### 3. Now I run tcpdump:
```
$ sudo tcpdump -Xi wlp1s0 src 192.168.1.3
tcpdump: verbose output suppressed, use -v or -vv for full protocol decode
listening on wlp1s0, link-type EN10MB (Ethernet), capture size 65535 bytes
10:04:27.977900 ARP, Request who-has 192.168.1.149 tell client.mydom.net, length 46
0x0000: 0001 0800 0604 0001 0019 d1e8 4c95 c0a8 ............L...
0x0010: 0103 0000 0000 0000 c0a8 0195 0000 0000 ................
0x0020: 0000 0000 0000 0000 0000 0000 0000 ..............
10:04:29.206642 ARP, Request who-has 192.168.1.149 tell client.mydom.net, length 46
0x0000: 0001 0800 0604 0001 0019 d1e8 4c95 c0a8 ............L...
0x0010: 0103 0000 0000 0000 c0a8 0195 0000 0000 ................
0x0020: 0000 0000 0000 0000 0000 0000 0000 ..............
10:04:29.337077 IP client.mydom.net.49878 > server.mydom.net.EtherNet/IP-1: Flags [P.], seq 1391164406:1391164421, ack 2721007444, win 46, options [nop,nop,TS val 535977938 ecr 956529523], length 15
0x0000: 4500 0043 8218 4000 4006 34f9 c0a8 0103 E..C..@[email protected].....
0x0010: c0a8 0150 c2d6 08ae 52eb 7bf6 a22f 4754 ...P....R.{../GT
0x0020: 8018 002e 964f 0000 0101 080a 1ff2 5fd2 .....O........_.
0x0030: 3903 7b73 5468 6973 2069 7320 6120 7465 9.{sThis.is.a.te
0x0040: 7374 0a st.
```
In the above scenario I typed the message "This is a test" on the client side and it showed up on the server's `socat` instance as well as within the output of `tcpdump`.
*Client output:*
```
$ socat - TCP:server.mydom.net:2222
This is a test
```
*Server output:*
```
$ socat - TCP-LISTEN:2222,crlf
This is a test
``` |
155,882 | I have a simple echo server program running on CentOS 7. If I run both the client and the server in the VM, I can connect to the server.
I'm using VirtualBox with the "bridged" network configuration. Using the IP of my Linux VM (found using ifconfig), I can successfully ssh into the Linux VM from Cygwin in Windows.
However when I try to connect to the server using putty from my Windows 7 host PC the connection won't work. I don't understand why the server doesn't see a connection request from the host PC. What could be causing this? The windows Firewall is disabled. | 2014/09/16 | [
"https://unix.stackexchange.com/questions/155882",
"https://unix.stackexchange.com",
"https://unix.stackexchange.com/users/84370/"
] | I suggest you capture the packets and write them to a file with the `<file>.pcap` extension, and then open with `wireshark`.
For example, in CentOS, to capture the packets:
```
$ tcpdump -i eth0 -s 1500 -w /root/<filename.pcap>
``` | For anyone who comes across this one another good answer is here <https://stackoverflow.com/questions/3130911/tcpdump-localhost-to-localhost>, if the traffic that isn't showing up is localhost->localhost traffic. I feel like in other situations I haven't had to do that, but at least a few times I've had to. |
155,882 | I have a simple echo server program running on CentOS 7. If I run both the client and the server in the VM, I can connect to the server.
I'm using VirtualBox with the "bridged" network configuration. Using the IP of my Linux VM (found using ifconfig), I can successfully ssh into the Linux VM from Cygwin in Windows.
However when I try to connect to the server using putty from my Windows 7 host PC the connection won't work. I don't understand why the server doesn't see a connection request from the host PC. What could be causing this? The windows Firewall is disabled. | 2014/09/16 | [
"https://unix.stackexchange.com/questions/155882",
"https://unix.stackexchange.com",
"https://unix.stackexchange.com/users/84370/"
] | I suggest you capture the packets and write them to a file with the `<file>.pcap` extension, and then open with `wireshark`.
For example, in CentOS, to capture the packets:
```
$ tcpdump -i eth0 -s 1500 -w /root/<filename.pcap>
``` | as suggested by wurtel:
Use `-n` with `tcpdump` to stop it trying to resolve IP addresses to names, which can take a long time and result this issue. |
155,882 | I have a simple echo server program running on CentOS 7. If I run both the client and the server in the VM, I can connect to the server.
I'm using VirtualBox with the "bridged" network configuration. Using the IP of my Linux VM (found using ifconfig), I can successfully ssh into the Linux VM from Cygwin in Windows.
However when I try to connect to the server using putty from my Windows 7 host PC the connection won't work. I don't understand why the server doesn't see a connection request from the host PC. What could be causing this? The windows Firewall is disabled. | 2014/09/16 | [
"https://unix.stackexchange.com/questions/155882",
"https://unix.stackexchange.com",
"https://unix.stackexchange.com/users/84370/"
] | I suggest you capture the packets and write them to a file with the `<file>.pcap` extension, and then open with `wireshark`.
For example, in CentOS, to capture the packets:
```
$ tcpdump -i eth0 -s 1500 -w /root/<filename.pcap>
``` | try this:
```
sudo bash
```
and then
```
tcpdump ...
```
On some Linux versions I see this from time to time that tcpdump or similar tools don't work with sudo as expected.. |
155,882 | I have a simple echo server program running on CentOS 7. If I run both the client and the server in the VM, I can connect to the server.
I'm using VirtualBox with the "bridged" network configuration. Using the IP of my Linux VM (found using ifconfig), I can successfully ssh into the Linux VM from Cygwin in Windows.
However when I try to connect to the server using putty from my Windows 7 host PC the connection won't work. I don't understand why the server doesn't see a connection request from the host PC. What could be causing this? The windows Firewall is disabled. | 2014/09/16 | [
"https://unix.stackexchange.com/questions/155882",
"https://unix.stackexchange.com",
"https://unix.stackexchange.com/users/84370/"
] | Something else must be up. The following test works fine for me. I'm using `socat` as both the client and server and I'm running `tcpdump` on my local system that I'm sitting at.
### 1. Setup socat server (listener)
```
$ socat - TCP-LISTEN:2222,crlf
```
### 2. Setup socat client
```
$ socat - TCP:192.168.1.80:2222
```
### 3. Now I run tcpdump:
```
$ sudo tcpdump -Xi wlp1s0 src 192.168.1.3
tcpdump: verbose output suppressed, use -v or -vv for full protocol decode
listening on wlp1s0, link-type EN10MB (Ethernet), capture size 65535 bytes
10:04:27.977900 ARP, Request who-has 192.168.1.149 tell client.mydom.net, length 46
0x0000: 0001 0800 0604 0001 0019 d1e8 4c95 c0a8 ............L...
0x0010: 0103 0000 0000 0000 c0a8 0195 0000 0000 ................
0x0020: 0000 0000 0000 0000 0000 0000 0000 ..............
10:04:29.206642 ARP, Request who-has 192.168.1.149 tell client.mydom.net, length 46
0x0000: 0001 0800 0604 0001 0019 d1e8 4c95 c0a8 ............L...
0x0010: 0103 0000 0000 0000 c0a8 0195 0000 0000 ................
0x0020: 0000 0000 0000 0000 0000 0000 0000 ..............
10:04:29.337077 IP client.mydom.net.49878 > server.mydom.net.EtherNet/IP-1: Flags [P.], seq 1391164406:1391164421, ack 2721007444, win 46, options [nop,nop,TS val 535977938 ecr 956529523], length 15
0x0000: 4500 0043 8218 4000 4006 34f9 c0a8 0103 E..C..@[email protected].....
0x0010: c0a8 0150 c2d6 08ae 52eb 7bf6 a22f 4754 ...P....R.{../GT
0x0020: 8018 002e 964f 0000 0101 080a 1ff2 5fd2 .....O........_.
0x0030: 3903 7b73 5468 6973 2069 7320 6120 7465 9.{sThis.is.a.te
0x0040: 7374 0a st.
```
In the above scenario I typed the message "This is a test" on the client side and it showed up on the server's `socat` instance as well as within the output of `tcpdump`.
*Client output:*
```
$ socat - TCP:server.mydom.net:2222
This is a test
```
*Server output:*
```
$ socat - TCP-LISTEN:2222,crlf
This is a test
``` | as suggested by wurtel:
Use `-n` with `tcpdump` to stop it trying to resolve IP addresses to names, which can take a long time and result this issue. |
155,882 | I have a simple echo server program running on CentOS 7. If I run both the client and the server in the VM, I can connect to the server.
I'm using VirtualBox with the "bridged" network configuration. Using the IP of my Linux VM (found using ifconfig), I can successfully ssh into the Linux VM from Cygwin in Windows.
However when I try to connect to the server using putty from my Windows 7 host PC the connection won't work. I don't understand why the server doesn't see a connection request from the host PC. What could be causing this? The windows Firewall is disabled. | 2014/09/16 | [
"https://unix.stackexchange.com/questions/155882",
"https://unix.stackexchange.com",
"https://unix.stackexchange.com/users/84370/"
] | Something else must be up. The following test works fine for me. I'm using `socat` as both the client and server and I'm running `tcpdump` on my local system that I'm sitting at.
### 1. Setup socat server (listener)
```
$ socat - TCP-LISTEN:2222,crlf
```
### 2. Setup socat client
```
$ socat - TCP:192.168.1.80:2222
```
### 3. Now I run tcpdump:
```
$ sudo tcpdump -Xi wlp1s0 src 192.168.1.3
tcpdump: verbose output suppressed, use -v or -vv for full protocol decode
listening on wlp1s0, link-type EN10MB (Ethernet), capture size 65535 bytes
10:04:27.977900 ARP, Request who-has 192.168.1.149 tell client.mydom.net, length 46
0x0000: 0001 0800 0604 0001 0019 d1e8 4c95 c0a8 ............L...
0x0010: 0103 0000 0000 0000 c0a8 0195 0000 0000 ................
0x0020: 0000 0000 0000 0000 0000 0000 0000 ..............
10:04:29.206642 ARP, Request who-has 192.168.1.149 tell client.mydom.net, length 46
0x0000: 0001 0800 0604 0001 0019 d1e8 4c95 c0a8 ............L...
0x0010: 0103 0000 0000 0000 c0a8 0195 0000 0000 ................
0x0020: 0000 0000 0000 0000 0000 0000 0000 ..............
10:04:29.337077 IP client.mydom.net.49878 > server.mydom.net.EtherNet/IP-1: Flags [P.], seq 1391164406:1391164421, ack 2721007444, win 46, options [nop,nop,TS val 535977938 ecr 956529523], length 15
0x0000: 4500 0043 8218 4000 4006 34f9 c0a8 0103 E..C..@[email protected].....
0x0010: c0a8 0150 c2d6 08ae 52eb 7bf6 a22f 4754 ...P....R.{../GT
0x0020: 8018 002e 964f 0000 0101 080a 1ff2 5fd2 .....O........_.
0x0030: 3903 7b73 5468 6973 2069 7320 6120 7465 9.{sThis.is.a.te
0x0040: 7374 0a st.
```
In the above scenario I typed the message "This is a test" on the client side and it showed up on the server's `socat` instance as well as within the output of `tcpdump`.
*Client output:*
```
$ socat - TCP:server.mydom.net:2222
This is a test
```
*Server output:*
```
$ socat - TCP-LISTEN:2222,crlf
This is a test
``` | try this:
```
sudo bash
```
and then
```
tcpdump ...
```
On some Linux versions I see this from time to time that tcpdump or similar tools don't work with sudo as expected.. |
155,882 | I have a simple echo server program running on CentOS 7. If I run both the client and the server in the VM, I can connect to the server.
I'm using VirtualBox with the "bridged" network configuration. Using the IP of my Linux VM (found using ifconfig), I can successfully ssh into the Linux VM from Cygwin in Windows.
However when I try to connect to the server using putty from my Windows 7 host PC the connection won't work. I don't understand why the server doesn't see a connection request from the host PC. What could be causing this? The windows Firewall is disabled. | 2014/09/16 | [
"https://unix.stackexchange.com/questions/155882",
"https://unix.stackexchange.com",
"https://unix.stackexchange.com/users/84370/"
] | For anyone who comes across this one another good answer is here <https://stackoverflow.com/questions/3130911/tcpdump-localhost-to-localhost>, if the traffic that isn't showing up is localhost->localhost traffic. I feel like in other situations I haven't had to do that, but at least a few times I've had to. | as suggested by wurtel:
Use `-n` with `tcpdump` to stop it trying to resolve IP addresses to names, which can take a long time and result this issue. |
155,882 | I have a simple echo server program running on CentOS 7. If I run both the client and the server in the VM, I can connect to the server.
I'm using VirtualBox with the "bridged" network configuration. Using the IP of my Linux VM (found using ifconfig), I can successfully ssh into the Linux VM from Cygwin in Windows.
However when I try to connect to the server using putty from my Windows 7 host PC the connection won't work. I don't understand why the server doesn't see a connection request from the host PC. What could be causing this? The windows Firewall is disabled. | 2014/09/16 | [
"https://unix.stackexchange.com/questions/155882",
"https://unix.stackexchange.com",
"https://unix.stackexchange.com/users/84370/"
] | For anyone who comes across this one another good answer is here <https://stackoverflow.com/questions/3130911/tcpdump-localhost-to-localhost>, if the traffic that isn't showing up is localhost->localhost traffic. I feel like in other situations I haven't had to do that, but at least a few times I've had to. | try this:
```
sudo bash
```
and then
```
tcpdump ...
```
On some Linux versions I see this from time to time that tcpdump or similar tools don't work with sudo as expected.. |
50,588,967 | I am trying to solve a problem given to me and it involves using basic loops, functions and conditions. I have been given the below:
```
// TODO: complete program
console.log(calculate(4, "+", 6)); // Must show 10
console.log(calculate(4, "-", 6)); // Must show -2
console.log(calculate(2, "*", 0)); // Must show 0
console.log(calculate(12, "/", 0)); // Must show Infinity
```
and this is my attempt (not working of course). Can anyone give me a nudge of a pointer as to what I am doing wrong?
```js
function calculate(n1, n2, n3) {
let calc
if n2 = "+" {
(calc = +)
};
else if n2 = "-" {
(calc = -)
};
else if n2 = "*" {
(calc = * )
};
else {
(calc = /)
};
let acalc = (n1 + n2 + n3);
return acalc;
}
console.log(calculate(4, "+", 6)); // Must show 10
console.log(calculate(4, "-", 6)); // Must show -2
console.log(calculate(2, "*", 0)); // Must show 0
console.log(calculate(12, "/", 0)); // Must show Infinity
``` | 2018/05/29 | [
"https://Stackoverflow.com/questions/50588967",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9865551/"
] | You can't set variables equal to operators. Your `if` blocks should look like this instead:
```
if (n2 == "+") {
return parseInt(n1) + parseInt(n3);
};
```
Use `parseInt` if you are passing in strings instead of numbers | I'd take the input given in the n2 parameter and return the calculation directly. Also you had some issues with () in your code.
```
function calculate(n1, n2, n3) {
if (n2 == "+") {
return n1 + n3;
} else if (n2 == "-") {
return n1 - n3;
} else if (n2 == "*") {
return n1 * n3;
} else {
return n1 / n3;
}; };
``` |
13,856,436 | I'm developing a Java project using Eclipse, and Ant as a build tool. When I run "ant all" from the command line, my project builds without any errors, but on Eclipse I get many compilation errors.
So I thought I'd copy Ant's Classpath onto my Eclipse Project's Build Path.
Is there an Ant task/command to show that? Like "ant just show me your assembled classpath" or something? | 2012/12/13 | [
"https://Stackoverflow.com/questions/13856436",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1264138/"
] | If you run Ant with the -verbose and -debug flags, you'll see all gory details of what javac is doing, including the classpath. | I would introduce a task for printing the classpath, and call that task with antcall. The classpath would be given as a parameter to that task. |
13,856,436 | I'm developing a Java project using Eclipse, and Ant as a build tool. When I run "ant all" from the command line, my project builds without any errors, but on Eclipse I get many compilation errors.
So I thought I'd copy Ant's Classpath onto my Eclipse Project's Build Path.
Is there an Ant task/command to show that? Like "ant just show me your assembled classpath" or something? | 2012/12/13 | [
"https://Stackoverflow.com/questions/13856436",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1264138/"
] | If you run Ant with the -verbose and -debug flags, you'll see all gory details of what javac is doing, including the classpath. | You can do something like this in your target, so for example
lets say you've defined your classpath as
```
<path id="project.classpath">
<fileset dir="${SERVER_DEV}/classes">
<include name="*.zip"/>
<include name="*.jar"/>
</fileset>
<pathelement location="${SERVER_DEV}/3rdParty/jre/NT/1.5.0/lib/jsse.jar"/>
</path>
```
then you can do something like
```
<target name="compile" depends="init" description="Compiles All Java Sources">
<property name="myclasspath" refid="project.classpath"/>
<echo message="Classpath = ${myclasspath}"/>
<javac ...>
....
</javac>
</target>
```
It will print out the classpath used to run the specific target |
13,856,436 | I'm developing a Java project using Eclipse, and Ant as a build tool. When I run "ant all" from the command line, my project builds without any errors, but on Eclipse I get many compilation errors.
So I thought I'd copy Ant's Classpath onto my Eclipse Project's Build Path.
Is there an Ant task/command to show that? Like "ant just show me your assembled classpath" or something? | 2012/12/13 | [
"https://Stackoverflow.com/questions/13856436",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1264138/"
] | I would introduce a task for printing the classpath, and call that task with antcall. The classpath would be given as a parameter to that task. | You can do something like this in your target, so for example
lets say you've defined your classpath as
```
<path id="project.classpath">
<fileset dir="${SERVER_DEV}/classes">
<include name="*.zip"/>
<include name="*.jar"/>
</fileset>
<pathelement location="${SERVER_DEV}/3rdParty/jre/NT/1.5.0/lib/jsse.jar"/>
</path>
```
then you can do something like
```
<target name="compile" depends="init" description="Compiles All Java Sources">
<property name="myclasspath" refid="project.classpath"/>
<echo message="Classpath = ${myclasspath}"/>
<javac ...>
....
</javac>
</target>
```
It will print out the classpath used to run the specific target |
20,983,535 | ```
/* result 1 */
select Id, Name
from Items
/* result 2 */
select Id,
Alias
from ItemAliases
where Id in (
select Id, Name
from table abc
)
```
We use SQL Server 2008.
Using the above example, it should be pretty straightforward what I'm trying to do.
I need to return the results of query 1... and return the results of query 2.
Query 2 however, needs to filter to only include records from result 1.
Here is my attempt to show what I would like to end up with.
```
VAR A = (
select Id, Name
from Items
)
/* result 1 */
select A.*
/* result 2 */
select Id,
Alias
from ItemAliases
where Id in ( A.Id )
``` | 2014/01/07 | [
"https://Stackoverflow.com/questions/20983535",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/704238/"
] | I think you just want to store Result1 and use it to compose Result2:
```
declare @Result1 table (Id int primary key, Name varchar(100));
insert into @Result1
-- store Result1
select Id, Name
from Items
--return Result1
select Id, Name
from @Result1;
--return Result2 using stored Result1
select Id,
Alias
from ItemAliases
where Id in (select Id from @Result1);
``` | ```
--Result 1
SELECT ID, Name
FROM Items
[You WHERE Clause here if any]
--Result 2
SELECT Id, Alias
FROM ItemAliases ia
INNER JOIN Items i ON ia.ID = i.ID
```
OR
```
--Using temporay in memory table
DECLARE @abc AS TABLE (
ID AS Int,
Name AS varchar(25)
)
SELECT ID, Name
INTO @abc
FROM Items
[You WHERE Clause here if any]
--Result 1
SELECT * FROM @abc
--Result 2
SELECT Id, Alias
FROM ItemAliases ia
INNER JOIN @abc i ON ia.ID = i.ID
``` |
38,464,876 | When I update my Google Play dependencies in my Gradle file from version 8.4.0 to 9.2.1, I get the following error:
>
> Error:Failed to resolve: com.google.android.gms:play-services-measurement:9.2.1
>
>
>
This was not an issue when using version 8.4.0. I tried to include it as an explicit dependency but makes no difference. The specific dependencies I’m using are:
```
compile 'com.google.android.gms:play-services-maps:9.2.1'
compile 'com.google.android.gms:play-services-auth:9.2.1'
compile 'com.google.android.gms:play-services-plus:9.2.1'
```
I would be grateful for any pointers on why this is happening. | 2016/07/19 | [
"https://Stackoverflow.com/questions/38464876",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2815375/"
] | Try update google-services plugin in main `build.gradle` file
```
buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:2.0.0'
classpath 'com.google.gms:google-services:3.0.0'
}
}
``` | Add the dependency to your project-level build.gradle:
```
dependencies {
classpath 'com.android.tools.build:gradle:2.1.3'
classpath 'com.google.gms:google-services:3.0.0'
}
``` |
14,367,906 | I trying to deploy an app to Heroku, but when I push my config.ru file I've got errors.
Follow Heroku's log:
```
2013-01-16T21:04:14+00:00 heroku[web.1]: Starting process with command `bundle exec rackup config.ru -p 29160`
2013-01-16T21:04:16+00:00 app[web.1]: from /app/vendor/bundle/ruby/1.9.1/gems/rack-1.4.4/lib/rack/builder.rb:51:in `initialize'
2013-01-16T21:04:16+00:00 app[web.1]: from /app/vendor/bundle/ruby/1.9.1/bin/rackup:19:in `<main>'
2013-01-16T21:04:16+00:00 app[web.1]: from /app/vendor/bundle/ruby/1.9.1/gems/rack-1.4.4/lib/rack/builder.rb:51:in `instance_eval'
2013-01-16T21:04:16+00:00 app[web.1]: from /app/vendor/bundle/ruby/1.9.1/gems/rack-1.4.4/lib/rack/server.rb:137:in `start'
2013-01-16T21:04:16+00:00 app[web.1]: from /app/config.ru:in `new'
2013-01-16T21:04:16+00:00 app[web.1]: from /app/vendor/bundle/ruby/1.9.1/gems/rack-1.4.4/lib/rack/server.rb:304:in `wrapped_app'
2013-01-16T21:04:16+00:00 app[web.1]: from /app/vendor/bundle/ruby/1.9.1/gems/rack-1.4.4/bin/rackup:4:in `<top (required)>'
2013-01-16T21:04:16+00:00 app[web.1]: from /app/vendor/bundle/ruby/1.9.1/gems/rack-1.4.4/lib/rack/builder.rb:40:in `parse_file'
2013-01-16T21:04:16+00:00 app[web.1]: from /app/vendor/bundle/ruby/1.9.1/gems/rack-1.4.4/lib/rack/server.rb:200:in `app'
2013-01-16T21:04:16+00:00 app[web.1]: from /app/config.ru:in `<main>'
2013-01-16T21:04:16+00:00 app[web.1]: from /app/vendor/bundle/ruby/1.9.1/gems/rack-1.4.4/lib/rack/builder.rb:40:in `eval'
2013-01-16T21:04:16+00:00 app[web.1]: /app/config.ru:1:in `block in <main>': undefined method `require' for #<Rack::Builder:0x0000000281d6a0 @run=nil, @map=nil, @use=[]> (NoMethodError)
2013-01-16T21:04:16+00:00 app[web.1]: from /app/vendor/bundle/ruby/1.9.1/gems/rack-1.4.4/lib/rack/server.rb:254:in `start'
2013-01-16T21:04:16+00:00 app[web.1]: from /app/vendor/bundle/ruby/1.9.1/bin/rackup:19:in `load'
2013-01-16T21:04:17+00:00 heroku[web.1]: State changed from starting to crashed
2013-01-16T21:04:17+00:00 heroku[web.1]: Process exited with status 1
2013-01-16T21:04:18+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path=/ host=mazzocato.herokuapp.com fwd=201.95.41.116 dyno= queue= wait= connect= service= status=503 bytes=
2013-01-16T21:04:19+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path=/favicon.ico host=mazzocato.herokuapp.com fwd=201.95.41.116 dyno= queue= wait= connect= service= status=503 bytes=
2013-01-16T21:04:20+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path=/favicon.ico host=mazzocato.herokuapp.com fwd=201.95.41.116 dyno= queue= wait= connect= service= status=503 bytes=
2013-01-16T21:04:37+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path=/ host=mazzocato.herokuapp.com fwd=201.95.41.116 dyno= queue= wait= connect= service= status=503 bytes=
2013-01-16T21:04:06+00:00 heroku[web.1]: Unidling
```
Follow my config.ru file:
```
require './app'
run Sinatra::Application
```
my main file is `app.rb`
Any help? | 2013/01/16 | [
"https://Stackoverflow.com/questions/14367906",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1472317/"
] | Try this:
```
<A.*HREF\s*=\s*(?:"|')([^"']*)(?:"|').*>(.*)<\/A>
```
Group1 and Group2 will give you the desired result. | Because the text `html` does not appear in your tag..... |
14,367,906 | I trying to deploy an app to Heroku, but when I push my config.ru file I've got errors.
Follow Heroku's log:
```
2013-01-16T21:04:14+00:00 heroku[web.1]: Starting process with command `bundle exec rackup config.ru -p 29160`
2013-01-16T21:04:16+00:00 app[web.1]: from /app/vendor/bundle/ruby/1.9.1/gems/rack-1.4.4/lib/rack/builder.rb:51:in `initialize'
2013-01-16T21:04:16+00:00 app[web.1]: from /app/vendor/bundle/ruby/1.9.1/bin/rackup:19:in `<main>'
2013-01-16T21:04:16+00:00 app[web.1]: from /app/vendor/bundle/ruby/1.9.1/gems/rack-1.4.4/lib/rack/builder.rb:51:in `instance_eval'
2013-01-16T21:04:16+00:00 app[web.1]: from /app/vendor/bundle/ruby/1.9.1/gems/rack-1.4.4/lib/rack/server.rb:137:in `start'
2013-01-16T21:04:16+00:00 app[web.1]: from /app/config.ru:in `new'
2013-01-16T21:04:16+00:00 app[web.1]: from /app/vendor/bundle/ruby/1.9.1/gems/rack-1.4.4/lib/rack/server.rb:304:in `wrapped_app'
2013-01-16T21:04:16+00:00 app[web.1]: from /app/vendor/bundle/ruby/1.9.1/gems/rack-1.4.4/bin/rackup:4:in `<top (required)>'
2013-01-16T21:04:16+00:00 app[web.1]: from /app/vendor/bundle/ruby/1.9.1/gems/rack-1.4.4/lib/rack/builder.rb:40:in `parse_file'
2013-01-16T21:04:16+00:00 app[web.1]: from /app/vendor/bundle/ruby/1.9.1/gems/rack-1.4.4/lib/rack/server.rb:200:in `app'
2013-01-16T21:04:16+00:00 app[web.1]: from /app/config.ru:in `<main>'
2013-01-16T21:04:16+00:00 app[web.1]: from /app/vendor/bundle/ruby/1.9.1/gems/rack-1.4.4/lib/rack/builder.rb:40:in `eval'
2013-01-16T21:04:16+00:00 app[web.1]: /app/config.ru:1:in `block in <main>': undefined method `require' for #<Rack::Builder:0x0000000281d6a0 @run=nil, @map=nil, @use=[]> (NoMethodError)
2013-01-16T21:04:16+00:00 app[web.1]: from /app/vendor/bundle/ruby/1.9.1/gems/rack-1.4.4/lib/rack/server.rb:254:in `start'
2013-01-16T21:04:16+00:00 app[web.1]: from /app/vendor/bundle/ruby/1.9.1/bin/rackup:19:in `load'
2013-01-16T21:04:17+00:00 heroku[web.1]: State changed from starting to crashed
2013-01-16T21:04:17+00:00 heroku[web.1]: Process exited with status 1
2013-01-16T21:04:18+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path=/ host=mazzocato.herokuapp.com fwd=201.95.41.116 dyno= queue= wait= connect= service= status=503 bytes=
2013-01-16T21:04:19+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path=/favicon.ico host=mazzocato.herokuapp.com fwd=201.95.41.116 dyno= queue= wait= connect= service= status=503 bytes=
2013-01-16T21:04:20+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path=/favicon.ico host=mazzocato.herokuapp.com fwd=201.95.41.116 dyno= queue= wait= connect= service= status=503 bytes=
2013-01-16T21:04:37+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path=/ host=mazzocato.herokuapp.com fwd=201.95.41.116 dyno= queue= wait= connect= service= status=503 bytes=
2013-01-16T21:04:06+00:00 heroku[web.1]: Unidling
```
Follow my config.ru file:
```
require './app'
run Sinatra::Application
```
my main file is `app.rb`
Any help? | 2013/01/16 | [
"https://Stackoverflow.com/questions/14367906",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1472317/"
] | Regular expressions for HTML can be brittle to change, but a regex for this exact case would be;
[`<A HREF="\(.*\)" .*>\(.*\)</A>`](http://refiddle.com/gjv) | Because the text `html` does not appear in your tag..... |
14,367,906 | I trying to deploy an app to Heroku, but when I push my config.ru file I've got errors.
Follow Heroku's log:
```
2013-01-16T21:04:14+00:00 heroku[web.1]: Starting process with command `bundle exec rackup config.ru -p 29160`
2013-01-16T21:04:16+00:00 app[web.1]: from /app/vendor/bundle/ruby/1.9.1/gems/rack-1.4.4/lib/rack/builder.rb:51:in `initialize'
2013-01-16T21:04:16+00:00 app[web.1]: from /app/vendor/bundle/ruby/1.9.1/bin/rackup:19:in `<main>'
2013-01-16T21:04:16+00:00 app[web.1]: from /app/vendor/bundle/ruby/1.9.1/gems/rack-1.4.4/lib/rack/builder.rb:51:in `instance_eval'
2013-01-16T21:04:16+00:00 app[web.1]: from /app/vendor/bundle/ruby/1.9.1/gems/rack-1.4.4/lib/rack/server.rb:137:in `start'
2013-01-16T21:04:16+00:00 app[web.1]: from /app/config.ru:in `new'
2013-01-16T21:04:16+00:00 app[web.1]: from /app/vendor/bundle/ruby/1.9.1/gems/rack-1.4.4/lib/rack/server.rb:304:in `wrapped_app'
2013-01-16T21:04:16+00:00 app[web.1]: from /app/vendor/bundle/ruby/1.9.1/gems/rack-1.4.4/bin/rackup:4:in `<top (required)>'
2013-01-16T21:04:16+00:00 app[web.1]: from /app/vendor/bundle/ruby/1.9.1/gems/rack-1.4.4/lib/rack/builder.rb:40:in `parse_file'
2013-01-16T21:04:16+00:00 app[web.1]: from /app/vendor/bundle/ruby/1.9.1/gems/rack-1.4.4/lib/rack/server.rb:200:in `app'
2013-01-16T21:04:16+00:00 app[web.1]: from /app/config.ru:in `<main>'
2013-01-16T21:04:16+00:00 app[web.1]: from /app/vendor/bundle/ruby/1.9.1/gems/rack-1.4.4/lib/rack/builder.rb:40:in `eval'
2013-01-16T21:04:16+00:00 app[web.1]: /app/config.ru:1:in `block in <main>': undefined method `require' for #<Rack::Builder:0x0000000281d6a0 @run=nil, @map=nil, @use=[]> (NoMethodError)
2013-01-16T21:04:16+00:00 app[web.1]: from /app/vendor/bundle/ruby/1.9.1/gems/rack-1.4.4/lib/rack/server.rb:254:in `start'
2013-01-16T21:04:16+00:00 app[web.1]: from /app/vendor/bundle/ruby/1.9.1/bin/rackup:19:in `load'
2013-01-16T21:04:17+00:00 heroku[web.1]: State changed from starting to crashed
2013-01-16T21:04:17+00:00 heroku[web.1]: Process exited with status 1
2013-01-16T21:04:18+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path=/ host=mazzocato.herokuapp.com fwd=201.95.41.116 dyno= queue= wait= connect= service= status=503 bytes=
2013-01-16T21:04:19+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path=/favicon.ico host=mazzocato.herokuapp.com fwd=201.95.41.116 dyno= queue= wait= connect= service= status=503 bytes=
2013-01-16T21:04:20+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path=/favicon.ico host=mazzocato.herokuapp.com fwd=201.95.41.116 dyno= queue= wait= connect= service= status=503 bytes=
2013-01-16T21:04:37+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path=/ host=mazzocato.herokuapp.com fwd=201.95.41.116 dyno= queue= wait= connect= service= status=503 bytes=
2013-01-16T21:04:06+00:00 heroku[web.1]: Unidling
```
Follow my config.ru file:
```
require './app'
run Sinatra::Application
```
my main file is `app.rb`
Any help? | 2013/01/16 | [
"https://Stackoverflow.com/questions/14367906",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1472317/"
] | Regular expressions for HTML can be brittle to change, but a regex for this exact case would be;
[`<A HREF="\(.*\)" .*>\(.*\)</A>`](http://refiddle.com/gjv) | Try this:
```
<A.*HREF\s*=\s*(?:"|')([^"']*)(?:"|').*>(.*)<\/A>
```
Group1 and Group2 will give you the desired result. |
1,853,771 | Find the probability that the birth days of 6 different persons will fall in exactly two calendar months.
Ans.is 341/(12^6)
Here each person has 12 option
So there are 6 persons .total no. Of ways 12^6
And out of 12 months 2 are randomly selected ..so $12$C$2$
B'day of 6 persons fall in 2 months in 2^6 ways.
Therefore requird probability is ($12$C$2$ × 2^$6$)/12^$6$
But not geting appropriate ans. | 2016/07/09 | [
"https://math.stackexchange.com/questions/1853771",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/351895/"
] | I'm assuming you mean
How do we find the derivative of $y= \frac{(4x^3 +8)^{\frac{1}{3}}}{(x+2)^5}$?
The quotation rule:
$\frac{f(x)}{g(x)}=\frac{f'(x)g(x)-g'(x)f(x)}{g^2(x)}$
The chain rule:
$f(g(x))=f'(g(x))g'(x)$
So to solve the question, we apply the quotation rule first
Letting
$$(4x^3 +8)^{\frac{1}{3}}=f(x)$$
$$(x+2)^5=g(x)$$
By applying the quotation rule, we get
$y'=\frac{f'(x)g(x)-g'(x)f(x)}{g^2(x)}$
You can use the chain rule to differentiate both $f(x)$ and $g(x)$
$f'(x)=\frac{1}{3}(4x^3+8)^{-\frac{2}{3}}12x^2$
$g'(x)=5(x+2)^4$
You can plug all of these into $y'=\frac{f'(x)g(x)-g'(x)f(x)}{g^2(x)}$ to get the derivative | Use this relation $$( \frac{f}{g})'=\frac{(f')g-(g')f}{g^2}$$
with
$$f(x)=(4x^3+8)^{1/3}$$
and
$$g(x)=(x+2)^5. $$
Also use the chain rule. |
1,853,771 | Find the probability that the birth days of 6 different persons will fall in exactly two calendar months.
Ans.is 341/(12^6)
Here each person has 12 option
So there are 6 persons .total no. Of ways 12^6
And out of 12 months 2 are randomly selected ..so $12$C$2$
B'day of 6 persons fall in 2 months in 2^6 ways.
Therefore requird probability is ($12$C$2$ × 2^$6$)/12^$6$
But not geting appropriate ans. | 2016/07/09 | [
"https://math.stackexchange.com/questions/1853771",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/351895/"
] | I'm assuming you mean
How do we find the derivative of $y= \frac{(4x^3 +8)^{\frac{1}{3}}}{(x+2)^5}$?
The quotation rule:
$\frac{f(x)}{g(x)}=\frac{f'(x)g(x)-g'(x)f(x)}{g^2(x)}$
The chain rule:
$f(g(x))=f'(g(x))g'(x)$
So to solve the question, we apply the quotation rule first
Letting
$$(4x^3 +8)^{\frac{1}{3}}=f(x)$$
$$(x+2)^5=g(x)$$
By applying the quotation rule, we get
$y'=\frac{f'(x)g(x)-g'(x)f(x)}{g^2(x)}$
You can use the chain rule to differentiate both $f(x)$ and $g(x)$
$f'(x)=\frac{1}{3}(4x^3+8)^{-\frac{2}{3}}12x^2$
$g'(x)=5(x+2)^4$
You can plug all of these into $y'=\frac{f'(x)g(x)-g'(x)f(x)}{g^2(x)}$ to get the derivative | You have optionnally two equivalent ways: $$(\frac{u}{v})'=(\frac{u'v-uv'}{v^2})\\(\frac 1v\cdot u)'=(\frac 1v)'\cdot u+(\frac 1v)\cdot u'$$
You must get after some care in calculations $$\left(\frac{\sqrt[3]{4x^3+8}}{(x+2)^5}\right)'=\frac{-16x^3+8x^2-40}{(x+2)^6\sqrt[3]{(4x^3+8)^2}}$$ |
1,853,771 | Find the probability that the birth days of 6 different persons will fall in exactly two calendar months.
Ans.is 341/(12^6)
Here each person has 12 option
So there are 6 persons .total no. Of ways 12^6
And out of 12 months 2 are randomly selected ..so $12$C$2$
B'day of 6 persons fall in 2 months in 2^6 ways.
Therefore requird probability is ($12$C$2$ × 2^$6$)/12^$6$
But not geting appropriate ans. | 2016/07/09 | [
"https://math.stackexchange.com/questions/1853771",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/351895/"
] | I'm assuming you mean
How do we find the derivative of $y= \frac{(4x^3 +8)^{\frac{1}{3}}}{(x+2)^5}$?
The quotation rule:
$\frac{f(x)}{g(x)}=\frac{f'(x)g(x)-g'(x)f(x)}{g^2(x)}$
The chain rule:
$f(g(x))=f'(g(x))g'(x)$
So to solve the question, we apply the quotation rule first
Letting
$$(4x^3 +8)^{\frac{1}{3}}=f(x)$$
$$(x+2)^5=g(x)$$
By applying the quotation rule, we get
$y'=\frac{f'(x)g(x)-g'(x)f(x)}{g^2(x)}$
You can use the chain rule to differentiate both $f(x)$ and $g(x)$
$f'(x)=\frac{1}{3}(4x^3+8)^{-\frac{2}{3}}12x^2$
$g'(x)=5(x+2)^4$
You can plug all of these into $y'=\frac{f'(x)g(x)-g'(x)f(x)}{g^2(x)}$ to get the derivative | **Hint**
When you face products, quotients, powers, .. , you can make life much easier using logarithmic differentiation. In your case $$y = \frac{\sqrt[3]{4x^3+8}}{(x+2)^5}\implies \log(y)=\frac 13 \log(4x^3+8)-5\log(x+2)$$ Now, differentiate $$\frac{y'}y=\frac 13 \times\frac {12x^2}{4x^2+8}-5\times\frac 1{x+2}= ??$$
Simplify (reducing to same denominator) and use $y'=y\times \frac{y'}y$ and simplify the powers. |
58,831,853 | ```
print("Please enter integers (then press enter key twice to show you're done):")
s = input() #whatever you're inputting after the print
first = True #What does this mean???
while s != "": #What does this mean???
lst = s.split() #split all your inputs into a list
for x in lst:
if first: #If its in ur lst?
maxV = int(x) #then the max value will be that input as an integer
first = False #What does this mean?
else:
if maxV < int(x):
maxV = int(x)
s= input()
print(maxV)
```
I'm confused as to what first=True and first= False in this code, what does it mean to set
a variable equal to true or false? Also confused as to what while s != "": means. Sorry,
I'm a complete beginner, would be forever grateful if someone could help me | 2019/11/13 | [
"https://Stackoverflow.com/questions/58831853",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12364974/"
] | I don't really know what programming language this is but with basic knowledge I can kinda tell you what these things mean. I hope it helps:
```
print("Please enter integers (then press enter key twice to show you're done):")
s = input() #Here s becomes your input
first = True #Here you set first as a boolean which can have the state true or false. In this example it gets the value True assigned
while s != "": #While repeats a certain process and in this example it keeps this process going while s isn't empty
lst = s.split() #splits all your inputs into a list <- you got that right
for x in lst:
if first: #It checks if first is true. If it is true it keeps going with the code right after the if
maxV = int(x) #then the max value will be that input as an integer
first = False #this sets a new value to first. which is false in this case
else:
if maxV < int(x):
maxV = int(x)
s= input()
print(maxV)
```
Additionally you said you didn't understand the `!=`. `!=` is like `==` but the opposite. It means unequal. Therefore if you say something like `1 == 1` this is true, because 1 equals 1. If you say `1 != 2` this is true because 1 is **not** the same as 2. | ```
first = True
```
set boolean variabel to `True`
```
while s != "":
```
check if input is empty. `!=` means not equal and is the opposite to `==` which means equal
```
if first:
```
if the `first` variable is `True` run the code for the if statement. In this case set the value as your max value and
```
first = False
```
set `first` to `False` since the next value isn't the first value anymore |
44,320,604 | I have a view like this:
```
Year | Month | Week | Category | Value |
2017 | 1 | 1 | A | 1
2017 | 1 | 1 | B | 2
2017 | 1 | 1 | C | 3
2017 | 1 | 2 | A | 4
2017 | 1 | 2 | B | 5
2017 | 1 | 2 | C | 6
2017 | 1 | 3 | A | 7
2017 | 1 | 3 | B | 8
2017 | 1 | 3 | C | 9
2017 | 1 | 4 | A | 10
2017 | 1 | 4 | B | 11
2017 | 1 | 4 | C | 12
2017 | 2 | 5 | A | 1
2017 | 2 | 5 | B | 2
2017 | 2 | 5 | C | 3
2017 | 2 | 6 | A | 4
2017 | 2 | 6 | B | 5
2017 | 2 | 6 | C | 6
2017 | 2 | 7 | A | 7
2017 | 2 | 7 | B | 8
2017 | 2 | 7 | C | 9
2017 | 2 | 8 | A | 10
2017 | 2 | 8 | B | 11
2017 | 2 | 8 | C | 12
```
And I need to make a new view which needs to show average of value column (let's call it avg\_val) and the value from the max week of the month (max\_val\_of\_month). Ex: max week of january is 4, so the value of category A is 10. Or something like this to be clear:
```
Year | Month | Category | avg_val | max_val_of_month
2017 | 1 | A | 5.5 | 10
2017 | 1 | B | 6.5 | 11
2017 | 1 | C | 7.5 | 12
2017 | 2 | A | 5.5 | 10
2017 | 2 | B | 6.5 | 11
2017 | 2 | C | 7.5 | 12
```
I have use window function, over partition by year, month, category to get the avg value. But how can I get the value of the max week of each month? | 2017/06/02 | [
"https://Stackoverflow.com/questions/44320604",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8091329/"
] | Assuming that you need a month average and a value for the max week not the max value per month
```
SELECT year, month, category, avg_val, value max_week_val
FROM (
SELECT *,
AVG(value) OVER (PARTITION BY year, month, category) avg_val,
ROW_NUMBER() OVER (PARTITION BY year, month, category ORDER BY week DESC) rn
FROM view1
) q
WHERE rn = 1
ORDER BY year, month, category
```
or more verbose version without window functions
```
SELECT q.year, q.month, q.category, q.avg_val, v.value max_week_val
FROM (
SELECT year, month, category, avg(value) avg_val, MAX(week) max_week
FROM view1
GROUP BY year, month, category
) q JOIN view1 v
ON q.year = v.year
AND q.month = v.month
AND q.category = v.category
AND q.max_week = v.week
ORDER BY year, month, category
```
Here is a [dbfiddle](http://dbfiddle.uk/?rdbms=postgres_9.6&fiddle=b3e36972ff6b186c0c3c82e4a627dc4b) demo for both queries | ```
with data (yr, mnth, wk, cat, val) as
(
-- begin test data
select 2017 , 1 , 1 , 'A' , 1 from dual union all
select 2017 , 1 , 1 , 'B' , 2 from dual union all
select 2017 , 1 , 1 , 'C' , 3 from dual union all
select 2017 , 1 , 2 , 'A' , 4 from dual union all
select 2017 , 1 , 2 , 'B' , 5 from dual union all
select 2017 , 1 , 2 , 'C' , 6 from dual union all
select 2017 , 1 , 3 , 'A' , 7 from dual union all
select 2017 , 1 , 3 , 'B' , 8 from dual union all
select 2017 , 1 , 3 , 'C' , 9 from dual union all
select 2017 , 1 , 4 , 'A' , 10 from dual union all
select 2017 , 1 , 4 , 'B' , 11 from dual union all
select 2017 , 1 , 4 , 'C' , 12 from dual union all
select 2017 , 2 , 5 , 'A' , 1 from dual union all
select 2017 , 2 , 5 , 'B' , 2 from dual union all
select 2017 , 2 , 5 , 'C' , 3 from dual union all
select 2017 , 2 , 6 , 'A' , 4 from dual union all
select 2017 , 2 , 6 , 'B' , 5 from dual union all
select 2017 , 2 , 6 , 'C' , 6 from dual union all
select 2017 , 2 , 7 , 'A' , 7 from dual union all
select 2017 , 2 , 8 , 'A' , 10 from dual union all
select 2017 , 2 , 8 , 'B' , 11 from dual union all
select 2017 , 2 , 7 , 'B' , 8 from dual union all
select 2017 , 2 , 7 , 'C' , 9 from dual union all
select 2018 , 2 , 7 , 'C' , 9 from dual union all
select 2017 , 2 , 8 , 'C' , 12 from dual
-- end test data
)
select * from
(
select
-- data.*: all columns of the data table
data.*,
-- avrg: partition by a combination of year,month and category to work out -
-- the avg for each category in a month of a year
avg(val) over (partition by yr, mnth, cat) avrg,
-- mwk: partition by year and month to work out -
-- the max week of a month in a year
max(wk) over (partition by yr, mnth) mwk
from
data
)
-- as OP's interest is in the max week of each month of a year, -
-- "wk" column value is matched against
-- the derived column "mwk"
where wk = mwk
order by yr,mnth,cat;
``` |
44,320,604 | I have a view like this:
```
Year | Month | Week | Category | Value |
2017 | 1 | 1 | A | 1
2017 | 1 | 1 | B | 2
2017 | 1 | 1 | C | 3
2017 | 1 | 2 | A | 4
2017 | 1 | 2 | B | 5
2017 | 1 | 2 | C | 6
2017 | 1 | 3 | A | 7
2017 | 1 | 3 | B | 8
2017 | 1 | 3 | C | 9
2017 | 1 | 4 | A | 10
2017 | 1 | 4 | B | 11
2017 | 1 | 4 | C | 12
2017 | 2 | 5 | A | 1
2017 | 2 | 5 | B | 2
2017 | 2 | 5 | C | 3
2017 | 2 | 6 | A | 4
2017 | 2 | 6 | B | 5
2017 | 2 | 6 | C | 6
2017 | 2 | 7 | A | 7
2017 | 2 | 7 | B | 8
2017 | 2 | 7 | C | 9
2017 | 2 | 8 | A | 10
2017 | 2 | 8 | B | 11
2017 | 2 | 8 | C | 12
```
And I need to make a new view which needs to show average of value column (let's call it avg\_val) and the value from the max week of the month (max\_val\_of\_month). Ex: max week of january is 4, so the value of category A is 10. Or something like this to be clear:
```
Year | Month | Category | avg_val | max_val_of_month
2017 | 1 | A | 5.5 | 10
2017 | 1 | B | 6.5 | 11
2017 | 1 | C | 7.5 | 12
2017 | 2 | A | 5.5 | 10
2017 | 2 | B | 6.5 | 11
2017 | 2 | C | 7.5 | 12
```
I have use window function, over partition by year, month, category to get the avg value. But how can I get the value of the max week of each month? | 2017/06/02 | [
"https://Stackoverflow.com/questions/44320604",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8091329/"
] | Assuming that you need a month average and a value for the max week not the max value per month
```
SELECT year, month, category, avg_val, value max_week_val
FROM (
SELECT *,
AVG(value) OVER (PARTITION BY year, month, category) avg_val,
ROW_NUMBER() OVER (PARTITION BY year, month, category ORDER BY week DESC) rn
FROM view1
) q
WHERE rn = 1
ORDER BY year, month, category
```
or more verbose version without window functions
```
SELECT q.year, q.month, q.category, q.avg_val, v.value max_week_val
FROM (
SELECT year, month, category, avg(value) avg_val, MAX(week) max_week
FROM view1
GROUP BY year, month, category
) q JOIN view1 v
ON q.year = v.year
AND q.month = v.month
AND q.category = v.category
AND q.max_week = v.week
ORDER BY year, month, category
```
Here is a [dbfiddle](http://dbfiddle.uk/?rdbms=postgres_9.6&fiddle=b3e36972ff6b186c0c3c82e4a627dc4b) demo for both queries | And here is my **NEW** version.
My thanks to @peterm for pointing me about the prior false value of `val_from_max_week_of_month`. So, I corrected it:
```
SELECT
a.Year,
a.Month,
a.Category,
max(a.Week) AS max_week,
AVG(a.Value) AS avg_val,
(
SELECT b.Value
FROM decades AS b
WHERE
b.Year = a.Year AND
b.Month = a.Month AND
b.Week = max(a.Week) AND
b.Category = a.Category
) AS val_from_max_week_of_month
FROM decades AS a
GROUP BY
a.Year,
a.Month,
a.Category
;
```
The new results:
[](https://i.stack.imgur.com/Oc3fP.png) |
44,320,604 | I have a view like this:
```
Year | Month | Week | Category | Value |
2017 | 1 | 1 | A | 1
2017 | 1 | 1 | B | 2
2017 | 1 | 1 | C | 3
2017 | 1 | 2 | A | 4
2017 | 1 | 2 | B | 5
2017 | 1 | 2 | C | 6
2017 | 1 | 3 | A | 7
2017 | 1 | 3 | B | 8
2017 | 1 | 3 | C | 9
2017 | 1 | 4 | A | 10
2017 | 1 | 4 | B | 11
2017 | 1 | 4 | C | 12
2017 | 2 | 5 | A | 1
2017 | 2 | 5 | B | 2
2017 | 2 | 5 | C | 3
2017 | 2 | 6 | A | 4
2017 | 2 | 6 | B | 5
2017 | 2 | 6 | C | 6
2017 | 2 | 7 | A | 7
2017 | 2 | 7 | B | 8
2017 | 2 | 7 | C | 9
2017 | 2 | 8 | A | 10
2017 | 2 | 8 | B | 11
2017 | 2 | 8 | C | 12
```
And I need to make a new view which needs to show average of value column (let's call it avg\_val) and the value from the max week of the month (max\_val\_of\_month). Ex: max week of january is 4, so the value of category A is 10. Or something like this to be clear:
```
Year | Month | Category | avg_val | max_val_of_month
2017 | 1 | A | 5.5 | 10
2017 | 1 | B | 6.5 | 11
2017 | 1 | C | 7.5 | 12
2017 | 2 | A | 5.5 | 10
2017 | 2 | B | 6.5 | 11
2017 | 2 | C | 7.5 | 12
```
I have use window function, over partition by year, month, category to get the avg value. But how can I get the value of the max week of each month? | 2017/06/02 | [
"https://Stackoverflow.com/questions/44320604",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8091329/"
] | Assuming that you need a month average and a value for the max week not the max value per month
```
SELECT year, month, category, avg_val, value max_week_val
FROM (
SELECT *,
AVG(value) OVER (PARTITION BY year, month, category) avg_val,
ROW_NUMBER() OVER (PARTITION BY year, month, category ORDER BY week DESC) rn
FROM view1
) q
WHERE rn = 1
ORDER BY year, month, category
```
or more verbose version without window functions
```
SELECT q.year, q.month, q.category, q.avg_val, v.value max_week_val
FROM (
SELECT year, month, category, avg(value) avg_val, MAX(week) max_week
FROM view1
GROUP BY year, month, category
) q JOIN view1 v
ON q.year = v.year
AND q.month = v.month
AND q.category = v.category
AND q.max_week = v.week
ORDER BY year, month, category
```
Here is a [dbfiddle](http://dbfiddle.uk/?rdbms=postgres_9.6&fiddle=b3e36972ff6b186c0c3c82e4a627dc4b) demo for both queries | First, you *might* need to check, how do you handle the first week in January. If 1st of January are not a Monday, there are several interpretations & not every one of them will fit the solutions here. You'll either need to use:
* the [ISO week concept](https://en.wikipedia.org/wiki/ISO_week_date), ie. the `week` column should hold the ISO week & the `year` column should hold the ISO year (week-year, rather). Note: in this concept, 1st of January actually sometimes belongs to the previous year
* use your own concept, where the first week of the year is "split" into two if 1st of January is not a Monday.
*Note*: the solutions below will not work if (in your table) the first week of January can be 52 or 53.
Given that `avg_val` is just a simple aggregation, while `max_val_of_month` can be calculated with typical [greatest-n-per-group](/questions/tagged/greatest-n-per-group "show questions tagged 'greatest-n-per-group'") queries. [It has a lot of possible solutions in PostgreSQL, with varying performance.](https://stackoverflow.com/a/34715134/1499698) Fortunately, your query will naturally have an easily determined selectivity: you'll always need (approx.) a quarter of your data.
Usual winners (in performance) are:
(These are not surprise though, as these 2 should perform more and more as you need more portion of the original data.)
`array_agg()` with `order by` variant:
--------------------------------------
```
select year, month, category, avg(value) avg_val,
(array_agg(value order by week desc))[1] max_val_of_month
from table_name
group by year, month, category;
```
`distinct on` variant:
----------------------
```
select distinct on (year, month, category) year, month, category,
avg(value) over (partition by year, month, category) avg_val,
value max_val_of_month
from table_name
order by year, month, category, week desc;
```
The pure window function variant is not that bad either:
`row_number()` variant:
-----------------------
```
select year, month, category, avg_val, max_val_of_month
from (select year, month, category, value max_val_of_month,
avg(value) over (partition by year, month, category) avg_val,
row_number() over (partition by year, month, category order by week desc) rn
from table_name) w
where rn = 1;
```
But the `LATERAL` variant is only viable with an index:
`LATERAL` variant:
------------------
```
create index idx_table_name_year_month_category_week_desc
on table_name(year, month, category, week desc);
select year, month, category,
avg(value) avg_val,
max_val_of_month
from table_name t
cross join lateral (select value max_val_of_month
from table_name
where (year, month, category) = (t.year, t.month, t.category)
order by week desc
limit 1) m
group by year, month, category, max_val_of_month;
```
**But** most of the solutions above can actually utilize this index, not just this last one.
Without the index: <http://rextester.com/WNEL86809>
With the index: <http://rextester.com/TYUA52054> |
39,931,342 | I have got a string
```
$key1={331015EA261D38A7}
$key2={9145A98BA37617DE}
$key3={EF745F23AA67243D}
```
How do i split each of the keys based on "$" and the "next line" element?
and then place it in an Arraylist?
The output should look like this:
Arraylist[0]:
```
$key1={331015EA261D38A7}
```
Arraylist[1]:
```
$key2={9145A98BA37617DE}
```
Arraylist[2]:
```
$key3={EF745F23AA67243D}
``` | 2016/10/08 | [
"https://Stackoverflow.com/questions/39931342",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6659196/"
] | If you just want to split by new line, it is as simple as :
```
yourstring.split("\n"):
``` | yourstring.split(System.getProperty("line.separator")); |
39,931,342 | I have got a string
```
$key1={331015EA261D38A7}
$key2={9145A98BA37617DE}
$key3={EF745F23AA67243D}
```
How do i split each of the keys based on "$" and the "next line" element?
and then place it in an Arraylist?
The output should look like this:
Arraylist[0]:
```
$key1={331015EA261D38A7}
```
Arraylist[1]:
```
$key2={9145A98BA37617DE}
```
Arraylist[2]:
```
$key3={EF745F23AA67243D}
``` | 2016/10/08 | [
"https://Stackoverflow.com/questions/39931342",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6659196/"
] | If you just want to split by new line, it is as simple as :
```
yourstring.split("\n"):
``` | Don't split, *search* your `String` for key value pairs:
```
\$(?<key>[^=]++)=\{(?<value>[^}]++)\}
```
For example:
```
final Pattern pattern = Pattern.compile("\\$(?<key>[^=]++)=\\{(?<value>[^}]++)\\}");
final String input = "$key1={331015EA261D38A7}\n$key2={9145A98BA37617DE}\n$key3={EF745F23AA67243D}";
final Matcher matcher = pattern.matcher(input);
final Map<String, String> parse = new HashMap<>();
while (matcher.find()) {
parse.put(matcher.group("key"), matcher.group("value"));
}
//print values
parse.forEach((k, v) -> System.out.printf("Key '%s' has value '%s'%n", k, v));
```
Output:
>
> Key 'key1' has value '331015EA261D38A7'
>
> Key 'key2' has value '9145A98BA37617DE'
>
> Key 'key3' has value 'EF745F23AA67243D'
>
>
> |
39,931,342 | I have got a string
```
$key1={331015EA261D38A7}
$key2={9145A98BA37617DE}
$key3={EF745F23AA67243D}
```
How do i split each of the keys based on "$" and the "next line" element?
and then place it in an Arraylist?
The output should look like this:
Arraylist[0]:
```
$key1={331015EA261D38A7}
```
Arraylist[1]:
```
$key2={9145A98BA37617DE}
```
Arraylist[2]:
```
$key3={EF745F23AA67243D}
``` | 2016/10/08 | [
"https://Stackoverflow.com/questions/39931342",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6659196/"
] | Don't split, *search* your `String` for key value pairs:
```
\$(?<key>[^=]++)=\{(?<value>[^}]++)\}
```
For example:
```
final Pattern pattern = Pattern.compile("\\$(?<key>[^=]++)=\\{(?<value>[^}]++)\\}");
final String input = "$key1={331015EA261D38A7}\n$key2={9145A98BA37617DE}\n$key3={EF745F23AA67243D}";
final Matcher matcher = pattern.matcher(input);
final Map<String, String> parse = new HashMap<>();
while (matcher.find()) {
parse.put(matcher.group("key"), matcher.group("value"));
}
//print values
parse.forEach((k, v) -> System.out.printf("Key '%s' has value '%s'%n", k, v));
```
Output:
>
> Key 'key1' has value '331015EA261D38A7'
>
> Key 'key2' has value '9145A98BA37617DE'
>
> Key 'key3' has value 'EF745F23AA67243D'
>
>
> | yourstring.split(System.getProperty("line.separator")); |
1,486,009 | I have the following norms:
$$
\|f\|\_1=\int\_{t\_0}^{t\_1}\|f(t)\|\_2dt
$$
$$
\|f\|\_2=\sqrt{\int\_{t\_0}^{t\_1}\|f(t)\|\_2^2dt}
$$
I need to show their non-equivalence, i.e. that there do not exist numbers $a,b\in\mathbb R$, $a\ge b>0$ such that $b\|f\|\_2\le\|f\|\_1\le a\|f\|\_2$.
I would like to do the proof by myself (don't show the full proof please). I am almost sure this has to be a proof by contradiction, so I somehow need to write a few inequalities that give something like this:
$$
\begin{array}{rll}
\|f\|\_1 & = & \int\_{t\_0}^{t\_1}\|f(t)\|\_2dt \\
& \le & ??? \\
& \vdots & \\
& \le & \text{something}\cdot\|f\|\_2 \\
\end{array}
$$
and show that this "something" can take a value that would contradict the assumption that an $a$ exists. However, I do not know how to make the journey from $\|f\|\_1$ to $\|f\|\_2$ using inequalities, primarily due to the presence of the square root. Could you please help me get started? Thanks a lot! | 2015/10/18 | [
"https://math.stackexchange.com/questions/1486009",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/218257/"
] | **Hint**: Try to construct a sequence of functions $f\_n$ in the vector space you work in such that $\frac{||f\_n||\_1}{||f\_n||\_2} < \frac{1}{n}$. This will show that a constant $b > 0$ such that $b ||f||\_2 \leq ||f||\_1$ for **all** $f$ does not exist. | HINT: To find a counterexample, think about $1/x$ on $(0,1]$.
HINT TO A HINT: $1/x$ is $f^2$, not $f$. |
1,486,009 | I have the following norms:
$$
\|f\|\_1=\int\_{t\_0}^{t\_1}\|f(t)\|\_2dt
$$
$$
\|f\|\_2=\sqrt{\int\_{t\_0}^{t\_1}\|f(t)\|\_2^2dt}
$$
I need to show their non-equivalence, i.e. that there do not exist numbers $a,b\in\mathbb R$, $a\ge b>0$ such that $b\|f\|\_2\le\|f\|\_1\le a\|f\|\_2$.
I would like to do the proof by myself (don't show the full proof please). I am almost sure this has to be a proof by contradiction, so I somehow need to write a few inequalities that give something like this:
$$
\begin{array}{rll}
\|f\|\_1 & = & \int\_{t\_0}^{t\_1}\|f(t)\|\_2dt \\
& \le & ??? \\
& \vdots & \\
& \le & \text{something}\cdot\|f\|\_2 \\
\end{array}
$$
and show that this "something" can take a value that would contradict the assumption that an $a$ exists. However, I do not know how to make the journey from $\|f\|\_1$ to $\|f\|\_2$ using inequalities, primarily due to the presence of the square root. Could you please help me get started? Thanks a lot! | 2015/10/18 | [
"https://math.stackexchange.com/questions/1486009",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/218257/"
] | Think of
$$
f(t)=\frac{1}{\sqrt{t-t\_0}}.
$$
You can show that $f$ belongs to $L^1$ but not $L^2$.
If you for some reason would like a sequence of functions $f\_n\in L^1\cap L^2$ such that
$$
\lim\_{n\to+\infty}\frac{\|f\_n\|\_{L^2}}{\|f\_n\|\_{L^1}}=+\infty,
$$
then you can cut the example above off, and consider
$$
f\_n(t)=\chi\_{(t\_0+1/n,t\_1)}\frac{1}{\sqrt{t-t\_0}}.
$$
Here $\chi\_{(t\_0+1/n,t\_1)}$ denotes the characteristic function of the interval $(t\_0+1/n,t\_1)$. (If you want, you might consider only large $n$ so that $(t\_0+1/n,t\_1)$ is not empty, but that is a minor detail.) | HINT: To find a counterexample, think about $1/x$ on $(0,1]$.
HINT TO A HINT: $1/x$ is $f^2$, not $f$. |
1,486,009 | I have the following norms:
$$
\|f\|\_1=\int\_{t\_0}^{t\_1}\|f(t)\|\_2dt
$$
$$
\|f\|\_2=\sqrt{\int\_{t\_0}^{t\_1}\|f(t)\|\_2^2dt}
$$
I need to show their non-equivalence, i.e. that there do not exist numbers $a,b\in\mathbb R$, $a\ge b>0$ such that $b\|f\|\_2\le\|f\|\_1\le a\|f\|\_2$.
I would like to do the proof by myself (don't show the full proof please). I am almost sure this has to be a proof by contradiction, so I somehow need to write a few inequalities that give something like this:
$$
\begin{array}{rll}
\|f\|\_1 & = & \int\_{t\_0}^{t\_1}\|f(t)\|\_2dt \\
& \le & ??? \\
& \vdots & \\
& \le & \text{something}\cdot\|f\|\_2 \\
\end{array}
$$
and show that this "something" can take a value that would contradict the assumption that an $a$ exists. However, I do not know how to make the journey from $\|f\|\_1$ to $\|f\|\_2$ using inequalities, primarily due to the presence of the square root. Could you please help me get started? Thanks a lot! | 2015/10/18 | [
"https://math.stackexchange.com/questions/1486009",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/218257/"
] | **Hint**: Try to construct a sequence of functions $f\_n$ in the vector space you work in such that $\frac{||f\_n||\_1}{||f\_n||\_2} < \frac{1}{n}$. This will show that a constant $b > 0$ such that $b ||f||\_2 \leq ||f||\_1$ for **all** $f$ does not exist. | Think of
$$
f(t)=\frac{1}{\sqrt{t-t\_0}}.
$$
You can show that $f$ belongs to $L^1$ but not $L^2$.
If you for some reason would like a sequence of functions $f\_n\in L^1\cap L^2$ such that
$$
\lim\_{n\to+\infty}\frac{\|f\_n\|\_{L^2}}{\|f\_n\|\_{L^1}}=+\infty,
$$
then you can cut the example above off, and consider
$$
f\_n(t)=\chi\_{(t\_0+1/n,t\_1)}\frac{1}{\sqrt{t-t\_0}}.
$$
Here $\chi\_{(t\_0+1/n,t\_1)}$ denotes the characteristic function of the interval $(t\_0+1/n,t\_1)$. (If you want, you might consider only large $n$ so that $(t\_0+1/n,t\_1)$ is not empty, but that is a minor detail.) |
25,446,685 | I have a simple tab system but I'm a bit stuck on exactly how to make this work.
I'm using ng-repeat to spit out the tabs and the content and so far this is working fine.
Here are my tabs:
```
<ul class="job-title-list">
<li ng-repeat="tab in tabBlocks">
<a href="javascript:;" ng-click="activeTab($index)">dummy content</a>
</li>
</ul>
```
And here's the repeated content which needs to match up to the tabs:
```
<div ng-repeat="content in contentBlocks">
<p>more dummy content</p>
</div>
```
And finally, my function (the console log returns the correct indexes from the tabs)
```
$scope.activeTab = function(i) {
$scope.selectedTab = i
console.log($scope.selectedTab)
}
```
Any suggestions on how I should go about this? I've looked into ng-show, ng-switch and ng-if to show and hide the appropriate content but I've been stuck on this for a while...
Many thanks! | 2014/08/22 | [
"https://Stackoverflow.com/questions/25446685",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1768250/"
] | ```
jFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
```
Now for a bit of explanation. The closest equivalent to as seen in the question is..
```
jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
```
But that kills the entire JRE irrespective of other non-daemon threads that are running. If they are running, they should be shut down or cleaned up explicitly.
If there are no other non-daemon threads running, `DISPOSE_ON_CLOSE` will dispose the current `JFrame` and end the virtual machine. | If you're talking about a `JButton` that you want to put into your form, then you want to invoke `JFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE)` in your constructor for the form, and then your button handler can invoke
```
dispose()
```
to close the form. |
25,446,685 | I have a simple tab system but I'm a bit stuck on exactly how to make this work.
I'm using ng-repeat to spit out the tabs and the content and so far this is working fine.
Here are my tabs:
```
<ul class="job-title-list">
<li ng-repeat="tab in tabBlocks">
<a href="javascript:;" ng-click="activeTab($index)">dummy content</a>
</li>
</ul>
```
And here's the repeated content which needs to match up to the tabs:
```
<div ng-repeat="content in contentBlocks">
<p>more dummy content</p>
</div>
```
And finally, my function (the console log returns the correct indexes from the tabs)
```
$scope.activeTab = function(i) {
$scope.selectedTab = i
console.log($scope.selectedTab)
}
```
Any suggestions on how I should go about this? I've looked into ng-show, ng-switch and ng-if to show and hide the appropriate content but I've been stuck on this for a while...
Many thanks! | 2014/08/22 | [
"https://Stackoverflow.com/questions/25446685",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1768250/"
] | If you want to create a button which exits the application when the user clicks it, try this:
```
JButton exit = new JButton("exit");
ActionListener al = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
};
exit.addActionListener(al);
```
Now when you press on that button the application will exit. | If you're talking about a `JButton` that you want to put into your form, then you want to invoke `JFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE)` in your constructor for the form, and then your button handler can invoke
```
dispose()
```
to close the form. |
25,446,685 | I have a simple tab system but I'm a bit stuck on exactly how to make this work.
I'm using ng-repeat to spit out the tabs and the content and so far this is working fine.
Here are my tabs:
```
<ul class="job-title-list">
<li ng-repeat="tab in tabBlocks">
<a href="javascript:;" ng-click="activeTab($index)">dummy content</a>
</li>
</ul>
```
And here's the repeated content which needs to match up to the tabs:
```
<div ng-repeat="content in contentBlocks">
<p>more dummy content</p>
</div>
```
And finally, my function (the console log returns the correct indexes from the tabs)
```
$scope.activeTab = function(i) {
$scope.selectedTab = i
console.log($scope.selectedTab)
}
```
Any suggestions on how I should go about this? I've looked into ng-show, ng-switch and ng-if to show and hide the appropriate content but I've been stuck on this for a while...
Many thanks! | 2014/08/22 | [
"https://Stackoverflow.com/questions/25446685",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1768250/"
] | @AndrewThompson is right about `JFrame.EXIT_ON_CLOSE` but you can take steps to avoid just killing stuff.
*`JFrame.EXIT_ON_CLOSE` is just fine, if you handle cleanup in an overridden `JFrame.processWindowEvent(WindowEvent)` checking for `WindowEvent.WINDOW_CLOSING` events.*
```java
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JProgressBar;
import javax.swing.Timer;
public class ExitJFrame extends JFrame {
public ExitJFrame() {
setLayout(new BorderLayout());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton button = new JButton("Exit");
add(button);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ExitJFrame.this.processWindowEvent(
new WindowEvent(
ExitJFrame.this, WindowEvent.WINDOW_CLOSING));
}
});
setSize(200, 200);
setLocationRelativeTo(null);
}
@Override
protected void processWindowEvent(WindowEvent e) {
// more powerful as a WindowListener, since you can consume the event
// if you so please - asking the user if she really wants to exit for
// example, do not delegate to super if consuming.
if (e.getID() == WindowEvent.WINDOW_CLOSING) {
doCleanup();
super.processWindowEvent(e);
} else {
super.processWindowEvent(e);
}
}
private void doCleanup() {
final JDialog dialog = new JDialog(this, true);
dialog.setLayout(new BorderLayout());
dialog.setUndecorated(true);
JProgressBar progress = new JProgressBar();
dialog.add(progress);
dialog.add(new JLabel("Waiting for non-daemon threads to exit gracefully..."), BorderLayout.NORTH);
progress.setIndeterminate(true);
Timer timer = new Timer(2000, new ActionListener() {
public void actionPerformed(ActionEvent e) {
dialog.setVisible(false);
dialog.dispose();
}
});
timer.setRepeats(false);
timer.start();
dialog.pack();
dialog.setLocationRelativeTo(this);
dialog.setVisible(true);
}
public static void main (String[] args) {
new ExitJFrame().setVisible(true);
}
}
``` | If you're talking about a `JButton` that you want to put into your form, then you want to invoke `JFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE)` in your constructor for the form, and then your button handler can invoke
```
dispose()
```
to close the form. |
25,446,685 | I have a simple tab system but I'm a bit stuck on exactly how to make this work.
I'm using ng-repeat to spit out the tabs and the content and so far this is working fine.
Here are my tabs:
```
<ul class="job-title-list">
<li ng-repeat="tab in tabBlocks">
<a href="javascript:;" ng-click="activeTab($index)">dummy content</a>
</li>
</ul>
```
And here's the repeated content which needs to match up to the tabs:
```
<div ng-repeat="content in contentBlocks">
<p>more dummy content</p>
</div>
```
And finally, my function (the console log returns the correct indexes from the tabs)
```
$scope.activeTab = function(i) {
$scope.selectedTab = i
console.log($scope.selectedTab)
}
```
Any suggestions on how I should go about this? I've looked into ng-show, ng-switch and ng-if to show and hide the appropriate content but I've been stuck on this for a while...
Many thanks! | 2014/08/22 | [
"https://Stackoverflow.com/questions/25446685",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1768250/"
] | ```
jFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
```
Now for a bit of explanation. The closest equivalent to as seen in the question is..
```
jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
```
But that kills the entire JRE irrespective of other non-daemon threads that are running. If they are running, they should be shut down or cleaned up explicitly.
If there are no other non-daemon threads running, `DISPOSE_ON_CLOSE` will dispose the current `JFrame` and end the virtual machine. | If you want to create a button which exits the application when the user clicks it, try this:
```
JButton exit = new JButton("exit");
ActionListener al = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
};
exit.addActionListener(al);
```
Now when you press on that button the application will exit. |
25,446,685 | I have a simple tab system but I'm a bit stuck on exactly how to make this work.
I'm using ng-repeat to spit out the tabs and the content and so far this is working fine.
Here are my tabs:
```
<ul class="job-title-list">
<li ng-repeat="tab in tabBlocks">
<a href="javascript:;" ng-click="activeTab($index)">dummy content</a>
</li>
</ul>
```
And here's the repeated content which needs to match up to the tabs:
```
<div ng-repeat="content in contentBlocks">
<p>more dummy content</p>
</div>
```
And finally, my function (the console log returns the correct indexes from the tabs)
```
$scope.activeTab = function(i) {
$scope.selectedTab = i
console.log($scope.selectedTab)
}
```
Any suggestions on how I should go about this? I've looked into ng-show, ng-switch and ng-if to show and hide the appropriate content but I've been stuck on this for a while...
Many thanks! | 2014/08/22 | [
"https://Stackoverflow.com/questions/25446685",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1768250/"
] | ```
jFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
```
Now for a bit of explanation. The closest equivalent to as seen in the question is..
```
jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
```
But that kills the entire JRE irrespective of other non-daemon threads that are running. If they are running, they should be shut down or cleaned up explicitly.
If there are no other non-daemon threads running, `DISPOSE_ON_CLOSE` will dispose the current `JFrame` and end the virtual machine. | Very simple answer is as @Andrew Thompson said.
```
jFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
```
**OR**
```
jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
```
and if u want to make it in other way by code. then u can put this code anywhere. in events.
System.exit(0);
hope this will help. |
25,446,685 | I have a simple tab system but I'm a bit stuck on exactly how to make this work.
I'm using ng-repeat to spit out the tabs and the content and so far this is working fine.
Here are my tabs:
```
<ul class="job-title-list">
<li ng-repeat="tab in tabBlocks">
<a href="javascript:;" ng-click="activeTab($index)">dummy content</a>
</li>
</ul>
```
And here's the repeated content which needs to match up to the tabs:
```
<div ng-repeat="content in contentBlocks">
<p>more dummy content</p>
</div>
```
And finally, my function (the console log returns the correct indexes from the tabs)
```
$scope.activeTab = function(i) {
$scope.selectedTab = i
console.log($scope.selectedTab)
}
```
Any suggestions on how I should go about this? I've looked into ng-show, ng-switch and ng-if to show and hide the appropriate content but I've been stuck on this for a while...
Many thanks! | 2014/08/22 | [
"https://Stackoverflow.com/questions/25446685",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1768250/"
] | ```
jFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
```
Now for a bit of explanation. The closest equivalent to as seen in the question is..
```
jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
```
But that kills the entire JRE irrespective of other non-daemon threads that are running. If they are running, they should be shut down or cleaned up explicitly.
If there are no other non-daemon threads running, `DISPOSE_ON_CLOSE` will dispose the current `JFrame` and end the virtual machine. | @AndrewThompson is right about `JFrame.EXIT_ON_CLOSE` but you can take steps to avoid just killing stuff.
*`JFrame.EXIT_ON_CLOSE` is just fine, if you handle cleanup in an overridden `JFrame.processWindowEvent(WindowEvent)` checking for `WindowEvent.WINDOW_CLOSING` events.*
```java
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JProgressBar;
import javax.swing.Timer;
public class ExitJFrame extends JFrame {
public ExitJFrame() {
setLayout(new BorderLayout());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton button = new JButton("Exit");
add(button);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ExitJFrame.this.processWindowEvent(
new WindowEvent(
ExitJFrame.this, WindowEvent.WINDOW_CLOSING));
}
});
setSize(200, 200);
setLocationRelativeTo(null);
}
@Override
protected void processWindowEvent(WindowEvent e) {
// more powerful as a WindowListener, since you can consume the event
// if you so please - asking the user if she really wants to exit for
// example, do not delegate to super if consuming.
if (e.getID() == WindowEvent.WINDOW_CLOSING) {
doCleanup();
super.processWindowEvent(e);
} else {
super.processWindowEvent(e);
}
}
private void doCleanup() {
final JDialog dialog = new JDialog(this, true);
dialog.setLayout(new BorderLayout());
dialog.setUndecorated(true);
JProgressBar progress = new JProgressBar();
dialog.add(progress);
dialog.add(new JLabel("Waiting for non-daemon threads to exit gracefully..."), BorderLayout.NORTH);
progress.setIndeterminate(true);
Timer timer = new Timer(2000, new ActionListener() {
public void actionPerformed(ActionEvent e) {
dialog.setVisible(false);
dialog.dispose();
}
});
timer.setRepeats(false);
timer.start();
dialog.pack();
dialog.setLocationRelativeTo(this);
dialog.setVisible(true);
}
public static void main (String[] args) {
new ExitJFrame().setVisible(true);
}
}
``` |
25,446,685 | I have a simple tab system but I'm a bit stuck on exactly how to make this work.
I'm using ng-repeat to spit out the tabs and the content and so far this is working fine.
Here are my tabs:
```
<ul class="job-title-list">
<li ng-repeat="tab in tabBlocks">
<a href="javascript:;" ng-click="activeTab($index)">dummy content</a>
</li>
</ul>
```
And here's the repeated content which needs to match up to the tabs:
```
<div ng-repeat="content in contentBlocks">
<p>more dummy content</p>
</div>
```
And finally, my function (the console log returns the correct indexes from the tabs)
```
$scope.activeTab = function(i) {
$scope.selectedTab = i
console.log($scope.selectedTab)
}
```
Any suggestions on how I should go about this? I've looked into ng-show, ng-switch and ng-if to show and hide the appropriate content but I've been stuck on this for a while...
Many thanks! | 2014/08/22 | [
"https://Stackoverflow.com/questions/25446685",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1768250/"
] | If you want to create a button which exits the application when the user clicks it, try this:
```
JButton exit = new JButton("exit");
ActionListener al = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
};
exit.addActionListener(al);
```
Now when you press on that button the application will exit. | Very simple answer is as @Andrew Thompson said.
```
jFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
```
**OR**
```
jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
```
and if u want to make it in other way by code. then u can put this code anywhere. in events.
System.exit(0);
hope this will help. |
25,446,685 | I have a simple tab system but I'm a bit stuck on exactly how to make this work.
I'm using ng-repeat to spit out the tabs and the content and so far this is working fine.
Here are my tabs:
```
<ul class="job-title-list">
<li ng-repeat="tab in tabBlocks">
<a href="javascript:;" ng-click="activeTab($index)">dummy content</a>
</li>
</ul>
```
And here's the repeated content which needs to match up to the tabs:
```
<div ng-repeat="content in contentBlocks">
<p>more dummy content</p>
</div>
```
And finally, my function (the console log returns the correct indexes from the tabs)
```
$scope.activeTab = function(i) {
$scope.selectedTab = i
console.log($scope.selectedTab)
}
```
Any suggestions on how I should go about this? I've looked into ng-show, ng-switch and ng-if to show and hide the appropriate content but I've been stuck on this for a while...
Many thanks! | 2014/08/22 | [
"https://Stackoverflow.com/questions/25446685",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1768250/"
] | @AndrewThompson is right about `JFrame.EXIT_ON_CLOSE` but you can take steps to avoid just killing stuff.
*`JFrame.EXIT_ON_CLOSE` is just fine, if you handle cleanup in an overridden `JFrame.processWindowEvent(WindowEvent)` checking for `WindowEvent.WINDOW_CLOSING` events.*
```java
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JProgressBar;
import javax.swing.Timer;
public class ExitJFrame extends JFrame {
public ExitJFrame() {
setLayout(new BorderLayout());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton button = new JButton("Exit");
add(button);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ExitJFrame.this.processWindowEvent(
new WindowEvent(
ExitJFrame.this, WindowEvent.WINDOW_CLOSING));
}
});
setSize(200, 200);
setLocationRelativeTo(null);
}
@Override
protected void processWindowEvent(WindowEvent e) {
// more powerful as a WindowListener, since you can consume the event
// if you so please - asking the user if she really wants to exit for
// example, do not delegate to super if consuming.
if (e.getID() == WindowEvent.WINDOW_CLOSING) {
doCleanup();
super.processWindowEvent(e);
} else {
super.processWindowEvent(e);
}
}
private void doCleanup() {
final JDialog dialog = new JDialog(this, true);
dialog.setLayout(new BorderLayout());
dialog.setUndecorated(true);
JProgressBar progress = new JProgressBar();
dialog.add(progress);
dialog.add(new JLabel("Waiting for non-daemon threads to exit gracefully..."), BorderLayout.NORTH);
progress.setIndeterminate(true);
Timer timer = new Timer(2000, new ActionListener() {
public void actionPerformed(ActionEvent e) {
dialog.setVisible(false);
dialog.dispose();
}
});
timer.setRepeats(false);
timer.start();
dialog.pack();
dialog.setLocationRelativeTo(this);
dialog.setVisible(true);
}
public static void main (String[] args) {
new ExitJFrame().setVisible(true);
}
}
``` | Very simple answer is as @Andrew Thompson said.
```
jFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
```
**OR**
```
jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
```
and if u want to make it in other way by code. then u can put this code anywhere. in events.
System.exit(0);
hope this will help. |
17,635,381 | I am new to triggers
i have two tables with names ArefSms And tblSalesProd
i want after an insert my trigger update ArefSms where tblSalesProd.SalesID=ArefSms.SalesID
for this propose i write below code
```
USE [ACEDB]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER TRIGGER [dbo].[areftblSalesProd] ON [dbo].[tblSalesProd]
AFTER INSERT
AS
Begin Try
Update ArefSms
set
qt=inserted.ProdQty
where ArefSms.SalesID=inserted.SalesID
End Try
Begin Catch
End catch
```
but now i have error
```
Msg 4104, Level 16, State 1, Procedure areftblSalesProd, Line 9
The multi-part identifier "inserted.SalesID" could not be bound.
```
What can I do? | 2013/07/14 | [
"https://Stackoverflow.com/questions/17635381",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2304094/"
] | You need to specify `inserted` in the `update` statement. It is a table reference:
```
Update ArefSms
set qt=inserted.ProdQty
from inserted
where ArefSms.SalesID=inserted.SalesID;
``` | When updating tables from other tables (in this case `inserted`), I prefer the syntax using `JOINs`:
```
UPDATE Aref
SET Aref.qt=inserted.ProdQty
FROM ArefSms Aref
INNER JOIN inserted ON Aref.SalesID=inserted.SalesID
```
* [Condensed Fiddle Demo](http://sqlfiddle.com/#!3/25771/1) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.