text:
Q: Use the annotations inside the method Is there a way to use the value of the annotation inside the same method that it has been declared ?
@GET
@Produces({MediaType.APPLICATION_XML})
@Path(CONSTANTS.PATH1)
public MyModel getInfo(
            @PathParam(CONSTANTS.ID) String id,
            @Context HttpServletRequest request,
            @Context HttpServletResponse response) {
    ...
}

In the above example, is it possible to use the value of  @Path(CONSTANTS.PATH1) inside the method? I can directly use the value of CONSTANTS.PATH1, but if it possible to get it from annotations itself ?


text:
Q: Volatile and multithreading: is the following thread-safe? Assume there are two threads running Thread1() and Thread2() respectively.  The thread 1 just sets a global flag to tell thread 2 to quit and thread 2 periodically checks if it should quit.
volatile bool is_terminate = false;

void Thread1()
{
    is_terminate = true;
}

void Thread2()
{
    while (!is_terminate) {
        // ...
    }
}

I want to ask if the above code is safe assuming that access to is_terminate is atomic.  I already know many materials state that volatile can not insure thread-safety generally.  But in the situation that only one atomic variable is shared, do we really need to protect the shared variable using a lock?

A: First, volatile is used for disabling compile optimization in c/c++. see this for understanding volatile.
The core of atomic is word align and size of is_terminate, if size of is_terminate is less than machine native size and aligned, then R and W of it is atomic.
In your context, with or without volatile, thread2 may read old value after thread1 modified it, but thread2 can read it eventually.
If eventually-read is OK for you, then your codes are thread safety.

A: it's safe because one thread is only reading and one is only writing.
The threads aren't really sharing that flag, one is reading, one is writing.  You can't have a race because the other thread will never write a bad result, and the reading thread will never read a bad result.  simple.

A: It is probably sort of thread-safe.
Thread safety tends to depend on context. Updating a bool is always thread safe, if you never read from it.
And if you do read from it, then the answer depends on when you read from it, and what that read signifies.
On some CPUs, but not all, writes to an object of type bool will be atomic. x86 CPUs will generally make it atomic, but others might not. If the update isn't atomic, then adding volatile won't help you.
But the next problem is reordering. The compiler (and CPU) will carry out reads/writes to volatile variables in the order specified, without any reordering. So that's good.
But it makes no guarantee about reordering one volatile memory access relative to all the non-volatile ones. So a common example is that you define some kind of flag to protect access to a resource, you make the flag volatile, and then the compiler moves the resource access up so it happens before you check the flag. It's allowed to do that, because it's not reordering the internal ordering of two volatile accesses, but merely a volatile and a non-volatile one.
Honestly, the question I'd ask is why not just do it properly?
It is possible that volatile will work in this situation, but why not save yourself the trouble, and make it clearer that it's correct? Slap a memory barrier around it instead.

A: It is not thread safe.
If the threads, for example, are run on CPUs with separate caches there are no language rules saying that the caches are to be synchronized when writing a volatile variable. The other thread may not see the change for a very long time, if ever.

To answer in another way:
If volatile is enough to be thread safe, why is C++0x adding an entire chapter with atomic operations?
http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n2047.html

A: No, it is not. It could be thread safe if the value access was atomic, but in C++ you can't assume that variables access is thread-safe unless you use some compiler-specific constructs or synchronization primitives.

A: It is still not safe. You should use synchronizaton to access is_terminate Access to the bool is not guaranteed to be an atomic operation.

A: I believe that this code is safe, until both the threads are not writing the bool (already you have mentioned that value access is atomic).

A: The big problem with assuming that the volatile keyword imposes any kind of thread safety, is that the C or C++ standards have no concept of threads in the abstract machine they describe.
The guarantees that the standard imposes on the volatile keyword, are only valid within a thread - not between multiple threads.
This leaves implementors with full liberty to do whatever they please when it comes to threads. If they chose to implement the volatile keyword to be safe across threads, then you're lucky. More often than not, that's not the case though.

A: This code isn't seems to be thread safe. Reason can be explained easily.
Problem lies in below code line
"is_terminate = true;"
Even if access to "is_terminate" is atomic, above statement is not atomic.
This statement includes more than 1 operations. Like load "is_terminate" and update "is_terminate".
Now gotcha is if is_terminate is loaded and not updated and thread switches to another one.
Now thread 2 expected result to be true but it won't get it.
Make sure "is_terminate = true;" is atomic. So lock it.
Hope it helps.

redpajama_set_name: RedPajamaStackExchange


text:
Q: React Native: Component occuping 100% width of his parent container Good morning everyone, I wanted to ask you about this problem I'm having with my React Native App. Basically it treats that my StatusComponent occupies 100% of the width of its container. I tried in many ways but I can't make its width independent. I share some images and part of my code so it is easier to understand.
In this case the width of the status component its okey because the name of the Event, is smaller than the width of the status component:
Link to Image
MatchComponent Code:
  <TouchableOpacity
      onPress={() => console.log('Test')})
      }>
      <LinearGradient
        start={{x: 0, y: 0}}
        end={{x: 1, y: 2}}
        colors={['#FE7062', '#FE8762']}
        style={styles.matchContainer}>
        <View style={styles.subContainer}>
          <View
            style={[
              styles.footballContainer,
              {
                backgroundColor: '#4D6FE2',
              },
            ]}>
            <Text
              style={[
                styles.footballText,
                {color: 'white'},
              ]}>
              F5
            </Text>
          </View>
          <View>
            <Text
              style={[
                styles.matchTitle,
                {color: 'white'},
              ]}>
              Partido 2
            </Text>
            <Text
              style={[
                styles.matchField,
                {color: 'white'},
              ]}>
              Cancha
            </Text>
            <StatusComponent
            />
          </View>
        </View>
        <View
          style={{
            alignItems: 'center',
            width: 110,
          }}>
            <Text style={styles.dateText}>27/08/22</Text>
          <View style={{flexDirection: 'row'}}>
            <Text
              style={[
                styles.dateText,
                {color: 'white'},
              ]}>
              10:00
            </Text>
          </View>
        </View>
      </LinearGradient>
    </TouchableOpacity>
  );
};

MatchComponent Style:
matchContainer: {
    position: 'relative',
    height: 95,
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    paddingHorizontal: 15,
    borderRadius: 20,
    marginBottom: 15,
  },
  subContainer: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  footballContainer: {
    backgroundColor: '#4D6FE2',
    height: 43,
    width: 43,
    justifyContent: 'center',
    alignItems: 'center',
    borderRadius: 10,
    marginRight: 15,
  },
  footballText: {
    color: 'white',
    fontFamily: 'OpenSans-SemiBold',
    fontSize: 18,
  },
  matchTitle: {
    fontFamily: 'OpenSans-Bold',
    color: 'white',
    fontSize: Platform.OS === 'ios' ? 19 : 18,
  },
  matchField: {
    fontFamily: 'OpenSans-Regular',
    color: 'white',
    fontSize: 14,
  },
  dateText: {
    fontFamily: 'Inter-Medium',
    fontSize: 14,
    color: 'white',
  },
  joinContainer: {
    backgroundColor: 'orange',
    height: 28,
    justifyContent: 'center',
    borderRadius: 30,
    paddingHorizontal: 5,
    marginBottom: 4,
  },
  joinText: {
    color: 'white',
    fontFamily: 'Inter-Bold',
    fontSize: Platform.OS === 'ios' ? 16 : 14,
  },

StatusComponent
    <View
      style={[
        styles.matchStatusContainer,
        {
          backgroundColor: 'red'
        },
      ]}>
        <Text
          style={[
            styles.matchStatusText,
            {
              color: 'white'
            },
          ]}>
          RESER
        </Text>
      )}
    </View>

StatusComponent Style
  matchStatusContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    paddingHorizontal: 8,
    marginVertical: 5,
    borderRadius: 30,
    height: 18,
  },
  matchStatusText: {
    fontFamily: 'Inter-Medium',
    fontSize: 12,
    marginLeft: 4,
  },


text:
Q: Find the minimal polynomial of $(x-1)^2(x-2)^3(x-3)$? Given ch. polynomial is $(x-1)^2(x-2)^3(x-3)$ and for the eigenvalue $1$, we have one eigenvector, for eigenvalue $2$ we have $2$ eigenvector and for $3$ we have $1$ eigenvector. Now determine the minimal polynomial?
I know that minimal polynomial divides the ch. polynomial, so I list the probable candidates as $$(x-1)(x-2)(x-3)$$ $$(x-1)(x-2)^2(x-3)$$ $$(x-1)^2(x-2)^2(x-3)$$ and $$(x-1)^2(x-2)(x-3).$$ But how to determine which one of these serves the purpose? There is no additional information given. Help me out

A: In fact there exist operators having your prescribed characteristic polynomial for each of the possible minimal polynomials provided:
Indeed,

*

*for $(x−1)(x−2)(x−3)$ we have the diagonal matrix diag$(1,1,2,2,2,3)$

*for $(x−1)^2(x−2)^2(x−3)$;
$$\left(\begin{smallmatrix}1 & 1& 0& 0&0 &0\\  0& 1& 0& 0&0 &0 \\ 0& 0& 2& 1 & 0 & 0 \\0 & 0 & 0& 2 & 0 & 0 \\ 0 & 0 & 0 & 0& 2 & 0 \\ 0 & 0 & 0 & 0 &0 &3 \end{smallmatrix}\right)$$
which is unique up to permutation of the Jordan blocks.

*for $(x−1)(x−2)^2(x−3)$;
$$\left(\begin{smallmatrix}1 & 0& 0& 0&0 &0\\  0& 1& 0& 0&0 &0 \\ 0& 0& 2& 1 & 0 & 0 \\0 & 0 & 0& 2 & 0 & 0 \\ 0 & 0 & 0 & 0& 2 & 0 \\ 0 & 0 & 0 & 0 &0 &3 \end{smallmatrix}\right)$$
again unique up to permutation of the Jordan blocks.
and finally

*

*for $(x−1)^2(x−2)^3(x−3)$;
$$\left(\begin{smallmatrix}1 & 1& 0& 0&0 &0\\  0& 1& 0& 0&0 &0 \\ 0& 0& 2& 1 & 0 & 0 \\0 & 0 & 0& 2 & 1 & 0 \\ 0 & 0 & 0 & 0& 2 & 0 \\ 0 & 0 & 0 & 0 &0 &3 \end{smallmatrix}\right)$$
up to permutation of the Jordan blocks.

Additionally, the combinatorial theory behind these ideas is very interesting. What you have specified in your problem (which is merely a characteristic polynomial) is

*

*the dimension of the vector space (a.k.a. the size of the matrix in question); this is the degree of the characteristic polynomial.

*the algebraic multiplicity of each of the eigenvalues occurring in its upper triangular form (i.e. exactly which values will appear on the diagonal of the Jordan form)

*The different possible minimal polynomials hold the geometric multiplicity of each of the eigenvalues which specify the size of the maximum Jordan block for each of the eigenvalues in question.


text:
Q: How retrieve in PHP the generated PRIMARY KEY from an AUTO_INCREMENT column for each row with an INSERT of multiple rows in MySQL? I have an INSERT with syntax for insert multiple rows:
INSERT INTO tbl_name (a,b,c) VALUES(1,2,3),(4,5,6),(7,8,9);
With MySQL function LAST_INSERT_ID() can retrieve the primary key of an generated AUTO_INCREMENT column, but how can I retrieve the primary key for row (1,2,3), (4,5,6) AND (7,8,9) inserted in one unique SQL INSERT instruction?
The programming language is PHP 5.4.13 and MySQL Server 5.6.10

A: There is no way to retrieve more than one generated auto-inc variable.  Calling LAST_INSERT_ID() returns you the first value generated by the last INSERT.
To get all the values, insert one row at a time, and call LAST_INSERT_ID() after each one.  This results in more overhead, but it's the only workaround.
This is especially an issue if you're doing INSERT...SELECT or LOAD DATA INFILE, generating many new id values in a batch.
See also MySQL LAST_INSERT_ID() used with multiple records INSERT statement

