model training starts all over again after unfreezing weights in tensorflow

Question: I am training an image classifier using Large EfficientNet:
base_model = EfficientNetV2L(input_shape = (300, 500, 3),
                            include_top = False,
                            weights = 'imagenet',
                            include_preprocessing = True)

model = tf.keras.Sequential([base_model,
                             layers.GlobalAveragePooling2D(),
                             layers.Dropout(0.2),
                             layers.Dense(128, activation = 'relu'),
                             layers.Dropout(0.3),
                             layers.Dense(6, activation = 'softmax')])

base_model.trainable = False

model.compile(optimizer = optimizers.Adam(learning_rate = 0.001),
              loss = losses.SparseCategoricalCrossentropy(),
              metrics = ['accuracy'])

callback = [callbacks.EarlyStopping(monitor = 'val_loss', patience = 2)]
history =  model.fit(ds_train, batch_size = 28, validation_data = ds_val, epochs = 20, verbose = 1, callbacks = callback)

it is working properly.
model summary:
Model: "sequential"
_________________________________________________________________
 Layer (type)                Output Shape              Param #
=================================================================
 efficientnetv2-l (Functiona  (None, 10, 16, 1280)     117746848
 l)

 global_average_pooling2d (G  (None, 1280)             0
 lobalAveragePooling2D)

 dropout (Dropout)           (None, 1280)              0

 dense (Dense)               (None, 128)               163968

 dropout_1 (Dropout)         (None, 128)               0

 dense_1 (Dense)             (None, 6)                 774

=================================================================
Total params: 117,911,590
Trainable params: 164,742
Non-trainable params: 117,746,848
_________________________________________________________________

output:
Epoch 4/20
179/179 [==============================] - 203s 1s/step - loss: 0.1559 - accuracy: 0.9474 - val_loss: 0.1732 - val_accuracy: 0.9428

But, while fine-tuning it, I am unfreezing some weights:
base_model.trainable = True

fine_tune_at = 900
for layer in base_model.layers[:fine_tune_at]:
  layer.trainable = False

model.compile(optimizer = optimizers.Adam(learning_rate = 0.0001),
              loss = losses.SparseCategoricalCrossentropy(),
              metrics = ['accuracy'])

history =  model.fit(ds_train, batch_size = 28, validation_data = ds_val, epochs = 20, verbose = 1, callbacks = callback)

model summary:
Model: "sequential"
_________________________________________________________________
 Layer (type)                Output Shape              Param #
=================================================================
 efficientnetv2-l (Functiona  (None, 10, 16, 1280)     117746848
 l)

 global_average_pooling2d (G  (None, 1280)             0
 lobalAveragePooling2D)

 dropout (Dropout)           (None, 1280)              0

 dense (Dense)               (None, 128)               163968

 dropout_1 (Dropout)         (None, 128)               0

 dense_1 (Dense)             (None, 6)                 774

=================================================================
Total params: 117,911,590
Trainable params: 44,592,230
Non-trainable params: 73,319,360
_________________________________________________________________

And, it is starting the training all over again. For the first time, when I trained it with freezed weights, the loss decreased to 0.1559, after unfreezing the weights, the model started training again from loss = 0.444. Why is this happening? I think fine tuning should't reset the weights.
Comment: The learning rate for the second run is large. You may want to reduce further.
Answer: When training again the Adam lr rate for each node is set again to the initial lr maybe that is the reason for the big jump after you start the learning again.You can also specify to save and load the optimizer values as well when saving/loading the model. Maybe look here. You are also retraining a lot of parameters maybe reduce the amount of parameters. If you keep more old parameters the jump might not be that high.


Why does cmake not find the components of the boost library or am I doing something fundamentally wrong?

Question: I have a given random walker implementation.
I'm using Windows 10, usually, I prefer Linux, but for this, I might need my GPU later on and I don't want dual boot on this machine.
The documentation is only this:

Installation Install from PyPI using pip install rw_noise.
Building The library itself is implemented in C++ and requires a
modern compiler that supports the C++20 standard. Further, the
following libraries have to be available:

Boost (with Python and NumPy support)
OpenMP
Python3
Eigen3
Magma, Cuda (optionally, for the GPU solver)

To build the library invoke python -m build and then install pip install <path_to_wheel> where <path_to_wheel> is likely a file in the
created dist subfolder with extension .whl.

When trying to run the installation using PyPi, I get a very long error message, though the important part should be the following:

Could NOT find Boost (missing: python numpy) (found version "1.66.0")

I downloaded the boost binaries from their page and extracted it in various locations at this point hoping that CMake would find it.
I have checked both Python and NumPy are included in this boost version.
I have tried out all the needed dependencies individually they all seem to work as far as I can tell, apart from Magma and Cuda since those are optional I decided to skip them at first and add them later once I know I can get it to work.
I added the boost file as an environment path as "BOOST_ROOT"
I also added the lib folder to the path variable.
Now I have realised that I probably shouldn't be using the binary boost version so I changed it to the normal one
This time I got the following error:

CMake Warning at
C:/Users/User/AppData/Local/Temp/pip-build-env-ujbspz4s/overlay/Lib/site-packages/cmake/data/share/cmake-3.28/Modules/FindBoost.cmake:1398
(message):
New Boost version may have incorrect or missing dependencies and imported
targets
Call Stack (most recent call first):
C:/Users/User/AppData/Local/Temp/pip-build-env-ujbspz4s/overlay/Lib/site-packages/cmake/data/share/cmake-3.28/Modules/FindBoost.cmake:1523
(_Boost_COMPONENT_DEPENDENCIES)
C:/Users/User/AppData/Local/Temp/pip-build-env-ujbspz4s/overlay/Lib/site-packages/cmake/data/share/cmake-3.28/Modules/FindBoost.cmake:2134
(_Boost_MISSING_DEPENDENCIES)
CMakeLists.txt:22 (find_package)
CMake Warning at C:/Users/User/AppData/Local/Temp/pip-build-env-ujbspz4s/overlay/Lib/site-packages/cmake/data/share/cmake-3.28/Modules/FindBoost.cmake:1398
(message):
New Boost version may have incorrect or missing dependencies and imported
targets
Call Stack (most recent call first):
C:/Users/User/AppData/Local/Temp/pip-build-env-ujbspz4s/overlay/Lib/site-packages/cmake/data/share/cmake-3.28/Modules/FindBoost.cmake:1523
(_Boost_COMPONENT_DEPENDENCIES)
C:/Users/User/AppData/Local/Temp/pip-build-env-ujbspz4s/overlay/Lib/site-packages/cmake/data/share/cmake-3.28/Modules/FindBoost.cmake:2134
(_Boost_MISSING_DEPENDENCIES)
CMakeLists.txt:22 (find_package)
CMake Error at C:/Users/User/AppData/Local/Temp/pip-build-env-ujbspz4s/overlay/Lib/site-packages/cmake/data/share/cmake-3.28/Modules/FindPackageHandleStandardArgs.cmake:230
(message):
Could NOT find Boost (missing: python numpy) (found version "1.84.0")
Call Stack (most recent call first):
C:/Users/User/AppData/Local/Temp/pip-build-env-ujbspz4s/overlay/Lib/site-packages/cmake/data/share/cmake-3.28/Modules/FindPackageHandleStandardArgs.cmake:600
(_FPHSA_FAILURE_MESSAGE)
C:/Users/User/AppData/Local/Temp/pip-build-env-ujbspz4s/overlay/Lib/site-packages/cmake/data/share/cmake-3.28/Modules/FindBoost.cmake:2392
(find_package_handle_standard_args)
CMakeLists.txt:22 (find_package)

I did check again, and both Python and NumPy are in the boost folder under .../boost_1_84_0/libs/python and .../boost_1_84_0/libs/python/src/numpy
Changing the CMake file should not be the answer, since it is given in the rw_noise git repository and it is made by someone more competent.
I might've forgotten something that I have tried already, I'm just very lost at this point.
If something is missing or you need more information don't hesitate to ask!
Any help would be greatly appreciated.
I have seen someone getting similar error messages, but their fixes all didn't work.
Comment: "Now i have realised i probably shouldnt be using the binary boost version" - No, you should use Boost in **binary** form. For debugging purposes, try to build the project directly with CMake (instead of via `pipi`). When run `cmake`, pass it additional parameter `-DBoost_DEBUG=ON`. That way CMake will print exact locations and exact names of Boost libraries which are searched. Check that on your PC you have those libraries.
Answer: As unsatisfying as it is.
I chose to opt for linux and it worked first try in less than 3min.


Como passar esse código JQuery em Javascript puro

Question: $(".checkbox-menu").on("change", "input[type='checkbox']", function() {
   $(this).closest("li").toggleClass("active", this.checked);
});

$(document).on('click', '.allow-focus', function (e) {
  e.stopPropagation();
});

Answer: Pode usar document.addEventListener verificando com event.target qual elemento foi clicado (click) ou modificado (change) (o event é o primeiro argumento do callback, onde eu posso dar um nome qualquer. No caso coloquei apenas e):

document.addEventListener("change", function(e){
   var el = e.target; // elemento alterado
   if(el.closest(".checkbox-menu")){ // verifico se ele está dentro da classe
      el.closest("li").classList.toggle("active", this.checked);
   }
});

document.addEventListener("click", function(e){
   var el = e.target;
   // aqui eu verifico se o elemento clicado é filho de .allow-focus
   // inclusive os nós de texto, ou o próprio .allow-focus
   if(el.classList.contains("allow-focus") || el.closest(".allow-focus")){
      console.log(".allow-focus clicado");
      e.stopPropagation();
   }
});
.active{
   color: red;
}

.allow-focus{
   background: red;
}

      <input type="checkbox"> Item 1

      <input type="checkbox"> Item 2

   <input type="checkbox"> clique aqui

    clique aqui também, ou em qualquer área vermelha


Async recursive function that takes a mutex

Question: How do you create an async recursive function that takes a mutex? Rust claims that this code holds a mutex across an await point. However, the value is dropped before the .await.
#[async_recursion]
async fn f(mutex: &Arc<Mutex<u128>>) {
    let mut unwrapped = mutex.lock().unwrap();
    *unwrapped += 1;
    let value = *unwrapped;
    drop(unwrapped);
    tokio::time::sleep(tokio::time::Duration::from_millis(1000)).await;
    if value < 100 {
        f(mutex);
    }
}

Error
future cannot be sent between threads safely
within `impl futures::Future<Output = ()>`, the trait `std::marker::Send` is not implemented for `std::sync::MutexGuard<'_, u128>`
required for the cast to the object type `dyn futures::Future<Output = ()> + std::marker::Send`rustc
lib.rs(251, 65): future is not `Send` as this value is used across an await

Answer: In this case, you can restructure the code to make it so unwrapped can't be used across an await:
let value = {
    let mut unwrapped = mutex.lock().unwrap();
    *unwrapped += 1;
    *unwrapped
};
tokio::time::sleep(tokio::time::Duration::from_millis(1000)).await;
if value < 100 {
    f(mutex);
}

