text:
Q: How to remove layer from pre-trained TensorFlow model? I trained the following model with three hidden layers in TensorFlow:
inputs = tf.keras.Input(shape=(timesteps, feature_size))

l = LSTM(units=state_size,
               return_sequences=True)(inputs)
l = LSTM(units=state_size,
               return_sequences=True)(l)
l = LSTM(units=state_size,
               return_sequences=True)(l)

output = TimeDistributed(Dense(output_size, activation='softmax'))(l)

model = tf.keras.Model(inputs=inputs, outputs=output)

Now, I would like to use the model but skip the second hidden layer, i.e. directly pass the output from the first layer to the third layer without going through the second layer.
I understand that I can get a hold of the output from the first layer by:
output = model.layers[idx].Output

But how could I feed this output to the third layer now?
Many thanks for any help!

A: One approach is to use layer names to create a new model.
The example below uses specified names. You can also use the default names given by Keras.
inputs = tf.keras.Input(shape=(timesteps, feature_size))

l = LSTM(units=state_size, return_sequences=True, name="lstm1")(inputs)
l = LSTM(units=state_size, return_sequences=True, name="lstm2")(l)
l = LSTM(units=state_size, return_sequences=True, name="lstm3")(l)

output = TimeDistributed(Dense(output_size, activation='softmax'))(l)

model = tf.keras.Model(inputs=inputs, outputs=output)

# Now create the second model using specific layers from the first model
reuse_layers = ["lstm1", "lstm3"]

inputs = tf.keras.Input(shape=(timesteps, feature_size))
l = inputs
for layer_name in reuse_layers:
    l = model.get_layer(layer_name)(l)

output = TimeDistributed(Dense(output_size, activation='softmax'))(l)
new_model = Model(inputs=inputs, outputs=output)


text:
Q: Run-time error '424' : Object Required checking if dynamic named range is blank I used the solution on this question Excel VBA Dynamic Named Ranges: How to check if range is blank but it doesn't work for me, i have a Run-time error'424': Ojbect required on the Set rng = [volTarget] line.
Here is the code, i've changed the name in the [] and it works with a non-empty dynamic named range.
Sub Sample()
    Dim rng As range
    Set rng = [volTarget]
    If Application.WorksheetFunction.CountA(rng) = 0 Then _
    MsgBox "Range is blank"
End Sub

A: If there's no range named as volTarget, VBA throws #NAME error when you try to evaluate it like this [volTarget].

In your code, you need to handle the scenario when the named range is missing.

One possible approach can be :
 Sub Sample()
   Dim rng As Range

   If Not IsError([volTarget]) Then
        Set rng = [volTarget]
        If Application.WorksheetFunction.CountA(rng) = 0 Then '=> This is redundant.
            MsgBox "Range is blank"
        End If
    Else
        MsgBox "No such range" '==> This is practically your black range as you are using dynamic named range.
    End If
End Sub

redpajama_set_name: RedPajamaStackExchange


text:
Q: Anyway to bring up suggestion box when typing python code I'm learning wxpython right now and one thing that helps me ALOT is when I'm typing in the text editor I sometimes press the tab key to give me a hint on what I'm looking for...This is great when it works but I notice sometimes it doesn't work and I get lost looking for a syntax I can't remember...
Question is how can I get the suggestion box to pop back up again, Or what am I doing that causes it to stop coming up...
if it matters I backtracked to 2.7 to learn wx, Windows 7
Edit: More specifically... when I type: wx.(Here is normally when I would press tab)

A: What editor do you use??
Without knowing that there's no way we can possibly help you.
FWIW in vim I use C-x [onp]


text:
Q: How can i call make file from other directory I have directory structure like this
containers/con1
containers/con2
containers/con3

Now every folder like con1, con2 has Makefile in it with targets like build, run
I run it like make run and make build
But i have to go inside that folder.
Is it possible that i have another Makefile in containers/Makefile
and i can run like
Make con1.run Make con2.run

A: Yes, you can do that. Something like the following should do what you want.
$ cat containers/Makefile
%.run: %
        $(MAKE) -C $@

That being said as you can see the command to do what you want is trivial enough to make such a makefile not really necessary (and a simple shell script is as useful here as a makefile).
$ cat run.sh
[ -d "$1" ] || { echo 'No such directory.' >&2; exit 1; }
#make -C "$1"
# OR
#cd "$1" && make

If you wanted to be able to build all the sub-directory projects at once then a makefile could help you with that but even that is a simple enough shell one-liner.
$ for mkfile in */Makefile; do make -C "$(dirname "$mkfile"); done
$ for mkfile in */Makefile; do (cd "$(dirname "$mkfile") && make); done

A: As far as I understand you want this:
   -C dir, --directory=dir
        Change to directory dir before reading the makefiles or doing anything else.  If multiple -C options are specified, each is interpreted relative to the previous one: -C / -C etc is equivalent to -C /etc.   This  is  typi‐
        cally used with recursive invocations of make.

Add -C option like this: make -C con1/

A: Recursive makes are evil, but if you want that:
# con1.run is a phony target...
.PHONY: con1.run

con1.run:
    $(MAKE) -C con1


text:
Q: Spring Amqp Consumer pauses after running for sometime We have a 2 node RabbitMQ cluster with Ha-all policy. We use Spring AMQP in our application to talk to RabbitMQ. Producer part is working fine, but consumer works for some time and pauses. Producer and consumer are running as different applications. More information on Consumer part.

*

*we use SimpleMessageListenerContainer with ChannelAwareMessageListener, use Manual ack mode and default prefetch(1)

*In our application we create queue (on-demand) and add it to the listener

*When we started with 10 ConcurrentConsumers and 20 MaxConcurrentConsumers, consumption happens for around 15 hours and pauses. This situation happens within 1 hour when we increase the MaxConcurrentConsumers to 75.

On RabbitMQ UI, we see channels with 3/4 unacked messages on the channel tab when this situation occurs, until then it just have 1 unacked message.
Our thread dump was similar to this. But having heartbeat set to 60 did not help improve this situation.
Most of the thread dump has the following message. If required I will attach the whole thread dump. Let me know if I am missing any setup which might cause the consumer to pause?
"pool-6-thread-16" #86 prio=5 os_prio=0 tid=0x00007f4db09cb000 nid=0x3b33 waiting on condition [0x00007f4ebebec000]
   java.lang.Thread.State: WAITING (parking)
    at sun.misc.Unsafe.park(Native Method)
    - parking to wait for  <0x00000007b9930b68> (a java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject)
    at java.util.concurrent.locks.LockSupport.park(LockSupport.java:175)
    at java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject.await(AbstractQueuedSynchronizer.java:2039)
    at java.util.concurrent.LinkedBlockingQueue.put(LinkedBlockingQueue.java:350)
    at org.springframework.amqp.rabbit.listener.BlockingQueueConsumer$InternalConsumer.handleDelivery(BlockingQueueConsumer.java:660)
    at com.rabbitmq.client.impl.ConsumerDispatcher$5.run(ConsumerDispatcher.java:144)
    at com.rabbitmq.client.impl.ConsumerWorkService$WorkPoolRunnable.run(ConsumerWorkService.java:99)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)

More Info
We dynamically add and remove queues to SimpleMessageListenerContainer and we suspect this is causing some problem, because every time we add or remove a queue from the listener, all the BlockingQueueConsumer are removed and created again. Do you think if this can cause this problem?

A: Your problem is somewhere downstream in the target listener.
Look, prefetch(1) cause this:
this.queue = new LinkedBlockingQueue<Delivery>(prefetchCount);

And further if we don't poll that queue what we have here?
BlockingQueueConsumer.this.queue.put(new Delivery(consumerTag, envelope, properties, body));

Right, parking on lock.

A: AMQP-621 is now merged to master; we will release 1.6.1.RELEASE in the next few days.


text:
Q: How can I find a limit using equivalent functions and substitutions ( without applying L'Hospital) for the following problem: How can I find a limit using equivalent functions and substitutions ( without applying L'Hospital) for the following problem?
There you can see the expression, I need to find the limit for, as x tends to 0
$\exp[(\cos(\sqrt x)-1)/x]$, square brackets for clarity.

A: You may set $x = t^2$ and use

*