A: You can insert records in loop and when each record is inserted store the Auto increment id in array by call last_insert_id(). So you use the array of inserted id's where ever you need.


text:
Q: Covariance of Random Variables and limit of empirical expected value
Let $\{X_i\}$ be uncorrelated, identically distributed random variables with $\mathbb{E}[X_1]=0$ and $\mathbb{E}[X_1^2]=1.$ Given are
$$
  Y_k=\frac{1}{2} X_{k-1}+X_{k}, k\geq 0
  $$
and
$$
  S_n=Y_1+Y_2+...+Y_n, n\geq 1.
  $$
(a) Calculate $\operatorname{Cov}(Y_k, Y_{k+j})$ for $k\geq 0, j\geq 1$.
(b) Show that for all $\varepsilon>0$.
$$
  \mathbb{P}\left(\left|\frac{S_n}{n}\right|\geq \varepsilon\right)\stackrel{n\rightarrow\infty}{\rightarrow}0.
  $$

I got this far:
(a) We have
$$
  \begin{aligned}
 & \operatorname{Cov}(Y_k, Y_{k+j})=\mathbb{E}[Y_k Y_{k+j}]-\mathbb{E}[Y_k]\mathbb{E}[Y_{k+j}]\\
      &= \mathbb{E}\left[\left(\frac{1}{2} X_{k-1}+X_{k}\right)\left(\frac{1}{2} X_{k+j-1}+X_{k+j}\right)\right]-\mathbb{E}\left[\frac{1}{2} X_{k-1}+X_{k}\right]\mathbb{E}\left[\frac{1}{2} X_{k+j-1}+X_{k+j}\right]\\
      &=\mathbb{E}\left[\frac{1}{4}X_{k-1}X_{k+j-1}+\frac{1}{2}X_{k-1}X_{k+j}+\frac{1}{2} X_{k}X_{k+j-1}+X_{k}X_{k+j}\right]\\
      &-\left(\frac{1}{2}\mathbb{E}\left[ X_{k-1}\right]+\mathbb{E}\left[X_{k}\right]\right)\left(\frac{1}{2}\mathbb{E}\left[ X_{k+j-1}\right]+\mathbb{E}\left[X_{k+j}\right]\right)\\
  \end{aligned}
  $$
Because of the identical distribution, the expected values that are subtracted are equal to $0$, so that only
$$
  \frac{1}{4}\mathbb{E}\left[X_{k-1}X_{k+j-1}\right]+\frac{1}{2}\mathbb{E}\left[X_{k-1}X_{k+j}\right]+\frac{1}{2}\mathbb{E}\left[ X_{k}X_{k+j-1}\right]+\mathbb{E}\left[X_{k}X_{k+j}\right]
  $$
remain. How to continue from here?
(b)
With the Chebyshev inequality we get
$$
  \mathbb{P}\left(\left|\frac{S_n}{n}\right|\geq \varepsilon\right)\leq\frac{\operatorname{Var}\left(\frac{S_n}{n}\right)}{\varepsilon^2}=\frac{\operatorname{Var}\left(S_n\right)}{\varepsilon^2n^2}
  $$
Here I am also stuck. Hints would be great, thanks in advance.

A: You can see that the covariance depends on $j$, that is
$$Cov(Y_k,Y_{k+j})=\frac{1}{4}\mathbb{E}\left[X_{k-1}X_{k+j-1}\right]+\frac{1}{2}\mathbb{E}\left[X_{k-1}X_{k+j}\right]+\frac{1}{2}\mathbb{E}\left[ X_{k}X_{k+j-1}\right]+\mathbb{E}\left[X_{k}X_{k+j}\right]$$
Since the random variables $X_i$ are uncorrelated, we get the following cases :

*

*If $j=0$ :
$$Cov(Y_k,Y_{k})=\frac{1}{4}\mathbb{E}\left[X_{k-1}X_{k-1}\right]+\frac{1}{2}\mathbb{E}\left[X_{k-1}X_{k}\right]+\frac{1}{2}\mathbb{E}\left[ X_{k}X_{k-1}\right]+\mathbb{E}\left[X_{k}X_{k}\right]$$
$$=\frac{1}{4}\mathbb{E}\left[X_{k-1}^2\right]+\mathbb{E}\left[X_{k}^2\right]=\frac{1}{4}+1=\frac{5}{4}$$

*If $j=1$ :
$$Cov(Y_k,Y_{k+1})=\frac{1}{4}\mathbb{E}[X_{k-1}]\mathbb E[X_{k}]+\frac{1}{2}\mathbb{E}[X_{k-1}]\mathbb E[X_{k+1}]+\frac{1}{2}\mathbb{E}[X_{k}X_{k}]+\mathbb{E}[X_{k}]\mathbb E[X_{k+1}]$$
$$=\frac{1}{2}\mathbb E[X_k^2]=\frac{1}{2} $$

*If $j>1$ :
$$Cov(Y_k,Y_{k+j})=\frac{1}{4}\mathbb{E}[X_{k-1}]\mathbb E[X_{k+j-1}]+\frac{1}{2}\mathbb{E}[X_{k-1}]\mathbb E[X_{k+j}]+\frac{1}{2}\mathbb{E}[X_{k}]\mathbb E[X_{k+j-1}]+\mathbb{E}[X_{k}]\mathbb E[X_{k+j}]$$
$$=0$$
We finally get
$$Cov(Y_k,Y_{k+j})=\frac{5}{4}\delta_0(j)+\frac{1}{2}\delta_1(j)$$
On the other hand,
$$Var(Yi)=Cov(Y_i,Y_i)=\frac{5}{4}$$
Which yields
$$Var(S_n)=\sum_{i=0}^n Var(Y_i)=\frac{5n}{4}$$
Using your inequality now yields
$$\mathbb P\left(\left|\frac{S_n}{n}\right|>\varepsilon\right)\leq \frac{Var(S_n)}{n^2\varepsilon^2}=\frac{5}{4n\varepsilon^2}\overset{n\rightarrow \infty}{\longrightarrow} 0$$
Finally
$$\lim_{n\rightarrow \infty}\mathbb P\left(\left|\frac{S_n}{n}\right|>\varepsilon\right)=0$$


text:
Q: The difference between validity and entailment in first order logic I'm a newbie to logic so please forgive me if this is a basic question. I've searched the web and stack exchange but can't seem to find an answer.
The book I'm reading on predicate logic (forallx) says that although the argument '${\rm A}$ therefore ${\rm B}$' may be valid, this doesn't mean that ${\rm A}$ necessarily entails ${\rm B}$.
To me, validity and entailment both seem to have the same definition, namely that ${\rm A}$ entails ${\rm B}$ (or an argument is valid) if it is not possible for the premise to be true and the conclusion false.
Clearly my understanding of the above definition is wrong if entailment and validity are in fact different things, but I can't see the difference between them.
Can anyone enlighten me please? And are the definitions different in propositional logic versus predicate logic?
Many thanks
Max

A: *

*OP: "It's the example regarding foxes and vixens on p. 281 of
forallx.openlogicproject.org/forallxyyc.pdf "

The author is ostensibly cautioning about the relationship between
the validity of an argument and FOL-entailment (first-order-logic
entailment), yet their given example is making a different point,
which is that one must be careful to retain all pertinent information
when symbolising an argument (in the example, the original argument
contains an implicit/unstated premise "Every vixen is a fox" that
became lost in translation).

*As for what the author says the relationship between argument
validity and FOL-entailment is, from a quick keyword-search of the
book, I believe it is this: "In FOL, an argument is valid iff its
conclusion is a FOL-entailment of its premises."

A: Consider the following instance:
 (0 != 0) therefore (God exists)

Since 0 = 0 the premise is false, hence the implication is valid.  Does this prove God exists?
[note: If you happen to believe in God, change the above conclusion to 'God does not exist'.  The argument still works]