If you weren't able to do this, then you'd need to make it so you don't return a Future that implements Send. The async_recursion docs specify an option you can pass to the macro to disable the Send bound it adds:
#[async_recursion(?Send)]
async fn f(mutex: &Arc<Mutex<u128>>) {
    ...

(playground)
You wouldn't be able to send such a Future across threads though.
Comment: @Test My understanding is that the compiler can't infer that `drop(unwrapped)` actually drops `unwrapped`, instead of perhaps sending it to another thread that would later use it after the `await` point (`drop` is just a normal function).
Comment: @Smitop While `drop` is a normal function, it moves the value and the compiler knows it. Little playing with the code suggests it is the lifetime `async_recursion` uses, but I'm not sure. [Drop tracking in async fns is known to be too conservative](https://github.com/rust-lang/rust/issues/57478).
Comment: Isn't this dangerous? Send exists for a reason.
Comment: @Test I added a way to fix this without `?Send`. The second way isn't dangerous though, the compiler stops you if you try to send a type that can't be sent between threads that doesn't implement `Send`.
Comment: Ok, thank you. Why doesn't `drop` accomplish the same thing?


Ways to stabilize OLS betas

Question: I am estimating the parameters of a system of OLS equations in Matlab. $y=X\beta+\epsilon \to \hat \beta=(X'X)^{-1}X'y$. My $X$ is a $5\times 5$ matrix and $y$ is a $5\times 1000$ matrix, so $\beta$ is also a $5\times 1000$ matrix. The problem is that my parameters are quite unstable as sudden jumps in parameters can occur and they will revert back to normal for the next regression.
My idea for reducing the instability in the $\beta$ is to set a maximum tolerance for $e=y-X\hat \beta$ and find the most stable $\beta$ parameters within this error.
Would you know of any literatures which talks about this that can provide me with the basics? What are some other methods for reducing the parameter instability?
Comment: What exactly do you mean by "jumps in parameters"? What is changing that causes the solution to this system to change? Since this obviously is not a set of regression equations (despite the formal appearance), what "literature" are you referring to?
Answer: I think you have everything transposed.  $X$ should be $m \times n$ where $m$ is the number of observations and $n$ is the number of parameters you're trying to estimate.  Similarly, $y$ should be $m \times k$ where $k$ is the number of sets of observations you have (this is typically 1).  As a result, $\beta$ will come out to be $n \times k$.  In your case, $X$ should be $1000 \times 5$, $\beta$ should be $5 \times 1$ and $y$ should be $1000 \times 1$.
Since you specifically asked about MATLAB: In MATLAB, you should use the backslash operator to solve linear least squares problems, like so:
<code>beta = X \ y
</code>
This is just a shortcut for the QR factorization.  The QR factorization avoids having to compute $X^T X$, which adds numerically instability.
Comment: I've never heard of factor mimicking regression, so I can't offer you any insight there.  But I can tell you this: If the matrix dimensions are correct as stated in your original post, this is not a least squares problem.  Rather, you're solving a fully-determined (assuming X is full-rank) linear system with 1000 different right-hand sides.  If the solution, $\beta$, changes **dramatically** with small changes in $y$, that suggests that $X$ is ill-conditioned.  Check out the condition number with `cond(X)`.
Comment: Hi Bill, you are right about the regular OLS. what I'm doing is a factor mimicking regression. It helps to think of the betas as factors and the factors as betas... So in matlab I am using the \ operator to solve the equations. Thanks.
Comment: @AllenLi I'm confused. The title to your questions says that you're interested in OLS regression, but your comment says that this is factor-mimicking regression. Which is it? Can you please edit your question to provide more information about what, exactly, you're trying to do?
Comment: Have you considered bootstrapping your data and using the resulting average  of the $\beta$ ?

Ways to stabilize OLS betas


stm32 timers: starts and resets on same trigger

Question: I has a periodic signal (22 kHz square), connected to IC1 of TIM3. I need to measure a duration of this signal.
Current realisation is:
1. TIM2 is programmed as one-pulse, arr = signal period + little deviation, trigger mode slave, with CEN as master output, trigger INT  enabled.
2. in TIM2 ISR just do TIM2->CNT = 0;
3. TIM3 is slave timer in gated mode, connected to tim2. trigger INT enabled.
4. in TIM3 ISR just count a diffrence current CNT and prev CNT to meas  ure a signal duration.
It is works, but times is not 100% accurate due to ISR calling & execution time.
Questions:
1. Can i use same external event for starting AND reseting same timer?
2. Can i use input capure registers in my realisation?
3. Some better ideas for my task?
i'm realy break my brains for a days. Please help... ;-)
Comment: Definitely - just use the input capture mode.
Answer: @P__J__ is right - you should configure and use the input capture mode many timers on STM32 offer you. Then you won't need any ISR (software) in the moments when the signal flanks are recognized because the MCU will do that for you. You'll only need some software to read out the measurements from the Input Capture, but you'll be more or less free to do this in ISR or poll from main program.
The TIMx peripherals are pretty complex.
Therefore, I suggest to have a look at
this Application Note from ST
as well as
that one.


comparing the difference of two random variables with a value

Question: Suppose I have random variables $X$ and $Y$, both are normally distributed. $X$ has mean $a_1$ and variance $b_1$, and $Y$ has mean $a_2$ and variance $b_2$. Is there a way to test whether $X-Y$ is significantly different from zero?
Comment: Please specify your attempts thus far
Comment: What does it mean "$X-Y$ to be significantly different from zero"? $X-Y$ is a random variable, and will never take on a value of zero.
Answer: If X and Y are independent then $X-Y$ is normal with mean $a_1-a_2$ and variance $b_1-b_2$. You can calculate, for a given $\delta$, the probability that $X-Y$ is greater than $\delta$ or less than -$\delta$ where you define "significantly different from 0" to mean that $X-Y$ is at least $\delta$ away from 0.
Note that if $X$ and $Y$ are not independent there is no solution unless you specify the correlation.


Prove for any postive $k$,such $2^m-2^n|k^m-k^n$

Question: Let positive integers such $m>n$,and if $$2^m-2^n|3^m-3^n$$
then for any positive integers $k$ have
$$2^m-2^n|k^m-k^n$$
I have looked at the simpler case $k=1,2,3$.I was able to solve this,How to prove $k\ge 4$. Any progress on the problem is welcome.
Comment: @Mufasa Is not zero divisible by every number?
Comment: FWIW I did a small Mathematica search. If $1\le n\le 100$ and $n13$ occurs as a factor of $2^m-2^n$ in those cases.
Comment: Surely this does not hold for $k=1$? Shouldn't this be for $k\ge2$?
Comment: @ChadShin - Oops! Sorry I misread this as the other way around - thanks for clarifying
Comment: Could anyone give me $(m,n)$ such that $m-n$ is not 2 or 1?
Comment: $(m,n)=(5,1)$ and $(m.n)=(8,2)$ are examples of pairs with such a property. It also follows from Little Fermat and such that the claim works for all $k$ for those pairs.
Comment: But, I'm also getting a deja vu vibe. Have we seen this before on our site?
Answer: There are only finitely many of $(m,n)$'s for which $2^m-2^n|k^m-k^n$ holds for all $k$ (as observed also by Jyrki in comments).
This is proven in paper by Sun Qi and Zhang Ming-Zhi Pairs where $2^a - 2^b$ divides $n^a - n^b$ for all $n$, where they show that only $(m,n)$ for which this holds with $0 \leq n < m$ are:
$$
(1,0),(2,1),(3,1),(4,2),(5,3),(5,1),(6, 2), (7, 3),
(8, 4), (8, 2), (9, 3), (14, 2), (15, 3), (16, 4).
$$
This is also referred in $B47$ in Richard Guy's book Unsolved Problems in Number Theory.


Finding ratio based on count in Oracle SQL

Question: I'm trying to list each teams ratio of matches lost from total matches played.
I've tried the following but it doesn't seem to work:
select teams.name as Name,
Lost
from teams
join matches on teams.name in (matches.home, matches.away)
group by teams.name
having (1 - (matches.winner / (count (matches.home) + count (matches.away)))) as Lost;

Is the problem with the way I wrote the function in the last line?
Relational diagram for reference:
Comment: I just +1 your question because it isn't that bad, although you do need to provide the error you are receiving rather than it doesn't work.
Comment: I find your ER model "format" rather confusing to be honest. I have never seen such a graphical representation.
Answer: The HAVING clause is used to filter the resultset after any grouping has occured, not to define functions.
You need to write all the logic for the columns that you need returned within the SELECT clause.
SELECT  T.NAME
        ,COUNT(M.*) AS MATCHES_PLAYED
        ,SUM(CASE WHEN M.WINNER = T.NAME THEN 1 ELSE 0 END) AS WINS
        ,SUM(CASE WHEN M.WINNER = T.NAME THEN 0 ELSE 1 END) AS LOSSES
        ,SUM(CASE WHEN M.WINNER = T.NAME THEN 1 ELSE 0 END)/COUNT(M.*) AS WIN_PERCENT
        ,SUM(CASE WHEN M.WINNER = T.NAME THEN 0 ELSE 1 END)/COUNT(M.*) AS LOSS_PERCENT
FROM    TEAMS T
INNER JOIN
        MATCHES M
ON      T.NAME = M.HOME
OR      T.NAME = M.AWAY
GROUP BY
        T.NAME

Comment: Thanks, but i'm getting an error for `count(m.*)`, is there any other way to write it? (the error is: `invalid user.table.column, table.column, or column specification`)
Comment: try `count(m.ID)` in all three instances.


How can I find out if the present theme version would work

Question: In the last years I've used pixture reloaded, a subtheme to adaptive theme, on some drupal sites and I was wondering whether this will work on Drupal 9. I've seen that the Adaptive theme homepage has not been reachable for some weeks and that the last update of Adaptive themes was 3 years ago. So I don't expect them to further develop the theme. How can I find out if the present version would work in Drupal 9?
Answer: Install the Upgrade Status module and then visit /admin/reports/upgrade-status and scan the Adaptive Theme and your sub-theme and get a report on all problems regarding Drupal 9 compatibility.

This module scans the code of the contributed and custom projects you
  have installed, and reports on any deprecated code that must be
  replaced before the next major version. Available project updates are
  also suggested to keep your site up to date as project will resolve
  deprecation errors over time.
Due to third party PHP library dependencies, the module needs to be
  installed with Composer.
Comment: Thanks for your answer. The scan showed that the AT-Core depends on deprecated libraries. So I guess I shouldn't use it.
Comment: @paul77 – Last commit 2 years ago. 400 open issues. Well... difficult... yeah.


Finding Partial Derivatives

Question:
For the equation below, of Van der Waal form:
  $$\left(P+\frac{n^{2}a}{V^{2}}\right)(V-nb)=nRT$$
Determine the partial derivatives; $\Bigl(\frac{\partial V}{\partial T}\Bigr)_{P,n}    \text{and }  \Bigl(\frac{\partial P}{\partial V}\Bigr)_{T,n}$
Where $a,b, n, R$ are constants.

This is what I've done so far for one of the partial derivatives. I dont know what else to do from here, sorry.
$$P=\frac{nRT}{V-nb}-\frac{n^{2}a}{V^{2}}$$
$$\frac{\partial P}{\partial V}=-\frac{nRT}{(V-nb)^2}+\frac{2n^{2}a}{V^{3}}$$
Comment: Do you know how to take normal derivatives? Because a partial derivative is exactly a normal derivative except every variable is a constant except for the variable that you are taking the derivative to respect to. in the dP/dV case, V is the only variable that is not a constant...This is pretty much an issue of product rule (f = g/h, f' = ((h)(g') - (g)(h'))/h^2
Comment: @mathguy So would this be what you said? $P=\frac{nRT}{V-nb}-\frac{n^{2}a}{V^{2}}$

$$\frac{\partial P}{\partial V}= \frac{nRT}{-nb}-\frac{n^{2}a}{2V}$$
Comment: No, I think you are taking that derivative wrong. I did it by hand and you should end up with what's on your question (the last expression)
Answer: You can try to find $\partial P / \partial T$ and $\partial P / \partial V$ such that: $$\frac{\frac{\partial P}{\partial T}}{\frac{\partial P}{\partial V}}=\frac{\partial V}{\partial T}$$
I hope this will help you
Comment: Im still not sure anything else you can tell me?
Comment: You can see $P(V)$ as $\alpha\cdot(V-\beta)^{-1}-\gamma V^{-2}$ where $\alpha=nRT,\beta=nb,\gamma=n^2 a$
are constants so taking the derivative:
$$\frac{\partial P}{\partial V}=\frac{\partial}{\partial V}[\alpha\cdot(V-\beta)^{-1}]-\frac{\partial}{\partial V}[\gamma V^{-2}]$$
$$\frac{\partial P}{\partial V}=(-1)\alpha\cdot(V-\beta)^{-2}-(-2)\gamma V^{-3}=-\frac{\alpha}{(V-\beta)^2} + \frac{2\gamma}{V^3}
=-\frac{nRT}{(V-nb)^2} + \frac{2n^2 a}{V^3}$$

You can do the same for $P(T)$

Finding Partial Derivatives


Symfony2: Check the checkboxes in a form

Question: I have 3 entity: Person, Affiliation and PersonAffiliation.
The person can be edited with the possibility to add or delete affiliatons.
In my view, I should have a checkbox for every existing affiliation and the checkbox shuld be checked if the person has allready this affiliation.
I know how to display all affiliations in the view (twig) but I don't know how to check the checkboxes if the person has allready this affiliation.
Here is how the two tables looks like:
Person
    id
    firstname
    lastname
    ...
    affiliations

Affiliation
    id
    affiliation

PersonAffiliation
    id
    person_id
    affiliation_id

Now, my question is: Is there a possibility to use the controller and the view (twig) for doing this or the only possibility is to use Javascript (with JQuery)?
Comment: how about adding a function to the person like `public function hasAffiliation($affiliation)` and then in twig when looping through the affiliations, just call `{% if person.hasAffiliation(affiliation) }%....`
Comment: @mogoman, thank you for your reply. I had that idea but the problem I encountered is that in the twig, I have {% for aff in form.affiliations %} so the affiliaations are a form object and I don't know how and if it is possible to get the string or the affiliation object from.
Answer: Rather than using a proxy class, arrange your objects like this:
Person
    id
    ... as before
Affiliation
    id
    .. as before
-- remove PersonAffiliation --

but add this relation to your Person class
/**
 * @ManyToMany(targetEntity="Affiliation")
 * @JoinTable(name="person_affiliation",
 *      joinColumns={@JoinColumn(name="person_id", referencedColumnName="id")},
 *      inverseJoinColumns={@JoinColumn(name="affiliation_id", referencedColumnName="id")}
 *      )
 */

You could do it all in the form builder like this:
    $builder
        ->add('person')
        ->add(
            'affiliation',
            'entity',
            array(
                'class'         => 'AcmeDemoBundle:Affiliation',
                'query_builder' => function($em) { return $em->createQueryBuilder('p')->orderBy('p.id', 'ASC'); },
                'property'    => 'affiliation',
                'multiple'    => true,
                'expanded'    => true,
                'required'    => false
            )
        );

And then just render your form with
{{ form_widget(form) }}

Comment: I believe the object isn't saved there because you run `form->createView` in the controller. What you could do is (in your controller) make an indexed affiliation list `$affliations[$aff1->id] = $affiliation` etc - then in twig `{{ affiliations[aff.vars.value] }}`
Comment: Thank you very much mogoman, but how to check those checkboxes now?
Comment: ah - I understand the problem. Is there a reason why you have the "proxy" entity (PersonAffiliation) and not using a manytomany unidirectional relation (http://docs.doctrine-project.org/en/2.0.x/reference/association-mapping.html#many-to-many-unidirectional). The form will then work without problems.
Comment: In fact, my database is created like that, but  do you think that I can use manytoMany and negligate the proxy table PersonAffiliation ?
Comment: Thank you, I will try this immediately, but something I don't understand, how can I check then if the corresponding affiliation should be checked? And also how to check the box?
Comment: I sow the possibility to get the value of the twig form objec, for example I have affiliations and a for loop, then inside I can do aff.vars.value but I am geting only ints (1,2,3 etc.). If I could get the object affiliation from there...
Comment: Great idea.. Do you maybe know how to get all the affiliations from the Affiliation table (with EntityManager).
Comment: do you mean `$entities = $em->getRepository('AcmeDemoBundle:Affiliation')->findAll();` ?
Comment: I have it, it's getAll(). But another problem now... The "aff.vars.value" returns me 1,2,3, that's not the id's of the affiliations, it's the first, the second and the 3rd affiliation
Comment: what about this. In your person class make a method `public function checkAffiliation($id) return true/false` then in twig `{% if person.checkAffiliation(aff.vars.value) %}CHECKED{% endif %}`
Comment: The problem is that aff.vars.value is returning me 1 for the first aff, 2 for the 2nd one, 3 for the third one etc. This is not the id of the aff...
Comment: It might be aff.vars.value.id
Comment: let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/19291/discussion-between-mogoman-and-milos)


DOM Selectors in jQuery for elements that do not have ID or CLASS name tags

Question: How do I use jQuery to select DOM elements that do not have ID or CLASS name tags?
I noticed that Chrome debugger shows the DOM location on the bottom taskbar which is very helpful.
QUESTION:
What would be the jQuery() selector for the following DOM element?
Here is a screenshot of my Chrome Debugger.
Answer: Instead of writing a complex query selector use something like this:
<code>$("table").eq(1);
</code>
This selector will grab the second table on the page


When a high frequency can affect normal distribution

Question: I have a sample of n=77 change over time scores (T2-T1). In a lot of cases a score of 0 (no change over time) is modal, at times 33% of the sample. I am wondering if this impacts the assumption of normality at all, due to the high frequency, compared to other scores. I should note that when I make the bins smaller, there is still one response that remains the mode by quite a bit.
Here is another screenshot where there may or may/not be left skew . It is difficult to tell with that mode and a single extreme value. I have avoided doing statistical tests of normality as I hear they can be very sensitive, and I'd prefer to use parametric tests if possible.
Comment: Please tell us what you are assuming has a Normal distribution and what role that assumption might play in your analysis.  (It is unusual for any statistical procedure to require the *data* to be normal.)
Comment: I would expect that the responses to have a normal distribution. I have three groups and would like to know if I should be an ANOVA or non-parametric test
Comment: ANOVA does not require the responses to have a Normal distribution, nor does it require the responses conditional on the explanatory variables to be Normal.  It only supposes that the conditional responses will be close enough to Normal to support the usual assertions about the distributions of test statistics.  That will be an issue in this case for an ANOVA F statistic, for instance, but not for the t-statistic for any individual parameter estimate.
Answer: I will assume you ask about the normality of your change scores. About how to analyze such data.  You could do much better than just plotting a histogram, which will depend on the binning. See here: Is there a rule of thumb to choose a normality test?
Other graphical methods is qqplot Interpreting QQplot - Is there any rule of thumb to decide for non-normality? which you could try. And, if there really is an appreciable number of exact zeros in your differences, you should investigate why. But maybe it is just about binning.


Jplayer with XML not working

Question: I am trying to get Jplayer to work using an XML doc so my customer can easily update the playlist. I was able to get it working without issues when I code the songs into the JS. My current code is:

play

pause

stop

mute

unmute

Update Required

                    To play the media you will need to update your browser to a newer version.

And then my JS code is:

My XML file is:
<playlist>
    <track>
        <title>Waving Not Drowning</title>
        <artist>Orbital</artist>
        <mp3>http://www.beyondhyper.com/mp3/Orbital-The Altogether-WavingNotDrowning.mp3</mp3>
    </track>
    <track>
        <title>Crazy People</title>
        <artist>3 Monkeys</artist>
        <mp3>http://www.beyondhyper.com/mp3/3Monkeys-CrazyPeople.mp3</mp3>
    </track>
    <track>
        <title>Voices</title>
        <artist>Bedrock</artist>
        <mp3>http://www.beyondhyper.com/mp3/Bedrock- Voices.mp3</mp3>
    </track>
    <track>
        <title>Timeless</title>
        <artist>Transa</artist>
        <mp3>http://www.beyondhyper.com/mp3/Transa-Timeless.mp3</mp3>
    </track>
</playlist>

No matter what I do, I only see the 'no solution' tag. If anyone has any idea as to what I am missing please let me know.
Thanks in advance.
Answer: There are several possible causes:

jp-no-solution is shown if HTML5 is not available and Flash is not installed
jp-no-solution is shown if Flash is installed but Flash is outdated
jp-no-solution is shown if JavaScript is disabled

References

jplayer Release Notes
jPlayer doesn't work (I suppose because of old flash-plugin)

Jplayer with XML not working


Como rodar o cron do schedule:run no Windows

Question: Criei uma cron que deve verificar a cada minuto se o valor da data final é menor que a atual... se sim deve atualizar o campo status dessa tabela.
class SetStatus extends Command
{

protected $signature = 'SetStatus:cron';

public function handle()
{
    //o código ta uma zona apenas pra teste...
    $sql = 'select id from promotions where dt_end < NOW()';
    $dados = \DB::select($sql);
    foreach($dados as $i)
    {
        $updateStatus = 'update promotions set status = "inativo" where id IN ('.$i->id.')';
        $return = \DB::update($updateStatus);
    }
    var_dump($return);
}

}
e adicionei no kernel
 protected $commands = [
    Commands\SetStatus::class,
];

protected function schedule(Schedule $schedule)
{
    $schedule->command('SetStatus:cron')->everyMinute();
}

A minha duvida é que sempre que rodo os comando abaixo a CRON é executada com sucesso, porém para por ai. No minuto seguinte ela não executa novamente.
php artisan SetStatus:cron
php c:/projetos/marcelo/painel/artisan schedule:run

Após rodar esses comandos acima, já não deveria ser rodado a cada minuto igual defini no kernel?
Achei algo interessante nesse link Agendar carregamento de página através do CRON na linha
# crontab -e 00 * * * * /usr/local/bin/php /home/pedrodelfino/meu-script.php

Mas não consegui desenrolar... vi algo também como criar uma .bat, mas não achei funcional.
Estou em ambiente de desenvolvimento usando Windows, alguém poderia dar uma luz?
Answer: No Linux, o recomendado é adicionar uma entrada no cron como é sugerido pela documentação do Laravel.
* * * * * php /path-to-your-project/artisan schedule:run >> /dev/null 2>&1

Esse cron rodará a cada minuto o comando schedule:run.
No Windows é possível usar o Agendador de Tarefas do sistema para fazer isso.
Abra o agendador de tarefas (ou task scheduler)

Vá em criar uma nova tarefa

Na aba geral defina um nome para a tarefa e para ela executar mesmo que o usuário não esteja logado (isso faz rodar em background)

Na aba seguinte, crie um trigger para ser executado a cada minuto indefinidamente.

E na aba de ações, crie uma nova ação especificando o executável do php, o comando artisan schedule run e o diretório do seu projeto.

Depois disso basta dar um ok e informar uma credencial do seu usuário e o schedule será executado como um cron.
Comment: @hisoka se não me engano pra isso não acontecer ter que selecionar o "executar quando usuário estiver logado ou não"
Comment: Valeu amigo, exatamente isso. O único lado ruim é q toda hora abre o prompt do php e desfoca oq to fazendo no momento kkk + me ajudou bastante. Mt obrigado!


Best possible regression models

Question: I am looking for different types of regression models for such data in which the dependent variable is always decreasing with the independent variables.
The two's, I know and have used so for are
Y = C + C_a A + C_b B

and
Y = C + C_a A + C_b B + C_a2 A^2 + C_b2 B^2 + C_ab A B

The second one give me the best fit so far. I want to try some other ones too but don't know. Please suggest some.
Thanks
Answer: Just trying lots and lots of terms without a basis for any one is liable to give you non-reproducible results.  Try dividing your data set in two and, on the first set, visually examining scatterplots of each predictor with Y.  You might also call up a lowess curve to assess the nature of any relationship.  Then if you see a complex relationship such as would be defined by, say, a cubic or quartic term, you can test such a term on your holdout set.

Best possible regression models


Fill in feasible region with Fill_between

Question: I'm trying to fill in the maximum outward region as attached in the image. Below code will generate the line graph, however, I'm struggling to fill in the region as in the image.
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
x = np.linspace(0,20,2000)
y1 = (-2*x) + 6
y2 = 5-x
y3 = (20 - (2*x))/10
plt.plot(x,y1,label = r'$2x1+x2geq6$')
plt.plot(x,y2,label = r'$x+ygeq5$')
plt.plot(x,y3,label = r'$2x+10ygeq20$')
plt.xlim((0,10))
plt.ylim((0,10))
plt.xlabel(r'$x$')
plt.ylabel(r'$y$')

Comment: did you try the `fill_between` method you mention in the title?
Answer: The easiest way, would be to use the maximum of the 3 curves:

import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0, 20, 2000)
y1 = (-2 * x) + 6
y2 = 5 - x
y3 = (20 - (2 * x)) / 10
plt.plot(x, y1, label=r'$2x1+x2geq6$')
plt.plot(x, y2, label=r'$x+ygeq5$')
plt.plot(x, y3, label=r'$2x+10ygeq20$')
plt.fill_between(x, np.amax([y1, y2, y3], axis=0), 10, color='black', alpha=0.3)
plt.xlim((0, 10))
plt.ylim((0, 10))
plt.xlabel(r'$x$')
plt.ylabel(r'$y$')
plt.show()

Answer: You could fill the entire background with a color, then use fill_between make the area below the lines white.
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline

plt.rcParams['axes.facecolor'] = 'lightgrey'

x = np.linspace(0,20,2000)
y1 = (-2*x) + 6
y2 = 5-x
y3 = (20 - (2*x))/10
plt.plot(x,y1,label = r'$2x1+x2geq6$')
plt.plot(x,y2,label = r'$x+ygeq5$')
plt.plot(x,y3,label = r'$2x+10ygeq20$')
plt.xlim((0,10))
plt.ylim((0,10))
plt.xlabel(r'$x$')
plt.ylabel(r'$y$')

plt.fill_between(x,y3, color='white')
plt.fill_between(x,y2, color='white')
plt.fill_between(x,y1, color='white');

Comment: Hi Chris, thanks so much!


How to mark a XCTest as pending?

Question: I have a subclass of XCTestCase and I would like to mark some test as pending, in the same way that is possible with RSpec
https://www.relishapp.com/rspec/rspec-core/v/2-0/docs/pending/pending-examples
Answer: There is no simple way to do this. The most pragmatic solution is to comment out or rename your test:
@implementation MyTestCase

- (void)testSomething { /* ... */ }

// Option 1: Comment out the test.
// - (void)testSomething { /* ... */ }

// Option 2: Rename the test such that XCTest does not consider
// it a valid test method. In order to be "valid", it needs to:
//
// - Have a return type of `void`
// - Take no parameters
// - Begin with "test"
//
// Here, we rename the test so that it does not begin with "test".
- (void)PENDING_testSomething { /* ... */ }

@end

Of course, one of the nice things about RSpec is that it prints out a warning of some kind. You could add these yourself using #warning:
#pragma Pending!
- (void)PENDING_testSomething { /* ... */ }

This displays a warning in Xcode. Keep in mind that #warning is only available in Objective-C, not Swift.
Testing frameworks like Quick and Specta provide pending examples:
pending("tests something") { /* ... */ }
xit("tests something") { /* ... */ }
xdescribe("describes something") { /* ... */ }
xcontext("provides context for something") { /* ... */ }

These test frameworks prevent "pending" tests from being run by overriding -[XCTestCase testInvocations]. Doing so is a lot of work, but if you wanted to implement "pending tests" yourself, you could look into doing so as well.
Comment: One reason to prefer renaming over commenting out is that the compiler will tell you if the pending test fails to build.
Answer: It's not exactly pending, but if your lead considers pending tests a failing suite (I am the lead for my team, and I do), then a simple XCTFail() does the job:
#pragma mark - Something Tests

- (void)testSomething_scenario_result {
    XCTFail(@"Pending Test: %@",NSStringFromSelector(_cmd));
}

Then you can easily see what failures are relevant if you need to leave a pending test in for whatever reason (maybe a personal development branch), but the whole suite still fails until you complete it.
For "true" pending, modocache's answer is far more complete.
Answer: Although semantically perhaps slightly different, XCTSkip() may provide what you're looking for as I use it in this manner. It's part of the core XCTest framework.

Use XCTSkipIf() or XCTSkipUnless() when you have a Boolean condition
that you can use to evaluate when to skip tests.
Throw an XCTSkip error when you have other circumstances that result
in skipped tests.

func testUpdatesSealCompletedCount() async throws {
    throw XCTSkip("Pending")
}

In spite of what having to throw this might imply, your test suite will still pass.
The nice bit about this is that it updates the Test Navigator with an icon that looks the debugger "skip over".

How to mark a XCTest as pending?


Spring Webflux disabling login

Question: Let me shortly describe what problem i am facing right now.
I have configured spring security for webflux application, and i am getting login form prompted, when i try to access the route that doesn't require authentication. The route is /swagger-ui/ and it should get opened without any login forms or whatever.
Below is the code i have within the SecurityWebFilterChain

@Bean
public SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) {
    //@formatter:off
    return http
            .formLogin().disable()
            .httpBasic().disable()
            .authenticationManager(authenticationManager)
            .securityContextRepository(securityContextRepository)
            .authorizeExchange()
            .pathMatchers(HttpMethod.OPTIONS).permitAll()
            .pathMatchers("/v2/api-docs", "/v3/api-docs", "/configuration/ui", "/swagger-resources",
                    "/configuration/security", "/swagger-ui/", "/swagger-ui",
                    "/webjars/**", "/swagger-resources/configuration/ui",
                    "/swagger-resources/configuration/security").permitAll()  // Allowed routes for swagger
            .pathMatchers("/api/auth", "/api/auth/**").permitAll() // Allowed routes for auth
            .and()
            .authorizeExchange()
            .anyExchange()
            .authenticated() // All other routes require authentication
            .and()
            .csrf().disable()
            .headers()
            .hsts()
            .includeSubdomains(true)
            .maxAge(Duration.ofSeconds(31536000))
            .and()
            .frameOptions().mode(XFrameOptionsServerHttpHeadersWriter.Mode.SAMEORIGIN)
            .and()
            .build();
    //@formatter:on
    }
}