*$\lim_{y\to 0}\frac{1-\cos y}{y^2} = \frac{1}{2}$ (easy to verify with L'Hospital).

\begin{eqnarray*} e^{\frac{\cos\sqrt x -1}{x}}
& = & e^{\frac{\cos t -1}{t^2}}\\
& \stackrel{t\to 0}{\longrightarrow} & e^{-\frac{1}{2}} =\frac{1}{\sqrt{e}}\\
\end{eqnarray*}


text:
Q: Vector product of a list of array, array by array I've a list of array and each array contains 5 softmax arrays. I want, as an output, a final list with only one element per array, which is the product of all the 5 arrays.
 vals_pred = [res.iloc[i]['y_pred'][0:5] for i in range(len(res))
             if len(res.iloc[i]['y_pred']) > lookahead]

res is a dataframe. This is an example of what is found within the list.
array([[1.34866089e-01, 5.28018773e-02, 2.23537564e-01, 4.62821350e-02,
    8.76934379e-02, 4.26145524e-01, 5.53494925e-03, 2.31384877e-02],
   [1.10163569e-01, 7.80740231e-02, 5.52961051e-01, 4.57449956e-03,
    4.64441329e-02, 2.07768157e-01, 1.45530776e-05, 4.66483916e-18],
   [1.82191223e-01, 1.10042050e-01, 3.27700675e-01, 3.38860601e-03,
    1.07456036e-01, 2.69037366e-01, 1.84074364e-04, 3.74613562e-13],
   [1.80145595e-02, 7.61333853e-03, 8.86637151e-01, 1.02691650e-02,
    2.46689599e-02, 5.27242124e-02, 7.26214203e-05, 2.64242381e-19],
   [5.62842265e-02, 1.42695876e-02, 8.42117667e-01, 1.62272118e-02,
    4.17451970e-02, 2.88727339e-02, 4.83323034e-04, 2.92075066e-13]],
  dtype=float32), array([[5.4129714e-04, 3.6672730e-02, 4.8940146e-06, 8.3479950e-05,
    6.5760143e-02, 1.6968355e-02, 8.7981069e-01, 1.5837120e-04],
   [2.1086331e-07, 1.4350067e-03, 1.6849227e-16, 8.4671612e-08,
    2.4794264e-07, 3.8307374e-03, 9.9473369e-01, 6.4219920e-24],
   [1.7740911e-04, 2.1856705e-02, 1.5427456e-11, 1.2592359e-08,
    2.0797092e-03, 3.5571402e-01, 6.2017220e-01, 3.4836909e-20],
   [1.7687974e-07, 4.4844073e-05, 9.6608031e-14, 4.5008356e-08,
    1.0638499e-03, 1.0105613e-04, 9.9878997e-01, 4.8578437e-24],
   [6.6033276e-11, 5.1952496e-09, 5.8398927e-21, 4.5752773e-13,
    5.2611317e-06, 2.4885111e-07, 9.9999452e-01, 2.5868782e-10]],
  dtype=float32)

The desired output is a list similarly composed of 2 arrays (in this example case), but each array is the multiplication of the 5 arrays (element by element) that contains the list element. Next I need to get the argmax.
Any ideas on how I could do this? I can use any Python library

A: Assuming your list is named array_list, you can use a list comprehension and numpy.prod:
import numpy as np
[np.prod(a) for a in array_list]

output: [1.2981583896975622e-116, 2.2208998715549213e-267]
Or maybe you want the product only on the fist axis per array:
[np.prod(a, axis=0) for a in array_list]

output:
[array([2.74459685e-06, 4.92834563e-08, 3.02441299e-02, 1.19552067e-10,
        4.50698513e-07, 3.62616474e-05, 5.20432043e-19, 3.12070056e-63]),
 array([2.36512231e-31, 2.67974413e-19, 7.17724310e-66, 1.83289538e-39,
        1.89791218e-19, 5.81467373e-16, 5.42100925e-01, 4.45251202e-80])]

And to get the argmax:
[np.argmax(np.prod(a, axis=0)) for a in array_list]

output: [2, 6]


text:
Q: Conjectured primality test for specific class of $N=k\cdot 6^n-1$ How to prove that this conjecture is true ?
Definition : $\text{Let}~ P_m(x)=2^{-m}\cdot \left(\left(x-\sqrt{x^2-4}\right)^{m}+\left(x+\sqrt{x^2-4}\right)^{m}\right)~ , \text{where}~ m ~\text{and}~ x ~\text{are nonnegative integers} .$
Conjecture : $$\text{Let} ~N=k\cdot 6^n-1~ \text{such that} ~ n>2 ,  k>0 ,$$
$$k \equiv 2,5 \pmod{7}~ \text{and}~ k<6^n .$$
$$\text{Let}~ S_i=P_6(S_{i-1})~ \text{with}~ S_0=P_{3k}(P_3(5)) ,~ \text{thus} $$
$$N ~\text{is prime iff} ~ S_{n-2} \equiv 0 \pmod{N}$$
Pari GP implementation of the test :
Tk6n1(k,n)=
{
my(s=Mod(2*polchebyshev(3*k,1,polchebyshev(3,1,5/2)),k*6^n-1));
for(i=1,n-2, s=2*polchebyshev(6,1,s/2));
s==0
}

Searching for counterexample (Pari GP)
Necessity
CEk6n1(k,lb,ub)=
{
for(n=lb,ub,s=2*polchebyshev(3*k,1,polchebyshev(3,1,5/2));
N=k*6^n-1;
for(i=1,n-2,s=Mod(2*polchebyshev(6,1,s/2),N));
if(!s==0 && isprime(N),print(n)))
}

Sufficiency
CEk6n1(k,lb,ub)=
{
for(n=lb,ub,s=2*polchebyshev(3*k,1,polchebyshev(3,1,5/2));
N=k*6^n-1;
for(i=1,n-2,s=Mod(2*polchebyshev(6,1,s/2),N));
if(s==0 && !isprime(N),print(n)))
}

Any help would be much appreciated .
EDIT:
One can formulate following conjecture also .
Conjecture : $$\text{Let} ~N=k\cdot 6^n-1~ \text{such that} ~ n>2 ,  k>0 ,$$
$$k \equiv 3,4 \pmod{5}~ \text{and}~ k<6^n .$$
$$\text{Let}~ S_i=P_6(S_{i-1})~ \text{with}~ S_0=P_{3k}(P_3(3)) ,~ \text{thus} $$
$$N ~\text{is prime iff} ~ S_{n-2} \equiv 0 \pmod{N}$$

A: This is a partial answer.
Edit : I'm going to prove that $$\text{if $N$ is prime, then $S_{n-2}\equiv 0\pmod N$}$$ for both conjectures.
(For the first conjecture)
First of all,
$$P_3(5)=2^{-3}\cdot \left(\left(5-\sqrt{21}\right)^3+\left(5+\sqrt{21}\right)^3\right)=110$$
So,
$$\begin{align}S_0=P_{3k}(P_3(5))=P_{3k}(110)&=2^{-3k}\cdot \left(\left(110-\sqrt{110^2-4}\right)^{3k}+\left(110+\sqrt{110^2-4}\right)^{3k}\right)\\&=\left(\frac{110-\sqrt{110^2-4}}{2}\right)^{3k}+\left(\frac{110+\sqrt{110^2-4}}{2}\right)^{3k}\\&=\left(55-12\sqrt{21}\right)^{3k}+\left(55+12\sqrt{21}\right)^{3k}\\&=(a^2)^{3k}+(b^2)^{3k}\\&=a^{6k}+b^{6k}\end{align}$$
where $a=2\sqrt 7-3\sqrt 3,b=2\sqrt 7+3\sqrt 3$ with $ab=1$.
From this, we can prove by induction that
$$S_i=a^{6^{i+1}k}+b^{6^{i+1}k}.$$
Thus,
$$S_{n-2}=a^{\frac{N+1}{6}}+b^{\frac{N+1}{6}}=\left(\frac{\sqrt 7}{2}-\frac{\sqrt 3}{2}\right)^{\frac{N+1}{2}}+\left(\frac{\sqrt 7}{2}+\frac{\sqrt 3}{2}\right)^{\frac{N+1}{2}}=2^{-\frac{N+1}{2}}\left((\sqrt 7-\sqrt 3)^{\frac{N+1}{2}}+(\sqrt 7+\sqrt 3)^{\frac{N+1}{2}}\right).$$
By the way, for $N$ prime,
$$\begin{align}(\sqrt 7-\sqrt 3)^{N+1}+(\sqrt 7+\sqrt 3)^{N+1}&=\sum_{i=0}^{N+1}\binom{N+1}{i}\left(\sqrt 7\right)^{i}((-\sqrt 3)^{N+1-i}+(\sqrt 3)^{N+1-i})\\&=\sum_{j=0}^{(N+1)/2}\binom{N+1}{2j}\left(\sqrt 7\right)^{2j}\cdot 2(\sqrt 3)^{N+1-2j}\\&=\sum_{j=0}^{(N+1)/2}\binom{N+1}{2j}7^{j}\cdot 2\cdot 3^{\frac{N+1}{2}-j}\\&\equiv 2\cdot 3^{\frac{N+1}{2}}+7^{\frac{N+1}{2}}\cdot 2\pmod{N}\\&\equiv 2\cdot 3+(-7)\cdot 2\pmod N\\&\equiv -8\pmod N\end{align}$$
This is because $N\equiv 2\pmod 3$ and $N\equiv \pm 2\cdot (-1)^n-1\equiv 1,4\pmod 7$ implies that $$3^{(N-1)/2}\equiv 1\pmod N,\quad 7^{(N-1)/2}\equiv -1\pmod N.$$
From this, since $2^{N-1}\equiv 1\pmod N$,
$$\begin{align}2^{N+1}S_{n-2}^2&=(\sqrt 7-\sqrt 3)^{N+1}+(\sqrt 7+\sqrt 3)^{N+1}+2\cdot 4^{\frac{N+1}{2}}\\&\equiv -8+2\cdot 2^{N-1}\cdot 4\pmod N\\&\equiv 0\pmod N\end{align}$$
Thus, $S_{n-2}\equiv 0\pmod N$.

(For the second conjecture)
$$P_3(3)=2^{-3}\cdot\left(\left(3-\sqrt{5}\right)^3+\left(3+\sqrt{5}\right)^3\right)=18$$
$$S_0=P_{3k}(P_3(3))=2^{-3k}\cdot\left(\left(18-\sqrt{18^2-4}\right)^{3k}+\left(18+\sqrt{18^2-4}\right)^{3k}\right)$$
$$=(9-4\sqrt{5})^{3k}+(9+4\sqrt 5)^{3k}=c^{6k}+d^{6k}$$
where $c=\sqrt 5-2,d=\sqrt 5+2$ with $cd=1$.
We can prove by induction that
$$S_i=c^{6^{i+1}k}+d^{6^{i+1}k}$$
Thus,
$$S_{n-2}=c^{\frac{N+1}{6}}+d^{\frac{N+1}{6}}=\left(\frac{\sqrt 5}{2}-\frac 12\right)^{\frac{N+1}{2}}+\left(\frac{\sqrt 5}{2}+\frac 12\right)^{\frac{N+1}{2}}=2^{-\frac{N+1}{2}}\left(\left(\sqrt 5-1\right)^{\frac{N+1}{2}}+\left(\sqrt 5+1\right)^{\frac{N+1}{2}}\right).$$
By the way, for $N$ prime,
$$\begin{align}\left(\sqrt 5-1\right)^{N+1}+\left(\sqrt 5+1\right)^{N+1}&=\sum_{i=0}^{N+1}\binom{N+1}{i}(\sqrt 5)^{i}\left((-1)^{N+1-i}+1^{N+1-i}\right)\\&=\sum_{j=0}^{(N+1)/2}\binom{N+1}{2j}(\sqrt 5)^{2j}\cdot 2\\&=\sum_{j=0}^{(N+1)/2}\binom{N+1}{2j}5^j\cdot 2\\&\equiv 2+5^{\frac{N+1}{2}}\cdot 2\pmod N\\&\equiv 2+(-5)\cdot 2\pmod N\\&\equiv -8\pmod N\end{align}$$
This is because $N\equiv 2,3\pmod 5$ implies that $$5^{\frac{N-1}{2}}\equiv -1\pmod N.$$
From this, since $2^{N-1}\equiv 1\pmod N$,
$$\begin{align}2^{N+1}S_{n-2}^2&=(\sqrt 5-1)^{N+1}+(\sqrt 5+1)^{N+1}+2\cdot 4^{\frac{N+1}{2}}\\&\equiv -8+2\cdot 2^{N-1}\cdot 4\pmod N\\&\equiv 0\pmod N\end{align}$$
Thus, $S_{n-2}\equiv 0\pmod N$.


text:
Q: How do you regex an address pattern? I want to match pattern in regex for address. For example, 456-123 Wall St. I want to set regex pattern similar to the this with (-123) could be optional and the last bit of the string must be an alphabet.
I tried this but it doesn't work.
bool(re.match(r'^(\d)[-]?(\d)?\s[a-zA-Z]+$','123-123 fs'))

A: I used https://regex101.com/ to try and match your example address. Is this what you were looking for?
^(\d+)([-]?)(\d+)(\s?)([a-zA-Z]+)(\s?)([a-zA-Z]+)$

If you want to include the period after St., you can use
^(\d+)([-]?)(\d+)(\s?)([a-zA-Z]+)(\s?)([a-zA-Z]+)(\.?)$


text:
Q: Parse microseconds datetime format in android kotlin I want to parse the following String :
2022-02-14T04:40:33.000000Z
So I'll be able to convert it to this date format:
14/Feb/2022 04:40 or dd/MMM/yyyy HH:mm.
But it throws an exception :
Caused by: java.text.ParseException: Unparseable date: "2022-02-14T04:40:33.000000Z"

My code is a basic SimpleDateFormat with the following code :
val datetime = "2022-02-14T04:40:33.000000Z"

val inputFormat = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ", Locale.getDefault())
val outputFormat = SimpleDateFormat("dd/MMM/yyyy HH:mm", Locale.getDefault())

val inputDate = inputFormat.parse(date) // exception thrown here.
val dateString = outputFormat.format(inputDate)

I had tried the following format :

*

*yyyy-MM-dd'T'HH:mm:ss.SSSZ

*yyyy-MM-dd'T'HH:mm:ss.SSS'000'Z (I was expecting to ignore the extra 000)

I had read about the PHP DateTime::format which had the u format character for microseconds.
But, the android SimpleDateFormat had no support for the microseconds character.

A: Please use following format
"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"


text:
Q: solving a problem with cursors I have a question. I am working on cursors. Each time, after fetching the last records and printing its data's, the cursor prints an addition line. To understand what I mean please consider the following sample example:
 I want to print the information about only 10 customers.
USE Northwind
GO

DECLARE myCursor CURSOR
FOR SELECT TOP(10) ContactName FROM Customers
DECLARE @RowNo int,@ContactName nvarchar(30)
SET @RowNo=1
OPEN myCursor
FETCH NEXT FROM myCursor INTO @ContactName
PRINT  LEFT(CAST(@rowNo as varchar) + '      ',6)+'  '+ @ContactName
SET @RowNo=@RowNo+1
SET @ContactName=''
WHILE @@FETCH_STATUS=0
  BEGIN
        FETCH NEXT FROM myCursor INTO @ContactName
        PRINT + LEFT(CAST(@rowNo as varchar) + '      ',6)+'  '+ @ContactName
        SET @RowNo=@RowNo+1
        SET @ContactName=''
  END
CLOSE myCursor
DEALLOCATE myCursor

Now look at the output:
1       Maria Anders
2       Ana Trujillo
3       Antonio Moreno
4       Thomas Hardy
5       Christina Berglund
6       Hanna Moos
7       Frédérique Citeaux
8       Martín Sommer
9       Laurence Lebihan
10      Elizabeth Lincoln
11

The row number 11 also has been printed. Is it a problem in a cursor or it always occurs?
Is there any way not to print this addition data? Thanks
(i use sql erver 2008)

A: Either...
FETCH NEXT FROM myCursor INTO @ContactName
WHILE @@FETCH_STATUS = 0
BEGIN
    -- do stuff

    FETCH NEXT FROM myCursor INTO @ContactName
END

Or...
WHILE @@FETCH_STATUS = 0
BEGIN
    FETCH NEXT FROM myCursor INTO @ContactName
    IF @@FETCH_STATUS = 0
    BEGIN
        -- do stuff
    END
END

Or...
WHILE (1 = 1)
BEGIN
    FETCH NEXT FROM myCursor INTO @ContactName
    IF @@FETCH_STATUS <> 0
        BREAK

    -- do stuff
END

A: You mentioned you're using SQL Server 2008. With SQL Server 2005 or greater, you don't need a cursor at all to do what you want.
select top 10 left(cast(row_number() over(order by ContactName) as varchar)+ '      ', 6) + ContactName
    from Customers

A: See how you have the printing logic duplicated? That's a pointer to what's going wrong. Your loop should look like this:
FETCH NEXT INTO @working_variables
WHILE @@FETCH_STATUS = 0
    -- process @working_variables
    FETCH NEXT INTO @working_variables

The only duplicated code should be the FETCH NEXT itself - the way you have it now, the last FETCH happens, but you PRINT a line before the WHILE can exit.

A: A FETCH at the end of the record set sets @@FETCH_STATUS to not 0.
The FETCH NEXT command should be the last line in the WHILE BLOCK.
USE Northwind
GO

DECLARE myCursor CURSOR
FOR SELECT TOP(10) ContactName FROM Customers
DECLARE @RowNo int,@ContactName nvarchar(30)
SET @RowNo=0
OPEN myCursor
FETCH NEXT FROM myCursor INTO @ContactName
WHILE @@FETCH_STATUS=0
  BEGIN

        SET @RowNo=@RowNo+1
        SET @ContactName=''
        PRINT + LEFT(CAST(@rowNo as varchar) + '      ',6)+'  '+ @ContactName
        FETCH NEXT FROM myCursor INTO @ContactName
  END
CLOSE myCursor
DEALLOCATE myCursor

A: This is an off-by-one error. Here's a better way to iterate through a cursor, w/ less code duplication:
USE Northwind
GO

DECLARE myCursor CURSOR
FOR SELECT TOP(10) ContactName FROM Customers
DECLARE @RowNo int,@ContactName nvarchar(30)
SET @RowNo=0 -- initialize counters at zero, increment after the fetch/break
OPEN myCursor
WHILE 1=1 BEGIN -- start an infinite loop
  FETCH NEXT FROM myCursor INTO @ContactName
  IF @@FETCH_STATUS <> 0 BREAK
  SET @RowNo=@RowNo+1
  PRINT  LEFT(CAST(@rowNo as varchar) + '      ',6)+'  '+ @ContactName
END
CLOSE myCursor
DEALLOCATE myCursor

For extra points, use a cursor variable and declare w/ FAST_FORWARD and TYPE_WARNING, or STATIC for small datasets. eg:
DECLARE @cursor CURSOR
SET @cursor = CURSOR FAST_FORWARD TYPE_WARNING FOR
  SELECT TOP (10) ContactName FROM Customers
OPEN @cursor
......
CLOSE @cursor
DEALLOCATE @cursor

CLOSE and DEALLOCATE are not strictly necessary, as the cursor variable will go out of scope at the end of the batch. It is still good form, however, as you might add more code at the end later on, and you should free up resources as early as possible.
TYPE_WARNING tells you when SQL Server implicitly converts the requested cursor type (FAST_FORWARD) to another type (typically STATIC), if the requested type is incompatible w/ your SELECT statement.


text:
Q: Silex: How and why to use testing The documentation on testing is not really clear to me. It says you can use testing to check whether my pages and my system works correctly.
In my opinion, that would mean it could check whether all rights are used properly or something like that. But I don't understand why I'd put so much time in coding the testing part.
I hope someon could explain and convince me why I should use testing, and as a second part: HOW I should use it!
So, as an example, this could be my basic index.php file:
<?php

require_once __DIR__.'/../vendor/autoload.php';

$app = new Silex\Application();
$app['debug'] = true;

$routes = $app['controllers_factory'];

$routes->match('/', function () use ($app) {
    return 'Hello';
});

$app->mount('/', $routes);
$app->run();

Could you give me an example or adjust my route and give some testing with it. And please don't use the examples from the documentation: they don't make sense to me and that's the whole reason why I'm asking it here.
EDIT
So, both your comments were helpfull. I think I'm starting to understand why it might be usefull. Now, all I need is an example to fully understand it. Let's say I've got this route:
$routes->match('/user/login', function (Request $request) use ($app) {

    $form = $app['form.factory']->createBuilder(FormType::class)
        ->add('username', TextType::class, array(
            'constraints' => array(new Assert\NotBlank(), new Assert\Length(array('min' => 3,'max' => 3))),
            'label' => 'Username',
            'required' => 'required',
            'attr' => array('class' => 'input-field', 'autocomplete' => 'off', 'placeholder' => 'Docent afkorting'),
            'label_attr' => array('class' => 'label'),
            'error_bubbling' => true
        ))
        ->add('password', PasswordType::class, array(
            'constraints' => array(new Assert\NotBlank(), new Assert\Length(array('min' => 5))),
            'label' => 'Password',
            'required' => 'required',
            'attr' => array('class' => 'input-field', 'autocomplete' => 'off', 'placeholder' => 'Wachtwoord'),
            'label_attr' => array('class' => 'label'),
            'error_bubbling' => true
        ))
        ->add('submit', SubmitType::class, [
            'label' => 'Login',
            'attr' => array('class' => 'submit'),
        ])
        ->getForm();

    $form->handleRequest($request);

    if ($form->isValid()) {
        $data = $form->getData();
        $user = new User();

        if($user->login($data['username'],$data['password'])){
            return $app->redirect($app['url_generator']->generate('home'));
        }
        else{
            return $app['twig']->render('form.twig', [
                'content' => 'Incorrect username or password

',
                'form' => $form->createView(),
            ]);
        }
    }

    return $app['twig']->render('form.twig', [
        'form' => $form->createView()
    ]);
})->bind('user.login');

What would I have to do to have a proper test?

A: If you are not familiar with software tests, you may be wondering why you would need this. Every time you make a change to your application, you have to test it. This means going through all the pages and making sure they are still working. Functional tests save you a lot of time, because they enable you to test your application in usually under a second by running a single command.
Source:
https://silex.symfony.com/doc/2.0/testing.html#why


text:
Q: How do I apply CSS to style the text in a UILabel? I would like to be able to style the text in a UILabel using CSS.  I know that you can use a UIWebView to load HTML to be formatted for display using
[webview loadHTMLString:myText baseURL:nil];

but I would like to simply style just a UILabel without relying on UIWebView.  How can I do this?

A: Look at the open source project called FontLabel at http://wiki.github.com/zynga/FontLabel.
Although it won't let you apply a CSS file to a UILabel, it does provide a subclass of UILabel that can use custom fonts and styling.
Of course you can also use the standard properties of UILabel like color, textAlignment, etc.

A: Since css file structure is very easy you could create a simple css parser that searches a certain id or class. Then get the font size, name, style and other attributes and instead of using UILabel you maybe want use CATextLayer because text is much more customizable (colors, font, size, style, and even more than one fonts in a single line)
But I wonder why do you need a UILabel and not UIWebView?
Hope it helps


text:
Q: Webpack exclusion with seperate entry points not working with file exclusion I have a webpack config file(version 5.28.0) that I am trying to alter, in order to create two versions of the user.js file that is generated. I'd like a user.js and legacy_user.js file to be generated. Both files I would like to be generated from the contents of the 'scripts/user' directory, with the exception of I'd like the user.js file to compile excluding the legacy_user.js file that is in the 'scripts/user' directory and the legacy_user.js file to compile excluding the user.js file that is in the 'scripts/user' directory.  I have tried the below but the contents of the user.js file keeps overwriting the contents of the legacy_user.js file and they end up being identical:
module.exports = (options = {}) => {
    return [
        {
            mode: options.production ? 'production' : 'development',
            entry: {
                app: path.resolve(__dirname, 'scripts/app'),
                user: path.resolve(__dirname, 'scripts/user'),
                'video/trim': path.resolve(__dirname, 'scripts/video/trim')
            },
            output: { path: path.resolve(__dirname, '../public_html/dist') },
            module: {
                rules: [
                    {
                        test: /\.js$/,
                        exclude: [/(node_modules)/, /legacy_user\.js$/],
                        use: {
                            loader: 'babel-loader',
                            options: {
                                presets: ['@babel/preset-env'],
                                plugins: ['@babel/plugin-transform-runtime']
                            }
                        }
                    }, {
                        test: /\.(s[ac]ss|css)$/i,
                        use: ['style-loader', 'css-loader', 'sass-loader']
                    },
                    { test: /\.(png|jpg|woff(2)?|ttf|eot|svg)$/, loader: 'file-loader' }
                ]

            },
        },
        {
            mode: options.production ? 'production' : 'development',
            entry: {
                legacy_user: path.resolve(__dirname, 'scripts/user')
            },
            output: {
                path: path.resolve(__dirname, '../public_html/dist')
            },
            module: {
                rules: [
                    {
                        test: /\.js$/,
                        exclude: [/(node_modules)/,  /user\.js$/],
                        use: {
                            loader: 'babel-loader',
                            options: {
                                presets: ['@babel/preset-env'],
                                plugins: ['@babel/plugin-transform-runtime']
                            }
                        }
                    }, {
                        test: /\.(s[ac]ss|css)$/i,
                        use: ['style-loader', 'css-loader', 'sass-loader']
                    },
                    { test: /\.(png|jpg|woff(2)?|ttf|eot|svg)$/, loader: 'file-loader' }
                ]

            },
        }
    ]
}

Any help on this would be greatly appreciated!


text:
Q: fest-swing and wrappers for swing/awt components I'd like to test GUI client with fest-swing but...
The client based on custom layer which wrapps swing components. The problem is that my custom gui components do not inherite from swing components but are composed from them (the author of the layer prefered composition over inheritance).
So now I am able to write a test using fest-swing, the test starts the client but I cannot refer to any Frame, Component, Dialog, Window because my ui components are not subclasses of standard swing/awt components. I got stuck here. I am now reading fest-swing code and it seems that I cannot use this lib in my case bacuase fest-swing use generalization with subtyping (inheritance) :(
Any one of you faced this problem? Any hinst?

A: Have you read the documentation article about creating a new Fixture for your onw GUI-Component?
Cite of Chapter 2. of the article:
If the custom GUI component does not extend any JDK Swig component, or if you prefer to create a FEST fixture from scratch, please read the following:
Extend ComponentFixture. This class provides all the necessary wiring of a GUI component to test and a Robot. It also provides some very basic functionality and convenience methods.
I did not try this, but this should help you fixing your problem.


text:
Q: Error when try to unwrap realm object I have following issue when I try to use data from one of Realm Objects
I have an error:

Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value

I'm confused because when I try to do it manually on debug console all works fine

(lldb) print meal?.mealName
  (String?) $R0 = "Krem buraczany"

I will attach whole code and show you on which line error appear
Realm Object:
import UIKit
import RealmSwift

class Meal: Object {

@objc dynamic var mealID : String = ""
@objc dynamic var mealName : String = ""
var ingredients = List<String>()
var mealDescription = List<String>()
@objc dynamic var kcal : Int = 0
@objc dynamic var preparingTime : Int = 0
@objc dynamic var imageName : String = ""

convenience init(mealID: String, mealName: String, kcal: Int, preparingTime: Int, imageName: String) {
    self.init()

    self.mealID = mealID
    self.mealName = mealName
    self.kcal = kcal
    self.preparingTime = preparingTime
    self.imageName = imageName

}

override static func primaryKey() -> String? {
    return "mealID"
}

}

Sending data via segue:
    @IBAction func ideaForMealButtonPressed(_ sender: UIButton) {
    performSegue(withIdentifier: "ideaForMeal", sender: self)
}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

    let destinationVC = segue.destination as! IdeaForMeal
    destinationVC.randomMeal = getRandomMeal()

}

func getRandomMeal() -> String {

    var mealsCount = realm.objects(Meal.self).count
    mealsCount += 1
    let randomMealID = arc4random_uniform(UInt32(mealsCount))
    print (randomMealID)

    return String(randomMealID)

}

Receiver:
//Global Variables
let realm = try! Realm()
var randomMeal : String? {
    didSet {
        let selectedMeal = downloadMealData(mealID: randomMeal!)
        setUIForMeal(meal: selectedMeal)
    }
}

override func viewDidLoad() {
    super.viewDidLoad()
    self.hideKeyboardWhenTappedAround()

}

//Background Operations

func downloadMealData(mealID: String?) -> Meal? {

    let currentMeal = realm.object(ofType: Meal.self, forPrimaryKey: mealID)
    return currentMeal

}

func checkPositionOfTopIngredientsLabel() -> CGFloat {

    let maxY = ingredientsTopLabel.frame.maxY
    return maxY

}

func setUIForMeal(meal: Meal?) {

    mealNameLabel.text = meal!.mealName // Error!
    mealImage.image = UIImage(named: meal!.imageName)
    preparingTimeLabel.text = String(meal!.preparingTime)
    kcalLabel.text = String(meal!.kcal)

}

Thanks!
BR
iMat

A: The error is not related to Realm. It's a very common view life cycle mistake.
Setting randomMeal in the destination view controller triggers the didSet observer. The observer is going to access an IBOutlet which is not connected yet.
A solution is to run the code in viewDidLoad
var randomMeal = ""

override func viewDidLoad() {
    super.viewDidLoad()
    self.hideKeyboardWhenTappedAround()
    if !randomMeal.isEmpty {
        let selectedMeal = downloadMealData(mealID: randomMeal)
        setUIForMeal(meal: selectedMeal)
    }

}


text:
Q: Is there a way to Elasticsearch diferentiate when a field does not exists vs when a field exists but is null ({}) I have 2 kinds of documents:
"doc1":{
    "dummy_attribute":"HI",
    ...
    "important_attribute":{}
}
"doc2":{
    "dummy_attribute":"HI",
    ...
}

If I search like this:
GET myindex/_search
{
  "query": {
    "bool": {
      "must_not": [{
        "exists": {
          "field": "important_attribute"
        }
      }]
    }
  }
}

it returns me both documents.
Is there a way to search only for the documents where "important_attribute" actually does not exist in the document ?

A: That's unfortunately not possible since ES treats a non-existent value the same way as an empty-ish value (null, "", [] or {}).
You could use script fields to quickly check whether a document contains empty dicts but this context cannot be used when filtering:
GET myindex/_search
{
  "query": {
    "bool": {
      "must_not": [
        {
          "exists": {
            "field": "important_attribute"
          }
        }
      ]
    }
  },
  "script_fields": {
    "has_empty_dict": {
      "script": {
        "source": "params._source.containsKey('important_attribute') && params._source.important_attribute.size() == 0"
      }
    }
  }
}


text:
Q: identifying new GPOs pushed down from Active Directory How do you identify the recent and Group Policy Objects that have been pushed down to a client machine?
I am trying to identify if any new IE settings were pushed down recently.

A: You can try pushing RSoP to a file then compare? Something like GPRESULT -h GPEDIT.html


text:
Q: Flex mx:DataGrid row index Is it possible to dynamically show row index for DataGrid rows ?
I have a static ArrayCollection which is set to be DataGrid's data provider and I would like to always have row numbering for each populated row (e.g. in a column called "#").
Thanks!

A: Yes, create a labelFunction that returns the ArrayCollction's getItemIndex for the current object, plus 1.  Example


text:
Q: How can I load the openai api configuration through js in html? I am trying to send a request through js in my html so that openai analyzes it and sends a response, but if in the js I put the following:
const { Configuration, OpenAIApi } = require("openai");

const configuration = new Configuration({
apiKey: "sk-0000000000000ZXXXXXXXXXXXXXX",
});
const openai = new OpenAIApi(configuration);

async function test() {
console("test")
const response = await openai.createCompletion("text-davinci-002", {
prompt: "hello",
temperature: 0.7,
max_tokens: 64,
top_p: 1,
frequency_penalty: 0,
presence_penalty: 0,
});
console.log(response)
}
test();

return console these error
Uncaught ReferenceError: require is not defined
at buttons.js:94:38

I have tried to install it with node.js and it works fine but I don't know how to make it work in my own html

A: It took me a little while to figure this out.

*

*Go to https://beta.openai.com/playground and choose the settings you want.

*Then, click "View code" in the top right.

*Select "curl" as the code type you want to view.

*Copy the "curl" code.

*Go to: https://reqbin.com/req/javascript/c-wyuctivp/convert-curl-to-javascript.

*Convert the code from "curl" to "javascript/AJAX". This will change it from "curl" to a javascript/AJAX XMLHttpRequest.

Use the javascript as you would normally. The code will console log the response. You can change that to use the response in some other way in your code.
Tested and working examples (You could just adjust these examples to meet your needs, but it may be best to create your own to get the exact results you want):
Regular prompt:

let open_ai_response;

openai_test();

async function openai_test() {

  var url = "https://api.openai.com/v1/engines/text-davinci-002/completions";

  var xhr = new XMLHttpRequest();
  xhr.open("POST", url);

  xhr.setRequestHeader("Content-Type", "application/json");
  xhr.setRequestHeader("Authorization", "Bearer YOUR_OPEN_AI_KEY_GOES_HERE");

  xhr.onreadystatechange = function () {
     if (xhr.readyState === 4) {
        console.log(xhr.status);
        console.log(xhr.responseText);
        open_ai_response = xhr.responseText;
        console.log(open_ai_response);
     }};

  var data = `{
    "prompt": "YOUR TEXT HERE.",
    "temperature": 0.7,
    "max_tokens": 256,
    "top_p": 1,
    "frequency_penalty": 0.75,
    "presence_penalty": 0
  }`;

  xhr.send(data);
}

Using variables for the prompt:

let open_ai_response;

openai_test();

async function openai_test() {

  var prompt_text = "YOUR TEXT HERE."
  var prompt_text2 = "MORE TEXT HERE."

  var url = "https://api.openai.com/v1/engines/text-davinci-002/completions";

  var xhr = new XMLHttpRequest();
  xhr.open("POST", url);

  xhr.setRequestHeader("Content-Type", "application/json");
  xhr.setRequestHeader("Authorization", "Bearer YOUR_OPEN_AI_KEY_GOES_HERE");

  xhr.onreadystatechange = function () {
     if (xhr.readyState === 4) {
        console.log(xhr.status);
        console.log(xhr.responseText);
        open_ai_response = xhr.responseText;
        console.log(open_ai_response);
     }};

  var data = `{
    "prompt": "${prompt_text + prompt_text2}",
    "temperature": 0.7,
    "max_tokens": 256,
    "top_p": 1,
    "frequency_penalty": 0.75,
    "presence_penalty": 0
  }`;

  xhr.send(data);
}


text:
Q: Can't connect laptop on domain to private network (home wireless) Please, help. Tried most of the troubleshooting that I came across Google. None of them worked so far. I can not connect neither via wireless nor cable to my home internet. Uninstalled the drivers, reinstalled. Turned off firewall.
It did not connect to another private wireless that I tried. It did connect to public wireless which did not require password. It connects to the internet when it is on domain network flawlessly. Can't figure out what the problem is. Planning to remove from domain and place in workgroup, then try again.
Any help appreciated? Thanks.

A: Did you check to make sure you don't have a static IP? You would need to check in Network Adapters and make sure TCP/IP Protocol version 4 is set to get dynamic addresses. Also check for alternate DNS Servers in the Advanced section.
Run ipconfig /release and ipconfig /renew.
Potentially Group Policy is applied to your computer to restrict off-site internet access.


text:
Q: Sharing service between 2 applications on same page not updating bindings I have a Configuration service
@Injectable()
export class ConfigService {

    private config: PageConfig = new PageConfig({});

    public getConfig = (): PageConfig => {
        return this.config;
    }
}

var configInstance = null;

export function ConfigServiceFactory() {
    if (configInstance == null) {
        configInstance = new ConfigService();
    }

    return configInstance;
}

That uses a factory to return a single instance of the ConfigService, this is my "app.ts"
bootstrap(App, [
    HTTP_PROVIDERS,
    ROUTER_PROVIDERS,
    bind(ConfigService).toFactory(ConfigServiceFactory),
    provide(APP_BASE_HREF, { useValue: '/App/' }),
    provide(LocationStrategy, { useClass: PathLocationStrategy })
])
    .catch(err => console.error(err));

bootstrap(PageConfigComponent, [
    bind(ConfigService).toFactory(ConfigServiceFactory)
])
    .catch(err => console.error(err));

Sadly the Application is in 2 separate components (I cannot change this) and they both need to share specific configuration values, now I have a simple template with a binding to a string
@Component({
    selector: 'pagetitle',
    template: '<span>{{ pageConfig.Title }}ABC</span>',
    directives: [CORE_DIRECTIVES]
})

export class PageTitleComponent {
    public pageConfig: PageConfig = null;

    constructor(_configService: ConfigService) {
        this.pageConfig = _configService.getConfig();
    }
}

This binding is being initialized but its not changing the value even though the value stored in the ConfigService is being updated.

A: This code copies the config from _configService once when PageTitleComponent is created. Besides that there is no relation at all between PageTitleComponent andConfigService`.
export class PageTitleComponent {
    public pageConfig: PageConfig = null;

    constructor(_configService: ConfigService) {
        this.pageConfig = _configService.getConfig();
    }
}

If you use an Observable then interested components can subscribe to changes.
@Injectable()
export class ConfigService {

    config: BehaviorSubject<PageConfig> = new BehaviorSubject<PageConfig>(new PageConfig({}));

    getConfig(): PageConfig => {
        return this.config;
    }

    // set a new config
    setConfig(PageConfig config) => {
        this.config.next(config);
    }
}

export class PageTitleComponent {

    constructor(_configService: ConfigService) {
      _configService.getConfig().subscribe(config => this.pageConfig = config);
    }
}

See also https://stackoverflow.com/a/36566919/217408 for a full example

A: You could do the following:
let configService = new ConfigService();

bootstrap(App, [
  HTTP_PROVIDERS,
  ROUTER_PROVIDERS,
  provide(ConfigService, { useFactory => { configService) }), // <----
  provide(APP_BASE_HREF, { useValue: '/App/' }),
  provide(LocationStrategy, { useClass: PathLocationStrategy })
])
  .catch(err => console.error(err));

bootstrap(PageConfigComponent, [
  provide(ConfigService, { useFactory => { configService) }), // <----
])
  .catch(err => console.error(err));


text:
Q: Conditionally show a card component in React only when all the data/ images have loaded? I'm new to React but I have managed to get React to render a card component based on data from PokeAPI (the data itself is passed down to the component through props). The issue is that when the data changes (e.g user makes a new search) that data loads at different times, especially images which take a while to update.
I have looked at various solutions for conditionally rendering the card or a spinner/ loading text, including onload and useRef but due to my limited understanding and likely messy code I have not been able to get any of them to work. I understand that solutions are likely to involve setting a loading state but I have struggled to ascertain where exactly to set it.
I am sure there are many other issues with my code but I would hugely appreciate any help with this problem in particular.
import { useState, useEffect } from "react"

// Icon imports here
...

// Background imports here
...

function PokeCard(props) {
  const {pokeObj} = props
  const {pokemon, species, abilities} = pokeObj

  const [description, setDescription] = useState('')
  const [bgImage, setBgImage] = useState('')
  const [typeIcon, setTypeIcon] = useState('')
  const [circleColor, setCircleColor] = useState('')

  const [abilityArray, setAbilityArray] = useState([])

  useEffect(() => {
    if(pokeObj){
      if(pokemon.id>905){
        return
      }

      const flavorArray = species.flavor_text_entries
      const desc = flavorArray.filter(flavor => flavor.language.name==='en')
      let formattedDesc = desc[0].flavor_text
        .replace('',' ')
        .replace('\n', '')
        .replace(/\b[A-Z]+\b/g, (word) => word[0].toUpperCase() + word.slice(1).toLowerCase())
      setDescription(formattedDesc)

      const getTypeDecoration = () => {
        let bg
        let circ
        let icon
        switch (pokemon.types[0].type.name){
          case 'bug':
            bg = (bgGreen)
            circ = ("bg-green-700")
            icon = (FaBug)
            break
         // Other cases here
         ...

        }
        setBgImage(bg)
        setTypeIcon(icon)
        setCircleColor(circ)
      }
      getTypeDecoration()

      setAbilityArray([])
      const newAbilities = []
      for (const a of abilities){
        const abilityObj ={}

        const abilityArr = a.names
        const name = abilityArr.filter(name => name.language.name==='en')
        abilityObj.abilityName=name[0].name

        const abilityFlavorArray = a.flavor_text_entries
        const desc = abilityFlavorArray.filter(flavor => flavor.language.name==='en')
        let formattedDesc = desc[0].flavor_text
          .replace(/\b[A-Z]+\b/g, (word) => word[0].toUpperCase() + word.slice(1).toLowerCase())
          .replace('Pp', 'PP')
          .replace('Hp', 'HP')
        abilityObj.abilityDescription=formattedDesc
        newAbilities.push(abilityObj)

        setAbilityArray(newAbilities)
        console.log('done')

      }
    }

  },[pokeObj])

    return (

          {pokemon.id<=905 ?

              <div style={{ backgroundImage: `url(${bgImage})` }}className="card-inner p-3 bg-hero bg-no-repeat bg-cover bg-center">

{pokemon.name.charAt(0).toUpperCase() + pokemon.name.slice(1)}

#{pokemon.id}

                  <div className={`type-button w-fit h-fit p-1 rounded-full ml-1 ${circleColor}`}>
                    {typeIcon}

                    <img className="h-full mx-auto" src={`${pokemon.sprites.other['official-artwork'].front_default}`} alt={pokemon.name} />

                    <svg width="40" height="40" viewBox="30 0 350 350" className="inline">
                      <defs>
                        <path id="MyPath"
                              d="M 200, 200
                                m -100, 0
                                a 100,100 0 1,1 200,0
                                a 100,100 0 1,1 -200,0"
                        />
                      </defs>
                      <text className="text-[70px]">
                        <textPath xlinkHref="#MyPath">
                          GENERATION
                        </textPath>
                      </text>
                      <circle fill="black" cx="200" cy="200" r="80" strokeWidth="10" />
                      <text x="200" y="205"
                        textAnchor="middle"
                        stroke="white"
                        fill="white"
                        strokeWidth="1px"
                        alignmentBaseline="middle"
                        className="text-[90px]"
                      >
                        {species && species.generation.url.charAt(species.generation.url.length - 2)}
                      </text>
                    </svg>

Height: {pokemon.height/10}m, Weight: {pokemon.weight/10}kg

                  {
                    abilityArray && abilityArray.map((a) => {
                      return (
                        <>

                              {a.abilityName}
                              {a.abilityDescription}

                        </>
                      )
                    })
                  }

                  {description}

                  Pokémon and Pokémon character names are trademarks of Nintendo.

            :
            find &&
Oops! Couldn't find that Pokémon, sorry!

          }

    )
}

export default PokeCard


text:
Q: Maths for finding out when the bottom of the window is at an element So I am trying to create an event when an element is at the bottom of the window. Of course window sizes could be anything, so I am struggling here on how to work this out.
My current code goes like this, but doesnt really take into account any window size:
$(window).scroll(function(){
    win_height = $(window).height();
    scroll = $(window).scrollTop();
    pos = $('#home_process').offset().top;
    height = $('#home_intro_bg').height();
    //$('#header_logo').html(win_height+' '+scroll+' '+pos+' '+height);
    if(scroll > win_height-height) {
        $('#home_process_steps li').fadeIn();
    }
});

I want a code that essentially says this:
if #home_process becomes viewable within the window - do an action.
How can I work that out?

A: Please try this
$(window).scroll(function(){
    var $elem = $("#home_process");
    var $window = $(window);

    var docViewTop = $window.scrollTop();
    var docViewBottom = docViewTop + $window.height();

    var elemTop = $elem.offset().top;
    var elemBottom = elemTop + $elem.height();

    if((elemBottom <= docViewBottom) && (elemTop >= docViewTop)){
        alert(11)
    }
});

DEMO


text:
Q: ORACLE - Return cursor from stored procedure I need to return a cursor object from a stored procedure, but I need to process data first.
For example, let's consider this simple stored procedure:
create or replace PROCEDURE TEST
(
   query_str IN VARCHAR2,
   CURSOR_ OUT SYS_REFCURSOR
)
AS
BEGIN
   OPEN CURSOR_ FOR query_str;
END;

This procedure returns data as is, with no postprocessing.
The improvement I need is the following:

*

*process data coming from the execution of query_str;

*return the processed data in the form of a cursor.

Anyone could suggest me a way to accomplish this?
Thanks

A: It is difficult to do what you are suggesting with dynamic SQL (unless all the statements you are passing to the procedure all have a similar output format). If you can know what the SELECT will be then you can store it in a collection and process it:
CREATE TABLE TEST_DATA ( id, name, dt ) AS
  SELECT 1, 'A', SYSDATE FROM DUAL UNION ALL
  SELECT 2, 'B', DATE '2017-01-01' FROM DUAL;

CREATE TYPE processed_data_obj AS OBJECT(
  id   INTEGER,
  etag VARCHAR2(20)
);
/

CREATE OR REPLACE TYPE processed_data_table AS TABLE OF processed_data_obj;
/

CREATE OR REPLACE PROCEDURE TEST
(
   CURSOR_ OUT SYS_REFCURSOR
)
AS
  processed PROCESSED_DATA_TABLE;
BEGIN
  -- Process it in the select statement
  SELECT processed_data_obj(
           id,
           name || '_' || ROUND( ( dt - DATE '1970-01-01' ) * 24*60*60 )
         )
  BULK COLLECT INTO processed
  FROM  test_data;

  -- Process it more in PL/SQL
  FOR i IN 1 .. processed.COUNT LOOP
    processed[i].etag := processed[i].etag || '_' || i;
  END LOOP;

  OPEN cursor_out FOR
    SELECT *
    FROM   TABLE( processed );
END;
/


text:
Q: Cannot Parse JSON in UWP I created an application on UWP whose data is parsed to JSON with JSON as below:
JSON
I'm having trouble parsing json on "jawaban" and an error message appears like below:

Code:
JsonArray jsonDataOption = groupObjectSoal["jawaban"].GetArray();
                                    foreach (JsonValue groupValueOption in jsonDataSoal)
                                    {
                                        JsonObject groupObjectOption = groupValueSoal.GetObject();

                                        string oid = groupObjectOption["oid"].GetString();
                                        string option = groupObjectOption["q_option"].GetString();
                                        string score = groupObjectOption["score"].GetString();

                                        QuizOption pilihan = new QuizOption();
                                        pilihan.OID = oid;
                                        pilihan.Option = option;
                                        pilihan.Score = score;
                                    }

How to handle it?
Note:
For the full code, can be seen here

A: Property "list_soal" contains an array with two elements. The first element does not have property "jawaban", so your code fails on parsing first element

A: Use JSON.net
Newtonsoft
There are plenty examples on the site.
It will automatically fill your data model.
You can deserialize to object by calling.
YourObject m = JsonConvert.DeserializeObject<YourObject>(json);

where json is your json string and YourObject is your model


text:
Q: Definition of almost sure convergence from Casella & Berger In Casella and Berger, the definition of almost sure convergence of $\{X_n\}$ to $X$ is
$$P(\lim\limits_{n \rightarrow \infty}|X_n - X| < \epsilon) = 1$$
for all $\epsilon > 0$.
I cannot figure why the inequality is necessary? Why not define it as:
$$P(\lim\limits_{n \rightarrow \infty}|X_n - X| = 0) = 1$$
Assume some sequence is almost sure converges. Then, if there is some point in the sample space $s \in S$ such that the limit is not $0$, then there exists $\epsilon$ s.t. this limit is larger than this $\epsilon$. Thus, this $s$ must NOT belong to the subset of almost sure convergence. As such, we can remove all $s$ with limits which are not equal to zero. Thus, the second definition is created.
PS. Plz explain without measure theory. Set theory allowed ofc.


text:
Q: R read_excel readxl sometimes incorrectly converts numbers to dates When I use read_excel to import data from Excel to R, some numeric columns are automatically converted to dates.
# e.g.
5600 to 1915-05-01

Is there a way to turn of this feature? Other than using "col_types" argument in read_excel.

A: The readxl package, like readr for raw data files, has a type guesser to determine how to read columns in an Excel spreadsheet. As noted in the package vignette, the guessing process is not perfect, especially as it relates to date formats because they are stored as a special type of number.

As stated in the package documentation (as well as the comments on the OP), the way to avoid inaccurate guesses from the column type guesser is to explicitly specify the column types with the col_types argument on read_excel().


text:
Q: Involution of Legendre Family I'm trying to understand why automorphisms of elliptic curves lead to non-existance of the moduli space (as a variety). Some notes suggest to consider the following example:
Consider the Legendre family $X \to \mathbb{A}^1 \setminus \{0, 1\}$ given by $(x, y, z)$ goes to $z$ where $X$ is the subset of $\mathbb{A}^3$ given by $y^2=x(x-1)(x-z)$.  Fibers over $z$ and $1-z$ are isomorphic because they have the same $j$-invariant. Then they say that if such a moduli space exists then this involution should lift to the whole family which is not true. I have two questions: why should it lift and why doesn't it lift?


text:
Q: Error Unabled to add User controls to a form I get these two error messages, when trying to add a User Control to a Form.
Worked fine for long, no problems. Now the Design won't show the already added User Controls. Where is the problem? I've heard the Constructor must be untouched if possible and that is not the problem here.
Thanks in advance!
Error Message
Settings.settings
Referring to Settings property user
Second Error Message when no settings property used

A: Please Check the Settings Class because the user value is not retrieved.
Check the value of user.


text:
Q: image map in Slider of wowslider I want to Add image map on each slide in Slider that is generated by WowSlider.PFB code generated
function ws_blur(p,n,c){var h=jQuery;var b=!p.noCanvas&&!window.opera&&!!document.createElement("canvas").getContext;if(b){try{document.createElement("canvas").getContext("2d").getImageData(0,0,1,1)}catch(m){b=0}}var d;function k(q,e,r){q.css({opacity:0,visibility:"visible"});q.animate({opacity:1},e,"linear",r)}function i(q,e,r){q.animate({opacity:0},e,"linear",r)}var l;this.go=function(e,q){if(l){return -1}l=1;var u=h(n.get(q)),s=h(n.get(e));var t;if(b){if(!d){d='<canvas width="'+c.width()+'" height="'+c.height()+'"/>';d=h(d+d).css({"z-index":8,position:"absolute",width:"100%",height:"100%",left:0,top:0,visibility:"hidden"}).appendTo(c)}t=g(u,30,d.get(0))}if(b&&t){var r=g(s,30,d.get(1));k(t,p.duration/3,function(){c.find("ul").css({visibility:"hidden"});i(t,p.duration/6);k(r,p.duration/6,function(){t.css({visibility:"hidden"});c.find("ul").css({left:-e+"00%"}).css({visibility:"visible"});i(r,p.duration/2,function(){l=0})})})}else{b=0;t=g(u,8);t.fadeIn(p.duration/3,"linear",function(){c.find("ul").css({left:-e+"00%"});t.fadeOut(p.duration/3,"linear",function(){t.remove();l=0})})}return e};function g(v,u,q){var A=(parseInt(v.parent().css("z-index"))||0)+1;if(b){var D=q.getContext("2d");D.drawImage(v.get(0),0,0);if(!j(D,0,0,q.width,q.height,u)){return 0}return h(q)}var E=h("

").css({position:"absolute","z-index":A,left:0,top:0,width:"100%",height:"100%",display:"none"}).appendTo(c);var C=(Math.sqrt(5)+1)/2;var s=1-C/2;for(var t=0;s*t<u;t++){var w=Math.PI*C*t;var e=(s*t+1);var B=e*Math.cos(w);var z=e*Math.sin(w);h(document.createElement("img")).attr("src",v.attr("src")).css({opacity:1/(t/1.8+1),position:"absolute","z-index":A,left:Math.round(B)+"px",top:Math.round(z)+"px",width:"100%",height:"100%"}).appendTo(E)}return E}var o=[512,512,456,512,328,456,335,512,405,328,271,456,388,335,292,512,454,405,364,328,298,271,496,456,420,388,360,335,312,292,273,512,482,454,428,405,383,364,345,328,312,298,284,271,259,496,475,456,437,420,404,388,374,360,347,335,323,312,302,292,282,273,265,512,497,482,468,454,441,428,417,405,394,383,373,364,354,345,337,328,320,312,305,298,291,284,278,271,265,259,507,496,485,475,465,456,446,437,428,420,412,404,396,388,381,374,367,360,354,347,341,335,329,323,318,312,307,302,297,292,287,282,278,273,269,265,261,512,505,497,489,482,475,468,461,454,447,441,435,428,422,417,411,405,399,394,389,383,378,373,368,364,359,354,350,345,341,337,332,328,324,320,316,312,309,305,301,298,294,291,287,284,281,278,274,271,268,265,262,259,257,507,501,496,491,485,480,475,470,465,460,456,451,446,442,437,433,428,424,420,416,412,408,404,400,396,392,388,385,381,377,374,370,367,363,360,357,354,350,347,344,341,338,335,332,329,326,323,320,318,315,312,310,307,304,302,299,297,294,292,289,287,285,282,280,278,275,273,271,269,267,265,263,261,259];var a=[9,11,12,13,13,14,14,15,15,15,15,16,16,16,16,17,17,17,17,17,17,17,18,18,18,18,18,18,18,18,18,19,19,19,19,19,19,19,19,19,19,19,19,19,19,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24];function j(ah,P,N,q,r,Y){if(isNaN(Y)||Y<1){return}Y|=0;var ac;try{ac=ah.getImageData(P,N,q,r)}catch(ag){console.log("error:unable to access image data: "+ag);return false}var v=ac.data;var W,V,ae,ab,E,H,B,t,u,M,C,O,K,S,X,F,A,G,I,R;var af=Y+Y+1;var T=q<<2;var D=q-1;var aa=r-1;var z=Y+1;var Z=z*(z+1)/2;var Q=new f();var L=Q;for(ae=1;ae<af;ae++){L=L.next=new f();if(ae==z){var w=L}}L.next=Q;var ad=null;var U=null;B=H=0;var J=o[Y];var s=a[Y];for(V=0;V<r;V++){S=X=F=t=u=M=0;C=z*(A=v[H]);O=z*(G=v[H+1]);K=z*(I=v[H+2]);t+=Z*A;u+=Z*G;M+=Z*I;L=Q;for(ae=0;ae<z;ae++){L.r=A;L.g=G;L.b=I;L=L.next}for(ae=1;ae<z;ae++){ab=H+((D<ae?D:ae)<<2);t+=(L.r=(A=v[ab]))*(R=z-ae);u+=(L.g=(G=v[ab+1]))*R;M+=(L.b=(I=v[ab+2]))*R;S+=A;X+=G;F+=I;L=L.next}ad=Q;U=w;for(W=0;W<q;W++){v[H]=(t*J)>>s;v[H+1]=(u*J)>>s;v[H+2]=(M*J)>>s;t-=C;u-=O;M-=K;C-=ad.r;O-=ad.g;K-=ad.b;ab=(B+((ab=W+Y+1)<D?ab:D))<<2;S+=(ad.r=v[ab]);X+=(ad.g=v[ab+1]);F+=(ad.b=v[ab+2]);t+=S;u+=X;M+=F;ad=ad.next;C+=(A=U.r);O+=(G=U.g);K+=(I=U.b);S-=A;X-=G;F-=I;U=U.next;H+=4}B+=q}for(W=0;W<q;W++){X=F=S=u=M=t=0;H=W<<2;C=z*(A=v[H]);O=z*(G=v[H+1]);K=z*(I=v[H+2]);t+=Z*A;u+=Z*G;M+=Z*I;L=Q;for(ae=0;ae<z;ae++){L.r=A;L.g=G;L.b=I;L=L.next}E=q;for(ae=1;ae<=Y;ae++){H=(E+W)<<2;t+=(L.r=(A=v[H]))*(R=z-ae);u+=(L.g=(G=v[H+1]))*R;M+=(L.b=(I=v[H+2]))*R;S+=A;X+=G;F+=I;L=L.next;if(ae<aa){E+=q}}H=W;ad=Q;U=w;for(V=0;V<r;V++){ab=H<<2;v[ab]=(t*J)>>s;v[ab+1]=(u*J)>>s;v[ab+2]=(M*J)>>s;t-=C;u-=O;M-=K;C-=ad.r;O-=ad.g;K-=ad.b;ab=(W+(((ab=V+z)<aa?ab:aa)*q))<<2;t+=(S+=(ad.r=v[ab]));u+=(X+=(ad.g=v[ab+1]));M+=(F+=(ad.b=v[ab+2]));ad=ad.next;C+=(A=U.r);O+=(G=U.g);K+=(I=U.b);S-=A;X-=G;F-=I;U=U.next;H+=q}}ah.putImageData(ac,P,N);return true}function f(){this.r=0;this.g=0;this.b=0;this.a=0;this.next=null}};// -----------------------------------------------------------------------------------

    jQuery("#wowslider-container1").wowSlider({effect:"blur",prev:"",next:"",duration:60*100,delay:60*100,width:960,height:360,autoPlay:true,stopOnHover:true,loop:false,bullets:0,caption:true,captionEffect:"slide",controls:true,onBeforeStep:0,images:[{src:"./collage.png",title:"IaaS",usemap:"#1"},{src:"./collage_DBaas.png",title:"DBaaS"},{src:"./collage_Paas.png",title:"PaaS"},{src:"./collage_Saas.png",title:"SaaS"}]});

html code

<map name="1" id="1">

<area shape="rect" coords="12,5,384,135" href="http://aws.amazon.com" />
<area shape="rect" coords="27,140,128,191" href="http://lunacloud.com" />
<area shape="rect" coords="187,147,339,199" href="http://hpcloud.com" />
<area shape="rect" coords="7,202,355,294" href="http://rackspace.com" />
<area shape="rect" coords="388,3,733,100" href="http://linode.com" />
<area shape="rect" coords="399,112,681,194" href="http://joyent.com" />
<area shape="rect" coords="419,222,670,290" href="http://reliacloud.com" />
<area shape="rect" coords="740,42,947,240" href="http://appengine.google.com" />
<area shape="rect" coords="702,245,932,287" href="http://opsource.com" />
<area shape="rect" coords="685,181,738,236" href="http://appengine.google.com" />
</map>

Any help is  appreciated


text:
Q: Spring Boot GzipResourceResolver with IE 11 not working I have a Spring boot based application and my resource handler registry is configured as below
    registry.addResourceHandler("/resources/**")
            .addResourceLocations("classpath:static/")
            .setCachePeriod(365 * 24 * 60 * 60)
            .resourceChain(true)

            .addResolver(new GzipResourceResolver())
            .addResolver(new VersionResourceResolver()
                            .addFixedVersionStrategy("dev", "/**/*.js", "/**/*.map")
                            .addContentVersionStrategy("/**")
                        )

            .addTransformer(new CssLinkResourceTransformer())
            .addTransformer(new AppCacheManifestTransformer());

I have a js file named app.min.js and on the same folder there is also a app.min.js.gz file available.
When accessed from Chrome (v43) the GZ file is served correctly.
But, when accessed from IE 11, though the request header has an accept-encoding of "gzip,deflate", the application still sends a .min.js file instead of .min.js.gz file.
Any idea on why this error would occur?
Thanks!


text:
Q: Special sectioning requirements I'm writing a book chapter and the editor has some specific formatting requirements.  In particular, he wants the section titles to be centered and not bold.  I'm using titlesec with:
\titleformat{\section}
  {\normalfont\fontfamily{cm}\fontsize{16}{19}\selectfont}{\thesection}{1em}{}

This ensures the section title is not bold.  To make it centered, I did:
\titleformat{\section}
  \centering{{\normalfont\fontfamily{cm}\fontsize{16}{19}\selectfont}{\thesection}}{1em}{}

However, this somehow ignores the fontsize, resulting in a unbolded, centered, but small font sized section title.  How can I ensure the fontsize is larger, as indicated in the command?

A: Your syntax is wrong; here is a more correct one. The arguments to \titleformat needn't be specified in this format, but this I find it more readable to keep each one in a separate line.
\documentclass{book}
\usepackage{lmodern}
\usepackage{titlesec}

\titleformat{\section}
 {\centering\normalfont\fontsize{16}{19}\selectfont}
 {\thesection}
 {1em}
 {}

\begin{document}
\chapter{First}
\section{A title}
\end{document}

I added \usepackage{lmodern} in order to have arbitrarily scalable fonts. Note that giving \fontfamily is redundant, because \normalfont already sets the default font family.


text:
Q: Finite Element method Implementation I have written a program for the finite element method for an elliptic one dimensional problem.Initially I assumed a mesh that had only 10 points , but since the error was far above my tolerance level, I changed my mesh size to 30 points.But while applying the FEM for the mesh with 30 points , I had to run my program all over again with N=30.
My question is -:
 Even though I have found the exact values of the solution at 10 points( for FEM for 1d case ,the fem solution can be proved to be exactly the actual solution at the nodal points), why should I start the process all over again and find values at 30 nodal points.Why can't I do it for just the newly added 20 nodal points.Is there a way to do so?

A: When you apply the FEM to a differential equation, you first write the problem in the weak/variational form, for a narrower solution space, for example
$${V} = \{ { \omega :| \omega  | +  |\omega ' | < \infty } \}.$$
Then, to actually solve the problem, you have to discretize that solution space, i.e., you have consider a finite subspace of the solution space. Most likely, you decide to consider your solution as a linear combination of hat functions and hence
$V_h = \left\{ {{\omega _h} \in V:{\omega _h}{\textrm{ is piecewise linear, continuous on the chosen mesh}}}\right\}$
and the basis of this space consists of $\{\varphi_j\}^{N}_{j=1}$, where
$${\varphi _j}\left( x \right) = \left\{ {\begin{array}{*{20}{c}}{\frac{{x - {x_{j - 1}}}}{h}}&{,x \in [{x_{j - 1}},{x_j}]}\\{\frac{{{x_{j + 1}} - x}}{h}}&{,x \in [{x_j},{x_{j + 1}}]}\\0&{,x \notin [{x_{j - 1}},{x_{j + 1}}]}\end{array}} \right. , j=1,\cdots ,N.$$
At this point, I hope you've already figured out the answer to your question :)
Each time you modify your mesh, you also modify your hat functions, that is, the basis of your discrete solution space. Thus, to find your new solution in the new basis, you have to perform the calculations all over again.
-EDIT-
If you're looking for a method that allows you to avoid computing your solution all over again, then you should read about Structure Adaptive Mesh Refinement (SAMR) used within the finite difference method (FDM) framework.
A good way to get a grasp of the concept is by reading the following master thesis:
"A patch-based partitioner for
Structured Adaptive Mesh Refinement" by A. Vakili


text:
Q: Row colour change based on text in a cell How do I change the whole row's colour if one of the cells (C3) is "YES", then also the same row a second colour if that cell is "no", a third colour if that cell is "maybe" and then no colour if nothing is in that cell?

A: Select the whole worksheet, Go to Home > Conditional Formatting.
Choose New Rule. Formula type choose "Use a formula to determine which cells to format".
In the Rule type =$C1="NO" assuming that column C contains the value, then press Format and choose your formatting options.
Repeat New Rule for Yes and Maybe.

A: Is the Cell C3 fixed in your sample?
This is a sample if you only need to confirm value in column C for Row 3:
"Yes" color: Red
"No" color: Yellow
"Maybe" color: Blue
Set 3 rules from Row 3 with formula:
=$C$3="Yes"
=$C$3="No"
=$C$3="Maybe"


text:
Q: Threaded reading of files in C++ I have written a program (using FFTW) to perform Fourier transforms of some data files written in OpenFOAM.
The program first finds the paths to each data file (501 files in my current example), then splits the paths between threads, such that thread0 gets paths 0->61, thread1 gets 62-> 123 or so, etc, and then runs the remaining files in serial at the end.
I have implemented timers throughout the code to try and see where it bottlenecks, since run in serial each file takes around 3.5s and for 8 files in parallel the time taken is around 21s (a reduction from the 28s for 8x3.5 (serial time), but not by so much)
The problematic section of my code is below
if (DIAG_timers) {readTimer = timerNow();}
for (yindex=0; yindex<ycells; yindex++)
{
    for (xindex=0; xindex<xcells; xindex++)
    {
        getline(alphaFile, alphaStringValue);
        convertToNumber(alphaStringValue, alphaValue[xindex][yindex]);
    }
}
if (DIAG_timers) {endTimerP(readTimer, tid, "reading value and converting", false);}

Here, timerNow() returns the clock value, and endTimerP calculates the time that has passed in ms. (The remaining arguments relate to it running in a parallel thread, to avoid outputting 8 lines for each loop etc, and a description of what the timer measures).
convertToNumber takes the value on alphaStringValue, and converts it to a double, which is then stored in the alphaValue array.
alphaFile is a std::ifstream object, and alphaStringValue is a std::string which stores the text on each line.
The files to be read are approximately 40MB each (just a few lines more than 5120000, each containing only one value, between 0 and 1 (in most cases == (0||1) ), and I have 16GB of RAM, so copying all the files to memory would certainly be possible, since only 8 (1 per thread) should be open at once. I am unsure if mmap would do this better? Several threads on stackoverflow argue about the merits of mmap vs more straightforward read operations, in particular for sequential access, so I don't know if that would be beneficial.
I tried surrounding the code block with a mutex so that only one thread could run the block at once, in case reading multiple files was leading to slow IO via vaguely random access, but that just reduced the process to roughly serial-speed times.
Any suggestions allowing me to run this section more quickly, possibly via copying the file, or indeed anything else, would be appreciated.
Edit:
template<class T> inline void convertToNumber(std::string const& s, T &result)
{
    std::istringstream i(s);
    T x;
    if (!(i >> x))
        throw BadConversion("convertToNumber(\"" + s + "\")");
    result = x;
}

turns out to have been the slow section. I assume this is due to the creation of 5 million stringstreams per file, followed by the testing of 5 million if conditions? Replacing it with TonyD's suggestion presumably removes the possibility of catching an error, but saves a vast number of (at least in this controlled case) unnecessary operations.

A:
The files to be read are approximately 40MB each (just a few lines more than 5120000, each containing only one value, between 0 and 1 (in most cases == (0||1) ), and I have 16GB of RAM, so copying all the files to memory would certainly be possible,

Yes. But loading them there will still count towards your process' wall clock time unless they were already read by another process short before.

since only 8 (1 per thread) should be open at once.

Since any files that were not loaded in memory before the process started will have to be loaded and thus the loading will count towards the process wall clock time, it does not matter how many are open at once. Any that are not cache will slow down the process.

I am unsure if mmap would do this better?

No, it wouldn't. mmap is faster, but because it saves the copy from kernel buffer to application buffer and some system call overhead (with read you do a kernel entry for each page while with mmap pages that are read with read-ahead won't cause further page faults). But it will not save you the time to read the files from disk if they are not already cached.
mmap does not load anything in memory. The kernel loads data from disk to internal buffers, the page cache. read copies the data from there to your application buffer while mmap exposes parts of the page cache directly in your address space. But in either case the data are fetched on first access and remain there until the memory manager drops them to reuse the memory. The page cache is global, so if one process causes some data to be cached, next process will get them faster. But if it's first access after longer time, the data will have to be read and this will affect read and mmap exactly the same way.
Since parallelizing the process didn't improve the time much, it seems majority of the time is the actual I/O. So you can optimize a bit more and mmap can help, but don't expect much. The only way to improve I/O time is to get a faster disk.

You should be able to ask the system to tell you how much time was spent on the CPU and how much was spent waiting for data (I/O) using getrusage(2) (call it at end of each thread to get data for that thread). So you can confirm how much time was spent by I/O.

A: mmap is certainly the most efficient way to get large amounts of data into memory. The main benefit here is that there is no extra copying involved.
It does however make the code slightly more complex, since you can't directly use the file I/O functions to use mmap (and the main benefit is sort of lost if you use "m" mode of stdio functions, as you are now getting at least one copy). From past experiments that I've made, mmap beats all other file reading variants by some amount. How much depends on what proportion of the overall time is spent on waiting for the disk, and how much time is spent actually processing the file content.


text:
Q: ProgressBar Update in two Activities I have two Activities, BookStoreActivity and BookDetailActivity. In BookStoreActivity, when I click on BookItem, it will go to BookDetailActivity. In BookDetailActivity, when I click "Download" book, it will show download progress in BookDetailActivity.
I also want to show progress update in BookItem's of BookStoreActivity. The two progress update must be the same. Now I'm using AsyncHttpClient from loopj.com. It is look like Google Play App Downloading process.
Please see the image: http://i.stack.imgur.com/5F5g1.png. First is App's Detail and Second is My AppList, I want to like that.


text:
Q: Size of typedef does not change after malloc I have a small code that starts an rtsp server. After I start a specific server I add the information regarding to the server such as its processor id (because I start each server as a sub-process), what kind of source it has, port and mounting point name to an array of struct which I call rtsp_server_list. I have a static int server_count = 1 at the beginning of code which increases by 1 whenever I add a new server. So my add_server() function is as follows:
struct rtsp_server_list* add_server() {

    char  *port, *mountName, *source;
    pid_t child_process_id;
    printf("Server count: %d\n", server_count);
    struct rtsp_server_list *server = malloc(server_count*sizeof(struct rtsp_server_list));
    printf("Size of server list: %lu\n", sizeof(server));

    source = malloc(256);
    port = malloc(256);
    mountName = malloc(256);
    g_print("Enter a source: ");
    scanf("%255s", source);
    g_print("Enter a port: ");
    scanf("%255s", port);
    g_print("Enter a mount name: ");
    scanf("%255s", mountName);
    child_process_id = fork();
    if (child_process_id < 0) {
        perror("Fork for child failed.\n");
    } else if (child_process_id == 0) {
        g_print("Child process... \n");
        execl("/home/tunc/workspace/gstreamer_rtsp_server/Debug/gstreamer_rtsp_server", "/home/tunc/workspace/gstreamer_rtsp_server/Debug/gstreamer_rtsp_server", source, port, mountName, NULL);
    } else {
        g_print("Child created, child is running.\n");
    }
    server[server_count-1].source = strdup(source);
    server[server_count-1].mountName = strdup(mountName);
    server[server_count-1].port = strdup(port);
    server[server_count-1].process_id = child_process_id;
    server_count++;
    // wait a bit to not mess the console outputs.
    sleep(1);
    return server;
}

In the above code, size of *server never changes, it always stays at 8 bytes. But when I add a server server count increases by 1 so if I happen to add a 2nd server, *server should have size 16. Is it because I don't allocate memory for the char arrays in the struct? My struct is as follows:
struct rtsp_server_list {
    char *source;
    char *mountName;
    char *port;
    pid_t process_id;
} rtsp_server_list;

I also have a code that removes an rtsp server by terminating its process but I am also not able to update the list in the way that I want. So what I am doing wrong? I tried doing these with realloc but results are exactly same.

A: sizeof(server) will give the size of the pointer, not the total size of the array.
It is implementation dependent (8 bytes in your case)


text:
Q: C# Getting StreamWriter to Write to text file I have reviewed my Professor's lecture numerous times, reviewed the text book, searched endlessly online for answers, and tried every reasonable suggested fix out there.  I am certainly missing something.  The address book writes to the list box, the file is created, but the name and address is not written to the file.  Any help with what I am missing would be greatly appreciated.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.IO;

namespace LAB7A
{
    public partial class Form1 : Form
    {

        public Form1()
        {
            InitializeComponent();
        }

        List<Person> people = new List<Person>();
        class Person
        {
            public string Name
            {
                get;
                set;
            }

            public string Email
            {
                get;
                set;
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {

            try
            {
               StreamWriter address = new StreamWriter("addressbook.txt");
               address.WriteLine(textBox1.Text, textBox2.Text);
            }
            catch (DirectoryNotFoundException exc)
            {
                MessageBox.Show("Directory Could Not Be Found");
            }
        }

        private void button1_Click(object sender, System.EventArgs e)

        {

            Person p = new Person();
            p.Name = textBox1.Text;
            p.Email = textBox2.Text;
            people.Add(p);
            listBox1.Items.Add(p.Name);
            listBox1.Items.Add(p.Email);

            //StreamWriter address.WriteLine(textBox1.Text);
            //address.WriteLine(textBox2.Text);
            //listBox1.Items.Add(textBox1.Text);
            //listBox1.Items.Add(textBox2.Text);
        }

        private void listBox1_SelectedIndexChanged(object sender, System.EventArgs e)
        {

        }
    }
}

A: You are saving data to file on form load when all fields are empty. Move writing code to some button click handler after you have chance to type values in the text fields.
You are also using version of TextWriter.WriteLine method that take format as first argument. Unless you really want to do that either 2 separate WriteLine calls or one with correct format string would probably do what you want.
Also make sure to close/dispose your stream writer so it commits changes to file and closes the file. Usual way to do that is to use using:
using (var writer = new StreamWriter("addressbook.txt"))
{
     writer.WriteLine("First textbox:{0}, second:{1}", textBox1.Text, textBox2.Text);
}

A: Try either calling Flush or Close on the stream.  Best practice is to wrap it in a using though.
using(StreamWriter address = new StreamWriter("addressbook.txt"))
{
    ...
}

http://msdn.microsoft.com/en-us/library/system.io.streamwriter.aspx
Scroll down to the example code.

A: You forgot to add complete address,try this:
 private void Window_Loaded(object sender, RoutedEventArgs e)
    {

        try
        {

           using (StreamWriter address = new StreamWriter("d:\\addressbook.txt"))//Add correct address
            {
              address.WriteLine(textBox1.Text + textBox2.Text);
              //OR
              address.WriteLine(string.Format("Name:{0}, Email:{1}", textBox1.Text,    textBox2.Text));
            }
        }
        catch (DirectoryNotFoundException exc)
        {
            MessageBox.Show("Directory Could Not Be Found");
        }
    }


text:
Q: what's the stack space of this code? The question is to check if a Tree is a valid BST. There are two recursive method to solve. I think their space complexity both are O(logN), N is the number of TreeNode, so logN is actually the height of tree. But in a solution book, it said the stack space is O(N), I can't figure out. Could anyone help me? Thanks!
public class Solution {
        public boolean isValidBST(TreeNode root) {
            return isValidBST(root, null, null);
        }

        private boolean isValidBST(TreeNode x, Integer min, Integer max) {
            return x == null || (min == null || x.val > min) && (max == null || x.val < max) &&
                                isValidBST(x.left, min, x.val) && isValidBST(x.right, x.val, max);
        }
    }

public class Solution {
    private TreeNode prev;

    public boolean isValidBST(TreeNode root) {
        prev = null;
        return isMonotonicIncreasing(root);
    }

    private boolean isMonotonicIncreasing(TreeNode p) {
        if (p == null)  return true;
        if (isMonotonicIncreasing(p.left)) {
            if (prev != null && p.val <= prev.val) return false;
            prev = p;
            return isMonotonicIncreasing(p.right);
        }

        return false;
    }
}

A: Space requirements will be O(h), where h is the height of the tree.
Log(n) is the best case for this code when the tree is balanced.
But in case of skewed trees the space complexity will be O(n) i.e. linear.
For example, for following trees, the code will take Exactly S(n) space:
               1                            5
                 2                        4
                   3                    3
                     4                2
                       5            1


text:
Q: Get the first and last names of all employee who entered the project at the same time as at least one other employee SELECT
    EmpFname
    ,EmpLname
FROM
    Employee_m
WHERE
    (
    SELECT
        COUNT (w1.EnterDate)
    FROM
        WorksOn_m w1,WorksOn_m w2
    WHERE
        w1.EnterDate = w2.EnterDate
    ) >= 1

I tried this but the output gives all the names as the same row is compared. Any way around this?
my data:

A: You are missing conditions that say that the employee is working on the project in w1, and that the project in w2 is the same as the project in w1 but that the employee in w2 is not the same as the employee in w1.
The reason you get all rows is because the where condition always evaluates to true, for all employees. That is because the sub query simply asks for at least one row that has the same date in both w1 and w2. Consider that WorksOn_m has only one row:

WorksOn_m
  -------------- EnterDate 12/03/2014

Is there a record in both w1 and w2 with the date 12/03/2014? Yes, because they're the same table. Are you applying any other conditions in the WHERE clause? No. So you'll get all employees, because you're basically saying "Give me all employees WHERE 1=1".

A: You will have to fill in the join condition since your post does not reveal those details:
SELECT EmpFname, EmpLname
FROM (
    SELECT EmpFname
         , EmpLname
         , row_number() over (order by EnterDate asc) as r1
         , row_number() over (order by EnterDate desc) as r2
    FROM Employee_m
    JOIN WorksOn_m
        ON ...
) AS T
WHERE 1 IN (r1,r2)


text:
Q: Discord bot TypeError. Can't connect it to my server I am trying to make a Discord bot that sends a specific message ("!clean") to a specified text channel on Discord every 30 minutes or something like that. I've run into a bunch of problems, and this is the furthest I've gotten.
I get this error:
TypeError: Cannot read property 'find' of undefined
This is what happens when I try to start the bot:

My Code
No, I did not write any of the code myself... This is my first time ever using JS. I copied someone else's code and combined it.

*

*I use Node 14.4.0

Edit: All I want to do is to make a simple bot that sends a message to a specific text channel, the message being "!clean" every 30 minutes. My attempts have all failed miserably.
Thanks for your assistance!

A: Tad late, but when working with Eris, you cannot that easily access every channel from the Client. You can instead use Client.getChannel(<ChannelID>). If you must filter all channels, you can use Client.channelGuildMap which returns an Object of Guild IDs and their Channel IDs.
If the Channel ID changes based on what the user gives, make sure to check if the Channel allows sending messages!
(Be sure to replace Client with whatever your bot variable is :>)
EDIT: Keep in mind this as well: Bots ignore other bot accounts usually by design. To be on the safe side, you would have to make your own message purge command yourself. If this bot is running on a User account and not a bot account, I'd advise against that as you could be banned from Discord entirely.