text:
Q: Group theory, character, representations, delta function, unit element I am reading a physics paper (hep-th/9204083 v1 above eq (4.15)) where there is a nice formula that reads
$$
\delta(U-\mathbb{1}) = \sum\limits_{r} \dim(r)\, \mathrm{tr}_r(U)
$$
Here $\:U\:$ is a group element, $\:1\:$ is the unit group element, $\:r\:$ are the representations.
I would like to know if this formula has a name (for example something like Weyl's formula), if I can get any intuitive argument why it should be true.
I am not sure the formula applies to $\:U(1)\:$ group. The simplest case maybe would be $\:SU(2)\:$ and already there this formula seems quite complicated. I would like to verify the formula for the simplest possible case.
Is this formula a generalized Fourier transform?

A: Yes it is. You are writing down the projection to the origin of the group through its character expansion, indeed a generalization of the Fourier transform, as you guessed.
A good book would cover it all, such as Vilenkin's classic, Ch I, §4. I'll use the physicist's informal seat- of-the-pants language and avoid mathematese, which probably got you stranded in the first place.
Your formula is the Fourier expansion for U(1), whose reps are all one dimensional, $e^{ir\theta}$, and the group-invariant Haar measure is trivial/flat, dθ ; so you get the δ(θ-0), having projected to the origin of the group.
The point is $\mathrm{tr}_r(U)\equiv \chi_r(U)$ is the character of the rep,
a class function, that is it is the same for the entire equivalent class containing U, by the similarity invariance of the trace.
The character of the identity, then, is just   $\chi_r(\mathbb{1}) = \dim(r)$, the dimension of the rep.  From the orthogonality of the characters outlined in the linked WP article, you then see you may represent U as a direct sum of this U in every rep, with its character in that rep as a coefficient, so, then, just like the Fourier expansion.
So you are writing the completeness relation of your group with the origin of the group as the destination.
Note however, in what you write, that the right hand side is a class function, so the sloppy l.h.s. must be interpreted as acting on class functions and dialing their angles to the origin, e.g.  $\int dU \delta(U-\mathbb{1}) \chi_s (U)=  \dim(s) $.
For SU(2), the simplest case, this is not that recondite. There is only one equivalence class--recall a similarity transformation can represent any group element as a rotation $R_3$ around some Euler axis arrived at by this similarity transformation: so you are just looking at $e^{i\theta J_3}$. The characters then are just Chebyshev polynomials of the second kind, a Dirichlet kernel,
$$
\chi_s(\theta)=\frac{\sin ((2s+1)\theta/2)}{\sin (\theta/2)},
$$
the obvious sum of the 2s +1 exponentials in the trace of $R_3$. The Haar measure is
$$
\int_0^{4\pi} d\theta \frac{\sin^2 (\theta/2)}{2\pi}.
$$
You are then summing
$$
(n+1)\frac{e^{i(n+1)\theta/2} - e^{-i(n+1)\theta/2}}{e^{i\theta/2} - e^{-i\theta/2}}
$$
over all positive integers n=2s+1. (Cheap and dirty evaluations may end up yielding 0/0. My favorite formal wisecrack might be defining $S(\theta)\equiv \sum_{n=1}^{\infty}e^{in\theta/2}$, evaluating $\partial_\theta (S(\theta)+S(-\theta))$, whence $-\partial_\theta \delta(\theta/2)/\sin(\theta/2)$, given the Fourier kernel of the periodic δ, the
Dirac comb,
but no need to take it too seriously!). Large ns will net you periodic δs, as per the Dirichlet kernel WP article, but the point is the smaller n terms conspire to interfere destructively.
Still, technicalities aside, the projection is bound to work out. Check out that
$$
\int_0^{4\pi} d\theta \frac{\sin^2 (\theta/2)}{2\pi} \frac{(-\partial_\theta \delta(\theta/2))}{2\sin(\theta/2)} ~  \chi_7 (\theta)= 15,
$$
after the integration by parts.
 You may find practical examples of this technique in our paper here.

Note added in mathematese, since the OP appears interested in the structure of characters providing a complete orthonormal set for class functions. Fulton and Harris, p 440, summarize the Peter-Weyl theorem, which generalizes Fourier analysis to compact groups: "The characters of irreducible representations span a dense subspace of the space of continuous class functions." So the character completeness relation  projects the equivalence class of U  to the identity, an equivalence class of its own.
Here is a link to the stuff in Vilenkin & Klimyk 1991, not as good as the 68 classic, in my parochial view...
Finally, the WP section on D matrices' orthogonality illustrates completeness and the identity limit for SU(2), reviewed by Schwinger in eqn (3.96) of his monumental 1952 review.

A: Combining Zachos formula
$$\int dU \delta(U-1) \chi_r(U) = \chi_r(1) = dim(r)$$
with
$$\delta(U-1) = \sum_s dim(s) \chi_s(U)$$
leads me to
$$\sum_s dim(s) \int dU \chi_s(U)\chi_r(U) = dim(r)$$
In other words, we should have
$$\int dU \chi_s(U) \chi_r(U) = \delta_{r,s}$$
This might be easier to prove than the original formula.


text:
Q: Select/filter JSON by date_time value starts with I am trying to create a new JSON object containing the two items in this source JSON, where the 'date_time' value starts with '2015-09-21'. This should return items 160 and 161 (excluding 162). Here is the JSON:
{
   "data":[
      {
         "item":{
            "number":"160",
            "name":"Project example phase 2",
            "estimated_duration":{
               "duration_minutes":0.0
            },
            "remaining_duration":{
               "duration_minutes":0.0
            },
            "customer":{
               "company_name":null,
               "id":null
            },
            "reported_by_customer_contact":{
               "name":"",
               "id":null
            },
            "item_type":"features",
            "id":160
         },
         "user":{
            "name":"Joe Bloggs",
            "id":31
         },
         "work_log_type":{
            "name":"Architecture",
            "id":1
         },
         "work_done":{
            "duration_minutes":120.0,
            "time_unit":{
               "abbreviation":"min",
               "name":"Minutes",
               "id":1
            },
            "text":"120 min",
            "duration":120.0
         },
         "id":263,
         "description":"Testing",
         "date_time":"2015-09-21T13:48:00Z"
      },
      {
         "item":{
            "number":"161",
            "name":"Project abc",
            "estimated_duration":{
               "duration_minutes":0.0
            },
            "remaining_duration":{
               "duration_minutes":0.0
            },
            "customer":{
               "company_name":"Universal Exports",
               "id":2
            },
            "reported_by_customer_contact":{
               "name":"Mark Zuckerstein",
               "id":3
            },
            "item_type":"incidents",
            "id":1
         },
         "user":{
            "name":"Joe Bloggs",
            "id":31
         },
         "work_log_type":{
            "name":"Analysis",
            "id":2
         },
         "work_done":{
            "duration_minutes":300.0,
            "time_unit":{
               "abbreviation":"hrs",
               "name":"Hours",
               "id":2
            },
            "text":"5 hrs",
            "duration":5.0
         },
         "id":248,
         "description":"Stupid coffee cup",
         "date_time":"2015-09-21T11:28:00Z"
      },
      {
         "item":{
            "number":"162",
            "name":"I broke my cup holder",
            "estimated_duration":{
               "duration_minutes":0.0
            },
            "remaining_duration":{
               "duration_minutes":0.0
            },
            "customer":{
               "company_name":"Universal Exports",
               "id":2
            },
            "reported_by_customer_contact":{
               "name":"Mark Zuckerstein",
               "id":3
            },
            "item_type":"incidents",
            "id":1
         },
         "user":{
            "name":"Joe Bloggs",
            "id":31
         },
         "work_log_type":{
            "name":"Architecture",
            "id":1
         },
         "work_done":{
            "duration_minutes":10.0,
            "time_unit":{
               "abbreviation":"min",
               "name":"Minutes",
               "id":1
            },
            "text":"10 min",
            "duration":10.0
         },
         "id":249,
         "description":"Trying to fix his cup holder",
         "date_time":"2015-09-22T11:33:00Z"
      }
   ],
   "metadata":{
      "total_count":3,
   }
}

I started to play with lodash but quickly got out of my depth after filtering for the actual time and trying to combine the 'filter' with other lodash functions.
var filtered = _.filter(object.data, { date_time: "2015-09-21T13:48:00Z"});

Any help would be much appreciated.

A: There is no need to use lodash. You can use the Array.prototype.filter method. Array.prototype.filter method for filtering the array and String.prototype.indexOf method for checking the index of that specific string.
yourVariable.data.filter(function(el) {
    return el.date_time.indexOf('2015-09-21') === 0;
});

A: var final = [];
var by = "2015-09-21";

_.map(data.data, function(o){
    if (o.date_time.match(by + ".*")) {
        final.push(o);
     }
});

console.log(final);


text:
Q: Amazon Dynamo DB - Issue in creating table in local database I am using local Amazon Dynamo DB and trying to create a table as;
Id | StartPoint1 | EndPoint 1 | StartPoint2 | EndPoint2 | Speed | Distance
I tried using CreateTable() function but finding it difficult to create one.
I am making use of .Net API.
Can anyone please help me out in getting this.
Sample code I tried was;
var response = client.CreateTable(new CreateTableRequest
      {
        TableName = tableName,
        AttributeDefinitions = new List<AttributeDefinition>()
        {
          new AttributeDefinition
          {
            AttributeName = "Id",
            AttributeType = "S"
          },
          new AttributeDefinition
          {
            AttributeName = "ReplyDateTime",
            AttributeType = "S"
          }
        },
        KeySchema = new List<KeySchemaElement>()
        {
          new KeySchemaElement()
          {
            AttributeName = "Id",
            KeyType = "HASH"
          },
          new KeySchemaElement()
          {
            AttributeName = "ReplyDateTime",
            KeyType = "RANGE"
          }
        },
        ProvisionedThroughput = new ProvisionedThroughput
        {
          ReadCapacityUnits = 10,
          WriteCapacityUnits = 5
        }
      });

For 2 columns it is working fine. For more than 2 columns, how to achieve this ?
Thanks and Regards,
Vijay

A: The only attributes that you define when you create the table are the hash and (optionally) the range.  This is not a relational database where each row necessarily has the same attributes.

A: I haven't used from C#, but seen that some APIs fail on local because you are accessing a new feature and using an older package of Dynamo DB. (One example is GSI, which is just couple of months old).
This page always hosts the latest: http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Tools.DynamoDBLocal.html
(Earlier there was a place on the doc page, which by mistake kept hosting an older one)


text:
Q: SELinux vs. AppArmor vs. grsecurity I have to set up a server that should be as secure as possible. Which security enhancement would you use and why, SELinux, AppArmor or grsecurity? Can you give me some tips, hints, pros/cons for those three?
AFAIK:

*

*SELinux: most powerful but most complex

*AppArmor: simpler configuration / management than SELinux

*grsecurity: simple configuration due to auto training, more features than just access control

A: I have done a lot of research in this area.  I have even exploited AppArmor's rulesets for MySQL.   AppArmor is the weakest form of processes separation.   The property that I'm exploiting is that all processes have write privileges to some of the same directories such as /tmp/.  What nice about AppArmor is that it breaks some exploits without getting in the user/administrators way.  However AppArmor has some fundamental flaws that aren't going to be fixed any time soon.
SELinux is very secure,  its also very annoying.  Unlike AppAmoror most legitimate applications will not run until SELinux has been reconfigured.  Most often this results in the administrator misconfiguration SELinux or disabling it all together.
grsecurity is a very large package of tools. The one i like the most is grsecuirty's enhanced chroot.   This is even more secure then SELinux,  although it takes some skill and some time to setup a chroot jail where as SELinux and AppAprmor "just work".
There is a 4th system,  a Virtual Machine.   Vulnerabilities have been found in VM environments that can allow an attacker to "break out".  However  a VM has a even greater separation than a chroot becuase in a VM you are sharing less resources between processes.  The resources available to a VM are virtual,  and can have little or no overlap between other VMs.  This also relates to <buzzword> "cloud computing" </buzzword>.  In a cloud environment you could have a very clean separation between your database and web application,  which is important for security.  It also maybe possible that 1 exploit could own the entire cloud and all VM's running on it.

A: Personally, I would use SELinux because I would end up targeting some flavor of RHEL which has this set up out of the box for the most part.  There is also a responsive set of maintainers at Red Hat and a lot of very good documentation out there about configuring SELinux.  Useful links below.

*

*Fedora 12 SELinux User Guide

*RHEL 5 SELinux Documentation


text:
Q: What is the inverse of $f(x) = \dfrac{x}{x^2 - 1}$ I need to find a continuous inverse of $$f(x) = \dfrac{x}{x^2 - 1}$$
Let $y = f(x) = \dfrac{x}{x^2 - 1} \Rightarrow y(x^2-1) = x \Rightarrow yx^2-x = y$
How should I proceed from here?

A: A plot of the function looks like this
To be invertible, a function of x and y must pass the horizontal line test. That is, any horizontal line cannot pass through more than one point of the graph.
This function fails the horizontal line test. But if you break the graph up into the blue and red branches shown (where we consider the two red branches to really be just one branch) each branch does pass the horizontal line test.
We haven't done any math yet, but we should expect that, when we solve for x in terms of y, we will get two answers. So let's do the math
\begin{align}
   y &= \dfrac{x}{x^2 - 1}\\
  y x^2 - y &= x\\
  y x^2 - x - y &= 0\\
  x &= \dfrac{1 \pm \sqrt{1 + 4y^2}}{2y}
\end{align}
A plot of $ \color{red}{x = \dfrac{1 + \sqrt{1 + 4y^2}}{2y}}$ and
$ \color{blue}{x = \dfrac{1 - \sqrt{1 + 4y^2}}{2y}}$ is shown below.

and the correspondences with the brances of the original function should be obvious.
There are a few things that still bother me.
First note that $ \color{blue}{x = \dfrac{1 - \sqrt{1 + 4y^2}}{2y}}$ passes through the origin even though it is undefined when $y = 0$. We also see that x is bound between plus and minus one but it is hard to see that by looking at the equation. For these reasons, I think we should write this particular equation in a different, more useful, form.
\begin{align}
  x
  &= \dfrac{1 - \sqrt{1 + 4y^2}}{2y}\\
  &= \dfrac{1 - \sqrt{1 + 4y^2}}{2y}
     \cdot
     \dfrac{1 + \sqrt{1 + 4y^2}}{1 + \sqrt{1 + 4y^2}}\\
  &= \dfrac{1 - (1 + 4y^2)}{2y(1 + \sqrt{1 + 4y^2})}\\
  &= \dfrac{-4y^2}{2y(1 + \sqrt{1 + 4y^2})}\\
  x &= \dfrac{-2y}{1 + \sqrt{1 + 4y^2}}
\end{align}
Now it's fairly clear that $x = 0$ when $y = 0$ and, as $y$ approaches minus and plus infinity, $x$ approaches plus and minus one.

A: Let $f(x) = y = \frac{x}{x^{2} - 1}.$ To find the inverse of $f(x),$ we switch $x$ and $y$ in the equation and solve for $y.$ This yields $x = \frac{y}{y^{2} - 1},$ which we can rearrange to get $xy^{2} - y - x = 0.$ This is a quadratic with respect to $y.$ Using the quadratic equation, we get that $y = \boxed{f(x) = \frac{1 \pm \sqrt{1 + 4x^{2}}}{2x}}.$


text:
Q: Add JQuery MultiSelect to existing MultiSelect object I am trying to detect changes on a JQuery MultiSelect to trigger an update in another place. The normal javascript on change stuff does not work because the select does not change. I found a method called  "beforeclose" that is called from the close function of the MultiSelect. I think I can use that. I found that if I add it when making the MultiSelect it works as expected and logs the message when closing the select. See bellow:
$j("#selectId").multiselect({
    checkAllText: 'Select all',
    uncheckAllText: 'Deselect all',
    beforeclose : function() {
        console.log("before close")
    }
}).multiselectfilter();

But I can not do this because the MultiSelect is created some other place, so I need to just add that method to it. I tried lots of different things like:
$j("#selectId").multiselect().data("ech-multiselect").beforeclose = function() {
    console.log("before close")
};

But nothing seems to work. Any ideas? Thanks

A: Can you create a codepen or jsfiddle to replicate the issue you're having? I'm sure I or someone else could assist with a working model.
I think your syntax is a little off if you want to use beforeclose. If it were a dialog, you'd use
$( ".selector" ).dialog({
  beforeClose: function( event, ui ) {}
});
// and bind an event listener
$( ".selector" ).on( "dialogbeforeclose", function( event, ui ) {} );

Alternatively, you could use jQuery's on function. On change would look like:
$(document).on('change', '#selectId', function() {
  // Fires every time selectId is changed
});

https://api.jquery.com/on/#example-7 a custom event handler could work for you.


text:
Q: Unable to view WebSocket frame in Chrome DevTools This issue has been plaguing me for about a week now. On the latest Chrome version, I'm unable to open a WebSocket request via DevTools to see individual frames. This is happening on all websites.

I have no filter added anywhere I can see, so the invalid regex issue that I'm seeing in the Devtools' devtools window is a mystery.
I'm on Chrome Version 106.0.5249.103 (Official Build) (arm64), on OSX, and haven't seen this problem before.


text:
Q: $ \sum_{p } \sum_{k=2}^{\infty} \frac{\log p}{p^k}$ is Convergent How can I show the sum $ \sum_{p } \sum_{k=2}^{\infty} \frac{\log p}{p^k}$ where $p$ varies over all the primes, is Convergent?
I tried comparing with the convergent series $\sum_{p} \frac{1}{p^2}$, but it doesn't seem to work.
Any help would be appreciated. Thanks in advance.


text:
Q: how to extend WPF GridRow Contents into next row without expanding the current row I'm new to WPF and I'm trying to build a dropdown menu using the expander.  Page layout is being handled with a Grid.
The extender sits inside the first row of the grid and I would I would like the contents of the expander to expand over top of the contents of everything below when it's clicked.  Unfortunately, right now, the entire row is expanded to accommodate the height of the expanded control.
I tried playing around with the ZIndex of the Expander but it doesn't seem to have any effect.  No matter what, the row always expands forcing everything else on the page to move.
<Expander FontSize="18" Name="moduleSelect" Width="100" Header=" Goto -> "
          Background="#000033" MouseEnter="moduleSelect_MouseEnter"
          MouseLeave="moduleSelect_MouseLeave" Foreground="White"
          Grid.Column="0" Grid.ColumnSpan="3" Grid.Row="1" HorizontalAlignment="Left">
    <StackPanel>
        <Button Name="btnTasks" Width="100" Foreground="White"
                Background="#000033">Tasks</Button>
        <Button Name="btnNotes" Width="100" Foreground="White"
                Background="#000033">Notes</Button>
    </StackPanel>
</Expander>

How can I make this expand 'above' the subsequent rows without distorting the grid?

A: What would happen if you set the Grid.RowSpan of the Expander to 2 (or how ever many rows you'd like it to span when expanded)?
So, for a two-row grid, you'd have something like this:
<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="30" /> <!--set this to the height of the expander's header area-->
        <RowDefinition Height="Auto" />
    </Grid.RowDefinitions>
    <WhateverGoesInRow2 Grid.Row="1" />
    <Expander FontSize="18" Name="moduleSelect" Width="100" Header=" Goto -> "
        Background="#000033" MouseEnter="moduleSelect_MouseEnter"
        MouseLeave="moduleSelect_MouseLeave" Foreground="White"
        Grid.Column="0" Grid.ColumnSpan="3" HorizontalAlignment="Left"
        Grid.Row=0 Grid.RowSpan="2">
        <StackPanel>
            <Button Name="btnTasks" Width="100" Foreground="White" Background="#000033">Tasks</Button>
            <Button Name="btnNotes" Width="100" Foreground="White" Background="#000033">Notes</Button>
        </StackPanel>
    </Expander>
</Grid>

You may need to adjust your RowDefinition section for your particular situation, but if I'm understanding your problem correctly, I think this will work.

A: You want something that pops up over the grid, not expands within the grid.  A ComboBox, say, or - this being a menu, after all - a ContextMenu.
You could also build some combination of a ToggleButton and a Popup, but that's essentially the same thing as a ComboBox with IsEditable turned off.

A: The built-in drop-down control makes use of a Popup control in its default control template to do a similar thing.


text:
Q: How to run selenium scripts on jenkins server situated in different country? I have created selenium scripts on my local machine using Selenium + Maven + TestNG  and now i want to run the selenium scripts on Jenkins server which is situated in different country where selenium jars are not present. How i can achieve this? Any Solution would be appreciated.

A: This is what you need to do.

*

*Need to install Jenkins slave on that machine. (I think you will need Java Client)

*Make sure that machine also have JDK and Maven.

*Bind you Jenkins job to run on that particular slave.

*in you job, apart from taking the checkout of latest code you just need to run following command
mvn clean test


text:
Q: How to get all containers using Dockerode and Javascript I'm trying to display on a Meteor app all running containers and all stopped containers that I have in Docker. For the moment I can only display the running containers when I stop one he's deleted from the DB automatically.
There is my code where I get the containers (and where I need a little bit help to got the stopped containers too):
    infosContainers.initContainers': function() {
    /* create Docker object */
    docker = new Docker({socketPath: '/var/run/docker.sock'});
    /* create 2 var that are my containers running in docker */
    meteorCtn = docker.getContainer('vialfeedmaclecturearticle_app_1');
    mongoCtn = docker.getContainer('vialfeedmaclecturearticle_mongo_1');
    /* I don't really understand but it's on the Dockerode page */
    meteorCtn.defaultOptions.start.Binds = ["/tmp:/tmp:rw"];
    mongoCtn.defaultOptions.start.Binds = ["/tmp:/tmp:rw"];

    /* Add the id in the collection */
    docker.listContainers(Meteor.bindEnvironment(function (err, containers) {
      containers.forEach(function (containerInfo) {
        InfosContainers.insert({
          idContainer: containerInfo.Id,
          nameContainer: containerInfo.Names[0],
          stateContainer: containerInfo.State
        });
      });
    }));
  },

Someone has already done that ? Thank you for the help

A: As always when you ask you find... so there is the solution
   docker.listContainers({all: true}, function(err, containers) {
   console.log('ALL: ' + containers.length);
   });


text:
Q: data load in extjs panel from button ajax responce i am new to extjs 4 and i am struck at when i am click button then ajax request get data from url and that ajax responce data will load in panel
below code is buttion code
                                        xtype: 'button',
                                        flex:1,
                                        height: 30,
                                        text : 'GEography',
                                          handler:function() {
                                                    Ext.Ajax.request({
                                                    url: 'charts/states.php',
                                                    method: 'GET',
                                                    scripts:true,
                                                    success: function (response) {
                                                        Ext.get('ajaxpanel').dom.innerHTML = response.responseText;
                                                        }
                                                                        });
                                                }
                                    },{

and below code is panel code
  var ajaxForm = Ext.create('Ext.form.Panel', {
        title: 'ajaxpanel',
        id:'ajaxpanel',
        frame: true,
        bodyPadding: 5,

        fieldDefaults: {
            labelAlign: 'left',
            msgTarget: 'side'
        },

        layout: {
            type: 'vbox',
            align: 'stretch'
        },

        items: []
        });

so please help me in above problem
main aim is that's url dat load in ajaxpanel

A: below answer for above question
for ajax loading
                                             listeners: {
                                                click: function(){

                                                        Ext.get('ajaxpanel').load({url:'ur url here',scripts:true});

                                                        }
                                                }


text:
Q: OleDbDataReader does not read last record I see 5 records to be inserted, but only 4 are inserted. The last record is not inserted, and I can not figure out why. Copying from one database to the other. First is an access database, the second is a sql server database.
OleDbCommand cmd2 = new OleDbCommand();
OleDbDataReader oledbReader2;
using (cmd2 = new OleDbCommand())
{
    query = "SELECT ID, STRAATNAAM, 'NL' AS TAALCODE, PKANCODE, CITY FROM Temp_Unique_Streetnames WHERE TRIM(Temp_Unique_Streetnames.STRAATNAAM) <> '' AND ID > " + lastId.ToString() + " ORDER BY ID";
    WriteToFile(query);
    cmd2.CommandText = query;
    cmd2.CommandType = CommandType.Text;
    cmd2.Connection = cn2;

    using (oledbReader2 = cmd2.ExecuteReader())
    {
        while (oledbReader2.Read())
        {
            try
            {
                counter += 1;

                query = "insert into tblgeo_street ( autoid, street_id, language, country, city, streetname, zip) values (" + counter.ToString() +
                    " , " + oledbReader2.GetValue(0).ToString() +
                    " , 'NL', 23, " + oledbReader2.GetValue(4).ToString() +
                    " , '" + oledbReader2.GetValue(1).ToString().Replace('\'', '´') + "'" +
                    " , " +  oledbReader2.GetValue(3).ToString() +  ") ";
                OleDbCommand cmd3 = new OleDbCommand(query, cn3);

                WriteToFile(query);

                cmd3.ExecuteNonQuery();
            }
            catch (Exception errorException)
            {
                actionSucceedded = false;
                //eventLog1.WriteEntry("Open db threw exception " + errorException.Message);
                WriteToFile("insert tblgeo_street threw exception " + errorException.Message);
            }

        }
    }
}


text:
Q: AJAX causing a page to become unresponsive I have the following code running in a game kind of thing on my website.
function checkGameState(n) {
    $.ajax({
        url: "gamestate.php?c="+player_correct+"&i="+player_incorrect+"&id="+n,
        context: document.body
    }).done(function( data ) {
        checkGameState(n)
        if (getCookie("gid")!=false) {
            obj = jQuery.parseJSON(data);
            player = getCookie('player');
            if (player=='1') {
                if ((opponent_correct<=parseFloat(obj.player2c)) && (opponent_incorrect<=parseFloat(obj.player2i))) {
                    opponent_correct = parseFloat(obj.player2c);
                    opponent_incorrect = parseFloat(obj.player2i);
                }
            } else {
                if ((opponent_correct<=parseFloat(obj.player1c)) && (opponent_incorrect<=parseFloat(obj.player1i))) {
                    opponent_correct = parseFloat(obj.player1c);
                    opponent_incorrect = parseFloat(obj.player1i);
                }
            }
            renderBars();
        }
    });
}

The function checkGameState is called when the game starts and as you can see recursively calls after that.  There is also a single player version of this game which obviously doesn't use this code.  The problem is that seemingly randomly chrome becomes unresponsive while playing the multiplayer version of this game.  The only thing that is different is the above AJAX code.
Does anyone know how to stop this error from occurring?
UPDATE renderBars() as requested
function renderBars() {
    //players calculations
    c = player_correct;
    i = player_incorrect;
    s = player_startTime;
    $correct = $(".score-correct");
    $incorrect = $(".score-incorrect");
    t=c+i;
    t=(t==0)?1:t;
    x=5;
    h=0
    if (get_cookie("high"+getLevel())) {
        h=parseFloat(get_cookie("high"+getLevel()));
        $(".levitate .row h5").last().text(h);
        h+=i;
        h=Math.round(h/2);
    }
    while (x<t || x<h) {
        x+=5;
    }
    $(".levitate .row h5").first().text((c*2)-i);
    //players high score bar calculations
    if (h || h==0) {
        if (h<=x) {
            if (c<h) {
                $(".score-high").css("opacity","1").css("height",(Math.round((h/x)*100*0.9))+"%");
                $(".score-high b").html(""+h+"")
            } else {
                $(".score-high").css("opacity","0");
            }
        }
    }
    //opponent calculations
    var ox=0;
    if (typeof opponent_correct !== 'undefined') {
        c = opponent_correct;
        i = opponent_incorrect;
        s = player_startTime;
        $ocorrect = $(".score-correct").last();
        $oincorrect = $(".score-incorrect").last();
        t=c+i;
        t=(t==0)?1:t;
        ox=5;
        while (x<t) {
            ox+=5;
        }
    }
    //determine which scale to use
    if (x<=ox) {
        x=ox;
    }
    //change heights of the score bars
    $incorrect.css("height",((Math.round((player_incorrect/(x))*100))*0.9)+"%");
    $correct.css("height",((Math.round((player_correct/(x))*100))*0.9)+"%");
    if (($correct.parent().height()*(((Math.round((player_correct/(x))*100))*0.9)/100))>25) {
        $correct.html(""+player_correct+"")
    } else {
        $correct.html(""+player_correct+"")
    }
    if (($incorrect.parent().height()*(((Math.round((player_incorrect/(x))*100))*0.9)/100))>25) {
        $incorrect.html(""+player_incorrect+"")
    } else {
        $incorrect.html(""+player_incorrect+"")
    }
    if (typeof opponent_correct !== 'undefined') {
        $oincorrect.css("height",((Math.round((opponent_incorrect/(x))*100))*0.9)+"%");
        $ocorrect.css("height",((Math.round((opponent_correct/(x))*100))*0.9)+"%");
        if (($ocorrect.parent().height()*(((Math.round((opponent_correct/(x))*100))*0.9)/100))>25) {
            $ocorrect.html(""+opponent_correct+"")
        } else {
            $ocorrect.html(""+opponent_correct+"")
        }
        if (($oincorrect.parent().height()*(((Math.round((opponent_incorrect/(x))*100))*0.9)/100))>25) {
            $oincorrect.html(""+opponent_incorrect+"")
        } else {
            $oincorrect.html(""+opponent_incorrect+"")
        }
    }
}


text:
Q: a Reactify Error :Unexpected identifier

var React = require('react');
var EventListItem = require('./EventListItem.js');

var EventList = React.createClass({
 var events = this.props.events;
 if (!Array.isArray(events)) throw new Error ('it must be Array');
 var eventsComps = events.map(function(eve){
  return (<EventListItem key={eve.key}
  title={eve.title}
  description={eve.description}
  voteCount={eve.voteCount} />)
 });

 render:function(){
  return(

    {eventsComps}

  );
 }
});

module.exports = EventList;

Line 5: Unexpected identifier
I search the problem and checked my ","or ";"but I don't find the problem,what's  wrong with it?

A: You cannot write any random statements inside an object literal. All you code need to be inside you render function or you must define a different function and write this code inside it.
var React = require('react');
var EventListItem = require('./EventListItem.js');

var EventList = React.createClass({

    render:function(){
            var {events} = this.props;
        if (!Array.isArray(events)) throw new Error ('it must be Array');
           var eventsComps = events.map(function(eve){
           return (<EventListItem key={eve.key}
           title={eve.title}
           description={eve.description}
           voteCount={eve.voteCount} />)
        });
        return(

                {eventsComps}

        );
    }
});

module.exports = EventList;


text:
Q: Google JS Coding Conventions - "The var keyword must not be used" I am having troubles understanding this paragraph:

Declare all local variables with either const or let.
  Use const by default, unless a variable needs to be reassigned.
  The var keyword must not be used

Could someone please explain what this means? Why shouldn't I use the 'var' keyword?

A: Those conventions are assuming ES2015 and above, which have let and const, which can be used to replace var. They're saying don't use var anymore, because the let and const semantics are more useful (according to those conventions [and my own personal opinion, not that that matters]).
So for example, they're saying don't do this:
function foo() {
    for (var i = 0; i < 10; ++i) {
        // Do something with i
    }
}

instead, either do this:
function foo() {
    let i;
    for (i = 0; i < 10; ++i) {
        // Do something with i
    }
}

or this (but note that performance will be slightly slower with this last version, not that it usually matters1):
function foo() {
    for (let i = 0; i < 10; ++i) {
        // Do something with i
    }
}

Similarly, if you're using a variable whose value will never change, use const:
function getTomorrow() {
    const date = new Date();
    date.setDate(date.getDate() + 1);
    return date;
}

We can use const there because the value of date never changes (just the state of the object it refers to).
If you're anything like me, when you put these into practice (I don't follow those conventions, but I do follow this specific example of using let and const), if you're using other good practices (like keeping functions small, etc.), you'll be surprised at just how often you use const rather than let because you end up with a lot of "variables" whose values you never want to change.