If anyone has any suggestions, please let me know, i will appreciate it. Here is the picture what i got in the browser.
Comment: @ThomasAndolf I have fixed it accidentally,  .httpBasic()
                .and()
                .formLogin().disable()    i have removed .disable() from the httpBasic() and apparently its working, but let me chek once again if i have modified something else also.
Comment: Are you sure it is even loaded, and what does your debug output tell you, and the browser logs
Comment: @ThomasAndolf well browser console logs are empty, i will try to debug it now.
Comment: But the browser request log, what requests are performed and what requests are red, return statuses, etc
Comment: That diolog box looks like "basic auth" and is given by the webbrowser and not spring. The path "/" seems to still have basic auth and someone is requesting that path
Comment: @ThomasAndolf yeah well besides removing disable(), there is one more thing that i have done and that is in authenticate method which is overriden method from ReactiveAuthenticantionManager. Well in that method, i have created UsernamePasswordAuthenticationToken with hardcoded values like principal, authorities etc.
Answer: I was really annoyed by this issue too. The problem is that by putting .httpBasic().disable() in your code you would expect spring to skip basic authentication (that browser window) but it doesn't.
Instead, try providing a ServerAuthenticationEntryPoint to the .httpBasic().
The most simple one is the HttpStatusServerEntryPoint.
For example in your code change to:
***
return http
            .formLogin().disable()
            .httpBasic().authenticationEntryPoint(new HttpStatusServerEntryPoint(HttpStatus.UNAUTHORIZED))
            .authenticationManager(authenticationManager)
            ***

