text:
Q: Find out from weather data whether there was a tropical night I have a lot of weather data, where I have the temperature every hour. Now I want to find out whether there was a tropical night in the whole last month.
Definition from tropic night:

"A tropical night is a night in which the lowest air temperature does not drop below 20°C between 6pm and 6am"

To find out when a tropic night was, I have to check the temperature over 2 days (from 6pm from day 1 to 6am from day 2). So how can I reach this in MySLQ?
The table looks like follow:
CREATE TABLE `temperature` (
  `id` int(11) NOT NULL,
  `location` int(11) NOT NULL,
  `temperature` double NOT NULL,
  `timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

INSERT INTO `temperature` (`id`, `location`, `temperature`, `timestamp`) VALUES
(1, 1, 19.1, '2020-07-24 18:00:02'),
(2, 1, 17.8, '2020-07-24 19:00:02'),
(3, 1, 16.4, '2020-07-24 20:00:02'),
(4, 1, 16.2, '2020-07-24 21:00:02'),
(5, 1, 16.2, '2020-07-24 22:00:02'),
(6, 1, 15.7, '2020-07-24 23:00:02'),
(7, 1, 15.4, '2020-07-25 00:00:02'),
(8, 1, 15.5, '2020-07-25 01:00:02'),
(9, 1, 15.9, '2020-07-25 02:00:02'),
(10, 1, 15.5, '2020-07-25 03:00:01'),
(11, 1, 15, '2020-07-25 04:00:02'),
(12, 1, 14.4, '2020-07-25 05:00:02'),
(13, 1, 16.5, '2020-07-25 06:00:01'),
(14, 1, 24.8, '2020-07-25 07:00:01'),
(15, 1, 26.7, '2020-07-25 08:00:02'),
(16, 1, 32.5, '2020-07-25 09:00:02'),
(17, 1, 30.3, '2020-07-25 10:00:02'),
(18, 1, 30.7, '2020-07-25 11:00:02'),
(19, 1, 29.3, '2020-07-25 12:00:02'),
(20, 1, 30.4, '2020-07-25 13:00:01'),
(21, 1, 27.8, '2020-07-25 14:00:02'),
(22, 1, 27.1, '2020-07-25 15:00:02'),
(23, 1, 28, '2020-07-25 16:00:02'),
(24, 1, 27.1, '2020-07-25 17:00:02'),
(25, 1, 27.6, '2020-07-25 18:00:01'),
(26, 1, 24.1, '2020-07-25 19:00:01'),
(27, 1, 21.7, '2020-07-25 20:00:02'),
(28, 1, 20.7, '2020-07-25 21:00:02'),
(29, 1, 20.3, '2020-07-25 22:00:02'),
(30, 1, 19.2, '2020-07-25 23:00:02'),
(31, 1, 18.8, '2020-07-26 00:00:02'),
(32, 1, 18.9, '2020-07-26 01:00:02'),
(33, 1, 18.6, '2020-07-26 02:00:02'),
(34, 1, 18.6, '2020-07-26 03:00:02'),
(35, 1, 18.7, '2020-07-26 04:00:01'),
(36, 1, 18, '2020-07-26 05:00:02'),
(37, 1, 18.3, '2020-07-26 06:00:02'),
(38, 1, 25.4, '2020-07-26 07:00:02'),
(39, 1, 26.3, '2020-07-26 08:00:02'),
(40, 1, 32.7, '2020-07-26 09:00:02'),
(41, 1, 31.2, '2020-07-26 10:00:01'),
(42, 1, 31.2, '2020-07-26 11:00:02'),
(43, 1, 29.1, '2020-07-26 12:00:02'),
(44, 1, 27.9, '2020-07-26 13:00:02'),
(45, 1, 27.2, '2020-07-26 14:00:02'),
(46, 1, 28.6, '2020-07-26 15:00:02'),
(47, 1, 28.5, '2020-07-26 16:00:02'),
(48, 1, 26.3, '2020-07-26 17:00:02'),
(49, 1, 26, '2020-07-26 18:00:02'),
(50, 1, 24.5, '2020-07-26 19:00:02'),
(51, 1, 21.2, '2020-07-26 20:00:02'),
(52, 1, 20.4, '2020-07-26 21:00:02'),
(53, 1, 19.7, '2020-07-26 22:00:02'),
(54, 1, 18.3, '2020-07-26 23:00:02'),
(55, 1, 17.9, '2020-07-27 00:00:02'),
(56, 1, 16.9, '2020-07-27 01:00:02'),
(57, 1, 16.3, '2020-07-27 02:00:01'),
(58, 1, 16, '2020-07-27 03:00:02'),
(59, 1, 15.7, '2020-07-27 04:00:02'),
(60, 1, 15.6, '2020-07-27 05:00:02'),
(61, 1, 16.2, '2020-07-27 06:00:02'),
(62, 1, 29.8, '2020-07-27 07:00:02'),
(63, 1, 32.4, '2020-07-27 08:00:02'),
(64, 1, 37.9, '2020-07-27 09:00:02'),
(65, 1, 35.1, '2020-07-27 10:00:02'),
(66, 1, 33.1, '2020-07-27 11:00:02'),
(67, 1, 34.5, '2020-07-27 12:00:02'),
(68, 1, 32, '2020-07-27 13:00:02'),
(69, 1, 29.5, '2020-07-27 14:00:02'),
(70, 1, 29.7, '2020-07-27 15:00:02'),
(71, 1, 31, '2020-07-27 16:00:01'),
(72, 1, 30.8, '2020-07-27 17:00:02'),
(73, 1, 30.4, '2020-07-27 18:00:02'),
(74, 1, 29.6, '2020-07-27 19:00:02'),
(75, 1, 26.1, '2020-07-27 20:00:01'),
(76, 1, 25.3, '2020-07-27 21:00:02'),
(77, 1, 23.7, '2020-07-27 22:00:02'),
(78, 1, 22.8, '2020-07-27 23:00:02'),
(79, 1, 23, '2020-07-28 00:00:02'),
(80, 1, 22.9, '2020-07-28 01:00:02'),
(81, 1, 22.9, '2020-07-28 02:00:01'),
(82, 1, 22.2, '2020-07-28 03:00:02'),
(83, 1, 22.3, '2020-07-28 04:00:02'),
(84, 1, 21.5, '2020-07-28 05:00:02'),
(85, 1, 22.1, '2020-07-28 06:00:02'),
(86, 1, 32.8, '2020-07-28 07:00:02'),
(87, 1, 33.4, '2020-07-28 08:00:02'),
(88, 1, 36.2, '2020-07-28 09:00:02'),
(89, 1, 37, '2020-07-28 10:00:02'),
(90, 1, 31.3, '2020-07-28 11:00:02'),
(91, 1, 34.2, '2020-07-28 12:00:01'),
(92, 1, 33.9, '2020-07-28 13:00:02'),
(93, 1, 33.3, '2020-07-28 14:00:02'),
(94, 1, 31.6, '2020-07-28 15:00:02'),
(95, 1, 32.3, '2020-07-28 16:00:02'),
(96, 1, 29.2, '2020-07-28 17:00:02'),
(97, 1, 28.5, '2020-07-28 18:00:02'),
(98, 1, 26.7, '2020-07-28 19:00:01'),
(99, 1, 24.4, '2020-07-28 20:00:01'),
(100, 1, 21.9, '2020-07-28 21:00:02'),
(101, 1, 22.9, '2020-07-28 22:00:02'),
(102, 1, 22.5, '2020-07-28 23:00:01'),
(103, 1, 21.9, '2020-07-29 00:00:02'),
(104, 1, 21.2, '2020-07-29 01:00:02'),
(105, 1, 20.5, '2020-07-29 02:00:01'),
(106, 1, 19.7, '2020-07-29 03:00:02'),
(107, 1, 19, '2020-07-29 04:00:02'),
(108, 1, 18.8, '2020-07-29 05:00:02'),
(109, 1, 19, '2020-07-29 06:00:01'),
(110, 1, 18.8, '2020-07-29 07:00:02'),
(111, 1, 18.9, '2020-07-29 08:00:02');

Just one night from 2020-07-27 (6pm) to 2020-07-28 (6am) was a tropic night in the data from my database.
To show the data from my database, I have create a SQLFIDDLE.
My desired result:
My favourite statement where, do show the date from each tropical night per month:

The night from 2020-07-27 to 2020-07-28 was a tropical night with a min temperature from 21.5°C.

So I will as output the both dates where the tropical night is and the min temperature in this night.
But I don't know how can I check from each day per month at 6pm to each next day at 6am to check the temperature.
Thanks for any helpful answer!

A: Normally, you'd do the presentation stuff in application code, but just for fun...:
SELECT CONCAT_WS(' '
                ,'The night from'
                ,DATE(timestamp)
                ,'to'
                ,DATE(timestamp+INTERVAL 1 DAY)
                ,'was a tropical night with a min temperature from'
                ,CONCAT(MIN(temperature),'°C')
                ) x
             FROM temperature
            WHERE TIME(timestamp) NOT BETWEEN '06:00:01' AND '17:59:59'
            GROUP
               BY DATE(timestamp+INTERVAL 12 HOUR)
           HAVING MIN(temperature) >= 20;

+-------------------------------------------------------------------------------------------------+
| x                                                                                |
+-------------------------------------------------------------------------------------------------+
| The night from 2020-07-27 to 2020-07-28 was a tropical night with a min temperature from 21.5°C |
+-------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)

In more recent versions of MySQL, it's possible that strict mode needs to be disabled for this to work.

A: select
    location,
    date(date_sub(`timestamp`, interval 7 hour)) tropical_night,
    min(temperature) min_tempurature
from temperature
where time(`timestamp`) not between '6:00:01' and '17:59:59'
group by location, tropical_night
having min_tempurature >= 20

I'm not clear on how month factors into it, perhaps you need to add a where condition for that.


text:
Q: Tensorflow conv2d result discrepancy on cpu vs gpu We've been working on a problem here that has yielded some discrepancies between results based on what we've observed to be caused by a couple of factors which should theoretically have no impact.
In our problem, we're dealing with a data set that is varying in size.  During training, the input is fixed to a specific size by either padding or chopping.  However, in the interest of performance and speed, we were hoping to take advantage of the fact that we should be able to pre-calculate the results of feeding an input consisting of only padding through the layers of our convolutional neural net.  Thus for inputs significantly smaller than the fixed size set in training, we would determine the bare minimum amount of padding required to have the activations generated by the final conv layer match those of the same input if it were padded out to that large fixed size, in addition to as much of the pre-calculated all-pad activations that would need to be appended to the result.
The conv-net portion of our model that we were experimenting with this on consists of 9 layers, the first eight performing a conv2d followed by a maxpool, and the final one being a single conv2d.  The training for the model was performed on gpu's, however, for testing we only have the cpu available.  Testing on a large set of data using the variable padding approach yielded for the most part identical results to what we would expect to see compared to the fixed size input.  However, there were a few cases where we observed discrepancies between the values obtained using the two approaches, sometimes on the order of e-4.
This issue looked to manifest itself only in input which were on the smaller end of the scale.  Digging down into these cases revealed that the activations from each layer in the model were always identical, and it wasn't until you reach the final convolution layer where the discrepancies appeared.  Surprisingly though, we discovered that adding enough padding (still far below the fixed size) could affect the value of the first few activations at the final layer, even though those cells don't depend on that extra padding at all.
We were able to replicate the problem using canned data, and even demonstrate it on a single conv2d operation.  In the code below, A simple conv2d with a single length:5 stride:1 filter is applied to a tensor of length 7 to produce 3 activations.  However, when you append 1 or 2 extra values on to the input, the values of the 2nd and 3rd activations change even though they have no dependence on these new input values at all.  Replicating the results by hand using tf.mul and reduce_sum ops, produces the same results as the input with the extra values, indicating that it's the correct result.  This is only observed when the ops are executed on the cpu, however, assigning them to the gpu instead always produces the same values regardless of whether the input is of length 7, 8, or 9.  Is this expected when performing conv on the cpu?  Is there a way to explain the variance in the conv output, eg. does it happen due to the algorithm used for small inputs?  All of the above refers to conv2d with VALID padding used.
example:
# Consider a length-T tensor x0 where T>=5.  Create another tensor
# x1 by adding an element onto the end of x0.  If you convolve both
# x0 and x1 with a length-5 filter with VALID padding, you'd expect
# the first (T-4) elements of the resulting tensors to have the
# exact same value because the calculation is being done on the
# same set of numbers.  It turns out you can get discrepancies
# though on the order of e^-5 if the convolution is done on the CPU.

#device = '/gpu:0'
device = '/cpu:0'

T = 7  # >=5

def expand_4d(f, n):
    f = tf.expand_dims(f, n[0])
    f = tf.expand_dims(f, n[1])
    f = tf.expand_dims(f, n[2])
    return f

# Convolution Filter and Bias
cnv = tf.cast([-0.7313, -1.1043, 1.8492, 1.3007, -0.1033], tf.float32)
cnv = expand_4d(cnv, [0, -1, -1])
bias = tf.constant([0.0401], tf.float32)

# Input
x0 = 10.0 * tf.cast(tf.range(T), tf.float32)
x1 = 10.0 * tf.cast(tf.range(T+1), tf.float32)
x2 = 10.0 * tf.cast(tf.range(T+2), tf.float32)
x0 = expand_4d(x0, [0, 0, -1])
x1 = expand_4d(x1, [0, 0, -1])
x2 = expand_4d(x2, [0, 0, -1])

# Run Convolution
def my_conv(x):
    with tf.device(device):
        return tf.nn.bias_add(tf.nn.conv2d(x, cnv, strides=[1,1,1,1], padding='VALID'), bias)

y0 = my_conv(x0)
y1 = my_conv(x1)
y2 = my_conv(x2)
n = T - 4   # length of y0

sess = tf.Session()
y0_, y1_, y2_ = sess.run([y0, y1, y2])
print('T =', T)
print('device =', device)
print('y0 = convolution with length-T tensor x0')
print(y0_)
print('y1 = convolution with length-(T+1) tensor x1')
print(y1_)
print('y2 = convolution with length-(T+2) tensor x2')
print(y2_)
# Compare the first n elements of each tensor (should all be equal)
print('y0 - y1[0:%s]' % n)
print(y0_[0][0] - y1_[0][0][0:n])
print('y1[0:%s] - y2[0:%s]' % (n, n))
print(y1_[0][0][0:n] - y2_[0][0][0:n])

sample output:
T = 7
device = /cpu:0
y0 = convolution with length-T tensor x0
[[[[ 60.87010574]
   [ 72.98010254]
   [ 85.09010315]]]]
y1 = convolution with length-(T+1) tensor x1
[[[[ 60.87010574]
   [ 72.98009491]
   [ 85.09008789]
   [ 97.20009613]]]]
y2 = convolution with length-(T+2) tensor x2
[[[[  60.87010574]
   [  72.98009491]
   [  85.09008789]
   [  97.20009613]
   [ 109.31010437]]]]
y0 - y1[0:3]
[[  0.00000000e+00]
 [  7.62939453e-06]
 [  1.52587891e-05]]
y1[0:3] - y2[0:3]
[[ 0.]
 [ 0.]
 [ 0.]]

redpajama_set_name: RedPajamaStackExchange


text:
Q: Optional parameters with named query in Hibernate? Is there any way to specify optional parameters (such as when search parameters are provided from a form and not all parameters are required) in a named query when using Hibernate? I'm using a native SQL query, but the question is probably applicable to named HQL queries as well.
I'm pretty sure the answer to this is 'no', but I haven't found the definitive answer in the documentation yet.

A: As mentioned in a different answer to the question referenced previously, the following HQL construct works for me:
select o from Product o WHERE :value is null or o.category = :value

if :value is passed in as null, all Products are returned.
See also Optional or Null Parameters
Note that this won't work in some versions of Sybase due to this bug, so the following is an alternative:
select o from Product o WHERE isnull(:value, 1) = 1 or o.category = :value

A: Another solution for handling optional list parameters is by checking for null using the COALESCE function. COALESCE is supported by Hibernate returns the first non-null parameter from a list, allowing you to check for null on a list without breaking the syntax when there are multiple items in the list.
HQL example with optional parameter and list parameter:
select obj from MyEntity obj
where ( COALESCE( null, :listParameter ) is null or obj.field1 in (:listParameter) )
  and ( :parameter is null or obj.field2 = :parameter )

This worked for me with a SQL Server dialect.

A: AFAIK, there is no such thing so you'll have to write a dynamic query for this. Maybe have a look at this previous answer showing how to do this in HQL (that you can transpose to SQL) and also showing how the Criteria API makes it simpler and is thus better suited for this job in my opinion.
Update: (answering a comment from the OP) Working with a legacy database can be indeed tricky with Hibernate. Maybe you can use a dynamic native query and return non-managed entities though. But on the long run, things might get worse (I can't tell that for you). Maybe Hibernate is not the best choice in your case and something like iBATIS would give you the flexibility you need.

A: unfortunately the solution under "Optional or Null Parameters" does not work for IN lists.
I had to changed the query as followed ...
Named query definition:
select ls from KiCOHeader co
...
join lu.handlingType ht
where (:inHandlingTypesX = 1 OR ht.name in (:inHandlingTypes))

Code:
Set<KiHandlingTypeEnum> inHandlingTypes = ...

Query query = persistence.getEm().createNamedQuery("NAMED_QUERY");
query.setParameter("inHandlingTypesX", (inHandlingTypes == null) ? 1 : 0);
query.setParameter("inHandlingTypes", inHandlingTypes);

List<KiLogicalStock> stocks = query.getResultList();

Much fun working.

A: For those having issues with NULL values, another option is to use an alternate value. In my case, I used only positive values for my category field, that allows me to use as my alternate value = -1.
Therefore, before to execute the query, you can make a small validation:
if(value==null) {
   value = -1;
}
....
....
select p from Product p WHERE :value = -1 or p.category = :value


text:
Q: django forms with ModelChoiceField After researching for days I'm still confused with creating a form involving 4 tables which are all connected via ForiegnKey. I'm not even sure if I'm using the right approach.
Should I use forms.Form or ModelForm? What I'm looking for I'm sure is common but all of my attempts are in vain. It seems like I'm making this more complicated than it should be since all 4 tables are related.
To the Point: To create a workorder, pick a Building, then pick a Unit within that Building, then pick a caller from Tenant(s) within that Unit. Then gather all data in view and save WorkOrder.
Using Django 1.6
# models.py
class Building(models.Model):
    name = models.CharField(max_length=30)
    address = models.CharField(max_length=200)
    ...

def __unicode__(self):
    return self.name

class Unit(models.Model):
    name = models.ForeignKey(Building)
    unit = models.CharField(max_length=30)
    ...

    def __unicode__(self):
        return self.unit

class Tenant(models.Model):
    unit = models.ForeignKey(Unit)
    name = models.ForeignKey(Building)
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=30)
    ...

    def __unicode__(self):
        return u'%s %s' % (self.first_name, self.last_name)

class WorkOrder(models.Model):
    name = models.ForeignKey(Building)
    unit = models.ForeignKey(Unit)
    ordernum = models.AutoField(primary_key=True)
    ...

    def __unicode__(self):
        return self.unit

forms.py
# forms.py

class WorkOrderForm(forms.Form):
    building_choice = forms.ModelChoiceField(queryset=Building.objects.all(),
                                             empty_label='Pick a building',
                                             )

    def __init__(self, *args, **kwargs):
        super(WorkOrderForm, self).__init__(*args, **kwargs)
        self.fields['building_choice'].label = 'Building'

    unit_choice = forms.ModelChoiceField(queryset=Unit.objects.(????),
                                         empty_label='Pick a unit',
                                         )

    def __init__(self, *args, **kwargs):
        super(WorkOrderForm, self).__init__(*args, **kwargs)
        self.fields['unit_choice'].label = 'Unit'

    caller_choice = forms.ModelChoiceField(queryset=Tenant.objects.(????),
                                       empty_label='Who called',
                                       )

    def __init__(self, *args, **kwargs):
        super(WorkOrderForm, self).__init__(*args, **kwargs)
        self.fields['caller_choice'].label = 'Tenant'

views.py (incomplete)
#views.py
def create(request):
    if request.method == 'POST':
        form = WorkOrderForm(request.POST)
        if form.is_valid():
            workorder = WorkOrder(name=form.cleaned_data['name'],
                                 unit=form.cleaned_data['unit'],
                                 call_date=form.cleaned_data['call_date'],
                                 caller=form.cleaned_data['caller'],
                                 problem_desc=form.cleaned_data['problem_desc'])
            workorder.save()

            return HttpResponseRedirect('/workorder/')
    else:
        form = WorkOrderForm()
    return render(request, 'workorder_form.html', {'form': form})

If someone could let me know the correct way to go about this I'd be forever grateful.

A: It's been a while since I posted this question but I found a django package django-clever-selects that met my needs. The docs and example project were well commented. Thanks to all that helped mr earlier.


text:
Q: $R_{n} = \lVert X_{n} \rVert \to 1$ in probability, where $ X_{n}$ has uniform distribution in the $n$-dimensional ball. Using the transformation method, with the polar coordinates transformation, it is
easy to show that the random variable $R_{2} = \lVert X_{2}\rVert$ has cumulative distribution
$$
F_{2}(x)= P(R_{2} \leq 2)
=
\begin{cases}
 0, & x<0,\\
x^{2}, & 0\leq x \leq 1\\
1, & x>1.
\end{cases}
$$
In the same way, using spherical coordinates we have that the cumulative distribution of $R_{3}=
\lVert X_{3} \rVert$ is
$$
F_{3}(x)
=
P(R_{3}\leq x)=
\begin{cases}
0 ,& x < 0,\\
x^{3},& 0\leq x \leq 1,\\
1, & x>1.
\end{cases}
$$
I don't know how to compute the distribution of $R_{n}$ for $n \geq 4$, but I conjecture
that it is
$$
F_{n}(x) = P(R_{n} \leq x)
=
\begin{cases}
0,& x< 1\\
x^{n},& 0 \leq x \leq 1\\
1, & x > 1.
\end{cases}
$$
If it is true, we can find that, for every $\epsilon > 0$
$$
\begin{align*}
P(\lvert R_{n} - 1\rvert \geq \epsilon) &= 1 - P(\lvert R_{n} - 1 \rvert < \epsilon)\\
&=1 - (F_{n}(1+\epsilon) -F_{n}(1-\epsilon))\\
&=
\begin{cases}
0 & \epsilon > 1\\
(1 - \epsilon)^{n} & 0 < \epsilon < 1.
\end{cases}
\end{align*}
$$
Then, $P(\lvert R_{n} - 1\rvert \geq \epsilon) \to 0$ as $n \to \infty$.
So I need to prove if my conjecture is true or false in order to solve the proposed problem.

A: Let $``\text{vol''}$ denote the $n$-dimensional
Lebesgue measure on $\mathbb{R}^{n}$. Since $X_{n}$ has uniform distribution in
the $n$-dimensional ball, $B_{n}(\mathbf{0},1)$,
we have that
$$
P(X_{n} \in A)=
\int_{A}
\frac{1}{\text{vol}(B_{n}(\mathbf{0}, 1))}
\chi_{B_{n}(\mathbf{0}, 1)}\,
d\text{vol}=
\frac{\text{vol}(B_{n}(\mathbf{0},1)\cap A)}
{\text{vol}(B_{n}(\mathbf{0}, 1))}
$$
for all  measurable set $A \subset \mathbb{R}^{n}$.
Let's compute the volumen of a ball centered at origin and with radius $r$, $B_{n}(\mathbf{0}, r)$,
in terms of the volumen of unitary ball $B_{n}(\mathbf{0}, 1)$. In fact, by the change of
variable $(u_{1}, \dots, u_{n}) = (r x_{1}, \dots, r x_{n})$ the unitary ball $B_{n}(\mathbf{0}, 1)$
is transformed in one-to-one fashion into the ball
$B_{n}(\mathbf{0}, 1)$, in addition, the jacobian
of this transformation is $r^{n}$. Then,
$$
\text{vol}(B_{n}(\mathbf{0}, r))
=
\int_{B_{n}(\mathbf{0},r)}
\, d\text{vol}
=
\int_{B_{n}(\mathbf{0}, 1)}
r^{n}\,
d\text{vol}
=
r^{n}\text{vol}(B_{n}(\mathbf{0},1))
$$
Hence, the distribution of $R_{n}$ is given by
$$
\begin{align*}
F_{R_{n}}(r) &=
P(\lVert X_{n} \rVert \leq r)\\
&=
P(X_{n} \in B_{n}(\mathbf{0}, r))
&=
\begin{cases}
0, & r \leq 0,\\[1em]
\dfrac{\text{vol}(B_{n}(\mathbf{0}, r))}
{\text{vol}(B_{n}(\mathbf{0}, 1))}=r^{n},
& 0 < r \leq 1,\\[1em]
\dfrac{
\text{vol}[B_{n}(\mathbf{0}, r) \cap B_{n}(\mathbf{0},1)]
}
{\text{vol}(B_{n}(\mathbf{0},1))} = 1, & r > 1.
\end{cases}.
\end{align*}
$$
Finally,
$$
P(\lvert R_{n}- 1\rvert \geq \epsilon)
= 1- P(\lvert R_{n} - 1 \rvert < \epsilon)
= F_{R_{n}}(1 - \epsilon).
$$
From this is easy to see that $P(\lvert R_{n} - 1\rvert \geq \epsilon) \to 0$ as $n \to \infty$.


text:
Q: Disable Featured Image Link I am an amateur in code development, but know enough to get around. I have been trying for days to disable the link associated with the featured image, so in fact, the image is static, and does not link to a post.
For information sake, I am using the Gridsby Theme.
Would love any advice.
Thanks!


text:
Q: Using IsNumeric in a function I wrote a function that generates a "score" (1,0,-1) based on a input cell, which should contain a number. However, sometimes the input field might not be numeric and then the function should return the output "0".
Function ScoreRoE(RoE_Field As Range, goodval As Range, badval As Range)

    Dim RoE As Double, result As Double

    RoE = RoE_Field.Value

        If IsNumeric(RoE_Field.Value) = False Then
            result = "0"
        Else:
            If RoE >= goodval.Value Then
                result = "1"
            ElseIf RoE <= badval.Value Then
                result = "-1"
            Else:
                result = "0"
            End If
        End If

    ScoreRoE = result

End Function

When the input cell is numeric the function works correctly. However, when not it doesn't and just returns an error "#VALUE!"
Thanks a lot in advance!

A: Declare RoE as Variant:
Function ScoreRoE(RoE_Field As Range, goodval As Range, badval As Range)

    Dim RoE As Variant, result As Double

    RoE = RoE_Field.Value

        If Not IsNumeric(RoE) Then
            result = 0
        Else
            If RoE >= goodval.Value Then
                result = 1
            ElseIf RoE <= badval.Value Then
                result = -1
            Else
                result = 0
            End If
        End If

    ScoreRoE = result

End Function

you cannot assign a text value to a double.

Personally I do not see the need for any of the variables:
Function ScoreRoE(RoE_Field As Range, goodval As Range, badval As Range)

    If Not IsNumeric(RoE_Field.Value) Then
        ScoreRoE = 0
    Else
        If RoE_Field.Value >= goodval.Value Then
            ScoreRoE = 1
        ElseIf RoE_Field.Value <= badval.Value Then
            ScoreRoE = -1
        Else
            ScoreRoE = 0
        End If
    End If

End Function

A: This is an interpretation of the intentions of the code:
Function ScoreRoe(roeInput As String, goodVal As String, badVal As String) As String

    If Not IsNumeric(roeInput) Or Not IsNumeric(goodVal) Or Not IsNumeric(badVal) Then
        ScoreRoe = "0"
    Else
        Dim goodValNumeric As Double: goodValNumeric = goodVal
        Dim badValNumeric As Double: badValNumeric = badVal
        Dim roeInputNumeric As Double: roeInputNumeric = roeInput

        If roeInputNumeric >= goodValNumeric Then
            ScoreRoe = "1"
        ElseIf roeInputNumeric <= badValNumeric Then
            ScoreRoe = "-1"
        Else
            ScoreRoe = "0"
        End If
    End If

End Function

The main idea is that the input is taken as String and then converted to Double for the comparison. Then if the input is not numeric, the returned value is 0 and if it is we go through If-Else.
In general, it could be a good idea to avoid : in VBA If-Else, in order to avoid unwanted problems like this one - VBA - How the colon `:` works in VBA code with condition


text:
Q: Qt cross-platform development? I just have a little question about running Qt created apps on different operating systems.
As a normal user do i have to install Qt framework to run Qt apps ?
I mean i've created Qt app using Windows , then i made a build for Linux .
Do i need to install the Qt framework on the Linux pc inorder to run that app ?
Or there is a way to package all the needed libraries into the app installer .
Best Regards

A: You can deliver the dynamic libs you need with your application, as it's described here:
http://doc.qt.io/qt-5/deployment.html

Since Qt is not a system library, it has to be redistributed along
  with your application; the minimum is to redistribute the run-time of
  the libraries used by the application. Using static linking, however,
  the Qt run-time is compiled into the executable.

A: Depends what you mean by 'framework', you will need the runtime libraries, unless you paid Nokia for a license to allow static linking.

A: For Linux, I think you would generally ensure that the Qt packages have been installed during installation (i.e. make them a requirement of the package you provide).  Under Mac OS you would need to package the .so (shared objects) with your application.  Under Windows you do the same (provide the .dlls) and install them with the application (not in the system folders).
The issue with static linking that @cbamber85 is alluding to, is the conformance with the LGPL licence where it's legal to link to the libraries at runtime but not at compile time (i.e. use the .so/.dll but not the .a files).


text:
Q: Switching from Limit() to First() in Laravel Model I'm stuck on an issue where I'm trying to clean up code presented to me, and I feel like I must've just been at this too long and can't see this issue.
At the moment I have the following code in one of my models:
public function attachments(){
    return $this->hasMany(volunteerAttachment::class, 'volunteerID','id');
}

 public function photoID() {
    $photoID= $this->attachments()->where('category','Drivers License')->orderBy('endDate','desc')->limit(1);
    return $photoID;
}

What I would like to do is what I believed was relatively simple in replacing the limit(1) of the function photoIdentification with a simple first().
But when I try that and simply put {{$volunteer->photoID->id}} in my blade, it simply returns the error App\volunteer::photoID must return a relationship instance.
I do however know that there is a relationship because if I continue to use the limit(1) and put:
@foreach($volunteer->photoID as $id)
   {{$id->id}}
@endforeach

It returns the relation and document correctly.
$volunteer is the variable for that particular model App\volunteer, and the following is how it is defined in the controller:
    public function show(Volunteer $volunteer){
            return view('volunteer.show', compact('volunteer'));
    }

A: The function photoID() will still return a full volunteerAttachment object. If you want to get the id using the first() function you will have to select the id property on the object like so:
{{ $volunteer->photoID()->id }}

You could also create an accessor on the model that directly returns this property:
public function getPhotoidAttribute($value)
{
    return $this->attachments()->where('category','Drivers License')->orderBy('endDate','desc')->first()->id;
}

Now in blade you can just use:
{{ $volunteer->photoid }}

A: When you call a function of a model as a variable Laravel assumes you try to return a related model. Try with an accessor instead:
public function getPhotoidAttribute($value) {
    $photoID= $this->attachments()->where('category','Drivers License')->orderBy('endDate','desc')->first();
    return $photoID->id;
}

and call it like this:
{{ $volunteer->photoid }}


text:
Q: Parsing time string in Go The Spark Rest API returns time in this format: 2016-10-28T16:56:50.497GMT.
I'm trying to parse that in Go, without any luck.
I keep getting 0001-01-01 00:00:00 +0000 UTC, but the time.Parse function doesn't throw any errors:
My function looks like this:
func getTime(timeStamp string) (t time.Time, e error) {
    t, e = time.Parse(
        time.RFC3339Nano,
        timeStamp)
    if e != nil {
        fmt.Errorf("Error parsing timestring", e)
    }
    return t, e
}

I've tried going through the documentation and created my custom layout, but I can't figure out how I should treat that GMT part of the string

A: You're trying to parse that time as time.RFC3339Nano, which it is not.
Use the format "2006-01-02T15:04:05.999MST"
https://play.golang.org/p/TYHnvclxEn


text:
Q: Почему через HTTPS сайт долго загружается? Недавно получили сертификат SSL для сайта организации. После установки и настройки сайт стал грузиться до 10-15 секунд. Сайт стоит на BitrixVM5.1 с CentOs. Настройка nginx и apache проводилась элементарная, включить ssl, указать путь до сертификата.
Wireshark при многократном тестировании показывает одну и ту же картину: ServerHello возвращается строго через 10 секунд.

Как подробней узнать, куда деваются эти 10 секунд?

A: Проблема заключалась в конфигурации nginx, а точнее в устаревшем наборе шифров.
было
ssl_ciphers RC4:HIGH:!aNULL:!MD5:!kEDH;
стало
ssl_ciphers "EECDH+ECDSA+AESGCM:EECDH+aRSA+AESGCM:EECDH+ECDSA+SHA384:EECDH+ECDSA+SHA256:EECDH+aRSA+SHA384:EECDH+aRSA+SHA256:EECDH:EDH+aRSA:!aNULL:!eNULL:!LOW:!3DES:!MD5:!EXP:!PSK:!SRP:!DSS:!RC4";


text:
Q: First order PDF of a stochastic process I've started studying about stochastic processes and I need some help in this question.
A random number generator is making numbers by this process:
First number (X0) is a sample from Normal Standard distribution and then other numbers are generated from

X(n) = a*X(n-1) + Z(n)

that "a" is a constant in range [0,1] and "Zn" is i.i.d random samples independent from X0 and their distribution is Normal(0,1-a^2).
I need to calculate first order PDF of this process.
Any help would be appreciated.


text:
Q: sqoop export from hdfs to oracle Error Command used:
sqoop export --connect jdbc:oracle:thin:@//xxx:1521/BDWDEV4 --username xxx --password xxx --table TW5T0 --export-dir '/data/raw/oltp/cogen/oraclexport/TW5T0/2015-08-18' -m 8 --input-fields-terminated-by '\001' --lines-terminated-by '\n' --input-escaped-by '\"' --input-optionally-enclosed-by '\"'

The destination table has columns with datatype date in oracle but as show in error it is parsing simple date as timestamp
Error:
15/09/11 06:07:12 INFO mapreduce.Job:  map 0% reduce 0% 15/09/11 06:07:17 INFO mapreduce.Job: Task Id : attempt_1438142065989_99811_m_000000_0, Status : FAILED Error: java.io.IOException: Can't export data, please check failed map task logs
        at org.apache.sqoop.mapreduce.TextExportMapper.map(TextExportMapper.java:112)
        at org.apache.sqoop.mapreduce.TextExportMapper.map(TextExportMapper.java:39)
        at org.apache.hadoop.mapreduce.Mapper.run(Mapper.java:145)
        at org.apache.sqoop.mapreduce.AutoProgressMapper.run(AutoProgressMapper.java:64)
        at org.apache.hadoop.mapred.MapTask.runNewMapper(MapTask.java:764)
        at org.apache.hadoop.mapred.MapTask.run(MapTask.java:340)
        at org.apache.hadoop.mapred.YarnChild$2.run(YarnChild.java:168)
        at java.security.AccessController.doPrivileged(Native Method)
        at javax.security.auth.Subject.doAs(Subject.java:415)
        at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1594)
        at org.apache.hadoop.mapred.YarnChild.main(YarnChild.java:163) Caused by: java.lang.RuntimeException: Can't parse input data: '2015-08-15'
        at TZ401.__loadFromFields(TZ401.java:792)
        at TZ401.parse(TZ401.java:645)
        at org.apache.sqoop.mapreduce.TextExportMapper.map(TextExportMapper.java:83)
        ... 10 more Caused by: java.lang.IllegalArgumentException: Timestamp format must be yyyy-mm-dd hh:mm:ss[.fffffffff]
       at java.sql.Timestamp.valueOf(Timestamp.java:202)
        at TZ401.__loadFromFields(TZ401.java:709)
        ... 12 more

A: Instead of changing your data files in Hadoop, you should use the --map-column-java argument in your sqoop export.
If you have for example two DATE columns named DATE_COLUMN_1 and DATE_COLUMN_2 in your Oracle table, then you can add the following argument to your sqoop command:
--map-column-java DATE_COLUMN_1=java.sql.Date,DATE_COLUMN_2=java.sql.Date

As mentioned before, the JDBC format has to be used in your Hadoop text file. But in this case yyyy-mm-dd will work.

A: From
http://archive.cloudera.com/cdh/3/sqoop/SqoopUserGuide.html#_dates_and_times,

Oracle JDBC represents DATE and TIME SQL types as TIMESTAMP values. Any DATE columns in an Oracle database will be imported as a TIMESTAMP in Sqoop, and Sqoop-generated code will store these values in java.sql.Timestamp fields.
When exporting data back to a database, Sqoop parses text fields as
  TIMESTAMP types (with the form yyyy-mm-dd HH:MM:SS.ffffffff) even if
  you expect these fields to be formatted with the JDBC date escape
  format of yyyy-mm-dd. Dates exported to Oracle should be formatted as
  full timestamps.

So you would need to format the dates in your files to conform to the format  yyyy-mm-dd HH:MM:SS.ffffffff before exporting to Oracle.
EDIT:
Answering the comment,

There around 70 files(tables) in hdfs I need to export..So,in all
  files I need to change the date from yyyy-mm-dd to yyyy-mm-dd
  HH:MM:SS.ffffffff, any simple way to format it.

Well you could write an awk script to do that for you. Or else you can check if the below idea works:

*

*Create a new temporary table TEMPIMPORT with the same structure as table TW5T0 except changing the column which has the DATE datatype to VARCHAR2

*Load using Sqoop into the new temporary table TEMPIMPORT.

*Run the DML below to export the data back int TW5T0 (and commit of course):
insert into tw5t0 (select   [[all_your_columns_here_except_date_column]],to_date(date_column,'yyyy-mm-dd') from tempimport);

A: used --connection-param-file ora.porperties in export sqoop
ora.properties contains
oracle.jdbc.mapDateToTimestamp=false

A:
Oracle drivers map oracle.sql.DATE to java.sql.Timestamp, retaining
  the time information.  If you still want the incorrect but 10g
  compatible oracle.sql.DATE to java.sql.Date mapping, then you can get
  it by setting the value of mapDateToTimestamp flag to false (default
  is true).

https://docs.oracle.com/cd/E11882_01/java.112/e16548/apxref.htm#JJDBC28920
For using with sqoop you need to add option:
--connection-param-file conn-param-file.txt
conn-param-file.txt:
oracle.jdbc.mapDateToTimestamp=false

A: For using with sqoop you need to add option:
--connection-param-file conn-param-file.txt
conn-param-file.txt:
oracle.jdbc.mapDateToTimestamp=false

A: If Hive table columns sequence doesn't match with RDBMS table columns sequence order then there is a chance of same error.
I have resolve my issue after rearrange the columns in RDBMS by creating the table again.


text:
Q: NPM and Yarn is having issues with fsevents I tried to spin up my project today and when I wanted to start it, I got an error saying that something was wrong with fsevents package.
After that I tried to reinstall all the packages again with yarn and I got the same, the install stops and fails when it comes to the fsevents package. Same thing happens with npm.
I have the latest node version if that counts.
Here is the errors I get when trying to install with npm:

Can I get some help with this please? Tried to google but couldn't find a solution.


text:
Q: Make the moon's 3D gif How do I make the following gif

I tried:
moon = Import[
 "https://upload.wikimedia.org/wikipedia/commons/f/f0/Full_Moon_as_Seen_From_Denmark.jpg"];

{r, g, b} = ColorSeparate[ImageResize[moon, 200]]

ListPlot3D[ImageData[r, DataReversed -> True], Mesh -> False,
ColorFunction -> "GrayTones", Boxed -> False, Axes -> False]

but..

A: moon = Import[
  "https://upload.wikimedia.org/wikipedia/commons/f/f0/Full_Moon_as_\
Seen_From_Denmark.jpg"]

Here are two ways to get something like that:

*

*with Texture or

*with ColorFunction

Texture:
pic = ImageCrop @ ImageResize[ColorConvert[moon, "Grayscale"], Scaled@.3]

Worse quality than is possible with this image but I had to make it smaller due to the lack of time :P. Feel free to change rescaling factor.
texture = ImageCrop @ ColorConvert[moon, "Grayscale"];

ListPlot3D[ImageData[pic, DataReversed -> True]^3,
 Mesh             -> None,
 PlotStyle        -> Texture[texture],
 Lighting         -> {{"Ambient",  White}},
 ViewPoint        -> 1000 {0, -.001, 1},
 ImageSize        -> 800,
 PlotRangePadding -> {50, 50, 0},
 RotationAction   -> "Clip",
 Boxed            -> False,
 Axes             -> False,
 Background       -> Black,
 PlotRange        -> All,
 ViewVertical     -> {0, 1, 0}
]

It is even responsible enough to play with:

ColorFunction
You need to:

*

*change the ColorFunction so it respects original color space, then it will look naturally. Also, make the Lighting less interfering: Lighting -> {{"Directional", White, {0, 0, 1000}}}

*transform values of pixels, as seen on linked example those peaks are way bigger that they should be comparing to other areas on the Moon: ImageData[...]^7

*use the inverse transformation for ColorFunction so the coloring doesn't care about what you've done with values:  ColorFunction -> (Blend[..., Surd[#3, 7]] &)

pic = ImageResize[ColorConvert[moon, "Grayscale"], Scaled@.2];

pics = Table[
   x = 1000 {0, Sin[i], 1};

   Rasterize @ ListPlot3D[
     ImageData[pic, DataReversed -> True]^7,
     Mesh            -> None,
     ColorFunction   -> (Blend[{Black, White}, Surd[#3, 7]] &),
     Lighting        -> {{"Directional", White, {0, 0, 1000}}},
     ViewPoint       -> x,
     Boxed           -> False,
     Axes            -> False,
     Background      -> Black,
     SphericalRegion -> True,
     PlotRange       -> All
   ],
   {i, .1, Pi, Pi/24.}
];

path = FileNameJoin[{$HomeDirectory, "Desktop", "moon.gif"}]

Export[
 path, pics, "GIF",
 "DisplayDurations" -> Append[ConstantArray[1/15., Length[pics] - 1], 1]
]

SystemOpen @ path

A: Here is an approach based on direct construction of Image3D from ImageData. The basic idea is taken from the subsection "Volume Creation" of the section "Scope" on the Documentation page for Image3D, some other ideas are from the answer by Kuba:
moon = Import[
 "https://upload.wikimedia.org/wikipedia/commons/f/f0/Full_Moon_as_Seen_From_Denmark.jpg"];

moonGray = ImageResize[ImageCrop@ColorConvert[moon, "Grayscale"], Scaled@.5];

height = 70;
data = ImageData[moonGray]^3;
data3D = Reverse@Table[data UnitStep[height data - k], {k, height}];

im = Image3D[data3D, ColorFunction -> (GrayLevel[Surd[#, 3], Sign[#]] &),
  SphericalRegion -> True, ViewPoint -> {0, 0, Infinity}, Background -> Black,
  ImageSize -> 500];

pics = Table[
   Rasterize[Image3D[im, ViewPoint -> 1000 {0, -Sin[i], 1}], "Image"],
    {i, .1, Pi, Pi/24.}];

Export["moon.gif", pics, "GIF",
 "DisplayDurations" -> Append[ConstantArray[1/15., Length[pics] - 1], 1]]

UPDATE
With RotationAction -> "Clip" (instead of SphericalRegion -> True) and fixed ImageSize -> {500, 512} we can get rid of the margins:
im = Image3D[data3D, ColorFunction -> (GrayLevel[Surd[#, 3], Sign[#]] &),
  RotationAction -> "Clip", ViewPoint -> {0, 0, Infinity}, Background -> Black,
  ImageSize -> {500, 512}]

pics = Table[
   Rasterize[Image3D[im, ViewPoint -> 1000 {0, -Sin[i], 1}], "Image"], {i, .1, Pi,
    Pi/24.}];

Export["moon.gif", pics, "GIF",
 "DisplayDurations" -> Append[ConstantArray[1/15., Length[pics] - 1], 1]]

(I have reduced the number of colors in the final GIF to 50 using gifsicle in order to fit the 2Mb file size limit).

A: I've always wished the moon was more habitable. Starting from the OPs picture:
moon = ColorConvert[
  Import["https://upload.wikimedia.org/wikipedia/commons/f/f0/Full_\
Moon_as_Seen_From_Denmark.jpg"], "Grayscale"];
ReliefPlot[ImageData[moon], ColorFunction -> "GreenBrownTerrain"]


text:
Q: Moving document causing this error " smaller version limit than the source " we want to move files from an online document library to another online document library inside the same site collection, using the "Move to" button, but i got this error:-

... a smaller version limit than the source

Although on the source and destination we have enabled versioning, as follow:-
1) On the source:-

2) on the destination:-

could the problem be in the number of drafts?

A: Sure, drafts are versions too, I think that you need in the new library versions + 1, because it will move all version and create maybe new one, so if you want try it, set the properties the same and add + 1 to all of them.
If you dont want versions, just copy files with Explorer or sync with OneDrive Client or disable version in the source library.


text:
Q: OpenCV 2.4 copyTo function Using OpenCV 2.4.2 C/C++
I am trying to use the copyTo function to add a binary CV_8UC1 image to a RGB CV_8UC3 image. However, it seems to crash the program whenever I do this. I'm assuming that the difference in the number of channels doesn't allow me to add them. Is there some type of conversion that can allow me to use this copyTo function? I'm stitching a camera feed with its thresholded image side by side.
I'm using src.copyTo(dst(Rect(x,y,w,h))); as the copying code, and inRange(src,Scalar(#,#,#),Scalar(#,#,#),dst) as the thresholding operation.
I've tried to use the convertTo function but not having much luck with it. Can anyone give some advice?
Thanks

A: You should use cv::cvtColor function, which can convert from one color space to another. Look here for details.


text:
Q: Validate Zipcode using api in php I want to validate that zip code entered by user is valid or not.
for example user entered 009876654 and it is not valid then an error
message should be given.
I know i can do it using javascript regulr expression or using
ajax-zip-code-database
But i don't want any of the above. i need some plugin sort of thing
which send request to some online application to check wheather it is
valid or not.I want this because i don't want to take care if in future
there is change in the zip-codes or new zip-codes get added.
P.S. :- I don't want to use javascript or using ajax-zip-code-database

A: USPS provides a list of API service providers that support ZIP Code Lookup: https://www.usps.com/business/webtools-service-providers.htm


text:
Q: Spotfire-IronPython: Set FilePath property In Spotfire, using ironpython...
I am trying to set the 'FilePath' property. Here is my try:
Document.Properties["FilePath"] = "E:\Spotfire_Export"
Here is what I get:
Traceback (most recent call last):
  File "Spotfire.Dxp.Application.ScriptSupport", line unknown, in ExecuteForDebugging
  File "<string>", line 15, in <module>
  File "Spotfire.Dxp.Application", line unknown, in SetPropertyValue
  File "Spotfire.Dxp.Data", line unknown, in GetProperty
KeyError: The property named 'FilePath' could not be found.

Any hints?

A: you need to first create a Document Property called FilePath.

*

*from the Edit menu select Document Properties...

*click the Properties tab

*click Mew...

*enter FilePath for the Property Name

*enter a Description (optional) and a temporary Value (required)

*click OK, click OK

*your code should work


text:
Q: Audio (AVAudioPlayer) stops video loop (MPMoviePlayerController) on iPhone 4 I develop an application for physical exercises which plays audio and video. Since audio and video come from separate files (audio is language dependent, video not), I play the audio with AVAudioPlayer and the video (which does not have a sound track) with MPMoviePlayerController. The video must run in a loop (moviePlayer.repeatMode = MPMovieRepeatModeOne).
Usually the audio (verbal explanation of an exercise) is started first, some seconds later the video is started (exercise is shown). This works like a charm on iPhone 4S (and of course, in the simulator), the audio plays and in parallel the video loops until it is stopped.
On an iPhone 4 (and on an iPad 1), however, the video does not enter the loop, i.e. is stopped after the first run, if the audio player is still playing when the video is started. (If the video is started after the audio stopped playing, the loop works fine also on the iPhone 4).
How can I make the MPMoviePlayerController perform the loop also on iPhone 4?


text:
Q: Filling in missing values with forward-backward method with lag in SAS Assume that you have a table with user name, counter and score for each counter.
data have;
input user $  counter  score;
cards;
A 1 .
A 2 .
A 3 40
A 4 .
A 5 20
A 6 .
B 1 30
B 2 .
C 1 .
C 2 .
C 3 .
;
run;

Some scores are missing beween some counters, and you want to put the same score as previous counter. So the result will look like below:
A 1 40
A 2 40
A 3 40
A 4 40
A 5 20
A 6 20
B 1 30
B 2 30
C 1 .
C 2 .
C 3 .

I managed to fill the missing score values forward by using the lag function like below:
data result1a;
  set have(keep=user);
  by user;

  *Look ahead;
    merge have have(firstobs=2 keep=score rename=(score=_NextScore));

    if first.user then do;
        if score= . then score=_NextScore;
        end;
    else do;
        _PrevScore = lag(score);
        if score= . then score=_PrevScore;
    end;
    output;
run;

Then I sorted the table backward by using descending funtion on counter like below:
proc sort data = result1a out= result1b;
by user descending counter ;
run;

Then finally I would fill the missing values forward in raaranged table (going backward according to the initial table) by using the lag function again like below.
I used the lag function in do-loop, because I wanted to update the previous value in each step (For example, the value 40 would be carried from the first score to the last score in the group all the way).
However, I get strange result. All missing values don't geta real value. Any idea about fixing the last data-step?
data result1c;
set result1b;
by user;

   if first.user then do;
        if score= . then score=_NextScore;
        else score = score;

        end;
   else do;
        _PrevScore = lag(score);
        if score= . then
        score=_PrevScore;
        else score = score;
   end;
   output;
run;

A: Don't need to use lag, use retain (or equivalent).  Here's a double DoW loop solution that does it in one datastep (and, effectively, one read - it buffers the read so this is as efficient as a single read).
First we loop through the dataset to get the first score found, so we can grab that for the initial prev_score value.  Then setting that, and re-looping through the rows for that user and outputting.  There's no actual retain here since I am doing the looping myself, but it's similar to if there were a retain prev_score; and this was a normal data step loop.  I don't actually retain it since I want it to go missing when a new user is met.
data want;
  do _n_ = 1 by 1 until (last.user);
    set have;
    by user;
    if missing(first_score) and not missing(score) then
      first_score = score;

  end;
  prev_score = first_score;
  do _n_ = 1 by 1 until (last.user);
    set have;
    by user;
    if missing(score) then
      score = prev_score;
    prev_score = score;
    output;
  end;
run;

A: lag() is a commonly misunderstood function. The name implies that when you call it SAS looks back at the previous row and grabs the value, but this is not at all the case.
In fact, lag<n>() is a function that creates a "queue" with n values. When you call lag<n>(x), it pushes the current value of x into that queue and reads a previous value from it (of course the pushing only occurs once per row). So if you have lag<n>() within a condition, the pushing only occurs when that condition is satisfied.
To fix your problem, you need the lag() function to run for every row, and to run after score has been corrected:
data result1c;
set result1b;
by user;
if first.user then do;
    if score= . then score=_NextScore;
    else score = score;
end;
else do;
    if score= . then
    score=_PrevScore;
    else score = score;
end;
_PrevScore = lag(score);
output;
run;

EDIT: I got hung up on the misuse of lag and didn't present a working alternative. Because you're modifying score, it's a bad idea to use lag at all. Retain will work here:
data result1c;
set result1b;
by user;
retain _PrevScore;
if first.user then do;
    if score= . then score=_NextScore;
    else score = score;
end;
else do;
    if score= . then
    score=_PrevScore;
    else score = score;
end;
_PrevScore = score;
output;
run;


text:
Q: Animating Graphs in xcode with ARKit I am working on an AR app that presents a graph in 3d.
However, I want to animate the graph and have it form gradually as opposed to the whole graph at once.
I am not sure how to go about this in xcode :(


text:
Q: Tool for prototyping TypeScript types faster Is there an online tool, IDE or VSCode settings option/extension that allows to prototype type definitions (easier/faster)?
The only option I am aware of is to hover over a typed statement which displays the associated type in a tooltip. It's very impractical to use as the types are trimmed and non-interactive, i.e. I cannot hover over a type sub-component to see the trimmed part. Also it's impossible to say which sub-type failed as it's not highlighted.

If I need to step through a complex type to discover the error, I have to deconstruct it like below and then keep hovering over each statement, which is very inconvenient. Maybe if only the IDE could generate those "result comments" automatically, that would make life easier.


text:
Q: Python set() constructor How to modify the Set() constructor to accept an optional variable argument to which a collection of initial values can be passed to initialize the set? The prototype for the new constructor should look as follows:
def Set( self, *initElements = None )

It can then be used as shown here to create a set initialized with the given values:
s = Set( 150, 75, 23, 86, 49 )

A: You can either use a list of numbers to initialize a set, like this
set([150, 75, 23, 86, 49])

Or you can use set literal notation, like this
{150, 75, 23, 86, 49}

The advantage of the set constructor is that, we can use any iterator which has hashble items in it.

A: It already does, you just need more brackets.
set([150, 75, 23, 86, 49])


text:
Q: How to create a variable where the value is taken from another variable matching values of a vector I have a dataframe with a variable that is composed of strings of product's names.
Ex.:
| Names                       | Price ...|
|-----------------------------|----------|
| milk                        | ...      |
| pizza with tomato           | ...      |
| tuna with olive and beans   | ...      |
| etc...                      | ...      |

I would like to create an other variable that take as values names stored in a vector that match those in variable Names
Basically, if I have a vector:
x <- c("milk", "pizza", "tuna")

The code should look into the variable Names and if it finds a match in vector x then it takes that value and stores it in a new variable called tag that should have as values milk, pizza, tuna.
Is it possible to create a variable whose values are taken from another variable if conditions are met?

A: If I am understanding correctly, you want to have a tag (like a keyword) in a new column in your dataframe. If so, then it is probably easier to just extract the word if it occurs in your search list using str_extract.
library(stringr)

search <- c("milk", "pizza", "tuna")

df$tag <- stringr::str_extract(df$Names, paste(search, collapse="|"))

Output
                       Names price   tag
1                       milk  3.99  milk
2          pizza with tomato  5.99 pizza
3 tuna with olives and beans  9.99  tuna
4                       crab  4.99  <NA>

Data
df <-
  structure(list(
    Names = c("milk", "pizza with tomato", "tuna with olives and beans",
              "crab"),
    price = c(3.99, 5.99, 9.99, 4.99),
    tag = c("milk", "pizza",
            "tuna", NA)
  ),
  row.names = c(NA,-4L),
  class = "data.frame")


text:
Q: Angularjs checkbox filter, how to do reset button? Help to solve the problem. I'm trying to make a button or checkbox with the name "all", which would reset all previous samples in the checkboxes. .......................

(function () {'use strict';

angular.
  module('myApp', []).
  controller('WineCtrl', WineCtrl);

// Functions - Definitions
function WineCtrl() {
  // Variables - Private
  var self = this;

  // Variables - Public
  self.filter = {};
  self.wines = [
    {name: 'Wine A', category: 'red'},
    {name: 'Wine B', category: 'red'},
    {name: 'Wine C', category: 'white'},
    {name: 'Wine D', category: 'red'},
    {name: 'Wine E', category: 'red'},
    {name: 'Wine F', category: 'white'},
    {name: 'Wine G', category: 'champagne'},
    {name: 'Wine H', category: 'champagne'}
  ];

  // Functions - Public
  self.filterByCategory = filterByCategory;
  self.getCategories = getCategories;

  // Functions - Definitions
  function filterByCategory(wine) {
    return self.filter[wine.category] || noFilter(self.filter);
  }

  function getCategories() {
    return (self.wines || []).
      map(function (wine) { return wine.category; }).
      filter(function (cat, idx, arr) { return arr.indexOf(cat) === idx; });
  }

  function noFilter(filterObj) {
    return Object.
      keys(filterObj).
      every(function (key) { return !filterObj[key]; });
  }
}

}());

Categories

        <input type="checkbox" ng-model="ctrl.filter[category]" />
        {{ category }}

Available Wines

      {{ wine.name }} ({{ wine.category }})

    Number of results: {{ filteredWines.length }}

I will be grateful for any help.

A: Reset means what you need exactly. Here is simple answer.

(function () {'use strict';

angular.
  module('myApp', []).
  controller('WineCtrl', WineCtrl);

// Functions - Definitions
function WineCtrl() {
  // Variables - Private
  var self = this;

  // Variables - Public
  self.filter = {};
  self.wines = [
    {name: 'Wine A', category: 'red'},
    {name: 'Wine B', category: 'red'},
    {name: 'Wine C', category: 'white'},
    {name: 'Wine D', category: 'red'},
    {name: 'Wine E', category: 'red'},
    {name: 'Wine F', category: 'white'},
    {name: 'Wine G', category: 'champagne'},
    {name: 'Wine H', category: 'champagne'}
  ];

  // Functions - Public
  self.filterByCategory = filterByCategory;
  self.getCategories = getCategories;
  self.reset = function(){self.filter = {};}
  // Functions - Definitions
  function filterByCategory(wine) {
    return self.filter[wine.category] || noFilter(self.filter);
  }

  function getCategories() {
    return (self.wines || []).
      map(function (wine) { return wine.category; }).
      filter(function (cat, idx, arr) { return arr.indexOf(cat) === idx; });
  }

  function noFilter(filterObj) {
    return Object.
      keys(filterObj).
      every(function (key) { return !filterObj[key]; });
  }
}

}());

Categories

    <button ng-click="ctrl.reset()">Reset</button>

        <input type="checkbox" ng-model="ctrl.filter[category]" />
        {{ category }}

Available Wines

      {{ wine.name }} ({{ wine.category }})

    Number of results: {{ filteredWines.length }}


text:
Q: Redis nodes.conf file locked? I am following this tutorial to create a Redis cluster:
http://redis.io/topics/cluster-tutorial
In this tutorial I need to run several redis-server instances on port 7000 through 7005. However after I run the first instance successfully and try to run the second instance the nodes.conf file seems to be locked and I get the following error message:
"Sorry, the cluster configuration file nodes.conf is already used by a different Redis Cluster node. Please make sure that different nodes use different cluster configuration files."
Do I need a separate nodes.conf for every server instance? Or do I need a separate redis-server executable in each instance directory and run it from there?

A: The tutorial suggests you to use separated folders for each instance configuration, so each instance will also generate the nodes.conf on its own folder.

Create a redis.conf file inside each of the directories, from 7000 to
  7005.

You need to have the .conf files on separated folders for each instance, and the executable must be ran from that folders.
Assuming you have the redis-server on /tmp/redis-cluster/, and the redis.conf on each /tmp/redis-cluster/700x folder:
cd /tmp/redis-cluster/7000
../redis-server ./redis.conf

This way the nodes.conf will be generated on the current folder 7000.
Note that you must first issue a cd to change the current directory, and from that folder execute the redis-server that is one folder up (../)


text:
Q: Postgres - partitioning a table How does the code look like to partition the following table. date and status are given, partition column shall be added. Column group is only to explain where the group starts and ends.
Finally, I like to do some analytics, e.g. how long takes the process per group.
In words but don't know to convert to code:
status 'approved' always defines the end. Only an 'open' after 'approval' defines the start. The other 'open' are not relevant.

date
status
Group
Partition

1.10.2022
open
Group 1 Starts
1

2.10.2022
waiting

1

3.10.2022
open

1

4.10.2022
waiting

1

5.10.2022
approved
Group 1 Ends
1

7.10.2022
open
Group 2 Start
2

8.10.2022
waiting

2

9.10.2022
open

2

10.10.2022
waiting

2

11.10.2022
open

2

12.10.2022
waiting

2

15.10.2022
approved
Group 2 Ends
2

17.10.2022
open
Group 3 Starts
3

20.10.2022
waiting

3

Thanks for the solution. Works fine :-) And sorry for not using the right expression. If Group is better than Partition even better...
Can we make it slightly more complicated?
This patter in the table applis to several parent records. So in reality there is an additional column Parent ID. This table below is then for example for parent ID A. There are many more parents.
How can an additional grouping be added by Parent ID?
At eeach new parent the counting starts again at 1

A: Assuming you have the first two columns and want to derive the last two, treat this as a gaps-and-islands problem:
with groups as (  -- Assign partitions
  select *,
         coalesce(
           sum(case when status = 'approved' then 1 else 0 end)
             over (order by date rows between unbounded preceding
                                          and 1 preceding),
           0
         ) + 1 as partition
    from do_part
)
select date, status,
       case   -- Construct text descriptions
         when partition != coalesce(lead(partition) over w, partition)
           then format('Group %s Ends', partition)
         when partition = lag(partition) over w
           then ''
         else format('Group %s Starts', partition)
       end as "group",
       partition
  from groups
window w as (order by date);

Fiddle here

A: demo based on (Mike Organek)'s fiddle.
idea: left join with distinct on can properly cut the group.
SELECT DISTINCT ON (date,status)
    date,
    status,
    coalesce(date_d, CURRENT_DATE) AS date_end
FROM
    do_part t
    LEFT JOIN (
        SELECT
            date AS date_d
        FROM
            do_part
        WHERE
            status = 'approved'
        ORDER BY
            date) s ON s.date_d >= t.date
ORDER BY
    date,status,
    date_d;

Final query (can be simplified):
   WITH cte AS (
    SELECT DISTINCT ON (date,
        status)
        date,
        status,
        coalesce(date_d, CURRENT_DATE) AS date_end
    FROM
        do_part t
        LEFT JOIN (
            SELECT
                date AS date_d
            FROM
                do_part
            WHERE
                status = 'approved'
            ORDER BY
                date) s ON s.date_d >= t.date
        ORDER BY
            date,
            status,
            date_d
),
cte1 AS (
    SELECT
        *,
        date_end - first_value(date) OVER (PARTITION BY date_end ORDER BY date) AS date_gap,
    dense_rank() OVER (ORDER BY date_end),
    CASE WHEN (date = first_value(date) OVER (PARTITION BY date_end ORDER BY date)) THEN
        'group begin'
    WHEN (status = 'approved') THEN
        'group end '
    ELSE
        NULL
    END AS grp
FROM
    cte
)
SELECT
    *,
    CASE WHEN grp IS NOT NULL THEN
        grp || dense_rank::text
    END
FROM
    cte1;


text:
Q: How to detect HTML in clipboard data using Qt I have a rich text editor I'm working on where I need to parse and clean data from the clipboard when appropriate. Whenever the text being pasted contains HTML, I will clean it up and update the text field with the correct html.
However, when there is no html in the clipboard, there is no need for me to run the html cleaning tool.
My first thought was to use Regex and check for any html tag in there, but I'm not sure this is the best solution for this problem as it can cause more headaches in the long run with false positives, etc.
My question is, how can I detect some HTML in the clipboard?
Is there a an elegant way to solve this problem without having to resort to Regex?

A: may be one of these functions:
bool QDomDocument::setContent(...)

This function reads the XML document from the string text, returning true if the content was successfully parsed; otherwise returns false. Since text is already a Unicode string, no encoding detection is done
Addition for a clipboard's mixed data:
// get a html data from a junk
QString htmlText = cliboardString.section("</html>", -2, 0,QString::SectionIncludeTrailingSep)
              .section("<html", 1,-1,String::SectionIncludeLeadingSep);
// check for a validness, correctness etc.
if( !htmlText.isEmpty() ) {
    QDomDocument::setContent(htmlText,...
}


text:
Q: How to show that action of an algebra $H$ on a vector space is the same as the coaction of $H^*$ on $V$? Let $H$ be a Hopf algebra and $V$ a finite dimensional $H$-module. How to show that action of an algebra $H$ on a vector space is the same as the coaction of $H^*$ on $V$? Thank you very much.

A: First, you need to be careful about left/right here.  Left $H$-modules would induce right comodules over the dual.  Provided that the dual actually makese sense, which leads us to...
Secondly, if $H$ is infinite dimensional then $H^*$ does not make sense as a Hopf algebra.  The multiplication map $m\colon H\otimes H\to H$ would formally dualize to $m^*\colon H^*\to (H\otimes H)^*$, and in infinite dimensions $H^*\otimes H^*$ is a proper subspace of $(H\otimes H)^*$, and the image of $m^*$ is almost never fully contained in this proper subspace.  But this is required for $m^*$ to be a comultiplication.  Whence the algebra structure generally does not dualize to a coalgebra structure.  This problem disappears in finite dimensions, and the dualizing makes sense.
For the infinite dimensional case you need to use something called the Sweedler dual of $H$, and suppose that the orbit of any $v\in V$ under the left $H$-action is finite dimensional.  I'll skip over the specific details for that.
Picking $v\in V$ and letting $\{v_1,...,v_n\}$ be a basis of $Hv$, then for any $h\in H$ we can write $hv = \displaystyle{\sum_i^n f_i(a)v_i}$ for some $f_i\in H^*$.  One can show that these $f_i$ always lie in the Sweedler dual in the infinite dimensional case, under the finite dimensional orbit assumption
We then make $V$ into a right comodule over the (Sweedler) dual via $\rho(v) = \displaystyle{\sum_i^n v_i\otimes f_i}$.
Note this only requires $H$ to be an algebra.
On the other hand, supposing you have a right $C$-comodule $V$, for $C$ a coalgebra, with structure map $\rho(v)=v_0\otimes v_1$, we can define a left $C^*$-module (note that a coalgebra always dualizes to an algebra) structure on $V$ by $fv=\langle f,m_1\rangle m_0$ for all $f\in C^*$.
It is then easy to see that the right comodule we obtained from the left module will then dualize back to the original left module.  It is in this sense that they are "the same".


text:
Q: using substring properly on a stringbuilder type I am building up a string of data using substring. The format of the data I want is
[1,2,3,4,5,6,7,8,9,10]

So I am building it up as follows
StringBuilder sb = new StringBuilder();
sb.append("1,");
sb.append("2,");
sb.append("3,");
.
.
.

The problem I run into is when I want to trim the final , before adding the closing ].
I could do
sb.ToString();
sb.Substring(0, (sb.Length - 1));
sb += "]";

But using the += is not very efficient as this creates a new string. Is there a better way of doing this?

A: var str = "[" + String.Join(", ",Enumerable.Range(1,10)) + "]";

A: Don't add the final , if you don't need it:
var sb = new StringBuilder().Append('[');
var first = true;
foreach (var item in collection)
{
    if (first)
        first = false;
    else
        sb.Append(',');
    sb.Append(item);
}
sb.Append(']');
var result = sb.ToString();

A: The easiest is to use -= on the StringBuilder's Length since it's writable:
sb.Length -= 1; // removes the last char

A: UPDATE
After a little testing
var result = string.Concat("[", string.Join(",", someEnumerable), "]");

is both much simpler and faster than a builder approach

You could always just do
var result = string.Format("[{0}]", string.Join(",", someEnumerable));

The sequence can be anything you want, for instance
var someEnumerable = Enumerable.Range(1, 10);

This seems simpler than reinventing the wheel, and avoids intermediate strings.
This does make assumptions about the implementation of String.Join but, I think you should assume that its good enough for this purpose.

For more information, this Question does a comparison between String.Join and StringBuilder.
This Question indicates that String.Format uses a StringBuilder.

A: Here is an example as a nice clean method:
    public static string WriteValues(int start, int end)
    {
        StringBuilder sb = new StringBuilder();
        sb.Append("[");
        for (int index = start; index <= end; index++)
        {
            sb.Append(index).Append(",");
        }
        sb.Length -= 1;
        sb.Append("]");
        return sb.ToString();
    }

This does all the work in the StringBuilder and then passes back a single string. Also you can specify the start and end values!


text:
Q: Multipeer connectivity with one device having app running in background I would like to connect 2 devices using multipeer connectivity framework where one of those devices is running the app in the background, just like Firechat does (I can't confirm this is working, I have installed it on an iPhone 5S and 4, but they just can't find each other - but I have read somewhere this works).
What's the best way to achieve this?
I'm using the following two methods from an example code:
-(void)setupPeerAndSessionWithDisplayName:(NSString *)displayName{
    _peerID = [[MCPeerID alloc] initWithDisplayName:displayName];

    _session = [[MCSession alloc] initWithPeer:_peerID];
    _session.delegate = self;
}

-(void)setupMCBrowser{
    _browser = [[MCBrowserViewController alloc] initWithServiceType:@"chat-files" session:_session];
}

-(void)advertiseSelf:(BOOL)shouldAdvertise{
    if (shouldAdvertise) {
        _advertiser = [[MCAdvertiserAssistant alloc] initWithServiceType:@"chat-files"
                                                           discoveryInfo:nil
                                                                 session:_session];
        [_advertiser start];
    }
    else{
        [_advertiser stop];
        _advertiser = nil;
    }
}

When I'm running the app in the foreground, it finds the other device flawlessly and also connects. But if I put one of the apps into background, the background-app-device is no longer visible.
I have already read this: Can I have a multipeer connectivity session run in the background? - But I can't believe this is not possible without any workaround.
FYI, my app is also using background location updates, if that's relevant...
Thanks!
EDIT:
Is there some other way of doing this?? Basically I just want to send a message to the other device (to the one who's app is running in the background) - since Multipeer connectivity doesn't work in the background, can I connect via bluetooth directly for example?

A: Apple have confirmed that "Multipeer Connectivity does not function in the background". The reason is that if your app is suspended then its socket resources can be reclaimed and everything falls apart.
However, it is possible to monitor iBeacons when in the background. Essentially, you set your app up to monitor proximity to a beacon with a specific id. Then, your app that is in the foreground becomes a beacon with that same id. This causes the following app delegate method to be called on the app in the background:
- (void)locationManager:(CLLocationManager *)manager didDetermineState:(CLRegionState)state forRegion:(CLRegion *)region {
    UILocalNotification *notification = [[UILocalNotification alloc] init];

    if(state == CLRegionStateInside) {
        notification.alertBody = NSLocalizedString(@"A nearby app would like to connect", @"");
    } else {
        return;
    }
    [[UIApplication sharedApplication] presentLocalNotificationNow:notification];
}

Here you issue a local notification that, when tapped on by the user, will bring your app into the foreground, at which point you can start advertising for a peer-to-peer connection.


text:
Q: Dynamically change a button-drop list in javascript? Trying to create a changeable button-drop-down from Bootstrap HTML in conjunction with Javascript. The HTML looks as:

    Menu

Choice1

Choice2

Choice3

Choice..

Would like to be able to change the choices of the drop-down button based on what else is happening on the page. So if user clicks a "profile" button somewhere on the page instead of Choice1, Choice2 and Choice3 there would be Resume, Contact Info, Education etc. The number of items in the menu would change as would the exact values for the display text. Ideally would like to use some type of array to push/pop from the choices. Have tried add, childappend, etc.

A: Here's one approach - have all your menu items in the HTML, and then use CSS to hide/show the appropriate ones

        Menu

Choice1

Choice2

Choice3

Choice..

Resume

Education

Eat a badger

CSS:
/* hide all menu items */
ul.dropdown-menu > li {
    display: none;
}

/* show menu items if they're relevant */
ul.dropdown-menu[data-menu-id=default] > li.default,
ul.dropdown-menu[data-menu-id=profile] > li.profile,
ul.dropdown-menu[data-menu-id=badgers] > li.badgers {
   display: list-item;
}

Now use javascript to change the data-menu-id attribute on your dropdown, and the menu items will change automatically:
var dropdownMenu = document.getElementById('my-dropdown');
dropdownMenu.setAttribute("data-menu-id", "profile");

Lots of other ways to do this, but this is probably the slickest approach. The CSS basically says "if the class of the list item matches the menu id attribute on the parent, make it visible".
An advantage of this approach is that you can make a menu item visible in multiple different menus just by giving it multiple classes:

Badger Resume


text:
Q: Per-directory permissions on git We are considering switching our VCS to either git or subversion. I'd prefer switching to git, but subversion has a nice feature that I don't see in git : per directory access control.
We currently have project1, project2 repositories in cvs, with different permissions.
We'd like to have one single repository, with two directories project1 & project2 with different permissions. Is it doable with git as it is with svn ?
I'm aware of submodules, which could probably achieve that, but the goal for us is to be able to do one single commit with changes in project1 & project2.
We mainly have IP issues, and want to be sure that some people can't read (not just push) some directories.
So, is git up for the challenge or will I have to use git-svn ?
Thanks

A: It is doable with a central repo with access (push/pull) managed by gitolite.
See its features.
If you combine that with submodules (which you are aware of), you would only manage per-repo or per branch access and still commit both project1 and project2 (with two commits in case of a subrepo: see this question)
If you insist on working with one repo (even though you have to set of data which could evolve with their own lifecycle, which should make them good candidates for modules), then the gitolite features do include:

file/dir NAME based restrictions
In addition to branch-name based restrictions, gitolite also allows you to restrict what files or directories can be involved in changes being pushed

dpk mentions in the comments that this last feature (the file/dir name restriction) is detailed in the conf/example.conf file of Gitolite.

A: Try nigit https://github.com/kingsimba/nigit. My team(over 30 people) has been using it for years.
It can manage correlated projects as a whole, by pulling them together, switching branch together, etc. Each project has its own collaborators and permissions.
If someone don't have permission to some source code(subprojects), they can use the compiled binaries.
$ nigit status
=== nigit ===
+ some_new_file
- some_deleted_file
M some_modified_file
? some_untracked_file
=== ncgeo ===
- other_deleted_file
? other_untracked_file


text:
Q: Making SIP Call immediately get 403 after ringing I am trying to make a phonecall using sipML5 library. The apps can successfully register into the SIP server.
How ever when i try to make a phone call, it says 403 Forbidden soon after ringing.
Here is some screenshot

Does anyone know why i am getting 403 Forbidden ? I can fully authenticate and register my account prior dialing any numbers. But this only happens soon after i dial another SIP number/account.

A: sipML5 is a SIP client. You should try to connect with a softphone using those credentials and trying to dial the same account/number.
You should see more details on the SIP server side of things if you have access to that.


text:
Q: Work done by force and tension of a string on a body
A person lifts a box using a string passing over a smooth pulley and inclines to the vertical with a 30 degrees angle. The tension force in the string is 120 newton to rise the box 3 meters.

Is there a difference between the work done by the force on the box and the work done by the tension on the box?

A: The difference is that $F$ is the force on the rope.  The force on the block is the tension force at the point the rope joins the block.  Forces are applied at a point.  It's often helpful to draw a line around the system which defines the system and it's environment.  If the object in question is the block, then no part of the rope should be included; the line would slip in between the end of the rope and the block.  Then look for places where the system touches the environment.  (This works for contact forces.  Non-contact forces have to be considered separately.)
If the rope is massless, then the magnitude of $F$ is the same as the tension force on the block.   If the rope is inextensible (can't stretch) the motion of the block is constrained to the motion of whatever is applying $F$.  So both $F$ and $\Delta x$ is the same.  Same work.
If the rope has mass, then the two forces are not equal. It's very instructive to analyze that case.  Hint:  take the system to be the block and part of the rope.  That is, your line defining the system cuts through the rope.  Part of the rope and it's mass is part of the system, and the remainder and it's mass is in the environment (aka surroundings).  Then you can set the mass of the rope to zero and see what happens.


text:
Q: Detecting edges of a card with rounded corners Hi currently i am working on an OCR reading app where i have successfully able to capture the card image by using AVFoundation framework.
For next step, i need to find out edges of the card , so that i can crop the card image from main captured image & later i can sent it to OCR engine for processing.
The main problem is now to find the edges of the card & i am using below code(taken from another open source project) which uses OpenCV for this purpose.It is working fine if the card is pure rectangular Card or Paper. But when i use a card with rounded corner (e.g Driving License), it is failed to detect . Also i dont have much expertise in OpenCV , Can any one help me in solving this issue?
- (void)detectEdges
{
    cv::Mat original = [MAOpenCV cvMatFromUIImage:_adjustedImage];
    CGSize targetSize = _sourceImageView.contentSize;
    cv::resize(original, original, cvSize(targetSize.width, targetSize.height));

    cv::vector<cv::vector<cv::Point>>squares;
    cv::vector<cv::Point> largest_square;

    find_squares(original, squares);
    find_largest_square(squares, largest_square);

    if (largest_square.size() == 4)
    {

        // Manually sorting points, needs major improvement. Sorry.

        NSMutableArray *points = [NSMutableArray array];
        NSMutableDictionary *sortedPoints = [NSMutableDictionary dictionary];

        for (int i = 0; i < 4; i++)
        {
            NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:[NSValue valueWithCGPoint:CGPointMake(largest_square[i].x, largest_square[i].y)], @"point" , [NSNumber numberWithInt:(largest_square[i].x + largest_square[i].y)], @"value", nil];
            [points addObject:dict];
        }

        int min = [[points valueForKeyPath:@"@min.value"] intValue];
        int max = [[points valueForKeyPath:@"@max.value"] intValue];

        int minIndex;
        int maxIndex;

        int missingIndexOne;
        int missingIndexTwo;

        for (int i = 0; i < 4; i++)
        {
            NSDictionary *dict = [points objectAtIndex:i];

            if ([[dict objectForKey:@"value"] intValue] == min)
            {
                [sortedPoints setObject:[dict objectForKey:@"point"] forKey:@"0"];
                minIndex = i;
                continue;
            }

            if ([[dict objectForKey:@"value"] intValue] == max)
            {
                [sortedPoints setObject:[dict objectForKey:@"point"] forKey:@"2"];
                maxIndex = i;
                continue;
            }

            NSLog(@"MSSSING %i", i);

            missingIndexOne = i;
        }

        for (int i = 0; i < 4; i++)
        {
            if (missingIndexOne != i && minIndex != i && maxIndex != i)
            {
                missingIndexTwo = i;
            }
        }

        if (largest_square[missingIndexOne].x < largest_square[missingIndexTwo].x)
        {
            //2nd Point Found
            [sortedPoints setObject:[[points objectAtIndex:missingIndexOne] objectForKey:@"point"] forKey:@"3"];
            [sortedPoints setObject:[[points objectAtIndex:missingIndexTwo] objectForKey:@"point"] forKey:@"1"];
        }
        else
        {
            //4rd Point Found
            [sortedPoints setObject:[[points objectAtIndex:missingIndexOne] objectForKey:@"point"] forKey:@"1"];
            [sortedPoints setObject:[[points objectAtIndex:missingIndexTwo] objectForKey:@"point"] forKey:@"3"];
        }

        [_adjustRect topLeftCornerToCGPoint:[(NSValue *)[sortedPoints objectForKey:@"0"] CGPointValue]];
        [_adjustRect topRightCornerToCGPoint:[(NSValue *)[sortedPoints objectForKey:@"1"] CGPointValue]];
        [_adjustRect bottomRightCornerToCGPoint:[(NSValue *)[sortedPoints objectForKey:@"2"] CGPointValue]];
        [_adjustRect bottomLeftCornerToCGPoint:[(NSValue *)[sortedPoints objectForKey:@"3"] CGPointValue]];
    }

    original.release();

}

A: instead of "pure" rectangular blobs, try to go for nearly rectangular ones.
1- gaussian blur
2- grayscale and canny edge detection
3- extract all blobs (contours) in your image and filter out small ones. you will use findcontours and contourarea functions for that purpose.
4- using moments, filter out non-rectangular ones. First you need to check out moments of rectangle-like objects. You can do it by yourself or google it. Then list those moments and find similarity between objects, create your filter as such.
Ex: After test, say you found out central moment m30's are similar for rectangle-like objects -> filter out objects having inaccurate m30.

A: I know maybe it's too late for this post, but I am posting this in case it might help someone else.
The iOS Core Image framework already has a good tool to detect features such as rectangles (since iOS 5), faces, QR codes and even regions containing text in a still image. If you check out the CIDetector class you'll find what you need. I am using it for an OCR app too, it's super easy and very reliable compared to what you can do with OpenCV (I am not good with OpenCV, but the CIDetector gives much better results with 3-5 lines of code).

A: This naive implementation is based on some of the techniques demonstrated in squares.cpp, available in the OpenCV sample directory. The following posts also discuss similar applications:

*

*OpenCV C++/Obj-C: Detecting a sheet of paper / Square Detection

*Square detection doesn't find squares

*Find corner of papers
@John, the code below has been tested with the sample image you provided and another one I created:

The processing pipeline starts with findSquares(), a simplification of the same function implemented by OpenCV's squares.cpp demo. This function converts the input image to grayscale and applies a blur to improve the detection of the edges (Canny):

The edge detection is good, but a morphological operation (dilation) is needed to join nearby lines:

After that we try to find the contours (edges) and assemble squares out of them. If we tried to draw all the detected squares on the input images, this would be the result:

It looks good, but it's not exactly what we are looking for since there are too many detected squares. However, the largest square is actually the card, so from here on it's pretty simple and we just figure out which of the squares is the largest. That's exactly what findLargestSquare() does.
Once we know the largest square, we simply paint red dots at the corners of the square for debugging purposes:

As you can see, the detection is not perfect but it seems good enough for most uses. This is not a robust solution and I only wanted to share one approach to solve the problem. I'm sure that there are other ways to deal with this that might be more interesting to you. Good luck!
#include <iostream>
#include <cmath>
#include <vector>

#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/imgproc/imgproc_c.h>

/* angle: finds a cosine of angle between vectors, from pt0->pt1 and from pt0->pt2
 */
double angle(cv::Point pt1, cv::Point pt2, cv::Point pt0)
{
    double dx1 = pt1.x - pt0.x;
    double dy1 = pt1.y - pt0.y;
    double dx2 = pt2.x - pt0.x;
    double dy2 = pt2.y - pt0.y;
    return (dx1*dx2 + dy1*dy2)/sqrt((dx1*dx1 + dy1*dy1)*(dx2*dx2 + dy2*dy2) + 1e-10);
}

/* findSquares: returns sequence of squares detected on the image
 */
void findSquares(const cv::Mat& src, std::vector<std::vector<cv::Point> >& squares)
{
    cv::Mat src_gray;
    cv::cvtColor(src, src_gray, cv::COLOR_BGR2GRAY);

    // Blur helps to decrease the amount of detected edges
    cv::Mat filtered;
    cv::blur(src_gray, filtered, cv::Size(3, 3));
    cv::imwrite("out_blur.jpg", filtered);

    // Detect edges
    cv::Mat edges;
    int thresh = 128;
    cv::Canny(filtered, edges, thresh, thresh*2, 3);
    cv::imwrite("out_edges.jpg", edges);

    // Dilate helps to connect nearby line segments
    cv::Mat dilated_edges;
    cv::dilate(edges, dilated_edges, cv::Mat(), cv::Point(-1, -1), 2, 1, 1); // default 3x3 kernel
    cv::imwrite("out_dilated.jpg", dilated_edges);

    // Find contours and store them in a list
    std::vector<std::vector<cv::Point> > contours;
    cv::findContours(dilated_edges, contours, cv::RETR_LIST, cv::CHAIN_APPROX_SIMPLE);

    // Test contours and assemble squares out of them
    std::vector<cv::Point> approx;
    for (size_t i = 0; i < contours.size(); i++)
    {
        // approximate contour with accuracy proportional to the contour perimeter
        cv::approxPolyDP(cv::Mat(contours[i]), approx, cv::arcLength(cv::Mat(contours[i]), true)*0.02, true);

        // Note: absolute value of an area is used because
        // area may be positive or negative - in accordance with the
        // contour orientation
        if (approx.size() == 4 && std::fabs(contourArea(cv::Mat(approx))) > 1000 &&
            cv::isContourConvex(cv::Mat(approx)))
        {
            double maxCosine = 0;
            for (int j = 2; j < 5; j++)
            {
                double cosine = std::fabs(angle(approx[j%4], approx[j-2], approx[j-1]));
                maxCosine = MAX(maxCosine, cosine);
            }

            if (maxCosine < 0.3)
                squares.push_back(approx);
        }
    }
}

/* findLargestSquare: find the largest square within a set of squares
 */
void findLargestSquare(const std::vector<std::vector<cv::Point> >& squares,
                       std::vector<cv::Point>& biggest_square)
{
    if (!squares.size())
    {
        std::cout << "findLargestSquare !!! No squares detect, nothing to do." << std::endl;
        return;
    }

    int max_width = 0;
    int max_height = 0;
    int max_square_idx = 0;
    for (size_t i = 0; i < squares.size(); i++)
    {
        // Convert a set of 4 unordered Points into a meaningful cv::Rect structure.
        cv::Rect rectangle = cv::boundingRect(cv::Mat(squares[i]));

        //std::cout << "find_largest_square: #" << i << " rectangle x:" << rectangle.x << " y:" << rectangle.y << " " << rectangle.width << "x" << rectangle.height << endl;

        // Store the index position of the biggest square found
        if ((rectangle.width >= max_width) && (rectangle.height >= max_height))
        {
            max_width = rectangle.width;
            max_height = rectangle.height;
            max_square_idx = i;
        }
    }

    biggest_square = squares[max_square_idx];
}

int main()
{
    cv::Mat src = cv::imread("cc.png");
    if (src.empty())
    {
        std::cout << "!!! Failed to open image" << std::endl;
        return -1;
    }

    std::vector<std::vector<cv::Point> > squares;
    findSquares(src, squares);

    // Draw all detected squares
    cv::Mat src_squares = src.clone();
    for (size_t i = 0; i < squares.size(); i++)
    {
        const cv::Point* p = &squares[i][0];
        int n = (int)squares[i].size();
        cv::polylines(src_squares, &p, &n, 1, true, cv::Scalar(0, 255, 0), 2, CV_AA);
    }
    cv::imwrite("out_squares.jpg", src_squares);
    cv::imshow("Squares", src_squares);

    std::vector<cv::Point> largest_square;
    findLargestSquare(squares, largest_square);

    // Draw circles at the corners
    for (size_t i = 0; i < largest_square.size(); i++ )
        cv::circle(src, largest_square[i], 4, cv::Scalar(0, 0, 255), cv::FILLED);
    cv::imwrite("out_corners.jpg", src);

    cv::imshow("Corners", src);
    cv::waitKey(0);

    return 0;
}

A: I don't know if it is an option, but you could have the user define the edges of it rather than trying to do it programatically.


text:
Q: How to bind data with Enable Property? How can i enabled/disable server control using Eval('bindata')?
<asp:TextBox ID="txtRemarks" runat="server" Text='<%#Eval("Remarks") %>'
    CssClass="remarkstest"  Enabled="'<%#Eval("IsSundayChangable") %>'"></asp:TextBox>

A: try something like this:
<asp:TextBox ID="txtRemarks" runat="server" Text='<%#Eval("Remarks") %>'    CssClass="remarkstest"  <%# GetStatus(Container.DataItem)%> ></asp:TextBox>

    protected string GetStatus(object oItem)
    {
          return DataBinder.Eval(oItem, "IsSundayChangable").toString()=="false"?"disabled",string.empty;
    }


text:
Q: Select does not work - Oracle i'm beginning in Oracle. I use SQL Developer and i'm trying to Launch an SQL request like that :
select date_depart,* from train where no_train='111';

An error message is displayed : "missing expression"
How i can resolve this problem please ?

A: If you want to use any other column or expression alongside the * wildcard, you have to specify which table the * refers too, either using the full name:
select no_train, train.* from train where no_train='111';

or with an alias:
select t.no_train, t.* from train t where no_train='111';

But as the wildcard * gets all columns, you'll see train_no twice. It's better to list the columns you want:
select t.train_no, t.train_type, t.depot, ... -- whatever your real columns are
from train t
where t.train_no = 111

If the train number is actually a number data type you should not be enclosing the literal 111 in quotes. Always use the right data type, don't force or rely on implicit data conversion.

A: Assuming that you want a result containing the column no_train followed by all the columns of the table, including no_train that will be showed twice, you may need to add an alias:
select no_train, t.*
from train t
where no_train='111';

For example, with a table like this
create table train(no_train, descr) as ( select 111, 'descr' from dual);

this will give:
SQL> select no_train, t.*
  2  from train t
  3  where no_train='111';

  NO_TRAIN   NO_TRAIN DESCR
---------- ---------- -----
       111        111 descr


text: Q: What is the right way to test website's backup? I have a wiki based on dokuwiki. I made a backup of it by archiving all files. I can automate testing it extracting files and manually see that website works. But what is the right way to check that all backup is correct? I thought it should be like that: while making backup script should go to all pages, which it can reach, compute and store the hash of retrieved page. And while testing backup script should do the same and compare hashes. Is it right?


text:
Q: Is there a shorthand for creating a String constant in Spring context XML file?

I need to define a string value in Spring context XML file that is shared by multiple beans.
This is how I do it:
<bean id="aSharedProperty" class="java.lang.String">
    <constructor-arg type="java.lang.String" value="All beans need me :)"/>
</bean>

Creating a java.lang.String bean by passing a constructor argument of java.lang.String seems kludgy.
Is there a shortcut?
I know this property can be passed using PropertyOverrideConfigurer, but I want to keep this property within the XML file.

A: You may be able to use the following:
<bean id="abstractParent" abstract="true">
    <property name="sharedProperty" value="All child beans need me" />
</bean>

<bean id="bean1" class="MyClass1" parent="abstractParent">
    ...non-shared properties...
</bean>

<bean id="bean2" class="MyClass2" parent="abstractParent">
    ...non-shared properties...
</bean>

However, that relies on the property having the same name, so may not be applicable for you.

A: Something I've used in the past is SpEL to make sure that a bean has the same value as another:
<bean id="myBean" class="xxx.yyy.Foo" >
    <property name="myProperty" value="1729" />
</bean>

<bean id="copyCat" class="xxx.yyy.Bar" >
    <property name="anotherProperty" value="#{myBean.myProperty}" />
</bean>

I have found this to be particularly useful when setting the value did something other than a simple assignment.

A: You can use PropertyPlaceholderConfigurer and keep values in xml:
<context:property-placeholder properties-ref="myProperties"/>

<bean id="myProperties"
    class="org.springframework.beans.factory.config.PropertiesFactoryBean">
  <property name="properties">
    <props>
      <prop key="aSharedProperty">All beans need me :)</prop>
    </props>
  </property>
</bean>

Then you reference it with:
<bean id="myBean" class="my.package.MyClass">
  <property name="someField" value="${aSharedProperty}"/>
</bean>

A: A shorthand to the solution proposed by mrembisz goes like this:
<context:property-placeholder properties-ref="myProperties"/>

<util:properties id="myProperties">
    <prop key="aSharedProperty">All beans need me :)</prop>
</util:properties>


text:
Q: Vuetify v-data-table with vuex. Not rendering in unit test vue 2.5.2
vuex 3.0.1
vuetify 1.0.16
I'm creating vuex+vuetify application.
Rendering data is in the vuex store.
It uses v-data-table with pagination.
The component code is
<template>
  <v-container>
    <v-text-field id="shopName" v-model="editedItem.name" required></v-text-field>
    <v-btn id="save" color="blue darken-1" flat @click.native="save">save</v-btn>
    <v-data-table :headers="headers" :pagination.sync="pagination" :items="shops" class="elevation-1">
      <template slot="items" slot-scope="props">
          {{ props.item.name }}
      </template>
      <template slot="no-data">
          no item
      </template>
    </v-data-table>
  </v-container>
</template>

And I added test code.
First one is 'adds a new shop' test , that add store.
The test passed.
And next test 'uses same store' is rendering with same store instance.
But test not passed.
When removing pagination setting from component, then test passed.
Why not rendering when pagination setting existing.
import { mount } from 'avoriaz'
import Vue from 'vue'
import Vuetify from 'vuetify'
import DataTable from '@/components/DataTable'
import { store } from '../../../src/store/store.js'

Vue.use(Vuetify)

describe('Shop.vue', () => {
  it('adds a new shop', async () => {
    // build component
    const wrapper = mount(DataTable, {store})
    const inputShopName = wrapper.find('input#shopName')[0]
    inputShopName.trigger('focus')
    inputShopName.element.value = 'AEON'
    inputShopName.trigger('input')
    await wrapper.vm.$nextTick()
    wrapper.find('button#save')[0].trigger('click')
    await wrapper.vm.$nextTick()
    expect(wrapper.html()).toContain('AEON')
  })
  it('uses same store', () => {
    // build component
    const wrapper2 = mount(DataTable, {store})
    expect(wrapper2.html()).toContain('AEON')
  })
})

Reproduction code in
https://github.com/dokechin/vue-test-example

A: I tried changed my problem more simple.
Making store data before mounting, not rendering when pagination.sync exists.
import { mount } from 'avoriaz'
import Vue from 'vue'
import Vuetify from 'vuetify'
import DataTable from '@/components/DataTable'
import { store } from '../../../src/store/store.js'

Vue.use(Vuetify)

describe('Shop.vue', () => {
  it('uses store', () => {
    // build component
    store.state.items.push({name: 'AEON'})
    const wrapper2 = mount(DataTable, {store})
    expect(wrapper2.html()).toContain('AEON')
  })
})


text:
Q: In Corona SDK, why is this function returning an error? LINE 212   function onCollision(e)
  LINE 213     transition.to(gameView, {time = 300, x = -gameView.height,  display.remove() gameView= nil

end})

   endGame = display.newImage('end_game_background.png', display.contentWidth, display.contentHeight-   300)

    transition.to(endGame)

background.isVisible = false
lineGroup.isVisible = false

end

When I try to run this code, I get an error that says this:
main.lua line:213: '}' expected near gameView

A: transition.to(gameView, {time = 300, x = -gameView.height,  display.remove() gameView= nil

end})

is not correct, try onComplete or onCancel, also use display.remove(gameView) instead of display.remove():
transition.to(gameView, {time = 300, x = -gameView.height, onComplete=function()
    display.remove(gameView)
    gameView= nil
end})