1 You may be wondering why there's a performance difference between
function foo() {
    let i;
    for (i = 0; i < 10; ++i) {
        // Do something with i
    }
}

and
function foo() {
    for (let i = 0; i < 10; ++i) {
        // Do something with i
    }
}

The reason is that in the second one, a new i variable is created for every loop iteration. We can see that if we create a closure inside the loop:

function foo1() {
    console.log("let outside the loop:");
    let i;
    for (i = 0; i < 5; ++i) {
        setTimeout(() => {
            console.log(i);
        }, 0);
    }
}
function foo2() {
    console.log("let inside the loop:");
    for (let i = 0; i < 5; ++i) {
        setTimeout(() => {
            console.log(i);
        }, 0);
    }
}

foo1();
setTimeout(foo2, 50);
.as-console-wrapper {
  max-height: 100% !important;
}

Again, the performance difference almost never matters (and will get smaller as engines get better at optimizing it out when they can), and lots of times you want the behavior of the second form (which is why it's defined that way). But it's there.


text:
Q: Google GClientGeocoder geocoder function - how to pass extra parm(s)? I am using Google GClientGeocoder geocoder function.
Method getLocations seems to be a a Google asynchronous callback function.
I would like to update the record identified with "id" with points found in GLatLng,
However I can't figure out how to add id as a parameter to my getGeoCode function.
   function fnGetEncoding(address,id)
   {
  // Create new geocoding object
  geocoder = new GClientGeocoder();

  // Retrieve location information, pass it to getGeoCode()
  geocoder.getLocations(address, getGeoCode);
   }

   function getGeoCode(response)
   {
  // Retrieve the object
  place = response.Placemark[0];

  // Retrieve the latitude and longitude
  point = new GLatLng(place.Point.coordinates[1],
        place.Point.coordinates[0]);

  $('#id_listing').append(response.name + point + '
');

  // I would like to update the record identified with "id" with points found GLatLng

  // fnWriteGeocodesToFile(response.name, id , point)

    }

A: I think, it's quite simple:
function fnGetEncoding(address,id)
{
  // Create new geocoding object
  geocoder = new GClientGeocoder();

  // Retrieve location information, pass it to getGeoCode()

  geocoder.getLocations(address,
  **function(response,id){**
   getGeoCode(response,id);
  **}**
}

function getGeoCode(response,id)
{
  // Retrieve the object
  place = response.Placemark[0];

  // Retrieve the latitude and longitude
  point = new GLatLng(place.Point.coordinates[1],
    place.Point.coordinates[0]);

  $('#id_listing').append(response.name + point + '
');

  // I would like to update the record identified with "id" with points found GLatLng

  // fnWriteGeocodesToFile(response.name, id , point)

}


text:
Q: Render view with data in Node JS [NO FRAMEWORK] I have an end point called /watch that get data and should return page with filled data. This app is not express just a http server
and the template ejs view
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>Test</title>

Data

        <% arr.forEach(function(elem) { %>

<%= elem %>

        <% }); %>

Is there any equivalent in node js
res.render('index', {
        arr: data,
    });

This is a snippet from the server code
const server = http.createServer((req,res)=>{

const parsedUrl = url.parse(req.url,true);

const path = parsedUrl.pathname;
const trimmedPath = path.replace(/^\/+|\/+$/g,'')

if(trimmedPath == "watch"){

    var data = await GetData();

            // here where i need to stuck sending the ejs template with data

}

})

A: You just need to send the String that ejs.render() creates.  Consider the barebones example that EJS shows: EJS#Get Started and combine that with the barebones HTTP server that node provides an example for:
const http = require("http");
const ejs = require("ejs");

const template = "
<%= people.join(',');%>
";
const people = ["bob", "sue", "steve"];

const server = http.createServer((req, res) => {
    res.end(ejs.render(template, {people}));
});

server.listen(8081, () => {
    console.log("Listening on 8081");
});

The network response I get back is:
*   Trying ::1...
* TCP_NODELAY set
* Connected to localhost (::1) port 8081 (#0)
> GET / HTTP/1.1
> Host: localhost:8081
> User-Agent: curl/7.54.0
> Accept: */*
>
< HTTP/1.1 200 OK
< Date: Mon, 27 Aug 2018 17:10:01 GMT
< Connection: keep-alive
< Content-Length: 24
<
* Connection #0 to host localhost left intact

bob,sue,steve


text:
Q: Server endpoint calling address and redirecting address returning different ip address I have two servers with different domain.
Server 2: Ip address is 200.200.200.200 (twohundred.com)
Server 1: Ip address is 100.100.100.100 (onehundred.com)
I am making a rest API request from server2 to server1. In server1 I have a java endpoint called /validate. From this endpoint, I make a request to /verify endpoint hosted in the same server.
@RequestMapping(value = "/validate", method = { RequestMethod.POST })
public String validateAndRedirect(HttpServletRequest request,
    HttpServletResponse response) throws JSONException, IOException {
    Url url = "https://onehundred.com/verify?queryParam=123";
    HttpURLConnection con = (HttpURLConnection) url.openConnection();
    con.setRequestMethod("POST");
    con.setDoOutput(true);

    response.sendRedirect("https://onehundred.com/successful/message");
}

If a request is sent from the browser to /verify endpoint and from their, if I redirect to /validate, Is it possible to redirect from server address.

A: It happen because sendRedirect will send redirection code to the client and client will make another http call to the server.
So if you want actual server IP than you have to make HTTP call from server 1 it self.
To Solve this problem just do the same thing for https://onehundred.com/successful which you have done for https://onehundred.com/verify?queryParam=123 API and parse the response of success API and display it in the current API(/validate).
Here in this case request made by server 1 it will not send redirection request to the client.
Sorry for English


text:
Q: Excel Macro To import CSV data fails with TextFileParseType I am trying to load CSV data from URL to my MS Excel sheet with this code:
Sub LoadCSVData()
    Dim sSheetName As String
    sSheetName = "Sheet1"

    ActiveWorkbook.Sheets(sSheetName).UsedRange.ClearContents

    With ActiveWorkbook.Sheets(sSheetName).QueryTables.Add(Connection:= _
        "URL;https://sampledomain.com/mydata.csv" _
        , Destination:=Sheets(sSheetName).Range("$A$1"))
        .TextFileParseType = xlDelimited
        .TextFileCommaDelimiter = True
        .AdjustColumnWidth = True
        .RefreshPeriod = 0
        .Refresh BackgroundQuery:=False
    End With

End Sub

It throws the

error: 1004 Application-defined or object defined error

on the lines with TextFileParseType and TextFileCommaDelimiter.
When i comment them out, the macro works, but all is loaded into A1 cell and it is not parsed.
Any idea how to fix it?

A: This is a nearly duplicate of Excel QueryTables.Add from URL Comma Delimited
Change "URL" to "TEXT"
Here's my quick rework of your code:
Sub LoadCSVData()
    Dim sSheetName As String
    sSheetName = "Sheet1"
    Dim myTable As QueryTable
    ActiveWorkbook.Sheets(sSheetName).UsedRange.ClearContents

Set myTable = ActiveWorkbook.Sheets(sSheetName).QueryTables.Add(Connection:= _
        "TEXT;http://samplecsvs.s3.amazonaws.com/Sacramentorealestatetransactions.csv" _
        , Destination:=Sheets(sSheetName).Range("$A$1"))

    With myTable
        .TextFileCommaDelimiter = True
        .TextFileParseType = xlDelimited
        .AdjustColumnWidth = True
        .RefreshPeriod = 0
        .Refresh BackgroundQuery:=False
    End With

End Sub


text:
Q: Trying to create a scrolling background effect with imageViews in javafx Im trying to create a scrolling background effect with two imageViews where one picture is on top of another picture and out of the window; then i try to scroll both down the window to create a scrolling effect by changing their y coordinates. I made a loop to do so and put a thread.sleep so it wouldnt do it too quickly. Then i reset the picutres positions and do the loop again. However, when i try to run the program, the window will never open. Taking out the loop obviously properly shows the window with the picutre.
public class TestBackground extends Application{

@Override
public void start(Stage stage) throws Exception {

    stage.setTitle("DRIFT STAGE");

    Pane game = new Pane();
    Scene gameScene = new Scene(game, 956, 740);
    ImageView background = new ImageView(getClass().getResource("bg.png").toExternalForm());
    game.getChildren().add(background);

    ImageView background2 = new ImageView(getClass().getResource("bg.png").toExternalForm());
    game.getChildren().add(background2);
    background2.setY(-740);

    //loop to scroll background vertically
    for (int j = 0; j < 20; j++) {
        for (double i = 1.0; i < 741.0; i++) {
            background.setY(background.getY() + i);
            background2.setY(background2.getY() + i);

            try {
                Thread.sleep(250);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        background.setY(0.0);
        background2.setY(-740.0);
    }

    stage.setScene(gameScene);
    stage.show();

    }
    public static void main(String[] args) { launch(args); }
}

A: Your loop is not the right thing to do.  Use a Transition Animation on each ImageView.  You want a TranslateTransition.
Something like this:
    // Animation to scroll background vertically
    TranslateTransition trans1 = new TranslateTransition(Duration.minutes(1), background);
    trans1.setFromY(0);
    trans1.setToY(740);
    trans1.setCycleCount(20);
    TranslateTransition trans2 = new TranslateTransition(Duration.minutes(1), background2);
    trans2.setFromY(-740);
    trans2.setToY(0);
    trans2.setCycleCount(20);
    ParallelTransition parTrans = new ParallelTransition(trans1, trans2);
    parTrans.play();

If your intention is to have these images as a parallax background that scrolls "forever", set the transitions to cycle indefinitely
    trans1.setCycleCount(Animation.INDEFINITE);

and use slightly different durations for each.
If you are using the same image, don't load it twice:
    Image bgImg = new Image(getClass().getResource("bg.png").toExternalForm());
    ImageView background = new ImageView(bgImg);
    game.getChildren().add(background);

    ImageView background2 = new ImageView(bgImg);
    game.getChildren().add(background2);

Here's the whole start method with an added speed slider, just for fun:
@Override
public void start(Stage stage) {

    stage.setTitle("DRIFT STAGE");

    Pane game = new Pane();
    Scene gameScene = new Scene(game, 956, 740);
    Image bgImg = new Image(getClass().getResource("bg.png").toExternalForm());
    ImageView background = new ImageView(bgImg);
    ImageView background2 = new ImageView(bgImg);
    Slider speedSlider = new Slider(0, 5, 1);
    game.getChildren().addAll(background, background2, speedSlider);

    // Animation to scroll background vertically
    TranslateTransition trans1 = new TranslateTransition(Duration.seconds(10), background);
    trans1.setFromY(0);
    trans1.setToY(740);
    trans1.setInterpolator(Interpolator.LINEAR);
    trans1.setCycleCount(Animation.INDEFINITE);
    TranslateTransition trans2 = new TranslateTransition(Duration.seconds(10), background2);
    trans2.setFromY(-740);
    trans2.setToY(0);
    trans2.setCycleCount(Animation.INDEFINITE);
    trans2.setInterpolator(Interpolator.LINEAR);
    ParallelTransition parTrans = new ParallelTransition(trans1, trans2);
    parTrans.rateProperty().bind(speedSlider.valueProperty());
    parTrans.play();

    stage.setScene(gameScene);
    stage.show();
}


text:
Q: How can I set up multihoming? I am running Mac OS X Server 10.6 on my iMac and I am wondering how to multihome a Mac. I know it's possible to accomplish this by using both Wi-fi and Ethernet, but I just want to use Ethernet. Any idea how to set this up? Thanks.

A: Got it. All you have to do is add multiple Ethernet interfaces in Network Preferences. And then just configure each one to the correct settings and you're set to go. I tested this by hosting two different websites on two different IPs by multihoming my iMac and it worked!

*

*System Prefs -> Network dialog

*Press the + button and select the interface you want to add to (you may need to go back  and identify which one if you have multiple Ethernet ports).

*Name the service and press "Create"

*Configure the new service as you would a static (manual) interface

*Click "Apply"


text:
Q: Earth tilt openGL c++ I'm working on the solar system and I'm trying to get the planet Earth to rotate properly around the Sun. I can get it to orbit and rotate on its axis, but I can't get it to be tilted in the right angle, as seen in the picture below:

I can tilt my planet, but it loos like this when it goes around (it doesn't "face" the same direction)

 Any ideas what I could do? Here is my code:
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
//sun
glMaterialAmbientAndDiffuse(GLMaterialEnums::FRONT,GLColor<GLfloat,4>(1.5f,1.0f,0.0f));
glTranslate(0.0f, 0.0f, 0.0f);
glRotate(0.0, 0.0, 0.0, 00.0);
drawEllipsoid(10.0, 1.0, 4, 4);

//Earth
glRotate(orbit, 0.0, 0.0, 1.0);
glTranslate(30.0, 0.0, 0.0);
glPushMatrix();
glMaterialAmbientAndDiffuse(GLMaterialEnums::FRONT,GLColor<GLfloat,4>(0.5f,10.5f,10.5f));
glRotatef(110,0.0,23.0,110.0f);
glRotatef(orbit2, 0.0f, 0.0f,1.0f);
drawPlanetGrid(5, 1, 4, 4, 1);

glRotate(30.0, 0.0,0.0,0.0);
glTranslate(orbit2, 0.0, 0.0);
glPopMatrix();
orbit += .2;

if (orbit > 360)
{
orbit = 0;
}
orbit2 += 6.5;
if (orbit2 > 360)
{
orbit2 = 0;
}

Sorry the code is not commented. I am just experimenting with it.

A: The relationship between the Sun and the Earth is not hierarchical as it is in the case of an arm and an elbow. They are independent objects. Therefore, instead of using nested matrices, you should compute the position of the Earth manually. You can do this using simple trigonometry:
earth_x = 30.0 * cos(orbit / 180.0 * PI)
earth_y = 30.0 * sin(orbit / 180.0 * PI)

After translating to this point, you can tilt the Earth using glRotate() in the same way you did before but this time the transformation won't be affected by the Earth's position.
In the end, your code should look like this:
drawTheSun();

glPushMatrix();  // enter the Earth's frame of reference
glTranslate(earth_x, earth_y, 0.0);
glRotate(110,0.0,23.0,110.0f);  // tilt however you wanna tilt
drawTheEarth();
glPopMatrix();  // exit the Earth's frame of reference

A: I know this is an ancient question, but I had the same question and this was the first result.  I believe it can be done with 'nested' matrices as the OP was trying to do.
For Earth, or any planet for that matter:
glRotatef(inclination, 0.0, 1.0, 0.0);
glRotatef(orbit,       0.0, 0.0, 1.0);
glTranslatef(            R, 0.0, 0.0);
glRotatef(-orbit,      0.0, 0.0, 1.0);
glRotatef(Tilt,        1.0, 0.0, 0.0);
glRotatef(orbit2,      0.0, 0.0, 1.0);
drawPlanet();

I used this code (with a different orientation of the coordinate system) to make a program that plots (or prints) the positions of the planets and stars. It roughly (good enough for animations) matches the output from the NASA Horizons system (NASA Horizons web interface, as well as matching other 'live' solar system diagrams on the net- Solar System calculator, In-the-Sky.


text:
Q: ValueError: Input 0 of layer conv2d is incompatible with the layer: : expected min_ndim=4, found ndim=3. Full shape received: (256, 256, 256) So I am working on a project Brain Tumor Detection using CNN. I have a model that takes 4 parameters as an input (BATCH_SIZE, IMAGE_SIZE, IMAGE_SIZE, CHANNELS) to make predictions. My model works fine with most of the images but with some images, it gives error as
ValueError: Input 0 of layer conv2d is incompatible with the layer: : expected min_ndim=4, found ndim=3. Full shape received: (256, 256, 256)
I have done image resizing(256,256) and reshaping(1,256,256,3) and still, I get the error. I have looked for an answer on google but couldn't find any reasonable answer. What could be the problem? I would appreciate any help. Screenshots of my model and the error are attached for reference.
Thanks!!
# Model
input_shape = (BATCH_SIZE, IMAGE_SIZE, IMAGE_SIZE, CHANNELS)
n_classes = 2

model = models.Sequential([
    resize_and_rescale,

    layers.Conv2D(32, kernel_size = (3,3), activation='relu', input_shape=input_shape),
    layers.MaxPooling2D((2, 2)),

    layers.Conv2D(64,  kernel_size = (3,3), activation='relu'),
    layers.MaxPooling2D((2, 2)),

    layers.Conv2D(64,  kernel_size = (3,3), activation='relu'),
    layers.MaxPooling2D((2, 2)),

    layers.Conv2D(64, (3, 3), activation='relu'),
    layers.MaxPooling2D((2, 2)),

    layers.Conv2D(64, (3, 3), activation='relu'),
    layers.MaxPooling2D((2, 2)),

    layers.Conv2D(64, (3, 3), activation='relu'),
    layers.MaxPooling2D((2, 2)),

    layers.Flatten(),

    layers.Dense(64, activation='relu'),
    layers.Dense(n_classes, activation='softmax'),
])

model.build(input_shape=input_shape)

# Function used in flask for deploying
def prediction():
    img = request.files['img']
    img.save("img.jpg")
    image = Image.open("img.jpg")
    x = np.array(image.resize((256,256)))
    # x = x.reshape(1,256,256,3)
    x = np.expand_dims(x,axis=0)
    res = (model.predict_on_batch(x))
    classification = np.where(res == np.amax(res))[1][0]
    # a=names(classification)
    a=str(res[0][classification]*100) + '% Confidence ' + names(classification)

    return render_template("prediction.html", data=a)

A: You should change input_shape = (BATCH_SIZE, IMAGE_SIZE, IMAGE_SIZE, CHANNELS) to input_shape = (IMAGE_SIZE, IMAGE_SIZE, CHANNELS), as the batch size parameter is automatically inferred.


text:
Q: how to clear off gridview? I'm creating a dynamic gridview function which will bind different tables from DB into a datatable and then assign the datatable to the gridview! This is how it works, i have a dropdownlist, gridview and a button, the button will fire specific function based on the dropdownlist selection and then gridview will bind the data, my problem is that, when u press the button for the 1st time, the gridview will bind the data from DB, for second time pressing, the gridview will duplicate the data from the data of 1st time pressing! how do i clear off the gridview to avoid data duplication?
Private Sub Login()
    sSql = "" & _
    "SELECT TYPE, SUBTYPE, LOGTS, ACTION, USERID, STAT1 " & _
    "FROM i_LOG " & _
    "WHERE TYPE = 'USR' AND SUBTYPE = 'LOG' " & _
    "AND CONVERT(VARCHAR(20), LOGTS, 103) >= '" & txtDTFrom.Text & _
    "' AND CONVERT(VARCHAR(20), LOGTS, 103) <= '" & txtDTTo.Text & "'"

    DT = CreateDataTable(sSql)     'Retrieve from database.

    Session(sSesDT) = DT
    GVM.DataTable = DT
    GVM.GVAddEmptyRow()

    Dim seq As New BoundField
    Dim Type As New BoundField
    Dim SubType As New BoundField
    Dim Logts As New BoundField
    Dim action As New BoundField
    Dim user As New BoundField
    Dim status As New BoundField

    seq.HeaderText = GVM.DTNumberField
    seq.DataField = GVM.DTNumberField

    Type.HeaderText = "Type"
    Type.DataField = "TYPE"

    SubType.HeaderText = "Subtype"
    SubType.DataField = "SUBTYPE"

    Logts.HeaderText = "Date and Time"
    Logts.DataField = "LOGTS"

    action.HeaderText = "Action"
    action.DataField = "ACTION"

    user.HeaderText = "User ID"
    user.DataField = "USERID"

    status.HeaderText = "Status"
    status.DataField = "STAT1"

    gv.AutoGenerateColumns = False
    gv.Columns.Add(Type)
    gv.Columns.Add(SubType)
    gv.Columns.Add(Logts)
    gv.Columns.Add(action)
    gv.Columns.Add(user)
    gv.Columns.Add(seq)
    gv.Columns.Add(status)

    gv.DataSource = Session(sSesDT)
    gv.DataBind()
End Sub

Private Overloads Function CreateDataTable(ByVal sSql As String) As DataTable
    Dim DA As New OleDb.OleDbDataAdapter
    Dim dtDataTbl As New DataTable
    Dim dcDataCol As New DataColumn

    With DBMgr
        .openCnn()
        .SQL = sSql
        .openRst()
        DA.Fill(dtDataTbl, .rst)
    End With

    '==Adding Columns==
    dcDataCol = New DataColumn  'No
    With dcDataCol
        .DataType = GetType(Int32)
        .ColumnName = GVM.DTNumberField
        .AutoIncrement = True
        '.AllowDBNull = True
    End With
    dtDataTbl.Columns.Add(dcDataCol)
    '**Adding Columns**

    Return dtDataTbl
End Function

A: Sorry, this is in C#, but just call it before you bind any new data and it'll clear any existing data... unless of course the problem is that the DataSource you are assigning has the duplicated data.
gridview.DataSource=null;
gridview.DataBind();

Also, just to note, you are adding every column in every time that procedure is called? You need to run:
gridview.Columns.Clear();

A: You can reset it's data source and rebind it for example
gv.datasource=""
gv.databind()

and then reuse it

A: Usually this does not happen when you rebind grid like:
grid.DataSource = 'NEW_DATA_SOURCE'
grid.DataBind

I think may be the problem is in your function fetching data:
 CreateDataTable(sSql)

Please check inside this if you are fetching data every time into a new DataTable or using same one (may be declared at global scope or passed from your class to data accessing component). I'd lost whole night once to fix this :(

A: Place your gridview in a table with an id:

<asp:GridView Width="765px" ID="mygrid" runat="server">
...
...
</asp:GridView>

Then call from a button click your javascript function:
function clearGridview()
{
var rows = document.getElementById('myTable').getElementsByTagName('tbody')  [0].getElementsByTagName('tr').length;
if(rows!=0)
    document.getElementById("myTable").deleteRow(0);
}


text:
Q: Automatically play next track in playlist I was following along in a tutorial of how to create a media player for some tracks...
Everything works as I wanted except that each song plays and then stops... I would like for the whole playlist to play...
that is for the next track to start automatically after the previous one has finished...
I have read that I should be using an event listener in combination with the 'ended()' method... although I have tried with no success. Any help with this would be greatly appreciated...
Here's my code...
HTML:

    <title>HTML5 Audio Player</title>
    <link rel="stylesheet" href="css/style.css">

                 -

            <input id="volume" type="range" min="0" max="10" value="4">

                    <button id="prev"></button>
                    <button id="play"></button>
                    <button id="pause"></button>
                    <button id="stop"></button>
                    <button id="next"></button>

                0:00

advert-1.mp3

advert-2.mp3

advert-3.mp3

advert-4.mp3

audiobook-part-1.mp3

audiobook-part-2.mp3

telephon-1.mp3

CSS:
*{
    margin:0;
    padding:0;
    border:none;
    outline:none;
}

body{
    font-family:Arial;
    font-size:13px;
    line-height:1.5em;
    color:#fff;

    background:#78284a; /* old browsers */
    background:-moz-linear-gradient(left, #78284a 0%, #6d8a9f 100%); /* FF3.6+ */
    background:-webkit-gradient(linear, left top, right top, color-stop(0%,#78284a), color-stop(100%,#6d8a9f));
    background:-webkit-linear-gradient(left, #78284a 0%, #6d8a9f 100%); /* Chrome10+, Safari5.1+ */
    background:-o-linear-gradient(left, #78284a 0%, #6d8a9f 100%); /* Opera 11.10+ */
    background:-ms-linear-gradient(left, #78284a 0%, #6d8a9f 100%); /* IE10+ */
    background:linear-gradient(to right, #78284a 0%, #6d8a9f 100%); /* W3C */
}

.clearfix{
    clear:both;
}

#container{
    width:330px;
    min-height:400px;
    background:#333;
    overflow:auto;
    margin:20px auto;
    border-radius:10px;
    box-shadow:0 10px 8px -8px #333;
}

#audio-image{
    position:relative;
    overflow:hidden;
    height:200px;
    margin-bottom:15px;
}

#audio-image .cover{
    width:100%;
}

#audio-info{
    text-align:center;
    margin-bottom: 7px; // added by self;
}

#audio-info .artist{
    font-weight:bold;
}

input#volume{
    width:95%;
    margin-left:2%;
/*    -webkit-appearance:none !important;   browser vol sytles overridden in vid*/
    background:#ccc;
    height:1px;
    margin-bottom:20px;
}

input#volume::-webkit-slider-thumb{
/*
    -webkit-appearance:none !important; browser volume styles overriden in vid
    background:url(../images/knob.png) no-repeat;   knob png required
*/
    height:12px;
    width:12px;
}

#buttons{
    width:90%;
    display:block;
    margin:15px auto;
    margin-left:23px;
    overflow:auto;
}

button#play{
    width:50px;     /*vid values set to 70px*/
    height:50px;    /*vid values set to 70px*/
    background:url(../images/circled-play.png);
    background-size:cover;      /*look for background short-hand*/
    background-repeat:no-repeat;
    background-position:center center;
    float:left;
    margin-left:-2px;
}

button#pause{
    width:50px;     /*vid values set to 70px*/
    height:50px;    /*vid values set to 70px*/
    background:url(../images/circled-pause.png);
    background-size:cover;      /*look for background short-hand*/
    background-repeat:no-repeat;
    background-position:center center;
    float:left;
    margin-left:-2px;
}

button#stop{
    width:50px;     /*vid values set to 70px*/
    height:50px;    /*vid values set to 70px*/
    background:url(../images/stop-circled.png);
    background-size:cover;      /*look for background short-hand*/
    background-repeat:no-repeat;
    background-position:center center;
    float:left;
    margin-left:3px;
}