By changing that your server will return a 401 UNAUTHORIZED HttpStatus instead of that browser window!
Cheers!
Answer: For those who would like to keep .httpBasic().disable() in their code while making the basic login go away I have the following setup that works.
The issue lies in that a default HttpBasicServerAuthenticationEntryPoint is configured as the fallback if there isn't another ServerAuthenticationEntryPoint. This entry point returns WWW-Authenticate header with value Basic realm="realm" which prompt the browser to pop the login prompt.
To this disable the entrypoint we cannot just disable httpBasic, but we must configure a custom ServerEntryPoint. I did it through a authentication filter but .exceptionHandling().authenticationEntryPoint(new HttpStatusServerEntryPoint(HttpStatus.UNAUTHORIZED)).and() should also work.
My setup (which use authentication filter):
http.
        .httpBasic().disable() // Disable Basic Login
        .formLogin().disable() // Disables Form Login
        .logout().disable() // Disables default Logout endpoint
        .authenticationManager(authManager)
        .addFilterAt(createCustomJwtFilter(), SecurityWebFiltersOrder.AUTHENTICATION)
        .authorizeExchange()
            .pathMatchers(HttpMethod.OPTIONS).permitAll()
            .pathMatchers("/", "/healthcheck").permitAll()
            .anyExchange().authenticated();
return http.build();

createCustomJwtFilter() method
private static AuthenticationWebFilter createCustomJwtFilter(ReactiveAuthenticationManager authManager)
{
    AuthenticationWebFilter filter = new AuthenticationWebFilter(authManager);
    // This line configures the custom entryPoint
    filter.setAuthenticationFailureHandler(
            new ServerAuthenticationEntryPointFailureHandler(HttpStatusServerEntryPoint(HttpStatus.UNAUTHORIZED)));
    return filter;
}

This should also return a 401, while keeping the httpBasic() disabled for better code readability.

Spring Webflux disabling login


What does it mean to initialize a variable in JavaScript 5?

Question: I am required to initialize a variable in JavaScript 5. The exact instructions are "Declare a variable chameleon and initialize it to the string "lizard"."
Comment: the same as "*assign initial value*".
Comment: Welcome to Stack Overflow! Please take the [tour], look around, and read through the [help], in particular [*How do I ask a good question?*](/help/how-to-ask) Assignments aren't usually arbitrary; your instructor, tutorial, or course will have covered the necessary topics to make it possible for you to do this. **Review your course materials, class notes, etc.,** and try to do the work. This is **extremely** basic, and will be covered.
Answer: Just use
var chameleon = "lizard";

Answer: var chameleon ="lizard";

Follow these links for further details
Clear explanation on declaration and initialization of javascript variables
Use full link for learning and testing javascript