button#prev{
    width:50px;     /*vid values set to 70px*/
    height:50px;    /*vid values set to 70px*/
    background:url(../images/rewind-button-round.png);
    background-size:cover;      /*look for background short-hand*/
    background-repeat:no-repeat;
    background-position:center center;
    float:left;
    margin-top:0; /*vid set to 15px*/
}

button#next{
    width:50px;     /*vid values set to 70px*/
    height:50px;    /*vid values set to 70px*/
    background:url(../images/fast-forward-round.png);
    background-size:cover;      /*look for background short-hand*/
    background-repeat:no-repeat;
    background-position:center center;
    float:left;     /*vid value set 'right'*/
    margin-left:0px;    /*vid value set 15px*/
}

#tracker{
    position:relative;
    width:100%;
}

#progress-bar{
    width:80%;
    margin-left:2%;    /*vid set to 2% */
    margin-bottom:20px;
    margin-top:9px;
    height:10px;
    background:url(../images/progress-bar.png) no-repeat;
    float:left;
}

#progress{
    background:url(../images/ ) no-repeat;  /* remember to update this selector (watch chap45 @ 08:36) */
    height:10px;
    display:inline-block;
}

#duration{
    position:absolute;
    top:0;
    right:10px;
    padding: 4px 8px;
    background:#000;
    border-radius:5px;
}

#playlist{
    list-style:none;
}

#playlist li{
    cursor:pointer;
    margin:5px;
}

#playlist li.active{
    font-weight:bold;
    padding:3px;
    background:#666;
}

Javascript [main.js]
var audio;

//Hide Pause
$('#pause').hide();

initAudio($('#playlist li:first-child'));

function initAudio(element){
    var song = element.attr('song');
    var title = element.text();
    var cover = element.attr('cover');
    var artist = element.attr('artist');

    //Create audio object
    audio = new Audio('media/'+ song);

    //Insert audio info
    $('.artist').text(artist);
    $('.title').text(title);

    //Insert song cover
    $('img.cover').attr('src','images/covers/'+cover);

    $('#playlist li').removeClass('active');
    element.addClass('active');
}

//Play button
$('#play').click(function(){
    audio.play();
    $('#play').hide();
    $('#pause').show();
    showDuration();
});

//Pause button
$('#pause').click(function(){
    audio.pause();
    $('#play').show();
    $('#pause').hide();
});

//Stop button
$('#stop').click(function(){
    audio.pause();
    audio.currentTime = 0;
});

//Next button
$('#next').click(function(){
    audio.pause();
    var next = $('#playlist li.active').next();
    if(next.length == 0){
        next = $('playlist li:first-child');
    }
    initAudio(next);
    audio.play();
    showDuration();
});