Maximum likelihood estimation with unknown distribution

Question: I want to fit a model to some data using structural time series modeling and Kalman filtering. The hyperparameters need to be tuned using maximum likelihood estimation.
I am using the Python package statsmodels that does this for me, but nowhere I need to put in which distribution I assume my model follows.
Does it automatically use a Gaussian distribution?
I am planning to select the right model using BIC. Should I check each one for normality first?
And if it's not, what would be a good next step to take?
Answer: The statespace module in the python package only supports Gaussian distributed observation and state innovations (at least as of v0.14), so not only is it automatically used, but it cannot be changed.
What you should do depends on your model, but one easy first step would be to construct your state space model and then use the [plot_diagnostics][1] method to see if the residuals appear to be approximately Gaussian.


Hibernate Envers Auditing

Question: I am using Hibernate4 with envers for audit logging purposes.
I have a table:
PRODUCTS(PRODUCT_ID(primaryKey),
         PRODUCT_CODE,
         PRODUCE_DESC,
         PRODUCT_FEE)

Hibernate has created an audit table PRODUCTS_AUD.
Whenever there is a change in the Product description, Hibernate is tracking the changes in the previous records.
Some records have only Product_desc changed. Some records have only product_fees changed for a particular Product_id. Is their a way to find out what all the changed fields are between revisions?
Comment: Welcome to StackOverflow! Please show us what you have tried, what results you expected and what results you received.
Answer: Product audit table should log only the changes happens to the product table. So, table structure should be PRODUCT_AUDIT(ID(Primary key),PRODUCT_ID, ATTRIBUTE_NAME, OLD_VALUE, NEW_VALUE).
Check whether is there any options to change audit table structure. Once you have table design like this, it is easy to find the what are changes happend.

Hibernate Envers Auditing


Exclude a page from indexing on a per page basis

Question: I would like to be able to remove a page from search engines (external and drupal). I want to add a checkbox on the content type to be able to specify which page should or should not be indexed.
My plan is to check via the hook_node_save if the checkbox is checked, and if so, edit the robots.txt to add a Disallow via the provided url. If the box is unchecked, I remove it from the robots.txt
This is complicated though. Does anyone has a better solution ?
Thanks,
Answer: I recommend installing the Metatag module. Once installed you will have a checkbox: Prevent search engines from indexing this page located on every node under Meta tags -> Advanced.
Answer: Have a look at  the noindex module. It should allow you to do what you want.
That is per-page configuration of indexing via the "robots" meta tag.


Valores em tempo real na classe input type="range"

Question: Bem, tentei fazer os valores em um input type="range" demostrar em tempo real ao usuário selecionar mais não estou conseguindo. com jquery também é do mesmo modo apenas ao soltar o mouse do botão da classe input type="range" que o valor é demostrado para o usuário final.
Answer: Dê uma olhada a este exemplo: http://jsfiddle.net/LuKBm/
Na prática não precisa de jQuery e tem duas opções. Ouvir o evento input que muda a cada passo que o mouse mexe, ou ouvir o event mouseup que dispara somente quando o mouse levanta.
O código do exemplo é:
var p = document.getElementById("price"),
    res1 = document.getElementById("resultado1"),
    res2 = document.getElementById("resultado2");

p.addEventListener("input", function () {
    res1.innerHTML = "€" + p.value;
}, false);
p.addEventListener("mouseup", function () {
    res2.innerHTML = "€" + p.value;
}, false);

Porém se quer usar jQuery, nalguns casos pode ter vantagens, entõ o que precisa é:
$('seletorElemento') // um seletor CSS
    .on('mouseup',   // quando ocorrer um mouse up naquele elemento... (pode também usar o "input"
    function(){
        // aqui pode correr o código que precisa, por exemplo mostrar o valor
        $('outroElemento').html(this.value); // no caso de querer mudar o html
    });

Sem os comentários:
$('#price').on('mouseup', function () {
    $('#resultado1').html(this.value);
});

Exemplo
Comment: é realmente isto onde estava minha dúvida, obrigado pela ajuda!
Comment: ótimo exemplo, funciona muito bem. ai vem mais uma dúvida se por exemplo for necessário inserir um valor decimal contendo números com as devidas virgulas para valores financeiros, tem alguma dica? Obrigado.
Comment: @theflash dê uma olhada nesta resposta: http://pt.stackoverflow.com/a/14729/129
Comment: @theflash: para usar casas decimais pode usar assim: __http://jsfiddle.net/zmW3T/__
Comment: Verifiquei o link enviado @sergio
Comment: @theflash, ok. Isso respondeu à sua pergunta? se não coloque mais informação do que precisa


Permitir envio automatico de email com Outlook

Question: Ola, preciso enviar vários emails para diferentes endereços de forma automática, porém quando o VBA inicia o processo de envio abre uma caixa de alerta solicitando minha permissão para concluir a tarefa.
Alguém sabe como anular esse alerta e enviar o email?
O codigo de envio de email:
Function Enviar_dados_celulas_email(subject As String, destiny As String, body As Range, introductin As String)

' selecão da planilha desejada.
If destiny <> "" Then
    body.Select
    ActiveWorkbook.EnvelopeVisible = True
End If

   With ActiveSheet.MailEnvelope
      .Introduction = introductin
      .Item.To = destiny
      .Item.subject = subject
      .Item.Send
   End With
[D1].Select

End Function

tenho este outro jeito, porém nao consigo enviar umar range no corppo do email D:
Function Enviar_dados_celulas_email(subject As String, destiny As String, body As Range, introduction As String)

Dim oOutlookApp As Object, oOutlookMessage As Object
Set oOutlookApp = CreateObject("Outlook.Application")
Set oOutlookMessage = oOutlookApp.CreateItem(0)

With oOutlookMessage
    .subject = subject
    .To = destiny
    .body = body
    .Display
     SendKeys "%e"
End With

Set objMsg = Nothing

End Function

Comment: Ola. Coloque o código que esta a usar para enviar os *emails* na pergunta para o podermos ajudar.
Comment: Alguém???????????????
Comment: Esse código não ajudou muito. Você só colocou a função do Enviar Emails, precisamos saber como você está usando a função na sub, um exemplo funcional.
Comment: sub qualquer
enviar_email = Enviar_dados_celulas_email("qualquer assunto",email@example.com, Range("A1:I17"), "segue exemplo")
end sub
Comment: essa ta dificil D:
Comment: alguem por please
Answer: Aqui funcionou normal sem nenhuma janela de notificação, com o código que você forneceu:
Function Enviar_dados_celulas_email(subject As String, destiny As String, body As Range, introductin As String)

' selecão da planilha desejada.
If destiny <> "" Then
    body.Select
    ActiveWorkbook.EnvelopeVisible = True
End If

   With ActiveSheet.MailEnvelope
      .Introduction = introductin
      .Item.To = destiny
      .Item.subject = subject
      .Item.Send
   End With
[D1].Select

End Function

sub qualquer:
Sub qualquer()

enviar_email = Enviar_dados_celulas_email("qualquer assunto", "email@example.com", Range("A1:A2"), "segue exemplo")

End Sub

Talvez porque eu já estava com o outlook aberto, mandou automático; Em todo caso tente utilizar o  Application.ScreenUpdating = False e Application.DisplayAlerts = False antes de executar a função (na sub) e no final não esqueça de trocar pra True.
Comment: Man, eu acho que pq o meu email é da empresa e tem firewall que estou tendo esse problema... ja havia tentado display alerts
eu consegui enviar sem alerta de permissão com um outro método de envio, porém nessa nova maneira, não estou conseguindo colocar uma range  no corpo do email. D:
Comment: Edite a pergunta com esse segundo jeito, pra ver se conseguimos ajudar você no problema.
Comment: Ja editei, mantive os 2 codigos, obrigado.
Comment: Aguem me ajuda por favor D=


Using pumping lemma to prove that $L = \{(01)^m 2^m \}$ is not regular?

Question: I'm trying to use pumping lemma to prove that $L = \{(01)^m 2^m \}$ is not regular.
This is what I have so far: Assume $L$ is regular and let $p$ be the pumping length, so $w = (01)^p 2^p$. Consider any pumping decomposition $w = xyz$; $|y| > p$ and $|xy| \leq p$.
I'm not sure what to do next.
Am I on the right track? Or am I way off?
Thank you in advance.
Comment: You should be able to model your proof quite closely after the proof that $\{0^m1^m\}$ is not regular, with $01$ playing the role in your proof that $0$ plays in the original, and your $2$ playing the role of $1$. That will introduce a numerical factor of 2 at one point.
Answer: It's fine to start with the word $w=(01)^p2^p$, where $p$ is the pumping length, but you've gone a bit astray after that. The pumping lemma tells you that $w$ has a decomposition $w=xyz$ such that $|y|\ge 1$, $|xy|\le p$, and for all $i\ge 0$, $xy^iz\in L$. In particular, $xz\in L$.
Since $|xy|\le p$, you know that $y$ is part of the first $p$ letters of $w$. The first $2p$ letters of $w$ are the alternating $0$'s and $1$'s, so $y$ cannot contain any $2$'s. In other words, $z$ includes $2^p$. Can $xz$ be in $L$? Remember, $y$ is not the empty string, so $xz\ne w$.
Comment: Thank you so much for your help. That makes sense. But how would I prove if xz is in L?
Comment: @Momagic: You know that $xz$ contains all $p$ of the $2$'s in $w$; does it start with a string $(01)^p$, or with something else?
Comment: I think it starts with a string (01)^p
Comment: @Momagic: It does not. The $y$ part of the decomposition contains at least one symbol, and $|w|=3p$, so $|xz|\le 3p-1$. We already know that $z$ contains all $p$ of the $2$'s in $w$; when you drop them off the end of $xz$, what's left can have at most $2p-1$ symbols, so it cannot possibly be $(01)^p$.
Comment: Oh I see now. Thank you!


Set CSS class for a View programmatically in a hook

Question: I want to set an extra class for the first page of a paged View.
<code>/**
 * Implements hook_views_pre_render().
 */
function my_module_views_pre_render(ViewExecutable $view) {
  if ($view->id() === 'my_view' && $view->current_display === 'page_1') {
    // Somehow set/override the css class here.
  }
}
</code>
How can I change the CSS class set in the advanced settings of the View?
Answer: Something like this should do it:
<code>$view->display_handler->setOption('css_class', 'your_class');
</code>
Good luck!
Comment: `setOption` is the correct method. Thanks! Are the options documented anywhere?
Comment: Yes, good catch. You need to look at `DisplayPluginBase::defaultableSections()` for a list of the options.
Answer: It works in drupal 9
<code> /**
 * Implements hook_views_pre_view().
 */
function MODULE_NAME_views_pre_view($view, $display_id, $args) {
  if ($view->id() == 'YOUR_VIEW_ID' && $display_id == 'YOUR_DISPLAY_NAME') {
    $view->display_handler->setOption('css_class', 'CLASS-NAME');
  }
}
</code>


Trend and Seasonal component fitting after decomposition of the time series