//Prev button
$('#prev').click(function(){
    audio.pause();
    var prev = $('#playlist li.active').prev();
    if(prev.length == 0){
        prev = $('playlist li:last-child');
    }
    initAudio(prev);
    audio.play();
    showDuration();
});

//Playlist song click
$('#playlist li').click(function(){
    audio.pause();
    initAudio($(this));
    $('#play').hide();
    $('#pause').show();
    audio.play();
    showDuration();
});

//Volume control
$('#volume').change(function(){
    audio.volume = parseFloat(this.value / 10);
});

//Time/Duration
function showDuration() {
    $(audio).bind('timeupdate',function(){
        //Get hours and minutes
        var s = parseInt(audio.currentTime % 60);
        var m = parseInt(audio.currentTime / 60) % 60;

        if(s < 10) {
            s = '0'+s;
        }
        $('#duration').html(m + ':'+ s);
        var value = 0;
        if(audio.currentTime > 0){
            value = Math.floor((100 / audio.duration) * audio.currentTime);
        }
        $('progress').css('width',value+'%');
    });
}

All of the media and images are working fine... I'm happy with what I have so far. It's just the aforementioned issue of the tracklist not playing sequentially from beginning to end.
Many thanks...

A: You can use AddEventListener with ended event
 audio.addEventListener('ended',function(){
   var next = $('#playlist li.active').next();
   if(next.length == 0){
      next = $('playlist li:first-child');
   }
   initAudio(next);
   audio.play();
   showDuration();
});

You could put that in initAudio function


text:
Q: java.sql.SQLException: This function is not supported using HSQL and Spring Can someone please tell me why am I geting java.sql.SQLException: This function is not supported using HSQL and Spring?  I am trying to insert a new row into my database..
Below is my DAO and I get the error on the mySession.save(message) line:
@Transactional
@Repository
public class MessageDaoImpl implements MessageDao
{

    private Log log = null;
    @Autowired
    private SessionFactory sessionFactory;

    public MessageDaoImpl()
    {
        super();
        log = LogFactory.getLog(MessageDaoImpl.class);

    }

    @SuppressWarnings("unchecked")
    @Transactional(readOnly = true, propagation = Propagation.REQUIRED)
    public List<Message> listMessages()
    {
        try
        {
            return (List<Message>) sessionFactory.getCurrentSession()
                    .createCriteria(Message.class).list();

        } catch (Exception e)
        {
            log.fatal(e.getMessage());
            return null;
        }
    }

    @SuppressWarnings("unchecked")
    @Transactional(readOnly = false, propagation = Propagation.REQUIRED)
    public void SaveOrUpdateMessage(Message message)
    {
        try
        {
            Session mySession = sessionFactory.getCurrentSession();
            mySession.save(message);
            mySession.flush();
        } catch (Exception e)
        {
            log.fatal(e.getMessage());
        }
    }

}

Here is my main class:
public static void main(String[] args)
    {
        ApplicationContext context = new AnnotationConfigApplicationContext(HelloWorldConfig.class);

        MessageService mService  = context.getBean(MessageService.class);

        HelloWorld helloWorld = context.getBean(HelloWorld.class);

        /**
         * Date:   4/26/13 / 9:26 AM
         * Comments:
         *
         *    I added Log4J to the example.
         */

        LOGGER.debug("Message from HelloWorld Bean: " + helloWorld.getMessage());

        Message message = new Message();
        message.setMessage(helloWorld.getMessage());
        //
        mService.SaveMessage(message);

        helloWorld.setMessage("I am in Staten Island, New York");

        LOGGER.debug("Message from HelloWorld Bean: " + helloWorld.getMessage());
    }
}

Here is my DatabaseConfig:
public class DatabaseConfig
{

    private static final Logger LOGGER = getLogger(DatabaseConfig.class);

    @Autowired
    Environment env;

    @Bean
    public DataSource dataSource() {

        EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder();
        EmbeddedDatabase db = builder.setType(EmbeddedDatabaseType.HSQL).
        addScript("schema.sql").build();

        return db;
    }

    @Bean
    public DataSource hsqlDataSource()  {

        BasicDataSource ds = new BasicDataSource();

        try {
            ds.setDriverClassName("org.hsqldb.jdbcDriver");
            ds.setUsername("sa");
            ds.setPassword("");
            ds.setUrl("jdbc:hsqldb:mem:mydb");
        }
        catch (Exception e)
        {
            LOGGER.error(e.getMessage());
        }
        return ds;

    }

    @Bean
    public SessionFactory sessionFactory()
    {

        LocalSessionFactoryBean factoryBean = new LocalSessionFactoryBean();
        factoryBean.setDataSource(hsqlDataSource());
        factoryBean.setHibernateProperties(getHibernateProperties());
        factoryBean.setPackagesToScan(new String[]{"com.xxxxx.HelloSpringJavaBasedJavaConfig.model"});

        try
        {
            factoryBean.afterPropertiesSet();
        } catch (IOException e)
        {
            LOGGER.error(e.getMessage());
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }

        return factoryBean.getObject();
    }

    @Bean
    public Properties getHibernateProperties()
    {
        Properties hibernateProperties = new Properties();

        hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect"));
        hibernateProperties.setProperty("hibernate.show_sql", env.getProperty("hibernate.show_sql"));
        hibernateProperties.setProperty("hibernate.use_sql_comments", env.getProperty("hibernate.use_sql_comments"));
        hibernateProperties.setProperty("hibernate.format_sql", env.getProperty("hibernate.format_sql"));
        hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto"));

        hibernateProperties.setProperty("hibernate.generate_statistics", env.getProperty("hibernate.generate_statistics"));

        hibernateProperties.setProperty("javax.persistence.validation.mode", env.getProperty("javax.persistence.validation.mode"));

        //Audit History flags
        hibernateProperties.setProperty("org.hibernate.envers.store_data_at_delete", env.getProperty("org.hibernate.envers.store_data_at_delete"));
        hibernateProperties.setProperty("org.hibernate.envers.global_with_modified_flag", env.getProperty("org.hibernate.envers.global_with_modified_flag"));

        return hibernateProperties;
    }

    @Bean
    public HibernateTransactionManager hibernateTransactionManager()
    {
        HibernateTransactionManager htm = new HibernateTransactionManager();
        htm.setSessionFactory(sessionFactory());
        htm.afterPropertiesSet();
        return htm;
    }

}

and here is what I am getting to the console:
Exception in thread "main" org.hibernate.AssertionFailure: null id in com.xxx.HelloSpringJavaBasedJavaConfig.model.Message entry (don't flush the Session after an exception occurs)

Here is my message model bean:
@Entity
@Table(name = "messages")
public class Message
{

    @Id
    @Column(name = "id")
    @GeneratedValue(strategy = GenerationType.AUTO)
    private String id;

    @Column(name = "message")
    private String message;

    public String getId()
    {
        return id;
    }

    public void setId(String id)
    {
        this.id = id;
    }

    public String getMessage()
    {
        return message;
    }

    public void setMessage(String message)
    {
        this.message = message;
    }

    @Override
    public String toString()
    {
        return "Message{" +
                "id='" + id + '\'' +
                ", message='" + message + '\'' +
                '}';
    }
}

A: This relates to the version of hsql being used probably the version causing issue was 1.8 with hibernate 4. Need to use 2.2.9 instead

A: You can't use a String with @GenerateValue with the Strategy GenerationType.AUTO since it uses sequence generator and those can't be used with non-numerical values.  You have to set it yourself. Use an Integer or Long if you want it to be generated for you.
Hibernate docs
Or use an id generator that uses string values
@Id
@GeneratedValue(generator="system-uuid")
@GenericGenerator(name="system-uuid", strategy = "uuid")

A: it was a version issues. I updated the versions and now everything works

A: I had the same issue after I upgraded hibernate to version 4.2.8 .Looking in the logs, I noticed that the sql query generated by hibernate tried to insert a record with a null primary key. The field was annotated just with: @Id @GeneratedValue
Upgrading hsqldb to version 2.2.9 made this disappear just like Denis said and I am very thankful to him for the reply.

A: It seems very likely that this issue is related to attempting to use a Session which has already signaled an error.  As Sotirios mentioned, it is a bad idea to catch exceptions in your DAO, and if you do, it is critical that you re-throw them.
Normally, once you catch a Hibernate exception, you must roll back your transaction and close the session as the session state may no longer be valid (Hibernate core documentation).

If the Session throws an exception, including any SQLException, immediately rollback the database transaction, call Session.close() and discard the Session instance. Certain methods of Session will not leave the session in a consistent state. No exception thrown by Hibernate can be treated as recoverable. Ensure that the Session will be closed by calling close() in a finally block.

Since you're using Spring, most of that doesn't apply to you, but the exception message you are seeing indicates that the actual cause of your problem probably was related to catching an exception and then continuing to use the same session.


text:
Q: How to change the Fill color of an SVG path via CSS I know that we can change the fill color of an SVG path using CSS if/when the raw SVG is added to the HTML page.
However, I don't know if it is possible to change the fill color if the SVG is referenced within an <img> tag. - Is it possible? If so, how?
Example: This fill example doesn't work because I am referencing the svg within an img tag.
<html>
    ...
    <style>
        #foo{
           fill: #ccc;
        }
    </style>
    <body>
        <img id="foo" src="myicon.svg" />
    </body>
</html>

A: You can't impact via CSS  on SVG Image that is source is in another file.
yo can impact only in the file itself or to put the SVG inline in the HTML and than the styles will wokrs.
SVG Inline Example:
<!DOCTYPE html>
<html>
<body>
<style>
  #foo{
    fill: #ccc;
  }
</style>

<svg id="foo" width="300" height="200">
  <polygon points="100,10 40,180 190,60 10,60 160,180"
  style="fill:lime;stroke:purple;stroke-width:5;fill-rule:evenodd;" />
</svg>

</body>
</html>


text:
Q: Deno and oak error: TS2315 [ERROR]: Type 'Conn' is not generic - with Deno using oak as server on macOs with basic example code I am trying out Deno with oak and I am running into the same error everytime - even when I try the default example. My working environment is macOs Big Sur. Does anybody know how to fix this issue?
$ deno run --allow-net server.ts
Check file:///.../server.ts
error: TS2315 [ERROR]: Type 'Conn' is not generic.
export function isConn(value: unknown): value is Deno.Conn<Deno.NetAddr> {
                                                 ~~~~~~~~~~~~~~~~~~~~~~~
    at https://deno.land/x/oak@v7.2.0/util.ts:66:50

TS2315 [ERROR]: Type 'Conn' is not generic.
  #conn?: Deno.Conn<Deno.NetAddr>;
          ~~~~~~~~~~~~~~~~~~~~~~~
    at https://deno.land/x/oak@v7.2.0/http_server_native.ts:41:11

TS2315 [ERROR]: Type 'Conn' is not generic.
  constructor(requestEvent: RequestEvent, conn?: Deno.Conn<Deno.NetAddr>) {
                                                 ~~~~~~~~~~~~~~~~~~~~~~~
    at https://deno.land/x/oak@v7.2.0/http_server_native.ts:49:50

TS2315 [ERROR]: Type 'Conn' is not generic.
        async function serve(conn: Deno.Conn<Deno.NetAddr>) {
                                   ~~~~~~~~~~~~~~~~~~~~~~~
    at https://deno.land/x/oak@v7.2.0/http_server_native.ts:149:36

TS2315 [ERROR]: Type 'Conn' is not generic.
    conn?: Deno.Conn<Deno.NetAddr>,
           ~~~~~~~~~~~~~~~~~~~~~~~
    at https://deno.land/x/oak@v7.2.0/application.ts:50:12

TS2315 [ERROR]: Type 'Conn' is not generic.
    secureOrConn: Deno.Conn<Deno.NetAddr> | boolean | undefined,
                  ~~~~~~~~~~~~~~~~~~~~~~~
    at https://deno.land/x/oak@v7.2.0/application.ts:374:19

Found 6 errors.

The sample code comes from here (https://github.com/oakserver/oak) and looks like this:
import { Application } from "https://deno.land/x/oak/mod.ts";

const app = new Application();

app.use((ctx) => {
    ctx.response.body = "Hello World!";
});

await app.listen({ port: 8000 });

Thank you!

A: The error comes from incompatibility between deno earlier than 1.9 and oak later than v7.
Since I installed deno a few hours ago I was not checking the versions. With homebrew I got an older version - now I used
curl -fsSL https://deno.land/x/install/install.sh | sh

instead.


text:
Q: Disabling YouTube or possible fix for devices besides desktops I have a website i have been working on where we have an iframe that pulls in the newest video from given YouTube channels. It works just fine on the desktop or device that can run flash but when a user is on an IOS device or some android devices nothing shows up there. Its an empty square. Is there a good fix that someone knows or a way I can get around this? I have tried detecting if it is a mobile platform and to display a filler image instead but still doesn't work on all devices. Any suggestions would be great.
I did also consider just taking the YouTube API and getting the image of the video and showing that then the user clicks it it just brings you to the video, which would be a fix but a last resort fix.
Also in-case anyone has a better way for the code to work then what I have below id love to see it!

    <?php
        $url = 'http://gdata.youtube.com/feeds/api/users/'. $Youtube .'/uploads?max-results=1';
        $xml = simplexml_load_file($url);
        foreach ($xml->entry as $entry) :

            // get nodes using mrss ('media' rss namespace)
            $kids = $entry->children('http://search.yahoo.com/mrss/');

            // for the embed src (just the flv location - you'll need to print out the rest of the object/embed tag
            $attributes = $kids->group->content[0]->attributes();
            $flv = $attributes['url'];

        endforeach;
    ?>
    <iframe align="left" width="100%" height="315" src="<?php echo $flv; ?>" frameborder="0" allowfullscreen>

The code to detect a mobile browser im using is just http://detectmobilebrowsers.com/

A: Taken from Drewid in on another stackoverflow post...
var hasFlash = false;
try {
  var fo = new ActiveXObject('ShockwaveFlash.ShockwaveFlash');
  if(fo) hasFlash = true;
}catch(e){
  if(navigator.mimeTypes ["application/x-shockwave-flash"] != undefined) hasFlash = true;
}

You can also stream youtube via html 5 by adding the url var ?html5=1 to the iframe address


text:
Q: Replicating canvas bug in iOS without hardware I'm hitting a problem with some javascript that only happens on iOS devices.
Annoyingly I can't replicate the problem because I don't own an iOS device. Users are unable to upload photos to this test website (iPhone5s iOS8): http://ios.oddprints.appspot.com the safari browser just hangs
I've tried to replicate the bug using the iOS simulator on my macbook (configured to iPhone 5s, iOS8) but there is no problem in that setup.
Are there any alternative iOS emulators / VMs / real hardware farms etc that I could use?


text:
Q: How to exit / return from class as null Usually in other languages it would looks like NullReferenceException, but I don't know how to do this in js, actually I am beginner with knowledge of C# - not JS
<script>
    var x = new fooClass(null);

    function fooClass(foo)
    {
        if(foo===null)
            return;     // The return type is "fooClass"
                        // I want to return something that will tell that the
                        // class were wrong initialized, maybe exception?

        alert(foo); // show that the script continues
    }
</script>

A: Yes. Exactly. You can throw an exception stating the error message
if(foo === null)
   throw "null not allowed" // throw an exception with a message

More about throw on MDN