Question: I am very new to Time Series Analysis (together with R). I have been practising with some very simple datasets to understand how to decompose the time series into Trend, Seasonal and Error components and then check whether the Error component is Gaussian or not. Till this point, everything is pretty much clear to me. However, after the decomposition, how do I fit the trend and seasonal component (using R)? I am confused on 'to what' do I fit my trend and seasonal component? I mean what should my predictors be? For the trend, I can use the time (specifically for the example below, the four quarters) perhaps? And as such, what does the fitting of seasonal component imply and how can it be achieved?
Below is one of time series datasets that I used. This time series is called jj and is present in the astsa package. The frequency of this time series is quarterly.:
    > jj
         Qtr1      Qtr2      Qtr3      Qtr4
  1960  0.710000  0.630000  0.850000  0.440000
  1961  0.610000  0.690000  0.920000  0.550000
  1962  0.720000  0.770000  0.920000  0.600000
  1963  0.830000  0.800000  1.000000  0.770000
  1964  0.920000  1.000000  1.240000  1.000000
  1965  1.160000  1.300000  1.450000  1.250000
  1966  1.260000  1.380000  1.860000  1.560000
  1967  1.530000  1.590000  1.830000  1.860000
  1968  1.530000  2.070000  2.340000  2.250000
  1969  2.160000  2.430000  2.700000  2.250000
  1970  2.790000  3.420000  3.690000  3.600000
  1971  3.600000  4.320000  4.320000  4.050000
  1972  4.860000  5.040000  5.040000  4.410000
  1973  5.580000  5.850000  6.570000  5.310000
  1974  6.030000  6.390000  6.930000  5.850000
  1975  6.930000  7.740000  7.830000  6.120000
  1976  7.740000  8.910000  8.280000  6.840000
  1977  9.540000 10.260000  9.540000  8.729999
  1978 11.880000 12.060000 12.150000  8.910000
  1979 14.040000 12.960000 14.850000  9.990000
  1980 16.200000 14.670000 16.020000 11.610000

    > decomp_JJ=stl(log(jj),s.window = 4)
    > plot(decomp_JJ)

Any help on this is much appreciated!

                                   UPDATE :

So, I tried a few different things and this is what I learnt:
a) In order to fit the trend, I can first extract the trend time series generated by the stl() function in R and then perform fitting on it as follows:
     > Trend=decomp_JJ$time.series[,2]
     > t=time(decomp_JJ$time.series[,2])
     > fit_Trend=lm(Trend~0+t)
     > summary(fit_Trend)
        Call:
       lm(formula = Trend ~ 0 + t)

       Residuals:
            Min       1Q   Median       3Q      Max
         -1.55503 -0.90810  0.07018  0.87686  1.60349

       Coefficients:
          Estimate Std. Error t value Pr(>|t|)
        t 5.628e-04  5.648e-05   9.965 7.72e-16 ***
        ---
        Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

         Residual standard error: 1.02 on 83 degrees of freedom
         Multiple R-squared:  0.5447,   Adjusted R-squared:  0.5392
         F-statistic:  99.3 on 1 and 83 DF,  p-value: 7.723e-16

but I am not sure, if this is the correct way to proceed. Also, I haven't still figured out how to fit the seasonal component
Comment: That's not completely accurate: the distinction is that you want to assume a parametric form for the trend and that `stl` fits a non-parametric model. In that case, there is no need to first apply `stl` and then fit a trend; you can just fit a trend, like you did with `lm` (although you should include the constant), directly on your raw data. Also, `stl` doesn't try to find the period, it simply fits LOESS on each sequence of quarters separately (since you put `s.window=4`). See the documentation for `stl` for details.
Comment: it appears from the graph of original data that there was a level shift change about halfway through you data and potentially another one at the 3/4 point. Also the seasonal factors seem to have changed over time. Your analysis should detect these kinds of identifiable factors.
Comment: Your decomposition has already "fit" both a trend and seasonal component. Those fitted components are available from the output. What are you trying to accomplish by "fitting" it again?
Comment: @ChrisHaug As I understand, the stl() procedure only decomposes the time series into the three components. It does not tell me anything like,for example, if I am interested in knowing the slope and intercept of the trend and the period of the seasonal component or I just want to extract the model of the trend and seasonal component. And I don't suppose one can get them from the decomposition.
Comment: @ChrisHaug , Thanks for the clarification, I shall go through the documentation. From what I gather from your comment above, using lm()  to fit the function:log(jj)~$\alpha_{0}$+$\alpha_{1}$*t+$\beta$*cos(2$\pi$/4)+$\gamma$*sin(2$\pi$/4) +$e_{t}$
Answer: As already mentioned by Chris Haug, stl is a non-parametric method. It returns the components (trend, seasonal, irregular) by smoothing the data; no model is involved in the analysis.
An alternative approach is to fit an ARIMA model to the original data and decompose it into ARIMA models for each component. This approach is well suited for quarterly and monthly time series data. The methodology is developed and described, among others, in Burman (1980)
and Hillmer and Tiao (1982).
The software SEATS (Gómez and Maravall) implements this methodology and is commonly used in statistical offices. A Matlab implementation is described in Gómez, 2015. In R, you can try the package tsdecomp.
This document introduces the methodology and the R package.

Illustration with your sample data. Decomposition of the ARIMA(0,1,1)(0,1,1) model.
library(tsdecomp)
x <- structure(c(0.71, 0.63, 0.85, 0.44, 0.61, 0.69, 0.92, 0.55, 0.72, 0.77, 0.92, 0.6, 0.83, 0.8, 1, 0.77, 0.92, 1, 1.24, 1, 1.16,
1.3, 1.45, 1.25, 1.26, 1.38, 1.86, 1.56, 1.53, 1.59, 1.83, 1.86, 1.53, 2.07, 2.34, 2.25, 2.16, 2.43, 2.7, 2.25, 2.79, 3.42, 3.69,
3.6, 3.6, 4.32, 4.32, 4.05, 4.86, 5.04, 5.04, 4.41, 5.58, 5.85, 6.57, 5.31, 6.03, 6.39, 6.93, 5.85, 6.93, 7.74, 7.83, 6.12, 7.74,
8.91, 8.28, 6.84, 9.54, 10.26, 9.54, 8.729999, 11.88, 12.06, 12.15, 8.91, 14.04, 12.96, 14.85, 9.99, 16.2, 14.67, 16.02, 11.61),
.Tsp = c(1, 21.75, 4), class = "ts")
x <- log(x)
fit <- arima(x, order=c(0,1,1), seasonal=list(order=c(0,1,1)))
res <- ARIMAdec(x, fit)

Summary output: (The interpretation may not be straightforward unless familiar with the methodology. Of particular interest are the AR roots allocated to each component and the variances of the components.)
print(res)
#Roots of AR polynomial
#----------------------
#(1 - L)(1 - L^4) = (1 - 2L + L^2)(1 + L + L^2 + L^3)
#  Component  Root Modulus Argument Period Cycles.per.Year
#1     trend  1+0i       1    0.000    Inf               0
#2     trend  1+0i       1    0.000    Inf               0
#3  seasonal  0+1i       1    1.571  4.000               1
#4  seasonal -1+0i       1    3.142  2.000               2
#5  seasonal  0-1i       1    4.712  1.333               3
#
#MA polynomials
#--------------
#
#Trend:
#(1 + 0.205L - 0.795L^2)a_t,  a_t ~ IID(0, 0.0178)
#Seasonal:
#(1 - 0.153L - 0.48L^2 - 0.367L^3)c_t,  c_t ~ IID(0, 0.0768)
#
#Variances
#---------
#
#trend  seasonal irregular
#0.01777   0.07683   0.25647
#
#Roots
#-----
#
#Component            Root Modulus Argument Period
#1     trend  0.7949-0.0000i  0.7949    0.000    Inf
#2     trend -1.0000+0.0000i  1.0000    3.142  2.000
#3  seasonal  1.0000+0.0000i  1.0000    0.000    Inf
#4  seasonal -0.4235+0.4327i  0.6055    2.345  2.679
#5  seasonal -0.4235-0.4327i  0.6055    3.938  1.596

Summary plot:
plot(res)

Note: the example is done for the logarithms of the data; you may take the exponential on the estimated components in order to recover the original scale.
Answer: The data can be adequately modelled using a hybrid ARIMA model and seasonal dummies while detecting and incorporating error variance changes and some 5 pulse alues. /The actual and outlier cleansed graph is informative  . The Actual,Fit and Forecast graph is here  with forecasts here  . The error variance changed deterministically at two points in time. The acf of the errors suggests sufficiency . This analysis was conducted automatically with AUTOBOX , a piece of software that I have helped to develop.


Necessary conditions for transforming a system of O.D.Es to a single O.D.E.

Question: Considering the system:
$$u' = a(x)u + b(x)v$$
$$v' = c(x)u + d(x)v$$
I transform it to the second order O.D.E.(please check me on this because I might have mistakes):
$$\displaystyle u'' - \left (\frac{b'(x)}{b(x)} + a(x) + b(x) \right )u' + \left ( \frac{a(x)b'(x)}{b(x)} - a'(x) - c(x)b(x) + a(x)d(x) \right )u = 0$$
In the process, I am allowed to assuming as much differentiability as I want (on every function). Are there any other necessary conditions on the coefficients $a, b, c, d$ to do the above transformation?
Answer: $v=(u'-au)/b$,
$v'=(-b'(u'-au)+b(u''-a'u-au'))/b^2=cu+d(u'-au)/b$,
$-b'u'+ab'u+bu''-a'bu-abu'=b^2cu+bdu'-abdu$,
$bu''-(bd+b'+ab)u'+(-b^2c+abd+ab'-a'b)u=0$
which is almost what you have --- I have a $du'$ where you have $bu'$.
The way you have written it, you need to worry about the possibility that $b(x)=0$ for some $x$ in the domain.
Comment: If I multiply everything by $b(x)$ will that resolve this problem? Would there be any others?
Comment: I don't see any other problems.
Comment: Τhanks a lot! Especially for catching the little mistake!


i want to set to Input Query to mac address automatically and none editable for inno setup key generator script

Question: this is my inno setup script (inno setup key generator script)
i want to  set to  Input Query to mac address and Private key automatically and none editable.
inno setup key generator  Download (sample2.iky, ISID.dll)
www.mjfreelancing.com/index.php?option=com_content&view=article&id=11&Itemid=13
inno setup  download
www.jrsoftware.org/isdl.php

http://i49.tinypic.com/nbodif.jpg

http://i49.tinypic.com/22iaub.jpg
Sorry For my English
Pleas help me
thanks

   [_ISTool]
EnableISX=true
Use7zip=false

[Files]
Source: sample2.iky; DestDir: {tmp}; Flags: ignoreversion

Source: ISID.dll; DestDir: {sys}\ISID; Flags: ignoreversion

[Setup]
AppName=Inno Key Generator2
AppVerName=Inno Key Generator 22.214.171.124 2
DefaultDirName={pf}\MJ Freelancing\IKG
InfoBeforeFile=readme.txt
DefaultGroupName=Inno Key Generator
OutputDir=output
AppCopyright=Copyright © Oct 2002 - 2006 MJ Freelancing
OutputBaseFilename=IKGSetup

[ThirdParty]
CompileLogMethod=append

[Code]

function ValidateSerialNumber(InnoKeyFile, User, Orgn, ProdCode, HDD, MAC, PrivateKey, Serial: AnsiString): Boolean;
external 'ValidateSerialNumber@files:ISID.dll stdcall';
function GetMACAddress(output: AnsiString): Boolean;
external 'GetMACAddress@files:ISID.dll stdcall';

var
    UserPage: TInputQueryWizardPage;
    UserValues: TArrayOfString;

procedure InitializeWizard();
begin

    { create the custom page }
    UserPage := CreateInputQueryPage(wpInfoBefore,      //wpWelcome,
        'Enter Registration Details', 'You need to be a registered user to be able to proceed',
        'Enter your registration details exactly (case sensitive), then click Next.');

    UserPage.Add('MAC Address:', true);
    UserPage.Add('Unlock Code:', False);
    UserPage.Add('Private Key:', False);

    { Set default values }
    SetArrayLength(UserValues, 3);
    RegQueryStringValue(HKLM, 'Software\Microsoft\Windows\Hitman', 'Hitman', UserValues[0]);
    RegQueryStringValue(HKLM, 'Software\Microsoft\Windows\Hitman', 'Hitman', UserValues[1]);
    if (UserValues[0] = '') and (UserValues[1] = '') then begin
        RegQueryStringValue(HKCU, 'Software\Microsoft\ND\User2', 'md', UserValues[0]);
        RegQueryStringValue(HKCU, 'Software\Microsoft\ND\User2', 'MD2', UserValues[1]);
    end;

    { Try to find the settings that were stored last time (also see below). }
    UserPage.Values[0] := GetPreviousData('MAC', UserValues[0]);
    UserPage.Values[1] := GetPreviousData('Unlock', UserValues[1]);
    UserPage.Values[2] := GetPreviousData('Private', UserValues[2]);

end;

procedure RegisterPreviousData(PreviousDataKey: Integer);
begin
  { Store the settings so we can restore them next time }

  SetPreviousData(PreviousDataKey, 'MAC', UserPage.Values[0]);
  SetPreviousData(PreviousDataKey, 'Unlock', UserPage.Values[1]);
  SetPreviousData(PreviousDataKey, 'Private', UserPage.Values[2]);

end;

function ScriptDlgPages(CurPage: Integer; BackClicked: Boolean): Boolean;
var
    ExpPath: String;

begin

    Result := True;

    if (CurPage = UserPage.ID) then
    begin
        ExtractTemporaryFile('sample2.iky');        { the public key file }

        ExpPath := ExpandConstant('{tmp}\sample2.iky');

        Result := False;

        UserValues[0] := UserPage.Values[0];
        UserValues[1] := UserPage.Values[1];
        UserValues[2] := UserPage.Values[2];

        if (UserValues[0] = '') or (UserValues[1] = '') or (UserValues[2] = '') then
            MsgBox('No fields can be blank !', mbError, MB_OK)
        else
        begin

        //UserPage.Values[0] := GetPreviousData('MAC', UserValues[0]);
        //UserPage.Values[1] := GetPreviousData('Unlock', UserValues[1]);
        //UserPage.Values[2] := GetPreviousData('Private', UserValues[2]);

    //function ValidateSerialNumber(InnoKeyFile, User,           Orgn,    PCe,HDD,MAC,PrivateKey, Serial: AnsiString): Boolean;
            Result := ValidateSerialNumber( ExpPath,'','','','',UserValues[0],UserValues[2],UserValues[1] );

if (not Result) then
                MsgBox('Invalid Entry !', mbError, MB_OK);

        end
    end

end;

function NextButtonClick(CurPage: Integer): Boolean;
begin
  Result := ScriptDlgPages(CurPage, False);
end;

function BackButtonClick(CurPage: Integer): Boolean;
begin
  Result := True;//ScriptDlgPages(CurPage, True);
end;

function HasHtmlHelp(): Boolean;
begin
    { HHCTRL.OCX GUID }
    Result := RegValueExists(HKCR, 'CLSID\{4662DAB0-D393-11D0-9A56-00C04FB68B66}\InprocServer32', '');
end;

function HasNoHtmlHelp(): Boolean;
begin
    Result := not HasHtmlHelp;
end;

Answer: To have edit boxes non editable simply use their property ReadOnly.
You have created 3 edit boxes (class TPasswordEdit) so now only set their ReadOnly to true:
UserPage.Values[0].ReadOnly := True;
UserPage.Values[1].ReadOnly := True;
UserPage.Values[2].ReadOnly := True;

Put this code at the end of procedure InitializeWizard().
Answer: function GetMacAddress(output:string): Integer;
external 'GetMACAddress@files:ISID.dll stdcall';

//after it create this function
function GetMacAdd(Output: string): string;
var
ClassName: String;
Ret: Integer;
begin
SetLength(ClassName, 256);
Ret := GetMacAddress(PChar(ClassName));
Result := Copy(ClassName, 1 , Ret);
end;

//and call it
UserPage.Values[0]:=(GetMACAdd(''));

Hope it helps.
Comment: Your `GetMacAdd` function prototype makes no sense (why there is the unused `Output` parameter ?), `ClassName` is no good name for variable that does absolutely something else (and is actually useless since you can work directly with the `Result` variable). And finally, if you define a function prototype that takes a `string` parameter, why do you pass a `PChar` ? Anyway, wouldn't [`this`](http://pastebin.com/bsKf4CYY) suffice (just a guess, don't know the library at all, so cannot tell if the `GetMACAddress` function prototype is even correct) ?


Exibir 2 dados no visualg com estrutura de repetição

Question: Estou tentado exibir 2 nomes com, Para e faça, se eu colocar o escreval dentro do laço ele vai ler e escrever ai fica bagunçado, como faria para ler os 2 depois escrever?
Algoritmo "semnome"
Var
i,:inteiro
nome:caractere

Inicio
para i de 1 ate 2 faca
escreval("Digite o nome: ")
leia(nome)

fimpara
escreval("Nome: ",cont)

Fimalgoritmo

Answer: Não conheço muito de Visualg, mas vamos pela logica:
Para você ler e armazenar vários valores é necessário que você tenha variáveis para dedicar espaço de memoria para isso. Ao invés de criar varias variáveis (nome1,nome2,nome3) você pode criar um vetor:
vet: nomes [1..10] de caractere //1..10 é o inicio e fim do seu vetor.

Assim é só ir adicionando nomes nessa "lista" de nomes atráves de um PARA e depois dar outro laço de repetição para percorrer este vetor.
Algoritmo "semnome"
Var i,:inteiro
vet: nomes [1..2] de caractere //1..2 é o inicio e fim do seu vetor.

Inicio
  para i de 1 ate 2 faca
    escreval("Digite o nome: ")
    leia(nomes[i])
  fimpara

//Inicio de outro PARA para escrever os nomes.
  para i de 1 ate 2 faca
    escreval("Nome: ",nomes[i])
  fimpara

Como eu disse, meu conhecimento de visualg não é lá aquelas coisas mas acredito que ajude :D
Comment: é isso msm valeu :D


Of the repair jobs that Bennie's Machine Shop receives, 20 percent are

Question: I am a student and while doing an exercise along with with my friends, given in my book Discrete Event System Simulation by Banks, I got a doubt. I have searched similar questions in internet and got the following question.

Of the repair jobs that Bennie's Machine Shop receives, 20 percent are
  welding jobs and 80 percent are machining jobs.
(a) What is the probability that the next three jobs to come in will
  be welding jobs?
(b) What is the probability that two of the next three jobs to come in
  will be the machining jobs?

I got a ppt from b1.rimg.tw/kochente/9a40d391.ppt in which the folling solution is given

P(A) = 0.2 Thus P(A)xP(A)xP(A) = 0.2 x 0.2 x 0.2 = 0.008
P(B) = 0.8 Thus P(B)xP(B)xP(B) = 0.8 x 0.8 x 0.8 = 0.512

But we felt this answer is wrong for P(B) because P(A) and P(B) cannot be calculated in similar ways.
We have posted the question in this  website  for clarification. But the explanation I got there is given below

"The question is not accurate and the following interpretations are
  possible and went on to explain each case with binomial distribution
  and obtained the following answers "
Probability that the next three jobs will be welding jobs = 1/125
Probability that exactly two of the next three jobs will be machining
  jobs =48/125
Probability that at least two of the next three jobs will be machining
  jobs =112/125

With all these, I have now the following doubts. Please help in a way I can easily understand.
(1) The question is taken from my text book and should be correct. Then,
why the latter site explained the following statement as ambiguous

"What is the probability that two of the next three jobs to come in
  will be the machining jobs?"

and explained each of the following instead

Case 1: Probability that exactly two of the next three jobs to come in
  will be machining jobs
Case 2: Probability that at least two of the next three jobs to come
  in will be machining jobs

who is right here? What are the difference between these statements?
what is the right answer and right approach? Or the first solution i gave (taken from the ppt) is right ? If you can guide and show me the right path, I can try hard and study these which will be helpful in my studies.
(2) The latter site gives a concept of binomial distribution. I guess they have made it complex.  Is it relevant for this? if yes, where I can study more about it?
Thanks in advance. Please guide.
Answer:
Of the repair jobs that Bennie's Machine Shop receives, 20 percent are welding jobs and 80 percent are machining jobs.
(a) What is the probability that the next three jobs to come in will be welding jobs?

If (big, big if) all jobs are independent, i.e. no matter what previous jobs were, next one has the same probability to be a welding job which equals given frequency, $P(a) = P(${job 1 will be a welding job}$)*P(${job 2 will be a welding job}$)*P(${job 3 will be a welding job}$) = 0.2^3 = 0.008$.

Case 1: Probability that exactly two of the next three jobs to come in will be machining jobs
Case 2: Probability that at least two of the next three jobs to come in will be machining jobs
What are the difference between these statements?

Suppose next three jobs are all machining jobs. This satisfies case 2, but not case 1.
For case 1 (with the same if as above), there are following sequences of jobs that fit ($w$ is wielding job and $m$ is machining job): $wmm, mwm, mmw$. Their probabilities are the same, $P(wmm)=P(mwm)=P(mmw)=0.8*0.8*0.2 = 0.128$. $P(${case 1}$)=P(wmm)+P(mwm)+P(mmw)=3*0.128=0.384$.
For case 2, fourth sequence appears: $mmm, P(mmm)=0.8^3=0.512$. So, $P(${case 2}$) = 3*0.2^1*0.8^2+1*0.2^0*0.8^3 = 0.896$.
Now some general info. When you have two mutually exclusive outcomes ($m$ and $w$, in our case), $p$ and $q=1-p$ are often used for their probabilities (for historical reasons). Then, probability of first outcome happening exactly $k$ times out of $n$ is $p^kq^{n-k}$ (probability of a single such outcome) multiplied by a number of such possible outcomes. Number of ways to choose $k$ unordered elements out of $n$ has special name, binomial coefficient, which is usually written $\binom{n}{k}$ or sometimes $C_n^k$ and calculated by formula $n! \over k!(n-k)!$. For our example, $\binom{3}{1}=3$, $\binom{3}{0}=1$.
Comment: in my text, the question is  just " What is the probability that two of the next three jobs to come in will be the machining jobs". Does this mean case 1 or case 2 ?
Comment: @user300718 This is linguistics question, not mathematics question. As a non-native speaker, I can only say that *to me* your question seems ambiguous and if I were to answer on such question, I would provide both solutions.
Comment: thanks a lot for clarifications

Of the repair jobs that Bennie’s Machine Shop receives, 20 percent are


Operator+ to add instances of different classes

Question: Problem statement: Let Matrix be a base class which is subclassed by DenseMatrix and SparseMatrix (and possibly others). What I would like to achieve is the following:
Matrix *A = new DenseMatrix();
Matrix *B = new SparseMatrix();
Matrix C = (*A) + (*B); // dense + sparse
Matrix D = (*A) + (*A); // dense + dense
Matrix E = (*B) + (*B); // sparse + sparse

Even better, I would like to have the following:
DenseMatrix C = (*A) + (*B);
DenseMatrix D = (*A) + (*A);
SparseMatrix E = (*B) + (*B);

Now, when adding a DenseMatrix with a SparseMatrix having declared both as Matrix implies that there must be an operator+ definition in Matrix.
I have already read this answer which makes use of an interface AddEnabled<Foo>, but doesn't seem to be a good solution when (almost) any possible combination of summands. I could possibly define in DenseMatrix the following functions:
friend DenseMatrix operator+ (DenseMatrix const& left, DenseMatrix const& right);

But then again it will be impossible to add two instances of DenseMatrix declared as Matrix (i.e., Matrix *A = new DenseMatrix();).
From various similar questions and answers I suspect that the pimpl idiom could be relevant, but I don't see how.
Note: I'm coding in C++98, not C++11.
Update: As Dieter Lücking suggested in his answer an opeator+ needs to be introduced in the base class. This makes sense, but the problem is that Matrix, being abstract, does not allow methods which return abstract types. However, it is possible to return a pointer or a reference to Matrix; this way we would have a definition like:
Matrix& operator+(const Matrix& right) const;

To an extent this would work, but users of my code would expect a + to return a Matrix instead of a reference to one.
Answer: You may give the base class a state indicating the matrix layout - having that, dispatch matrix operations (on the base class) accordingly. Keep the special matrices classes for construction, but they will elide to the base matrix after applying an operation.
Example:
Matrix = IdentityMatrix operation DiagonalMatrix

This would elide the argument types and result in a matrix having a state 'Diagonal'
Comment: So, you mean that I should implement methods like `DenseMatrix DenseMatrix::add(DenseMatrix&)` and `DenseMatrix DenseMatrix::add(SparseMatrix&)` and have a method like `int Matrix::getType();` so that I know what each object it, so that then I will be able to define a single `operator+` in the base class?
Comment: No, just Matrix operator Matrix (where the base class Matrix chooses the proper algorithm, depending on the states of the arguments)
Comment: True, but as I commented to @JohnP's answer, the definition of a `Matrix operator+(const GenericMatrix& right) const;` in `Matrix` results in an *"invalid abstract return type"* because `Matrix` is an abstract class, i.e., it has some other abstract methods. Maybe I could introduce some dummy implementations and throw an exception if one attempts to create instances of `Matrix`.
Comment: Also - given that `Matrix` contains abstract methods - does it make sense for the addition operator to return a pointer to `Matrix` instead of `Matrix`?
Answer: You might need to declare your Matrix::operator+ as virtual if you re-define it in your sub-classes and you initialize them as
Matrix *A = new DenseMatrix();

Also why is operator+ not a member of DenseMatrix? What I mean is
DenseMatrix DenseMatrix::operator+ (DenseMatrix const& right) const;

instead of
friend DenseMatrix operator+ (DenseMatrix const& left, DenseMatrix const& right);

Are you sure you need to re-overload operator+ in you derived classes again?
Can't you just inherit operator+ from your base class Matrix?
Edit:
If your base class does not have an operator+, but your derived ones do, you still need to declare (but not define) one as virtual in the base class, otherwise the derived classes cannot override it when they are pointed to by a Matrix* and not a DenseMatrix*.
Comment: If I attempt to declare a virtual abstract summation operator in the base class, i.e., `virtual Base operator+(const Base& right) const =0;` then I get a **invalid abstract return type for member function**. If I declare an `operator+` in my DenseMartix then (i) I will be able to do only **DenseMatrix+DenseMatrix** and not **DenseMatrix+SparseMatrix** and (ii) I will not be able to do what I explained in the problem statement in my question.
Comment: Why would you not be able to do Dense+Sparse?
Also, how is adding these matrices different from adding Matrix+Matrix? Why can't you simply define `Matrix::operator+(Matrix)`?
What type would Sparse+Dense be? What type would Dense+Sparse be?
Comment: If my base class `Matrix` is abstract then I get a "invalid abstract return type for member function 'Matrix Matrix::operator+(const Matrix&) const'". Should my base class have at least a "fake" implementation for every method I declare?
Answer: Not sure why you want multiple + operators. Matrix addition is the same, no matter what the matrix representation:
1. Ensure the matrices being added have the same dimensions.
2. Add corresponding entries from the input matrices to produce the values in the output matrix.
These operations will be done in the base class operator +.
Then all you need is to implement getDimensions() in each subclass and, if they are equal, perform:
result.put(x, y, inputA.get(x, y) + inputB.get(x, y));
for each entry in the matrices.
Comment: Adding two sparse matrices can be done in o(n), full blown addition n^2
Comment: @prakharsingh95 The assertion is not quite true. For adding 2 sparse matrices, it is O(nnz), where nnz is the count of the union of non-zero entries in both matrices. nnz can vary from 0 to n*m, the number of possible entries. The additional cost of modifying sparse matrices after creation can overwhelm the advantage in computation depending on the application.
Comment: of course. I had somehow kept the special case of diagonal matrices in mind rather than sparse matrix. Nonetheless, my point is that it can indeed be beneficial to have multiple matrix addition definitions.


Laravel 5: The server responded with a status of 405 (Method Not Allowed)

Question: I am trying to upload a file via ajax, but it throws this message: "The server responded with a status of 405 (Method Not Allowed)" The route is defined like this: Route::post('/file/upload', 'Upload@importFile');  And the Ajax code I'm using is this:
var upload_file=function(input_file,format){
            var formData = new FormData();
            formData.append("upload_file",input_file);
           // formData.append("format",format);
            return $.ajax({
                type: 'POST',
                dataType: 'json',
                processData: false,
                contentType:  false,
                data: formData,
                cache:false,
                url: '/file/upload/'
            });
        }

Somehow it works locally, but it throws this error when I try it on the server, however I've used this same code before and it's worked fine
Answer: You can try to remove last "/" in the url.Like that: url: '/file/upload'
var upload_file=function(input_file,format){
        var formData = new FormData();
        formData.append("upload_file",input_file);
       // formData.append("format",format);
        return $.ajax({
            type: 'POST',
            dataType: 'json',
            processData: false,
            contentType:  false,
            data: formData,
            cache:false,
            url: '/file/upload'
        });
    }

Comment: What a shame, thank you, by the way, why does it work locally with the last slash?
Comment: Probably you have apache or something like that on the local that but server has nginx so they have some differences.


Automatically-reconnecting TCP tunnel

Question: I have an unreliable network connection between two machines: sometimes active TCP connections get dropped for reasons beyond my control. I want to establish a reliable TCP connection between the two machines.
If the network was reliable, I'd just run ssh -L 1234:localhost:1234 remotehost, with the server listening on port 1234 on remotehost, and point the client at localhost:1234. But if the ssh connection dies, so will the forwarded connection. How can I arrange to automatically restore the connection between the client and the server?
Non-solutions:

This isn't for interactive applications, so screen does not apply.
This isn't just about reconnecting an SSH tunnel automatically, � la autossh. I want to continue using the same tunneled TCP connection, not start a new one.
In principle, a VPN would do the trick. But it seems overkill when I just want one TCP connection, and I'd like a solution that works even if I don't have root permissions on either side.

I have a dim memory of a program called rocks that did just that, but it seems to have fallen off the face of the web. I'm mostly interested in Linux on both sides (though I'd expect a program at this level to be portable to other unices), but if you know of a program that works between QNX and VMS, all the better.
Comment: Gilles, are you using tcp keepalives with your ssh connections?  If not, try this first... some NAT implementations time connections out quickly
Comment: @Mike: Thanks for the tip. I don't have an immediate need, but I've faced both situations where some intermediate route came and went (so TCP keepalives did more harm than good) and situations where a NAT overloaded and dropped me (so TCP keepalives might help). TCP keepalives wouldn't matter for a continuous stream anyway (e.g. scp), would they? In any case I'd like to keep this general: next time I'm faced with a flaky network of whatever flavor, what can I do?
Comment: Gilles, the solutions are different for constant streams like `scp`.  I was responding w/ ssh keepalives based on your port-forwarding example.  Re: flaky downstream hop, there isn't much you can do, other than create an ssh session with keepalives that are *more* tolerant (i.e. allow more dropped keepalives with `ServerAliveInterval > 0` and `ServerAliveCountMax > 3`).  NAT requires lower keepalives intervals.  The key issue is to identify what the problem is and tailor accordingly.  Put the options in `.ssh/config` so they are always there for you
Comment: @Mike: One of my use cases includes the client getting its IP from an overloaded NAT than randomly drops even active connections (think more P2P than there should be). After a few seconds, the client manages to reconnect but might get a different IP address. There's no way the TCP connection will survive in that case. Rocks copes, but I'd prefer something that compiles out of the box on today's systems.
Comment: in the case of the NAT giving you new IPs, there isn't much you can do than get the NAT fixed or hope for another `rocks` implementation... although this is obviously a real kludge
Answer: Is the old an unmaintained Reliable Sockets (Rocks) what you're looking for ?
Comment: Thank you, Rocks is indeed what I remembered. Of course I'd prefer something that's maintained.
Comment: @Gilles'SO-stopbeingevil' Not only is it unmaintaned, but it seems to have dropped off the face of the internet completely!
Comment: @Michael: [There's a link on FSF's website](https://directory.fsf.org/wiki/Rocks) that points to a, currently, functioning ftp server
Answer: The only standard protocol I know of with this capability is MPTCP. It is transparent to the application layer, so SSH on top of MPTCP should just work. It can run the underlying TCP connections over different paths with different IPs, so in principle it could be used to migrate your SSH connection in and out of the VPN connection depending on whether the VPN connection is up.
I don't know much about the maturity of MPTCP implementations, but the design of the protocol looks quite robust.
It should protect your SSH connections from getting lost due to flaky network connectivity. It won't protect you against a mitm who wants to break your SSH connection. A mitm can still inject corrupted data, which SSH will detect and break the connection.
An MPTCP like reconnect method build into the SSH protocol would be the method I could imagine keeping a connection alive for the longest possible time. But I don't think such a feature has been designed for the SSH protocol.
Answer: You could use daemontools to keep the ssh port forward up; it won't necessarily keep programs depending on the connection alive while it's down (as presumably when ssh disconnects the local port will start refusing their connections), but it's a start.
I suspect there are some iptables tricks, like causing that port to DROP packets as soon as the ssh forward goes away, so the connecting programs just know that packets are disappearing, not being refused.  I'm just learning daemontools myself (again) so I'm not sure if you can run a custom script when a service dies, but I suspect you can.
Answer: TCP does this automatically. You need only disable or weaken the typical practical cleanup hacks used to kill moribund TCP connections. Disable TCP keepalive for your connection, and greatly increase the limit for excessive retransmissions. On Linux, for example, write a large number into /proc/sys/net/ipv4/tcp_retries2.
However, in a modern network a stateful packet inspection firewall is likely to forget about a TCP connection which fails to exchange packets regularly, so it may rain on your parade.
Comment: It is true that TCP can handle the situation, as long as each endpoint has a static IP address and there are no stateful middleboxes. The question mentions `reasons beyond my control`, which I read as dynamic IP or stateful middleboxes. In such scenarios TCP keepalive can help a little bit. But no matter how you configure TCP keepalive, it won't be enough to keep the connection alive when a middlebox lose state due to being restarted.
Comment: @kasperd I agree. However, it's futile to try to keep a TCP connection open in those cases. Therefore, I assumed the questioner is not facing those particular challenges.
Comment: It is not futile if you control both endpoints and can upgrade them to a stack with MPTCP support. Additionally an application layer solution could be implemented on top of TCP without needing MPTCP.

Automatically-reconnecting TCP tunnel