Mutate and ifelse with NA and values from other variable in R

Question: I have a df that looks something like this:
id <- c(1:8)
born.swis <-  c(0, 1, NA, NA, NA, 2, NA, NA)
born2005 <- c(NA, NA, 2, NA, NA, NA, NA, NA)
born2006 <- c(NA, NA, NA, 1, NA, NA, NA, NA)
born2007 <- c(NA, NA, NA, NA, NA, NA, NA, 1)
born2008 <- c(NA, NA, NA, NA, NA, NA, 2, NA)
born2009 <- c(NA, NA, NA, NA, NA, NA, NA, NA)
df <- data.frame(id, born.swis, born2005, born2006, born2007, born2008, born2009)

I'm trying to mutate born.swis based on the values of the other variables. Basically, I want the value bornswis to be filled with the value one of the other variables IF born.id is NA and IF it is not NA for that variable. Something like this:
id <- c(1:8)
born.swis <-  c(0, 1, 2, 1, NA, 2, 2,1)
df.desired <- data.frame(id, born.swis)

I tried several things with mutate and ifelse, like this:
df <- df%>%
  mutate(born.swis = ifelse(is.na(born.swis), born2005, NA,
                            ifelse(is.na(born.swis), born2006, NA,
                                   ifelse(is.na(born.swis), born2007, NA,
                                          ifelse(is.na(born.swis), born2008, NA,
                                                 ifelse(is.na(born.swis), born2009, NA,)
         )))))

and similar things, but I'm not able to reach my desired outcome.
Any ideas?
Many thanks!
Answer: One dplyr option could be:
df %>%
 mutate(born.swis_res = coalesce(!!!select(., starts_with("born"))))

  id born.swis born2005 born2006 born2007 born2008 born2009 born.swis_res
1  1         0       NA       NA       NA       NA       NA             0
2  2         1       NA       NA       NA       NA       NA             1
3  3        NA        2       NA       NA       NA       NA             2
4  4        NA       NA        1       NA       NA       NA             1
5  5        NA       NA       NA       NA       NA       NA            NA
6  6         2       NA       NA       NA       NA       NA             2
7  7        NA       NA       NA       NA        2       NA             2
8  8        NA       NA       NA        1       NA       NA             1

Or with dplyr 1.0.0:
df %>%
 mutate(born.swis_res = Reduce(coalesce, across(starts_with("born"))))

Comment: This worked. Thanks a lot!
Answer: In base R, you can use max.col :
df[cbind(1:nrow(df), max.col(!is.na(df[-1])) + 1 )]
#[1]  0  1  2  1 NA  2  2  1

max.col gives the column position of the first non-NA value in each row (exlcuding first column), we create a matrix with row-index and use it to subset df.
Answer: base R
df$born.swis <- apply(df[-1], 1, function(x) ifelse(all(is.na(x)), NA, sum(x, na.rm = T)))


Vue js listen default events with vm.$on

Question: interesting to me it is possible to listen default event with vm.$on?Is it impossible then why?
This is my html

dsdsd

This is my script
let vm = new Vue({
            el:"#app",
            methods:{
                clickListener()
                {
                    console.log("called clickListener")
                }
            }
        })

        vm.$on('click',function(){
            console.log("hello")
        })

Answer: You need to emit an event you want to listen to first, use vm.$emit() like this:
let vm = new Vue({
  el:"#app",
  methods:{
    clickListener() {
      this.$emit('eventName', 'sample-value');
    }
  }
})

vm.$on('eventName', function(value){
  console.log(value); // 'sample-value'
});

EDIT: try something like this:
const vm = new Vue({
  el: '#app',
  mounted() {
    const app = document.getElementById('app');
    app.addEventListener('click', (event) => {
      this.$emit('click', event);
    });
  }
});

vm.$on('click', (event) => {
  console.log('click', event);
});

Comment: Yeah i know this method but i' interested this possible without emit?
Comment: @MuradSofiyev Why exactly? What's wrong in emiting events? Even if you could listen to default events, it wouldn't work the way you assumed - `vm.$on('click')` looks like you are waiting for click events on your Vue instance, but you have click handler on div inside your `#app` element. You could always use vanilla `addEventListener`, but I still don't understand why...
Comment: Example i want to listen every click event my template
Comment: @MuradSofiyev I edited my answer to do what you probably want.


java.lang.UnsupportedOperationException: Can't convert to dimension: type=0x12

Question: <?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/bg_criar_conta"
    tools:context="com.dietcode.radiovox.CriarMinhaConta">

    <ImageView
        android:id="@+id/diskId"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginEnd="8dp"
        android:layout_marginLeft="0dp"
        android:layout_marginRight="0dp"
        android:layout_marginStart="8dp"
        app:layout_constraintLeft_toLeftOf="@+id/guidelineEsquerda"
        app:layout_constraintRight_toLeftOf="@+id/guidelineDireita"
        app:layout_constraintTop_toTopOf="@+id/guidelineTop"
        app:srcCompat="@drawable/disk"
        app:layout_constraintHorizontal_bias="0.0"
        android:layout_marginTop="0dp" />

    <TextView
        android:id="@+id/textoCriarContaId"
        android:layout_width="0dp"
        android:layout_height="20dp"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:text="CRIE SUA CONTA"
        android:textAlignment="center"
        android:textAppearance="@style/TextAppearance.AppCompat.Medium"
        android:textStyle="bold"
        app:layout_constraintBottom_toTopOf="@+id/campoNomeId"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintLeft_toLeftOf="@+id/guidelineEsquerda"
        app:layout_constraintRight_toLeftOf="@+id/guidelineDireita"
        app:layout_constraintTop_toBottomOf="@+id/diskId" />

    <EditText
        android:id="@+id/campoNomeId"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginEnd="@+id/guidelineDireita"
        android:layout_marginStart="@+id/guidelineEsquerda"
        android:ems="10"
        android:hint="Nome"
        android:inputType="textPersonName"
        app:layout_constraintRight_toLeftOf="@+id/guidelineDireita"
        android:layout_marginRight="8dp"
        android:layout_marginLeft="8dp"
        app:layout_constraintLeft_toLeftOf="@+id/guidelineEsquerda"
        app:layout_constraintHorizontal_bias="0.0"
        android:layout_marginBottom="8dp"
        app:layout_constraintBottom_toTopOf="@+id/campoEmailId" />

    <EditText
        android:id="@+id/campoEmailId"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginEnd="8dp"
        android:layout_marginLeft="0dp"
        android:layout_marginRight="0dp"
        android:layout_marginStart="8dp"
        android:ems="10"
        android:hint="E-mail"
        android:inputType="textEmailAddress"
        app:layout_constraintLeft_toLeftOf="@+id/guidelineEsquerda"
        app:layout_constraintRight_toLeftOf="@+id/guidelineDireita"
        android:layout_marginBottom="8dp"
        app:layout_constraintBottom_toTopOf="@+id/campoSenhaId" />

    <EditText
        android:id="@+id/campoSenhaId"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginEnd="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginStart="8dp"
        android:ems="10"
        android:hint="Senha"
        android:inputType="textPassword"
        app:layout_constraintLeft_toLeftOf="@+id/guidelineEsquerda"
        app:layout_constraintRight_toLeftOf="@+id/guidelineDireita"
        app:layout_constraintHorizontal_bias="0.0"
        android:layout_marginBottom="8dp"
        app:layout_constraintBottom_toTopOf="@+id/campoConfirmarSenhaId" />

    <EditText
        android:id="@+id/campoConfirmarSenhaId"
        style="@android:style/Widget.EditText"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginStart="8dp"
        android:ems="10"
        android:hint="Confirmar senha"
        android:inputType="textPassword"
        app:layout_constraintBottom_toTopOf="@+id/botaoEntrarId"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintLeft_toLeftOf="@+id/guidelineEsquerda"
        app:layout_constraintRight_toLeftOf="@+id/guidelineDireita" />

    <android.support.constraint.Guideline
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/guidelineTop"
        android:orientation="horizontal"
        app:layout_constraintGuide_percent="0.16"
        tools:layout_editor_absoluteY="95dp"
        tools:layout_editor_absoluteX="0dp" />

    <android.support.constraint.Guideline
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/guidelineEsquerda"
        android:orientation="vertical"
        app:layout_constraintGuide_percent="0.17"
        tools:layout_editor_absoluteY="0dp"
        tools:layout_editor_absoluteX="61dp" />

    <android.support.constraint.Guideline
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/guidelineDireita"
        android:orientation="vertical"
        app:layout_constraintGuide_percent="0.83"
        tools:layout_editor_absoluteY="0dp"
        tools:layout_editor_absoluteX="299dp" />

    <android.support.constraint.Guideline
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/guidelineBotton"
        android:orientation="horizontal"
        app:layout_constraintGuide_percent="0.98" />

    <Button
        android:id="@+id/botaoEntrarId"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginBottom="16dp"
        android:layout_marginEnd="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginStart="8dp"
        android:background="@drawable/botao_entrar"
        app:layout_constraintBottom_toTopOf="@+id/possuiContaid"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintLeft_toLeftOf="@+id/guidelineEsquerda"
        app:layout_constraintRight_toLeftOf="@+id/guidelineDireita" />

    <TextView
        android:id="@+id/possuiContaid"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginEnd="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginStart="8dp"
        android:text="Já possui uma conta?"
        android:textAlignment="center"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintLeft_toLeftOf="@+id/guidelineEsquerda"
        app:layout_constraintRight_toLeftOf="@+id/guidelineDireita"
        android:layout_marginBottom="8dp"
        app:layout_constraintBottom_toTopOf="@+id/continueSemLogarId" />

    <TextView
        android:id="@+id/continueSemLogarId"
        android:layout_width="0dp"
        android:layout_height="17dp"
        android:layout_marginEnd="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginStart="8dp"
        android:text="Continue sem logar"
        android:textAlignment="center"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintLeft_toLeftOf="@+id/guidelineEsquerda"
        app:layout_constraintRight_toLeftOf="@+id/guidelineDireita"
        android:layout_marginBottom="8dp"
        app:layout_constraintBottom_toTopOf="@+id/guidelineBotton" />

</android.support.constraint.ConstraintLayout>

logcat
08-04 11:57:50.581 21423-21423/com.dietcode.radiovox E/AndroidRuntime: FATAL EXCEPTION: main
                                                                       Process: com.dietcode.radiovox, PID: 21423
                                                                       java.lang.RuntimeException: Unable to start activity ComponentInfo{com.dietcode.radiovox/com.dietcode.radiovox.CriarMinhaConta}: java.lang.UnsupportedOperationException: Can't convert to dimension: type=0x12
                                                                           at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2695)
                                                                           at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2769)
                                                                           at android.app.ActivityThread.access$900(ActivityThread.java:177)
                                                                           at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1430)
                                                                           at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                           at android.os.Looper.loop(Looper.java:135)
                                                                           at android.app.ActivityThread.main(ActivityThread.java:5910)
                                                                           at java.lang.reflect.Method.invoke(Native Method)
                                                                           at java.lang.reflect.Method.invoke(Method.java:372)
                                                                           at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1405)
                                                                           at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1200)
                                                                        Caused by: java.lang.UnsupportedOperationException: Can't convert to dimension: type=0x12
                                                                           at android.content.res.TypedArray.getDimensionPixelSize(TypedArray.java:584)
                                                                           at android.view.ViewGroup$MarginLayoutParams.<init>(ViewGroup.java:6937)
                                                                           at android.support.constraint.ConstraintLayout$LayoutParams.<init>(ConstraintLayout.java:1662)
                                                                           at android.support.constraint.ConstraintLayout.generateLayoutParams(ConstraintLayout.java:1223)
                                                                           at android.support.constraint.ConstraintLayout.generateLayoutParams(ConstraintLayout.java:383)
                                                                           at android.view.LayoutInflater.rInflate(LayoutInflater.java:808)
                                                                           at android.view.LayoutInflater.inflate(LayoutInflater.java:504)
                                                                           at android.view.LayoutInflater.inflate(LayoutInflater.java:414)
                                                                           at android.view.LayoutInflater.inflate(LayoutInflater.java:365)
                                                                           at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:436)
                                                                           at android.app.Activity.setContentView(Activity.java:2245)
                                                                           at com.dietcode.radiovox.CriarMinhaConta.onCreate(CriarMinhaConta.java:16)
                                                                           at android.app.Activity.performCreate(Activity.java:6178)
                                                                           at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
                                                                           at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2648)
                                                                           at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2769)
                                                                           at android.app.ActivityThread.access$900(ActivityThread.java:177)
                                                                           at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1430)
                                                                           at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                           at android.os.Looper.loop(Looper.java:135)
                                                                           at android.app.ActivityThread.main(ActivityThread.java:5910)
                                                                           at java.lang.reflect.Method.invoke(Native Method)
                                                                           at java.lang.reflect.Method.invoke(Method.java:372)
                                                                           at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1405)
                                                                           at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1200)

Comment: Eu criei essa activity, e quando vou abrir ela, o aplicativo se encerra. O que pode ser?
Comment: Igor a sua pergunta está com uma formatação terrível, onde está descrito as dificuldades que você está tendo? O que você já tentou fazer?
Comment: O seu erro está relacionado ao XML do layout. Tem algo errado nele que está fazendo o setContentView() da activity crashear. Se colocasse o XML inteiro ajudaria mais.
Comment: voce precisa estar os "anchors" do seu contraintlayout
Answer: No seu EditText, remova os atributos android:layout_marginEnd="@+id/guidelineDireita" e android:layout_marginStart="@+id/guidelineEsquerda"
<EditText
        android:id="@+id/campoNomeId"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginEnd="@+id/guidelineDireita"
        android:layout_marginStart="@+id/guidelineEsquerda"
        ...
        app:layout_constraintBottom_toTopOf="@+id/campoEmailId" />

Esses atributos esperam uma medida e não uma view.
Comment: Deu certo, obrigado Marcio!
Comment: Show de bola, não esqueça de aceitar a resposta, por favor.


How do i call a recursive function in this python program where I am supposed to convert decimal numbers to hexadecimal?

Question: x=""
def main():
    Decimal=int(input("Enter a decimal value"))
    print (DecimaltoHexa(Decimal))

def HexaLetters(Hexa):

this is where the hexa gets imported here for numbers greater than 9
    if Hexa==10:
        return "A"
    elif Hexa==11:
        return "B"
    elif Hexa==12:
        return "C"
    elif Hexa==13:
        return "D"
    elif Hexa==14:
        return "E"
    elif Hexa==15:
        return "F"

def DecimaltoHexa(Decimal):

need help here as this is the body of the program, i cant use loops because i have to add a recursive function but i need help in doing that.
    global x
    y=0
    LastDigit=0
    Hexa=Decimal%16
    if Hexa>9:
        Hexa=HexaLetters(Hexa)
    Decimal=int(Decimal/16)
    if Decimal<16:
        y=-1
        LastDigit=Decimal
    x=str(Hexa)+x
    final=str(LastDigit)+x
    return (final)
    DecimaltoHexa(Decimal)
main()

Answer: Modify your recursive method in the following way to convert a decimal to hexa-
def main():
    Decimal=int(input("Enter a decimal value"))
    print (DecimaltoHexa(Decimal, ""))

def HexaLetters(Hexa):
    if Hexa == 10:
        return "A"
    elif Hexa == 11:
        return "B"
    elif Hexa == 12:
        return "C"
    elif Hexa == 13:
        return "D"
    elif Hexa == 14:
        return "E"
    elif Hexa == 15:
        return "F"

def DecimaltoHexa(Decimal, prev_hexa):
    remainder = Decimal % 16
    remaining_Decimal = Decimal // 16
    hexa_char = str(remainder)
    if remainder > 9:
        hexa_char = HexaLetters(remainder)
    current_hexa = hexa_char + prev_hexa
    if remaining_Decimal != 0:
        current_hexa = DecimaltoHexa(remaining_Decimal, current_hexa)
    return current_hexa

main()

But if you want a more concise solution, you can use the following implementation -
hexa_chars = map(str, range(10)) + ["A", "B", "C", "D", "E", "F"]

def int_to_hexa(decimal, curr_hexa):
    rem = decimal % 16
    rem_decimal = decimal // 16
    curr_hexa = hexa_chars[rem] + curr_hexa
    if rem_decimal:
       curr_hexa = int_to_hexa(rem_decimal, curr_hexa)
    return curr_hexa

if __name__ == '__main__':
    dec = input()
    hexa_num = ""
    hexa_num = int_to_hexa(dec, hexa_num)
    print(hexa_num)

Comment: What does map(str, range(10)) do ? @yabhishek
Comment: `map` is an in-built method in Python which applies a function on each value of an iterable. Having said that, in this case, `range(10)` will generate list of numbers in the range `[0,9]` and `map(str, range(10))` will convert each of them into string and return a list of strings, i.e. `["0", "1", ....., "9"]`.


Deep learning theano

Question: I use Theano for developing a convolutional neural network using keras library.
when i tried to run my code , i reported the following error:
AssertionError: AbstractConv2d Theano optimization failed: there is no implementation available supporting the requested options. Did you exclude both "conv_dnn" and "conv_gemm" from the optimizer? If on GPU, is cuDNN available and does the GPU support it? If on CPU, do you have a BLAS library installed Theano can link against?
Please I need specific steps to solve the problem.
Thanks in advance.
Answer: Try adding optimizer = None to your .theanorc file
A sample .theanorc file might look like:
[global]
device = gpu
optimizer = None
[cuda]
root = /usr/local/cuda-VERSION

Comment: where  can i find this file?
Comment: If you use Linux, it is in your /home directory. If it is not there, make a file called .theanorc in /home. The .theanorc is the config file that tells theano what to do when you use it. You can configure your default device (CPU vs GPU), your cuda root directory, and your optimizer.
Comment: No, i use windows 7 and intel graphics .
Comment: An  OpenBLAS library , can help me to solve the problem ?
Comment: There is a step by step tutorial for installing Theano on windows, [here](http://deeplearning.net/software/theano/install_windows.html)
Comment: Many Thanks  for your effort. I changed optimizer to  None and my code run successfully

Deep learning theano


How to compute weighted average

Question: Country  life_expectancy   population

Germany     70               3000000
France      75               450000
USA         70               350000
India       65               4000000
Pakistan    60               560000
Belgium     68               230000

I want to calculate the weighted average life expectancy according to the formula below:
∑ ( × )/ ∑

where  = life expectancy
       = population

NOTE: The weighted average life expectancy is computed with the sum of the products of life expectancy by the total population of each country divided by the sum of the total population of each country
Can anyone please tell me how to solve this using for loop?
Comment: Any specific reasons why you would like to use the `for` loop, when it can be done without it and much faster?
Comment: The answer is here: https://stackoverflow.com/questions/26205922/calculate-weighted-average-using-a-pandas-dataframe and here: https://stackoverflow.com/questions/33657809/calculate-weighted-average-with-pandas-dataframe
Comment: I want to implement it using for loop and my formula is also different
Answer: Using numpy.average(..., weights=...):
Ref: https://docs.scipy.org/doc/numpy/reference/generated/numpy.average.html
import numpy as np

res=np.average(df["life_expectancy"], weights=df["population"])

Outputs:
67.22817229336438

Answer: with a for loop
numerator, denominator = 0, 0
for i in df.index:
    numerator += df.loc[i, 'life_expectancy'] * df.loc[i, 'population']
    denominator += df.loc[i, 'population']
weighted_average = numerator / denominator

or using pandas to do everything faster and in any easier to read way (this is my recommended solution)
weighted_average = (df['life_expectancy']*df['population']).sum() / df['population'].sum()

Comment: thanks for the solution. I have one more question if I add another column continents then how can I groupby it on continents and calculate the weighted avg?
Comment: i tried doing this df.groupby('continents').apply(lambda x : (df['life_expectancy']*df['population']).sum() / df['population'].sum()) but its giving me the same value for all the continents
Comment: your lambda function is wrong, it should be df.groupby('continents').apply(lambda x : (x['life_expectancy']*x['population']).sum() / x['population'].sum())
Comment: @peeps, you should accept the best answer once you have seen it
Answer: Actually for loop is not required here you can directly calculate
life_exp = (countries_df.life_expectancy*countries_df.population).sum()/countries_df.population.sum()

How to compute weighted average


Computing a parity check matrix given the minimum code distance

Question: As per the title, I would like to know if it is possible to construct a parity check matrix given the length of the code, dimension and the minimum distance of the code. For example, if I would like to construct a parity matrix for this code C[22, 13, 5], how do I go about doing this?
Comment: _In general,_ the answer is No, you cannot construct a parity check matrix for a $[n,k,d]$ code even if you can prove that such a code must exist.
Comment: Find 22 binary vectors of length nine such that no four are linearly dependent. If you can. I don't know if it's possible. IOW - agree with Dilip.
Answer: This question was answered in the comment by Dilip Sarwate.
From the comments:
"In general, the answer is No, you cannot construct a parity check matrix for a $[n,k,d]$ code even if you can prove that such a code must exist."


Como deixar html transferível entre computadores sem perder hyperlink e imagens?

Question: Comecei a programar a pouco tempo usando HTML e o meu maior problema é fazer um projeto e quando eu levo para ouros computadores demoro muito tempo mudando os caminhos de imagens e hyperlinks.
Como fazer com que os links não quebrem quando eu levar meu projeto pra outro computador?
Exemplo, no pc da minha empresa o link fica algo do tipo:

D:\Users\Programador\Desktop\meu-projeto\images\logo.png

No meu pc fica

C:\Users\Joao\Desktop\meu-projeto\images\logo.png
Comment: Você vai ir aprendendo isso com o tempo. Geralmente se usa uma linguagem de programação que **gera** o HTML que será enviado pro _browser_, com isso será possível criar funções nesta linguagem, onde esta função será responsável por criar um link dinâmico (tanto para outras páginas, como para imagens, etc.) apenas sabendo qual é o recurso que você pretende linkar. Só com HTML é mais difícil de se fazer algo, provavelmente a melhor ideia é trabalhar com endereços relativos ao invés de absolutos, isso já dá uma flexibilidade **bem** maior, mas ainda assim não resolve todos os casos.
Comment: Acho que entendi o que quis dizer. Tente colocar um caminho relativo nas sua imagens, ou seja, o caminho ocorre a partir da página atual. Por Exemplo: `` neste caso, a partir do local do site, ele irá buscar esse caminho para a imagem
Comment: Se em cada computador que vc levar seu projeto os caminhos forem diferentes, vai ter que mudar os caminhos mesmo. Sua pergunta está muito vaga sem um código de exemplo para ser analisado.
Comment: O estranho nessa pergunta é que a estrutura de diretórios e arquivos (caminhos) do site (HTML) não muda quando você carrega tudo junto para outro computador. Não sei o porquê em ter que alterar isso.
Answer: Para evitar ou minimizar esse tipo de problema você pode usar caminhos relativos.
Para referenciar partir da "pasta" a qual foi aberto o arquivo, comece o caminho sem barras, exemplo:
Você tem a seguinte estrutura:

index.html
imagens (pasta)

logo.png

outroarquivo.html
pessoas (pasta)

pessoa.html

Sua tag img ficaria:

Seu hyperlink ficaria:
    Outro arquivo
Já a imagem no arquivo pessoa.html teria que "voltar" uma pasta para localizar o arquivos, exemplo:

Você encontra mais detalhamento neste link: https://www.w3schools.com/html/html_filepaths.asp
Answer: O problema real é você utilizar caminhos absolutos para mapear seus recursos no Html, recomendo utilizar caminhos relativos, dessa forma, ao trocar de máquina o problema não existirá
No seu caso, se o arquivo Html fica na pasta D:\Users\Programador\Desktop\meu-projeto\ o caminho da página pode ser apenas images\logo.png, o sistema vai buscar a partir do caminho atual a pasta images e depois o arquivo logo.png, indiferente de onde esteja a pasta meu-projeto


Proof: If $f : [a,b] \to [0,M]$ is Riemann integrable and has integral zero then $f(x) = 0$ at every continuity point $x$ of $f$.

Question:
If $f : [a,b] \to [0,M]$ is Riemann integrable and has integral zero then $f(x) = 0$ at every continuity point $x$ of $f$.

I don't know how to prove this though I have faint idea stated below. Can we use this idea?
Proof:
We are given that function is Riemann integrable and integral is zero.
$$\lim_{mesh \space P  \to \space 0} R(f,P,T) = I$$
So,
Given $\epsilon > 0, \exists\delta>0, $ such that for any partition pair
$$mesh \space P < \delta \implies \left| R(f,P,T) - I\right| < \epsilon $$
If number of intervals are n then
$$ \left| \sum_{i=1}^n f(t_i)\Delta x_i \right| < \epsilon$$
Now we can take contradiction that function has value greater than 0 at some continuous points and then use this to contradict : If function is Riemann integrable, then it's set of discontinuities will be zero set.
But I am not able to formulate it. Give me hint. Thanks.
Comment: It is rather odd that your book presents this as a corollary of a deep and difficult theorem when the result is easily available via contradiction as shown in @DannyPak-KeungChan answer.
Comment: However I don't think the question deserves downvotes. +1 to compensate.
Comment: You can use a theorem that states that $f$ is Riemann integrable if and only if the set $D$ of points at which $f$ fails to be continuous has measure zero in $\mathbf{R}^n$?
Comment: @positrón0802 But I don't know how to use it.
Comment: @positrón0802 What you stated is a deep theorem due to Lebesgue and is not related to the current question. We are not asked to prove that $f=0$ a.e.. We are just asked to proved that $f(x_0)=0$ if f is continuous at $x_0$.
Comment: @DannyPak-KeungChan but this corollary was given after Riemann Lebesgue theorem, that is why I thought we should use that idea.
Comment: Yeah, I used the Lebesgue theorem but the other answer was much more easy, so I deleted my answer.
Answer: Prove by contradiction. Suppose that there exists $x_{0}\in[a,b]$
such that $f$ is continuous at $x_{0}$ and $f(x_{0})>0$. Let $c=\frac{1}{2}f(x_{0})>0$.
Since $f$ is continuous at $x_{0}$ and $f(x_{0})>c$, there exists
$\delta>0$ such that $f(x)>c$ for any $x\in[x_{0}-\delta,x_{0}+\delta]$.
(We need to adjust the interval $[x_{0}-\delta,x_{0}+\delta]$ accordingly
if $x_{0}=a$ or $x_{0}=b$.)
Since $f\geq0$, we have
$$
\int_{a}^{b}f(x)\,dx\geq\int_{x_{0}-\delta}^{x_{0}+\delta}f(x)\,dx\geq\int_{x_{0}-\delta}^{x_{0}+\delta}c\,dx=2\delta c>0,
$$
which is a contradiction.
Comment: For completeness' sake: With the mentioned adjustment for the boundaries, it is $$\int_a^bf(x)\,\mathrm dx\ge\int_{\max\{a,x_0-\delta\}}^{\min\{b,x_0+\delta\}}f(x)\,\mathrm dx\ge \int_{\max\{a,x_0-\delta\}}^{\min\{b,x_0+\delta\}}c,\mathrm dx\ge \min\{\delta,b-a\}c>0$$


Grouping by day + events spanning several days

Question: This is a question that has already been asked on Drupal.org. It's exactly what I need on my view, but it hasn't been answered yet.
Posted by Amanda-333 on April 12, 2011 at 5:58am
I wanted to ask how I can group events by day in a view.

It works fine if I only have events that have their start- and endtime on the same day.
2011-04-12
2011-04-12 10:00 – 2011-04-12 18:00 Event 1
2011-04-12 12:00 – 2011-04-12 14:00 Event 2

2011-04-13
2011-04-13 10:00 – 2011-04-13 18:00 Event 5
2011-04-13 12:00 – 2011-04-13 14:00 Event 8

The problem: I have some events that take several days or weeks.
Example: I create one event with the start date of 2011-04-12 10:00 and the end date of 2011-04-15 19:00 for example.

This event now shows up in the grouped view as
2011-04-12 - 2011-04-18
2011-04-12 10:00 - 2011-04-15 19:00 Event 11

I would like to have that event sorted into the regular day groups (split that event into day parts):
2011-04-12
2011-04-12 10:00 - 2011-04-15 19:00 Event 11

2011-04-13
2011-04-12 10:00 - 2011-04-15 19:00 Event 11

2011-04-14
2011-04-12 10:00 - 2011-04-15 19:00 Event 11

2011-04-15
2011-04-12 10:00 - 2011-04-15 19:05 Event 11

Similar to how it is done in the calendar – day view. But with a simple text list format.
I can not find a way to do this? Perhaps someone can give me a little help?

https://www.drupal.org/node/1124616
Answer: Make 2 or 3 computed view fields (which will require some php):

1field for day of event
1 or 2 fields for start time and end time dates.

You can group the View output by the first field. Then create the event time range by inlining the 2 other fields.
With these 3 pieces of info the calendar should be able to see the start and end datetimes and make a line representing the event duration.
Comment: I've thought about that, but say the event is spanning 3 days, how do you get the computed field to output all 3 days of the event that it spans for it to be sorted?
Comment: Also, he's not looking to visually represent the duration - it appears he needs a list view, and the multi-day to create an instance on each day that the event spans.
Comment: You nailed it! Thanks so much!
Attached are my gists for the fields:
https://gist.github.com/johnny5th/eb10748124641121eb12
https://gist.github.com/johnny5th/5d36d91169e7d4160316


Cucumber test: Unable to click on button

Question: I am new to cucumber and HTML. In my test I try to click on the "Check Inventory" button using -> click_button('Check Inventory') or click_on('Check Inventory'). I get this error:
no button with value or id or text 'Check Inventory' found (Capybara::ElementNotFound)

I have been able to successfully test clicking buttons with name or value tags. So I am not sure if the title tag behaves differently. Here's the HTML:

Inventory

Available Inventory
<input id="some stuff" name="some stuff" type="checkbox" value="1">Some stuff here

...
...

Comment: Your html stops where it becomes intressting ;)
Comment: Sorry, I'm still trying to get the hang of this. I am not sure how to post the HTML code so it shows up. Let me try it here:
Inventory
Available InventorySome stuff here
...
...
Comment: I just did it for you as edit. You basically need to mark the HTML code and press ctrl+k. Or indent each line individually using 4 (additional) spaces.
Answer: click_button in Capybara finds input elements (of type submit, reset, image, button or image), and button elements.  Your "button" is none of those, but rather a div styled to look like a button.  To click on that you'll need to find the element (by css selector, etc) and call click on it.  In this case something along the lines of
find(:css, 'div[title="Check Inventory"]').click

should do what you want


Composition of two Mobius maps on the unit disc in $\Bbb C$?

Question: Let $a,b \in \Bbb D$, the unit disc in the complex plane, and let $\varphi_{a}(z)$ and $\varphi_{b}(z)$ be two typical Mobius maps on $\Bbb D$. Is there a well known formula for the composition of these two maps? Is it another Mobius map?
Comment: Are $a$ and $b$ two-by-two matrices? If so, the composition is $\varphi_{ab}$. No matter what, they compose to a Möbius map.
Comment: They are points in the disc.
Answer: Assuming OP is referring to the unit disk automorphisms (special case of Möbius transformations):
$\varphi$ is a unit disk Automorphism, meaning $\varphi_a(z) = \lambda\frac{z-a}{1-\overline{a}z}$ with $|\lambda|=1 $.
The composition of two unit disk automorphisms remains a unit disk automorphism. You can calculate it exactly by using the matrix representation of Möbius maps, and the property that $T_A\circ T_B = T_{AB}$ for $T$ Mobius and $A,B$ matrices.
Another way to look at it is that $\varphi_a(z)=0$ iff $z=a$. Therefore,
$\varphi_a(z) \circ \varphi_b(z)$ = $\varphi_a(\varphi_b(z))=0$ iff $\varphi_b(z)=a$. Now taking $\varphi_b^{-1}$ on both sides [which is equal $\varphi_{-b}$] we get $a=\varphi_{-b}(z)$.
So $\varphi_a(z) \circ \varphi_b(z) = \varphi_{\varphi_{-b}(a)}(z)$.


permissions in django with dispatch method

Question: i'm trying to restrict users to view only the todos they have created using the dispatch method but i tried te below approach but still i'm seeing all todos appear under a user that did not create them
custom user model
from django.db import models

from django.contrib.auth.models import AbstractUser

# Create your models here.

class CustomUser(AbstractUser):
    profession = models.CharField(null=True, blank=True, max_length=30)

todo model
from django.db import models
from django.contrib.auth import get_user_model
from django.urls import reverse

# Create your models here.

class Todo(models.Model):
    title = models.CharField(max_length=120)
    description = models.TextField(max_length=320)
    to_be_done = models.DateTimeField(null=False)
    date_posted = models.DateTimeField(auto_now_add=True)
    user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE)

    def __str__(self):
        return self.title

    def get_absolute_url(self):
        return reverse('todo_detail', args=[str(self.id)])

listview for todos
class TodoListView(LoginRequiredMixin, ListView):
    model = Todo
    template_name = 'todo_list.html'
    login_url = 'login'

    def dispatch(self, request, *args, **kwargs):
        objects = self.objects.filter(user=self.request.user)
        for obj in objects:
            if obj.user != self.request.user:
                raise PermissionDenied
            return super().dispatch(request, *args, **kwargs)

any ideas on how i can adjust to implement above said task
Answer: Try something like this:
class TodoListView(LoginRequiredMixin, ListView):
    model = Todo

    def get_queryset(self):
        qs = Todo.objects.filter(user=self.request.user)
        return qs

Comment: thanks man, any resources you could recommend to further understand using query sets in generic views apart from the docs
Comment: Read office Django [Documentation](https://docs.djangoproject.com/en/3.0/topics/class-based-views/intro/#introduction-to-class-based-views) and also good documentation about Class Based View see [CCBV](https://ccbv.co.uk/)


How to forecast a set of different time series?

Question: I am trying to forecast a large set of time series that feature very different characteristics. The figure below shows three exemplary series:

My first idea was to identify periodical repetitions as they are present in the upmost subplot. For this I followed the advice from this answer. I hoped that for very periodic data I would find significant peaks in the power spectrum of the time series and could thus distinguish between series with and without repetitive patterns.
However when I used the scipy's periodogram function on the data I was not able to get a distinctive difference for the three example time series, as shown in the following figures:
Periodogram of time series #1:

Periodogram of time series #2:

Periodogram of time series #3:

What different method can I use to identify periodic patterns and utilize this information to optimize forecasting?
Answer: First of all, let me be clear on that there is no 'right approach' for time series modelling or forecasting in general. Since you have a large amount of different time series, it is imporatant to decide if you want to model them all seperately or that you assume some sort of dependence. From your question it seems to me that you assume they are independent.
An often used approach in time series is the Box-Jenkins methodology, which works based on identifying aspects such as periodic effects (e.g. monthly/yearly cycles) or non-periodicity. For more information about their approach on ARIMA modelling check the Wikipedia or the book they've written on this.
If you are into a differenct class of models, such as machine-learning you could look at LSTM. Without more information it will be hard/impossible to fully answer your question.
Comment: Hi Jan, thanks for your answer! I understand, that there is not one approach that solves every problem. However as the data set is quite large (~10k time series) and I know very little about the characteristics of the time series I need something like the basic approach that would be used in such a case. Yes, I am assuming the time series are a independent for now. Would I need to use a different model than ARIMA for dependent time series? Actually for me as a total statistics newbie, the ARIMA model is already is very good hint, thank you!
Comment: Maybe the time series are not all independent from each other, however I have no information about which time series are and which are not independent.


Espresso 2.2.1 exception :app:transformClassesWithDexForDebugAndroidTest

Question: In my app I want to Espresso in order to test the UI. However,when I try to run my project,I get message:
  Error:Execution failed for task
  ':app:transformClassesWithDexForDebugAndroidTest'.
  > com.android.build.api.transform.TransformException:
  com.android.ide.common.process.ProcessException:
  java.util.concurrent.ExecutionException:
  com.android.ide.common.process.ProcessException:
  org.gradle.process.internal.ExecException: Process 'command 'C:\Program
  Files\Java\jdk1.8.0_45\bin\java.exe'' finished with non-zero exit value 2

This is my gradle setup:
apply plugin: 'com.android.application'

android {
compileSdkVersion 24
buildToolsVersion "24.0.0"

defaultConfig {
    applicationId "theo.testing.androidespresso"
    minSdkVersion 18
    targetSdkVersion 24
    versionCode 1
    versionName "1.0"
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}
}
  dependencies {
  compile fileTree(dir: 'libs', include: ['*.jar'])
  testCompile 'junit:junit:4.12'
  androidTestCompile 'com.android.support:support-annotations:24.2.0'

  compile 'com.android.support:appcompat-v7:24.2.0'
  androidTestCompile('com.android.support.test.espresso:espresso-
  core:2.2.1')
  {
    exclude group: 'javax.inject'
}
   androidTestCompile 'com.android.support.test:testing-support-lib:0.1'

 }

Any ideas why is this happening?
Thanks.
Answer: I'm pretty sure, that it's your third post and it has the same problem.
You're  trying to use dependencies which you don't need to have during the test.
Change your build.gradle dependencies section to:
dependencies {
  compile fileTree(dir: 'libs', include: ['*.jar'])

compile 'com.android.support:appcompat-v7:24.2.0'

  testCompile 'junit:junit:4.12'

androidTestCompile 'com.android.support.test:runner:0.5'
androidTestCompile 'com.android.support:support-annotations:24.2.0'
androidTestCompile 'com.android.support.test.espresso:espresso-core:2.2.2'
androidTestCompile('com.android.support.test.espresso:espresso-contrib:2.2.1') {
    // Necessary to avoid version conflicts
    exclude group: 'com.android.support', module: 'appcompat'
    exclude group: 'com.android.support', module: 'support-v4'
    exclude group: 'com.android.support', module: 'support-annotations'
}

}

Google's official Android Testing Support Library site is enough to start Android testing.
See Espresso secton
Hope it will help


Erro ao executar no editor de textos Atom

Question: O programa quando executo da esse seguinte erro http://prntscr.com/m42sl8 Sei que tem algo relacionado as variáveis, mas não sei o que colocar lá. Já fiz o processo do C:\MinGW\bin porém agora da esse problema, uso o Windows 10, qualquer ajuda agradeço.
Comment: Seja bem-vindo ao SOPT. Coloque a imagem diretamente na postagem, outra coisa, já tentou compilar direto pelo terminal? Notei que teu arquivo ta nomeado como `sem titulo`, pelo que deu pra entender, ele esta tentando executar isso como um comando, o que causa este erro na palavra "sem".
Comment: Realmente era o "sem" que estava causando problema, muito obrigado!!!!
Comment: Bom, se resolveu vou postar como resposta para que tu posa aceitar e ficar registrado para o futuro.
Answer: Caso ainda não tenha tentado compilar pelo terminal/prompt, esta é uma boa forma de verificar os problemas da string de compilação. Teu arquivo esta nomeado como sem titulo, o erro esta na palavra "sem", pois ele esta tentando executar isto como um comando.
Para compilar via terminal/prompt use: g++ -o nome_do_arquivo.cpp nome_do_exe.exe -Wall, o -Wall vai ser útil para mostrar melhor qualquer erro no código, caso haja algum.


How to trace an Error: PDOException: SQLSTATE[23000]:

Question: I'm trying to trace this error which is shown when I save a new basic page node.
It seems to me that I am trying to save a duplicated title value in field_data_title_field, but it doesn't make any sense to me. I found this question PDOException: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '1532856' for key 'PRIMARY': INSERT INTO {watchdog} but it was related to dblog table (Watchdog module). Mine is related to: modules/field/modules/field_sql_storage/field_sql_storage.module
Drupal core is updated to last version.
How can I trace and fix this?
ERROR:

PDOException: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'node-4294967295-0-0-und' for key 'PRIMARY': INSERT INTO {field_data_title_field} (entity_type, entity_id, revision_id, bundle, delta, language, title_field_value, title_field_format) VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2, :db_insert_placeholder_3, :db_insert_placeholder_4, :db_insert_placeholder_5, :db_insert_placeholder_6, :db_insert_placeholder_7); Array ( [:db_insert_placeholder_0] => node [:db_insert_placeholder_1] => 4294967295 [:db_insert_placeholder_2] => 3187 [:db_insert_placeholder_3] => page [:db_insert_placeholder_4] => 0 [:db_insert_placeholder_5] => und [:db_insert_placeholder_6] => My node title [:db_insert_placeholder_7] => ) enfield_sql_storage_field_storage_write() (line 514 of /home/examplesite/www/modules/field/modules/field_sql_storage/field_sql_storage.module )
Answer: The composite primary key for field tables is entity_type,entity_id,deleted,delta,language. The error itself lists the key:
'node-4294967295-0-0-und'

You can confirm that there is a pre-existing field in the table by querying your database with a search on those values.
Also of note, your node id is at 4294967295. This is the upper limit of 32-bit unsigned integers; anything higher than that is going to start causing problems with your SQL storage.
Comment: Then I understand that the problem is the field reached it limit. And the problem is not a "duplicated" value. Am I right?
Comment: Without access to the DB I can't say for certain, but it does look like the duplicate entry is a side effect of your node id sequence being maxed out.
Answer: Since you've reached your limit for your data value in this column, the value is acting as a MAX and using the maximum value that can be stored in the column. In this case, it's already in use.


Files missing with npm pack

Question: I am building a npm module, in which I want to include two directories : /dist and /demo.
So far, my approach was to use the 'files' attribute, in package.json :
"files": [
    "dist",
    "demo"
]

When running npm pack, the tgz files successfully contains the demo folder, and the built files in /dist.
However, during the build phase, I added a shell script that is copying some files (generated mylib.js and mylib.css) to the /demo directory. And my problem is that npm pack does not care about these specific files, which are not included in the tgz (despite I can see them in my explorer).
However, if the shell script make changes to the content of /demo/index.html, these changes are included in the tgz.
How could I include the missing files?
Answer: Seems that I misinterpretated the problem:
if the files were not in the tgz, it is because I add a .gitignore in /demo, ignoring js and css files.
As I really don't want this files to be commited, the solution was to add a .npmignore file, with no rule matching css/js

Files missing with npm pack


GitLab Pipeline: perform job except user (Runner machine)

Question: Is it possible to run specific job only / except push comes from specific user?
I could do it by script searching for the commit author at the beginning of every job, but maybe there is more elegant way.

Explanation
We use git lab Runner to merge develop to all other branches when develop is changed.
Our gitlab Runner has its own user with writes to push so it works like a charm.
The one thing we want to avoid is running specific resources-consuming jobs for branches pushed by that user (runner).
Answer: You can use the <code>[skip ci]</code> string in the runners commit message for the merge. This wil skip the ci pipeline for that push. Docs here.
I use this when Gitlab runner pushes a tag.
Comment: oh, great! I didn't now that. But still - I wish to run tests, but not other jobs. It would be nice to have [skip ]


Why $(\frac{\partial x}{\partial z})_w$ can be expressed as-$\frac{\frac{\partial (F,G)}{\partial (z,y)}}{\frac{\partial (F,G)}{\partial (x,y)}}$

Question: Consider $F(x,y,z,w)=0$ and $G(x,y,z,w)=0$ . Why $(\frac{\partial x}{\partial z})_w$= -$\frac{\frac{\partial (F,G)}{\partial (z,y)}}{\frac{\partial (F,G)}{\partial (x,y)}}$.Noted that the  $(\frac{\partial x}{\partial z})_w$= -$\frac{\frac{\partial (F,G)}{\partial (z,y)}}{\frac{\partial (F,G)}{\partial (x,y)}}$=-$\frac{F_3G_2-F_2G_3}{F_1G_2-F_2G_1}$
Comment: What do you mean by $\left ( \frac {\partial x}{\partial z} \right )_w$ and $\frac{(\partial F,G)}{(\partial x,y)}$?
Comment: Why do you think it is true?
Comment: F and G are 2 function with variable xy z w and $(\frac{\partial x}{\partial Z})_w$ means we may find $(\frac{\partial x}{\partial Z})$ while setting w as a constant in the 2 function
Comment: That's shown in the textbook but i dont quite understand
Answer: The two equations $F(x,y,z,w_0)=0$, $\ G(x,y,z,w_0)=0$ define a curve $\gamma$ in the three-dimensional $(x,y,z)$-plane $w=w_0$ of ${\mathbb R}^4$. This curve should have a parametrization
$$\gamma:\quad z\mapsto \bigl(x(z),y(z),z, w_0\bigr)\qquad \qquad (z_0-h<z<z_0+h)\ ,$$
valid in the neighborhood of some "regular" point $(x_0,y_0,z_0,w_0)$. Since
$$F\bigl(x(z),y(z),z,w_0\bigr)\equiv0\ ,\qquad G\bigl(x(z),y(z),z,w_0\bigr)\equiv0\ ,$$
taking the derivative with respect to $z$  gives
$$F_x x'(z)+F_y y'(z) + F_z=0\ , \qquad G_x x'(z)+G_y y'(z) + G_z=0\ .$$
We now solve for $x'(z)$ and obtain
$$x'(z)=-{F_z G_y-G_z F_y \over F_x G_y-G_x F_y}=-{\det\left[{\partial(F,G)\over\partial(z,y)}\right] \over\det\left[{\partial(F,G)\over\partial(x,y)}\right]}\ .$$
In response to a comment by the OP: Here we had $r=3$ equations (incl. $w=w_0$) in $n=4$ variables, so there was one degree of freedom (the $z$ variable). In general you would have $r$ equations in $n$ variables and $d=n-r$ degrees of freedom. If you want explicit formulae you would have to declare beforehand which $d$ variables should be considered as the independent ones. Look at it this way:  There is no explicit formula for the solution set of a rank $r$ homogeneous linear system in $n$ unknowns.
Comment: the question is i dont think that it is just coincident to get $\frac{\frac{\partial (F,G)}{\partial (z,y)}}{\frac{\partial (F,G)}{\partial (x,y)}}$ as the answer and i think it applies to all similar cases but why?
Comment: Is it true to apply the same step(i.e.$-{\det\left[{\partial(F,G)\over\partial(z,y)}\right] \over\det\left[{\partial(F,G)\over\partial(x,y)}\right]}$) to calculate for the case like n variables


External content migration translation problem

Question: I am trying to import content into Drupal 8 from an external source (not previous Drupal version). I have crawled the original site and placed the content in a database. I am then writing a custom module to bring it into Druapl. I have the default language as English so when I run the migration for the English content there has no issue. It all imports perfectly. When I then run the translation migration, with French content, I get this error:
 [error]  SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'name' cannot be null: INSERT INTO {key_value} (name, collection, value) VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2); Array
(
    [:db_insert_placeholder_0] =>
    [:db_insert_placeholder_1] => node_translation_redirect
    [:db_insert_placeholder_2] => a:2:{i:0;N;i:1;N;}
)

Despite the error the content is imported, but as separate nodes instead of as translations to the original migration. I am using drush to run the migrations. Even though the French is imported, incorrectly, drush reports that the migration failed. I try to rollback both and the French does not get removed. I have to remove it manually.
I searched around but have not been able to find anyone having issues with SQL migrations.
Any help is appreciated. Thanks.
Here are my files:
mymigrate_content.yml
id: mymigrate_content
label: my content migration
langcode: en
source:
  plugin: mymigrate_content
  default_lang: true
  key: canada
  ids:
    pageid:
      type: integer
process:
  id: pageid
  title: title
  'body/value': body
  'body/format':
    plugin: default_value
    default_value: full_html
  'moderation_state/target_id':
    plugin: default_value
    default_value: published
destination:
  plugin: 'entity:node'
  default_bundle: page
  langcode: en
  no_stub: true

mymigrate_content_translation.yml
id: mymigrate_content_translation
label: my content migration
langcode: fr
source:
  plugin: mymigrate_content_translation
  translations: true
  default_lang: false
  key: canada
  ids:
    pageid:
      type: integer
process:
  id:
    plugin: migration_lookup
    migration: mymigrate_content
    source: pageid
  title: title
  'body/value': body
  'body/format':
    plugin: default_value
    default_value: full_html
  'moderation_state/target_id':
    plugin: default_value
    default_value: published
  content_translation_source:
    plugin: default_value
    default_value: "en"
destination:
  plugin: 'entity:node'
  default_bundle: page
  langcode: fr
  no_stub: true
  translations: true

MyMigrate.php
<?php
namespace Drupal\ca_migrate\Plugin\migrate\source;

use Drupal\migrate\Plugin\migrate\source\SqlBase;
use Drupal\migrate\Row;

/**
 * Migration
 *
 * @MigrateSource(
 *  id = "mymigrate_content",
 * source_module = "mymigrate",
 * )
 */
class MyMigrate extends SqlBase {
  /**
   * @var integer $rowCount
   */
  public $rowCount = -1;

  /**
   * {@inheritdoc}
   */
  public function query() {
    $query = $this->select('pagecontent', 'pc')
      ->condition('pc.language', 'en', '=')
      ->fields('pc', [
        'pageid',
        'language',
        'body',
        'originalurlpath',
        'title',
      ]);

    return $query;
  }

  /**
   * {@inheritdoc}
   */
  public function fields() {
    $fields = [
      'pageid' => $this->t('pageid'),
      'language' => $this->t('language'),
      'body' => $this->t('body'),
      'originalurlpath' => $this->t('originalurlpath'),
      'title' => $this->t('title'),
    ];

    return $fields;
  }

  /**
   * {@inheritdoc}
   */
  public function getIds() {
    return [
      'pageid' => [
        'type' => 'integer',
        'alias' => 'pc',
      ],
    ];
  }
}

MyMigrateFr.php
<?php
namespace Drupal\ca_migrate\Plugin\migrate\source;

use Drupal\migrate\Plugin\migrate\source\SqlBase;
use Drupal\migrate\Row;

/**
 * Migration
 *
 * @MigrateSource(
 *  id = "mymigrate_content_translation",
 * source_module = "mymigrate",
 * )
 */
class MyMigrateFr extends SqlBase {
  /**
   * @var integer $rowCount
   */
  public $rowCount = -1;

  /**
   * {@inheritdoc}
   */
  public function query() {
    $query = $this->select('pagecontent', 'pc')
      ->condition('pc.language', 'fr', '=')
      ->fields('pc', [
        'pageid',
        'language',
        'body',
        'originalurlpath',
        'title',
      ]);

    return $query;
  }

  /**
   * {@inheritdoc}
   */
  public function fields() {
    $fields = [
      'pageid' => $this->t('pageid'),
      'language' => $this->t('language'),
      'body' => $this->t('body'),
      'originalurlpath' => $this->t('originalurlpath'),
      'title' => $this->t('title'),
    ];

    return $fields;
  }

  /**
   * {@inheritdoc}
   */
  public function getIds() {
    return [
      'pageid' => [
        'type' => 'integer',
        'alias' => 'pc',
      ],
    ];
  }
}

Answer: I was finally able to trace the problem. The migration code was expecting a value for the key nid. I was able to provide the appropriate value by overriding the function prepareRow.
Here is the code I used in both MyMigrate.php and MyMigrateFr.php:
  /**
   * {@inheritdoc}
   */
  public function prepareRow(Row $row) {
    $nid = $row->getSourceProperty('pageid');
    $row->setSourceProperty('nid', $nid);
    $row->setDestinationProperty('nid', $nid);

    return parent::prepareRow($row);
  }

Answer: I encountered the same problem migrating from a JSON source:
Integrity constraint violation:
1048 Column 'name' cannot be null: INSERT INTO {key_value} (name, collection, value) ...
with empty value for 'name'.
I solved the problem by removing the line
  translations: true

from the source: block.
I think this is only needed in the destination: block.


How to access data in partialview loaded using Ajax

Question: I'm currently building a website where I have to update two separate targets from a single Ajax.BeginForm. I got it working by using an additional container to container the two separate targets. As in:

Original Form
@model Mod1
@using (Ajax.BeginForm("LoadData", new AjaxOptions{UpdateTargetID = "Div1"}))
{
  <select id="sel1" name="sel1" onchange="$(this.form).submit">
    // ...
  </select>
}
@using (Ajax.BeginForm("ProcessData", new AjaxOptions{UpdateTargetID = "Div2"}))
{

    // ...
  <input type="submit" value="GO!" />
}

Code File
public ActionResult LoadData(int sel1)
{
  // loading data from database
  return PartialView(mod1);
}

Partial View
@model Mod2
<select id="sel2" name="sel2">
  @foreach (var item in Model.SelectItems)
  {
    <option value="@item.Value">@item.Text</option>
  }
</select>

@foreach (var item in Model.CheckBoxItems)
{
  @item.Text<input type="checkbox" id="chk1" name="chk1" value="@item.Value">
}

For the processing method, I have tried:
    public ProcessData(Mod1 mod1, string[] chk1, int sel2)

However I am unable to retrieve the values for either chk1 or sel2 upon form submission. examination of chk1 and sel2 in Debug mode, chk1 is null while sel2 is 0 (no such value in the select options). Can anyone please offer some insight into the reason for this and also how I can go about solving it. Thank you in advance.
Answer: If I understand you correctly you can do what you want y having two submit buttons on the same form, each calling a separate action method. That way each submit button will have access to all the fields in the form. For a detailed explanation of how you can do that see my answer here:
How to use ajax link instead of submit button for form?
Edit
In response to comment: the action method LoadData should return a partial view that contains the other two controls and have the whole begin form included in it:
@using (Ajax.BeginForm("LoadData", new AjaxOptions{
                                                UpdateTargetID = "Div1",
                                                InsertionMode = InsertionMode.Replace
                                                  }))
{
    <select id="sel1" name="sel1" onchange="$(this.form).submit">
    // ...
    </select>
}

Move this to another partial view:
    @using (Ajax.BeginForm("ProcessData", new AjaxOptions{UpdateTargetID = "Div2"}))
    {

        // ...
        <input type="submit" value="GO!" />
    }

Comment: Not exactly what I wanted. My intention is that by selecting a value from a DropDownList. Another DropDownList and CheckBoxes enclosed in a div is updated with values. The user will select/ check the options in the div subsequently and submit the form. However I'm unable to access the submitted value in either fields as they are 0 (for int field) and null (for string[] field).
Comment: I'm still getting a null reference for the checkboxes when submitting the form. Using either int[] or string[] doesn't not solve the situation either...


Can we connect two raid controllers in standby?

Question: I'm new to server machines and even even installing raid controllers, so pardon me if its too basic question.
We have a SuperMicro X10DRH-I Motherboard connected to a raid controller AOC-S3108L-H8Ir, both are supermicro products. We need to add one more raid controller in hot/cold standby with this controller.
My doubt is is this even possible and if possible how?
If not possible then a general question say if the current raid controller fails how can we recover the data, since data can be stored in any any hardisks given the controller is configured in RAID6, is recovering 100% data possible safely with surety?
Answer: That's a normal LSI/3ware/Avago MegaRAID controller card, with SuperMicro branding.
If the card itself breaks, you replace it with another MegaRAID card. The configuration is stored on the disks, so you can restore arrays on the new card, this is a manual process though as there is a safety mechanism and the card requires confirmation before it will access disks that were initialized on another controller.
It is difficult to provision a standby, as most of the failure modes for the controller itself are not wear related, so the chance of the "standby" card failing first is rather high. I'd probably look into building a separate system and setting up replication.
Comment: @RishabhGupta, you should be able to use any controller from the MegaRAID family that has the required connectors, but you should verify that with Broadcom. The remaining failure modes should be handled with [backups](https://serverfault.com/questions/2888/why-is-raid-not-a-backup).
Comment: so it means we can always recover the data when the controller gets failed? and if so can we use other controller if not of same type to do so?
Answer: Hot standby was possible with MegaRAID Syncro CS RAID controllers (two controllers connected to dual-expander backplanes and SAS drives), but they were discontinued several years ago.
As for cold standby, Simon Richter is right. You can use any 3108 based controller from Supermicro (except AOC-S3108L-H8IR-16DD if you have more than 16 drives, as this controller is limited to 16 drives maximum) or 3108 based or newer controller from Broadcom: 9361 or 9460. Broadcom's latest 9560 series controllers are also backwards compatible, but have different connector — Slimline x8 instead of SFF-8643, so you will have to change the cables as well.


Achar valores em comum em dois dataframes diferentes

Question: Editando a pergunta:
Eu tenho dois DataFrames de tamanhos diferentes, sao eles:
 df1 = pd.DataFrame({'bc': bc_1}, index=altura_1)
 df1.shape()=(73,1)
 >>> print df1
             bc
  1.175441  0.002884
  1.115565  0.001905
  1.055689  0.003029
  0.995812  0.003366
  .
  .
  .

 df2 = pd.DataFrame({'bc': bc_2}, index=altura_2)
 df2.shape()=(18,1)
 >>> print df2
            bc
  0.150  0.000005
  0.165  0.000007
  0.180  0.000010
  .
  .
  .

E eles estão medindo a mesma variável, só que utilizando dois instrumentos diferentes.
O grafico que representa esses dados esta a seguir:

Percebem que em alguns momentos, as curvas (os pontos) ficam muito proximas(os)?
Eu preciso descobrir quais sao esses pontos e armazena-los em outro dataframe
Comment: Poderia editar a pergunta adicionando exemplos? Como um pedacinho de cada dataframe e a saída esperada?
Answer: Partindo destes dois dataframes:
>>> print df1
       dados
1.1    1.123
2.2    1.567
3.3    2.001
4.4    2.345

>>> print df2
       dados
1.0     1.12
2.3     1.56
3.5     2.00

Calculo a distância de dois pontos em um gráfico:
def calc_distancia(x1, y1, x2, y2):
    return ((x1-x2)**2 + (y1-y2)**2) ** (1/2.0)

Agora, definimos um df3 e calculamos a distância dos pontos de df1 e df2. Se a distância for menor que um valor, adicionamos o dado no df3:
DISTANCIA_MAXIMA = 0.5#Defini a distância máxima como 0.5

df3 = pd.DataFrame(data={'X1':[], 'Y1':[], 'X2':[], 'Y2':[], 'Distancia':[]})
#Verifia quais valores são iguais comparando todos os dados1 com todos os dados2
for index_df1, row_df1 in df1.iterrows():
    for index_df2, row_df2 in df2.iterrows():
        distancia = calc_distancia(index_df1, row_df1['dados'], index_df2, row_df2['dados'])
        if distancia < DISTANCIA_MAXIMA:
            df3 = df3.append({'X1':index_df1, 'Y1':row_df1['dados'], 'X2':index_df2, 'Y2':row_df2['dados'], 'Distancia':distancia}, ignore_index=True)

>>> print df3
   Distancia   X1   X2     Y1    Y2
0   0.100045  1.1  1.0  1.123  1.12
1   0.100245  2.2  2.3  1.567  1.56
2   0.200002  3.3  3.5  2.001  2.00

Comment: Eu usei essa logica que voce sugeriu, mas o dataframe resultante (df3) ficou com mais de 400 linhas quando na verdade, era para ele ter ficado menor que os outros dois. Eu editei a pergunta com os dados como voce pediu. Acho que agora esta mais facil para entender o que eu preciso fazer. Obrigada
Comment: @Luana ficou mais fácil haha. Veja se com a edição que fiz você consegue aplicar para o seu problema.
Comment: Ficou sim! Obrigada! Eu entendi o que voce fez, mas agora preciso fazer de uma outra maneira...Eu preciso achar onde a diferenca de altura eh minima (y1 e y2) e armazenar os valores de x refentes a esse ponto. Meu dataframe final tem que ter o mesmo numero de pontos do meu menor dataframe..no caso, df2..Deu pra entender? Estou com certa dificuldade para fazer isso tambem
Comment: @Luana se surgiu um novo problema que precisa de uma resposta diferente, faça uma outra pergunta abordando o novo problema.
Comment: Na verdade a pergunta eh a mesma...a abordagem p/ resolver que eh um pouco diferente da que vc sugeriu, ja que ao inves de calcular a distancia usando x e y, eu preciso levar somente o y em consideracao...Mas obrigada de qualquer forma


Fetching data in coredata

Question: -(void)getRecords
{
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];

    NSEntityDescription *entity = [NSEntityDescription entityForName:@"CustomerOrder"
                                              inManagedObjectContext:self.managedObjectContext];
    [fetchRequest setEntity:entity];
    NSError* error;

       NSArray *fetchedRecords = [self.managedObjectContext executeFetchRequest:fetchRequest error:&error];

    if (fetchedRecords)
    {
        if (fetchedRecords.count == 0) //create new Entity
        {
            NSLog(@"Balaiah babu");
        }

        else
        {
            int count =0;
            for (int i=0; i<fetchedRecords.count; i++) {

                CustomerOrder * record = [fetchedRecords objectAtIndex:i];
                NSLog(@"%@,%@,%@,%@,%@,%@,%@,%@,%@,%@,%@",record.customer_id,record.order_id,record.outletLatitude,record.outletLongitude,record.trigger_days,record.trigger_end_date,record.trigger_from_time,record.trigger_no_days,record.trigger_radius,record.trigger_start_date,record.trigger_to_time);

                NSLog(@"%d",count++);

            }
        }

    }

}

here fetched Records array is showing nil.But it is going through loop and printing the values of the log.I don't know how it is happening.
Comment: How are you verifying that `fetchedRecords` is nil?
Answer: In .h File
@property (strong, nonatomic) NSManagedObjectContext *managedObjectContext;

In .m File
Fetch entity "Info"
NSEntityDescription *entity =
 [NSEntityDescription entityForName:@"Info"
             inManagedObjectContext:managedObjectContext];

fetch entity request
NSFetchRequest *request = [[NSFetchRequest alloc] init];

[request setEntity:entity];

Fetch the records and handle an error
NSMutableArray *mutableFetchResults =
 [[managedObjectContext executeFetchRequest:request
                                      error:&error] mutableCopy];

if (!mutableFetchResults)
    {
    Nslog(@"nil");
}

Save our fetched data to an array
NSLog(@"get_Result==%@",[mutableFetchResults valueForKey:@"fname"]);

Comment: It is still showing mutableFetchResults as nil but it is going to this
if (!mutableFetchResults)
    {
    Nslog(@"nil");
}

Fetching data in coredata


Generate square image from portrait thumbnail

Question: I have portrait images with about 200x600 size. I would like to create a square version of it with 600x600 size.
Is it possible somehow?
Unfortunately the hard crop set the width first and I get only the center of the image.
add_image_size( 'square', 600, 600, true );
Required below. Upload portrait and get square version of it.
Answer: I recently found this plugin, https://wordpress.org/plugins/square-thumbnails which seems to do exactly what you need.
It will create a square thumbnail image and fit the original image inside the square.
I haven't tested it on a production site, so I can vouch for the plugin, but it's worth trying.
Comment: I haven't tested yet, but looks good. I had only 40-50 products, so I recropped them in Photoshop :/
Answer: WordPress functions for image manipulation can't work like this, they can crop images, but they can't fill them up to be expanded.
Images can have different backgrounds, and automatically choosing colours for that is not easy to do. If the images are with background transparency, then, it is easier to do, but still, WordPress can't do that. I am not sure of any plugin for WordPress that can do this.
Best way to do this is to hire someone to code it for you, and again, it will work fine only if images don't have background.


How to write string divisi sections w/ different instructions correctly

Question: There are two string parts in a piece I'm writing that use divisi, and I'm not sure how to write them correctly.
First, this violin section:

I want to make clear that all players should play sul pont. but that only half of them also play tremolo. Is the way I've instructed it correct? I added "ord." to try and distinguish it from the trem. marking beneath, but I'm not sure it's used correctly here.
Second, this split viola section:

The intention is to split the violas in three sections, have sections 2+3 play the staccatos, and have section 1 come in with the melody several bars later. Is this notated correctly?

UPDATE: I've changed the second example to the following:

(In the previous version I envisioned the violas (12 players) split into three coequal sections (4 each), but I've decided it's better to keep half playing the melody (since it should stand out more) and the other half re-split for the staccatos (3 each).)
Is this better?
Comment: For the first example, I'd separate the staves. To be clear, you're going to want to show the exact difference. As it currently stands the directions to a performer would be very confusing. Other solutions that come to mind would be equally confusing, so it's just not worth it. For the 2nd example, the first viola section (melody) should just be labeled "soli" or however many violas you want playing that melody. The 2nd line should be just labeled "div.". Players will automatically split the notes accordingly. No "div." label means you want each performer to play *both* notes.
Comment: As 2nd example is currently written: you have marked that you want 1st viola part divided 3 ways, but played in unison. You want the 2nd viola part divided three ways. These directions are confusing. If you do not yet own a copy of Elaine Gould's *Behind Bars*, I highly recommend adding it to your library.
Comment: Re: "soli", was just an example since I obviously wouldn't know the proper context. Your updated example looks much clearer. Re: first example, I will amend my previous comment by saying that: in the score, you could likely get away with using a double notehead, labeling it "div. sul pont", and then labeling the bottom side of the staff "trem." with added tremolo articulation markings on the doubled notehead to be clear. In the score, you could leave this on one staff. In the parts, you would want to create two staves for that section. No matter what you do you will have questions.
Comment: @jjmusicnotes Thanks for the feedback. Re: the second example, I've edited the OP with a new version that specifies the number of players for each section; is it clearer this way? (I'm not sure about using "_soli_" since that implies to "play in a soloistic manner" (Gould, _Behind Bars_) and that's not the sound I'm going for.
Comment: Thanks for clarifying. Re: the first example, I wrote it that way based on how a similar instruction – "½ ord., ½ trem." – appears in the _Edward Scissorhands_ score published by Omni, and I tried to adapt it to my own score where the same split happens, but with both playing _sul pont._. I'll give the double-noteheads trick a try, see how it looks. Thanks again.
Comment: I would not use a film score as an example for engraving. Film scores have a slightly different notation style / shorthand to reflect the work being done on soundstages. Such shorthand doesn't typically translate well to performers outside film.
Comment: In fairness, film scores are specifically the kind of music I compose (well, as an amateur at home, anyway).
Answer: The first example is fine IMO. If you split the staves and write a tremolo on one staff only, most likely you get a question in rehearsal about whether the trem is missing on the other staff! If you want to do it that way, I would write "(senza trem.)" over the part without the tremolo, to preempt the rehearsal question.
The second one is confusing. You write "div a 3" but only two notes, and then another "div a 3" later. In your revised version, you don't split the section into equal sized groups of players, but let's assume that originally you did want three equal groups.
Write "div a 3" at the start of the passage, and mark the bottom staff "2.3." to make it clear which groups should play it. Mark the top staff "1." where the notes start. You don't need the second "div a 3" marking.
The third example is fine, but it is common to write "6 soli" instead of "6 players". Of course if you are writing other performance instructions in English, "6 players" would be consistent with that. Note that "6 soli" does not mean "everybody should play like a soloist." A literal translation of the Italian would be "only 6 players"
If there are more than 12 viola players (unlikely, but possible in a very large orchestra) then a literal interpretation of two groups of "6 soli" means the others will play nothing. However, conductors, concert masters, and orchestra librarians routinely adjust this type of instruction to suit the actual numbers of players available, so don't worry too much about that. In the instrumentation list at the start of the piece, you should say "Viola (12 players)" if that is the exact number you are writing for, as an advance warning.
Comment: Thanks for the feedback. Re: the second example, I did want three coequal subdivisions in the first version, but I changed my mind in the second version. Indeed, I'm written the section sizes at the beginning of the score ("Viola (12)") for clarity's sake. Thanks also for the tip on the "2.3." / "1." player markings, I wasn't sure how to notate that if I had wanted to divide them that way.
Answer: First example: I think it's fine as-is. It's an unusual thing to ask for, so writing it out explicitly is appropriate. You could split into two staves, and as someone else said it will reduce confusion to write (senza trem.) or (non trem.) on the non-tremolo part. If you leave it combined, I'm not sure about using 1/2 to indicate each split; I've used 1. and 2. several times and never gotten any confusion.
Second example: I don't like dictating a specific number of players. Not every string section has exactly 12 violists. And I think that div. a3 implies that it should be three equal groups. My suggestion is to write something like 2 equal groups where the part splits into two staves, and then write a simple div. on the lower staff.
Comment: I got the idea to use "½" from the _Edward Scissorhands_ score published by Omni, where the instruction "½ ord., ½ trem." appears on single staves at points. I tried adapting it for my own needs here by adding "sul pont." to both. For the violas, I'm not writing for any real ensemble (though Hollywood composers frequently specify exact section sizes), so I take the liberty of dictating the exact player counts in my scores. As for the divisi, I've edited the OP to clarify that I've changed the split from 3 coequal sections (4 each) to the melody having 6 players and 3 each for the staccatos.


How to use Vue mouse events with composition api?

Question: I am just trying to see how @mouseup, @mousedown, @mousemove events are working.
I have just a div:
// html

{{x}}

// CSS
.test {
  height: 100px;
  width: 200px;
  background-color: red;
}

// Vue
  setup() {
    const x = ref(0);

    const mouseMove = event => {
      console.log("Mouse Moved ", event.x, event.y);
      x.value = event.x;
    };

    const mouseDown = event => {
      console.log("Mouse Down", event.x, event.y);
    };

    const mouseUp = event => {
      console.log("Mouse Up", event.x, event.y);
    };

    return {
      x,
      mouseMove,
      mouseDown,
      mouseUp
    };
  }

Now every time I click, I can see all 3 events called once, but nothing happens when I click and drag, no event is called.
Mouse Moved  106 729
Mouse Down 106 729
Mouse Up 106 729

Why is that ? I can't seem to understand why.
Comment: https://codepen.io/adrianstanciu24/pen/GRorVyj for some reason here it works. I don't get it...
Comment: Not really a Vue issue. See https://stackoverflow.com/questions/46186173/are-mousemove-events-disabled-while-dragging-an-element#:~:text=2%20Answers&text=From%20here%3A%20%22The%20mousemove%20event,moves%20synchronously%20with%20the%20element.
Comment: My bad, it works in my project too, but I always tested with the Developers tools open, in that case it doesn't work. Which is strange for me.
Comment: I want to resize the div and all examples are using mouseevent event, but not with Vue, just plain html. So I thought I will do the same, but using this event in vue. Why it is behaving differently ?
Comment: For example, https://codepen.io/mannuelf/pen/wJwMjX this works, but it is not using composition api, so not sure what exactly is wrong with my example :/
Comment: In your codepen, I'm not seeing the mouse events while dragging. Do you have a repro using the composition API?
Answer: If you are working with Vue composition API, a declarative approach would be to use the useMouse composable function


jQuery - Função .prop()

Question: Eu tenho um input que vem desabilitado por padrão, porém eu queria habilitar o mesmo no carregamento da página por meio de jQuery, porém não está dando certo.
Código do input:
<input type="text" title="Número" name="billing[street][2]" id="billing:street2" class="input-text required-entry" value="" autocomplete="off" disabled="">

Eu tentei o código abaixo, porém não obtive sucesso:
$j(document).ready(function(){
    $j('#billing:street2').prop('disabled',false);
})

Answer: Quando você precisa utilizar caracteres especiais no seu seletor, é necessário utilizar \\(duas barras invertidas), para que o caractere seja tratado como texto e não como uma expressão regular.
Outro erro contido no seu código é o caractere j após o $.

$(document).ready(function(){
    $("#billing\\:street2").prop('disabled',false);
});

<input type="text" title="Número" name="billing[street][2]" id="billing:street2" class="input-text required-entry" value="" autocomplete="off" disabled="">

Aprenda mais sobre seletores aqui.
Comment: Deu certo! Muito obrigado pela ajuda e atenção! Uma observação: o caractere `$j` não seria um erro, pois uso `$j.noConflict();` para que eu não tenha conflitos com outras bibliotecas. Mas enfim, muito obrigado pela ajuda!
Comment: Ah sim, compreendi...

jQuery - Função .prop()


How can I get data from from two different tables in a single MySQL query?

Question: I want to get data from two tables in my database. Here's what my tables might look like:

table 1 with fields id, author, profession, country
table 2 with fields id, quote, author, category

I want to select quote and author from table 2 and the corresponding profession from table 1, with the same author in both tables.
How do I construct a query that does this?
Answer: Supposing that your author column contains unique identifiers for authors, try:
SELECT t2.quote, t2.author, t1.profession
FROM table2 t2
  LEFT JOIN table1 t1 ON t2.author = t1.author

Answer: select T2.quote, T2.author, T1.profession
   from table1 T1, tabel2 T2
   where T1.id = T2.id

Answer: SELECT table2.quote, table2.author, table1.profession FROM table2, table1 WHERE table2.author=table1.author
you can add LIMIT 1 at the end to have single result.


what is marginal density based on this picture?

Question:
I am studying Gaussian mixtures from the book Pattern Recognition and Machine Learning by Chris Bishop. Figure (a) are contours of the mixture components (Gaussians) with the corresponding weights. Figure (c) is the surface graph of the same.
Figure (b) is the 'combination' of the individual components of the mixture. The book labels it as the contour of the marginal probability density of the mixture.
I do not understand why it is 'marginal'. Is it correct to say that 'marginal' is 'combination' of the individual mixtures because that is how is see it. Please provide some insights. Thanks
Answer: Quick recap:
Conditional distribution: $f(x|i)$
Marginal distribution: $f(x) = \sum_{i} f(x|i) \times \pi(i) $
where $\pi$ is the prior of $i$.
In this case the conditional distributions are: $f(x|red),f(x|green),f(x|blue)$. So if we know our object is a "red" then we know the distribution of $x$, it is $f(x|red)$. Otherwise if we don't know what type of object it is, we have to 'marginalise' over the groups, or as we stats people like to say 'integrate out' the groups. I assume the numbers below the ellipses represent the prior probabilities for each group so the marginal probability is $f(x) = \sum_{red,green,blue} f(x|colour) \times \pi(colour)$.


What does explosion of counting process mean?

Question: I've been reading this article regarding Hawkes processes https://arxiv.org/pdf/1507.02822.pdf, and I've noticed that the definition for explosion in the article in page 3, stating that a counting process explodes if we have for $N(t)$ counting process, $t,s\in\mathbb{R}$ that:
$$ N(t)-N(s)=\infty$$
That is, the probability of having infinite amount of "arrivals" in a finite interval is higher than $0$.
In page 8, the author says that given the ratio $n$, the process "explodes almost surely" for $n>1$. But, what he then shows is we have a series of arrivals $Z_i$ (You may view $Z_1$ as the first person and $Z_2$ as his son, and $Z_i$ being the $i$th son). Calculating the expectation of the amount of people we get that:
$$ \mathbb{E}\Big[\sum_{i=1}^\infty Z_i\Big]=\sum_{i=1}^\infty \mathbb{E}[Z_i]=\sum_{i=1}^\infty n^i = \infty$$
But, the author hasn't proved that the counting process explodes, he just proved that the expected amount of descendents is unbounded, but it does not mean that the process explodes (one might imagine a steadily exponentially increasing population, there need not be a finite time interval where we have infinite births).
Does it follow from this point and I just don't see it, or it is an extension of the definition of explosion of a counting process?
Comment: I think you have a point. Have you consulted their reference [23] ?  Intuitively I think that the link between the explosion of the expectation and the paths themselves lies in the self-exciting property of their Hawkes processes.
Answer: Not sure if this counts as a full answer given that I'm agreeing with you. But if I'm understanding things correctly then your idea of an exponentially increasing population over time actually seems pretty likely. I looked at the Asmussen reference ([24] in the paper), and if $1 < n < \infty$, then there should exist a $-\infty < \beta< 0$ such that $\int_{t > 0} e^{\beta t}\mu(t)\,dt = 1$.
Then Proposition V.7.1. of Asmussen states that $\lim_{t\to\infty}e^{\beta t}E[\lambda^*(t)] < \infty$. If the conditional intensity of the Hawkes process only increases exponentially fast we shouldn't expect explosion.
The only thing I can think of is that the authors were considering stationary distributions when they made that remark even though they they seem to be discussing the transient case up until that point. It's certainly true that if $n > 1$, the Hawkes process will not have a non-explosive, stationary distribution (assuming the constant $\lambda > 0$).
Comment: I think it does answer, because it means that those 2 condition are truly separate. Then we may ask a further research question - when does a "weak" explosive process, explodes "strong"ly ? But this is a question for a different time :)
Comment: By weakly explosive, do you mean $n > 1$ so that the intensity converges to infinity with time? With point processes, you will generally get explosion if the conditional intensity converges to infinity in a finite amount of time. For example if $\lambda^*(t) = \frac{1}{10-t}$ or something.


SBS 2011 Standard: Exchange Database Size Limit?

Question: Exchange 2010 Standard's limit is 1024 GB; is this the same for SBS 2011 Standard?
Answer: The default limit is 1TB but you can change it.  See this site for more info http://blogs.technet.com/b/uspartner_ts2team/archive/2011/03/20/exchange-2010-default-database-size.aspx


How to filter views block by content type

Question:
I added two content types for views slideshows.
I added slides to both content types.
I created a views slideshow block using one content type.
I cloned the above view > Now, I have two views slideshow blocks.

Now, both blocks are linked. Updating one setting updating the other. How can I do the settings so views block1 filtered by content type1 and views block 2 filtered by content type2?
Answer: Add a filter of content:type in one of your display Also,
You can select this block override at the top when you do any specific block related changes. check the screenshot https://i.stack.imgur.com/JIIx4.png


What do I conclude if I found the eigenvalues of a matrix, then noticed that one of those eigenvalues resulted in a zero eigenvector?

Question: By definition:
$$Ax = \lambda x$$
for $x \neq 0$
I was using this to calculate the eigenvectors for $A$:
$$A = \begin{bmatrix}2 & 0 & 0\\1 & 3 & 0\\ 2 & 3& 4\end{bmatrix}$$
I already found that the eigenvalues for this matrix are:
$$\lambda = 2,3,4$$
However, when I began evaluating the eigenvectors for these eigenvalues, I noticed that for $\lambda = 4$, the resulting eigenvector is:
$$x = \begin{bmatrix}0\\0\\0\end{bmatrix}$$
But how is this possible??

Please help me find my mistake.
To find the eigenvectors, we must solve the equation:
$$(\lambda I -A)x = 0$$
$$\begin{bmatrix} 4 & 0 & 0\\0 & 4& 0\\ 0 & 0 & 4 \end{bmatrix} - \begin{bmatrix}2 & 0 & 0\\1 & 3 & 0\\ 2 & 3& 4\end{bmatrix} = \begin{bmatrix}2 & 0 & 0\\-1 & 1 & 0\\ -2 & -3 & 0\end{bmatrix}$$
Row reducing, we see that
$$ \left[
    \begin{array}{ccc|c}
      1&0&0&0\\
      0&-1&0&0\\
      0&3&0&0
    \end{array}
\right] $$
...which tells us that $x_1=0, x_2=0, 3x_2=0$.
Comment: There is a nonzero eigenvector; you must have made a mistake somewhere.
Comment: The last line is wrong, $x_3$ is not $0$ from that equation system.
Comment: Well, it is always true that $(A-\lambda I) 0 = 0$, but an eigenvector must be **non zero**. In this case, you can 'read off' an eigenvector corresponding to $\lambda =4$ as $(0,0,1)^T$.
Comment: @whatwhatwhat Au contraire: $\;z\;$ doesn't appear **at all** in the homogeneous system and it thus can take *any* value whatsoever!
Comment: z is free choice because it has a 0 **coefficient** for each row. There is no equation that can restrict it if it is multiplied by 0 in the equations.
Comment: The null-vector is not considered to be an eigenvector. It always satisfies $Ax=\lambda x$. You have to find a non-zero vector satisfying the condition. You can always find such a non-zero vector.
Comment: It is true that some eigenvalues don't have an eigenvector associated with them. But as Javier points out it seems you have made a mistake here.
Comment: @mathreadler How can it be possible some eigenvalues have no eigenvector associated with them? Isn't that an oxymoron? If the characteristic pol. has a root on some given field *then* there **must be** an eigenvector attached to it.
Comment: I agree that this is not possible. I'm trying to figure out where I made my mistake.
Comment: After reducing (i talk of your very last edit) we see that it **must** be $\;x=y=0\;$ *and* $\;z\;$ is free...exactly as obtained below.
Comment: @mathreadler you're right. I fixed it.
Comment: @Joanpemo So we say that $z$ is a free choice simply because for ***all*** rows (in my reduced matrix), $z=0$??
Comment: Ah, makes sense. Thank you both.
Answer: The resulting homogeneous system for $\lambda=4$ ( i.e., $\;(\lambda I-A)\vec x=\vec0\;$) is:
$$\begin{cases}2x=0\\-x+y=0\\-2x-3y=0\end{cases}\implies\;\;x=y=0\implies \begin{pmatrix}0\\0\\1\end{pmatrix}$$
is an eigenvector for $\;\lambda=4\;$ and, in fact, it is a basis for the corresponding eigenspace
Comment: The difference between my work and yours is the $x+y$. I got $-x+y$. I got a negative value for $x$ because when doing $\lambda I -A$ we see that the 1st column 2nd row of $\lambda I$ is $0$. Subtracting the corresponding value from $A$, we get $0-1=-1$.
Comment: So how did you get a positive value?
Comment: @whatwhatwhat  Thank you, you're completely right: it must be $\;-x\;$ there and, in fact, also $\;-2x-3y=0\;$ in the last equation. I did it in my mind and, of course, it makes no difference in this case. I shall edit now.
Answer: You made a mistake, the (normed) eigenvector for the eigenvalue $4$ is $e_z$.
<code>>> A
A =

   2   0   0
   1   3   0
   2   3   4

>> [x,y]=eig(A)
x =

   0.00000   0.00000   0.66667
   0.00000   0.31623  -0.66667
   1.00000  -0.94868   0.33333

y =

Diagonal Matrix

   4   0   0
   0   3   0
   0   0   2
</code>
And this is easy to verify as $e_z = (0,0,1)^t$ picks the third column, $(0,0,4)^t$, of $A$ and this is $4 \cdot e_z$.
By hand you would solve $A_1 u = 0$ for
$$
A_1
=
\begin{pmatrix}
2 - 4 & 0 & 0 \\
1 & 3-4 & 0 \\
2 & 3 & 4-4
\end{pmatrix}
=
\begin{pmatrix}
-2 & 0 & 0 \\
1 & -1 & 0 \\
2 & 3  & 0
\end{pmatrix}
$$
This has the solutions $u = (x,y,z) = (0,0,z)$ for arbitrary $z \in \mathbb{R}$. Here is the Gauss elimination, using augmented matrices:
$$
A_1 u = 0 \iff \\
\left[
\begin{array}{rrr|c}
-2 & 0 & 0 & 0 \\
1 & -1 & 0 & 0 \\
2 & 3 & 0 & 0
\end{array}
\right]
\to
\left[
\begin{array}{rrr|c}
1 & 0 & 0 & 0 \\
1 & -1 & 0 & 0 \\
2 & 3 & 0 & 0
\end{array}
\right]
\to
\left[
\begin{array}{rrr|c}
1 & 0 & 0 & 0 \\
0 & -1 & 0 & 0 \\
0 & 3 & 0 & 0
\end{array}
\right]
\to
\left[
\begin{array}{rrr|c}
1 & 0 & 0 & 0 \\
0 & 1 & 0 & 0 \\
0 & 3 & 0 & 0
\end{array}
\right]
\to
\left[
\begin{array}{rrr|c}
1 & 0 & 0 & 0 \\
0 & 1 & 0 & 0 \\
0 & 0 & 0 & 0
\end{array}
\right]
$$
Update:

...which tells us that x1=0,x2=0,x3=0.

No it does not. It just tells you $x_1$ and $x_2$ are zero.
Comment: I don't understand what this is supposed to tell me.
Comment: $x$ is the matrix of eigenvectors, $y$ is the diagonal matrix with the corresponding eigenvalues. In other words I asked my machine for the results to compare with yours.
Answer: There seems to be some confusion here. The eigenvalues solve the characteristic equation $\det({\bf A}-\lambda {\bf I}) = 0$ , but there can be several eigenvalues for one eigenvector (multiple roots). Take for example the matrix $$A = \left[\begin{array}{ccc}
2&0&0\\1&2&0\\0&0&4
\end{array}\right] \hspace{1cm} A-2I = \left[\begin{array}{ccc}
0&0&0\\1&0&0\\0&0&2
\end{array}\right]$$
This only gives one vector ($[0,1,0]^T$), although there are two roots $\lambda = 2$.


Default installation of D8 treatment of .gif accesses?

Question: If I request a non-existent URL, say, /ddddd I get Page not found (as expected). If I do th4 same with an unusual extension /dddd.xcf I also get Page not found.
BUT if I request /ddddd.gif there's an Apache error as opposed to a 404?
I'm guessing this has something to do with security, but can someone clarify this?
Comment: Just .gif, or .jpg/.png/etc too? What about non-existent .js/.css files outside of sites/default/files? What error are you receiving (code and message)? If it's a 500, I'd wager you've just found a bug
Answer: By default drupal serves a different 404 page to save computational effort if it  is matching the following regex:
<code>'/\.(?:txt|png|gif|jpe?g|css|js|ico|swf|flv|cgi|bat|pl|dll|exe|asp)$/i'
</code>
You can configure this in the settings.php (Fast 404 pages) or in the config('system.performance')->get('fast_404.paths');
Comment: Yes, it was this. I was being asked by someone else, and didn't have a D8 installation to hand. So thanks.


Solução para replicar posts no wordpress

Question: Eu tenho um site WORDPRESS, vamos chamar-lo de site01
Por outro lado, eu tenho o site02, em wordpress novamente.
Eu gostaria que todo o conteúdo(posts e paginas), modificados no SITE01 fosse atualizado também no site02.
Eu já ouvi fala de uma solução chamada multi-site wordpress, mas não acredito que seja a melhor, por ser difícil configurar-la.
Alguma sugestão? Conectar as duas DB dos sites? O que faço?
PS: Não quero duplicar os posts uma vez só, preciso que o site01 seja clone do site02. Tudo que for atualizado no 01, ter que ser atualizado automaticamente no site 02.
PS: Os dois sites usam WORDPRESS.
Answer: Luan,
Eu já utilizei esse plugin WPEMATICO para puxar posts de vários sites externos, que seja em Wordpress. Para isso, basta você definir o endereço do feed do site que você quer.
Ele tem a versão gratuita mas, no meu caso, eu acabei comprando a versão paga.
Na época, fiz um site principal no qual eu agregava diversos posts, sem que eu necessitasse publicá-los manualmente, ou seja, o plugin já fazia automaticamente.
Então, quando o dono do blog publicava um novo post, em alguns segundos o conteúdo era publicado em meu site.
Espero que te ajude.


Magento - Get products price with tax and discounts in cart/order (Criteo tags)

Question: For the implementation of Criteo tags, I'm trying to get the price (among other things) of all products in the cart (and success page) with tax and discounts.
I'm currently doing something like this, but it only displays price with discount and without tax :
$cartAllItems = Mage::getModel('checkout/cart')->getItems();
foreach ($cartAllItems as $item){
    $price = Mage::helper('tax')->getPrice($item->getProduct(), $item->getProduct()->getFinalPrice());
    // other things
}

I've been testing around a lot of things and can't make it work.
Thx for the help
Answer: I think you can use,
Mage::helper('checkout')->getQuote()->getShippingAddress()->getData('tax_amount')

This will return you total tax amount.
or you can use
$totalItemsInCart = Mage::helper('checkout/cart')->getItemsCount();
$totals = Mage::getSingleton('checkout/session')->getQuote()->getTotals();
$subtotal = round($totals["subtotal"]->getValue());
$grandtotal = round($totals["grand_total"]->getValue());
if(isset($totals['discount']) && $totals['discount']->getValue()) {
   $discount = round($totals['discount']->getValue());
} else {
   $discount = '';
}
if(isset($totals['tax']) && $totals['tax']->getValue()) {
  $tax = round($totals['tax']->getValue());
} else {
  $tax = '';
}

Modified
I guess for your requirement
foreach ($productIds as $productId) {
  $_product  = Mage::getModel('catalog/product')->load($productId);
  $productsPrice = floatval($_product->getData("price"));

  // Get the product's tax class' ID
  $taxClassId = $_product->getData("tax_class_id");
  echo 'Tax Class ID '.$taxClassId.'
';
  // Get the tax rates of each tax class in an associative array
  $taxClasses  = Mage::helper("core")->jsonDecode( Mage::helper("tax")-
>getAllRatesByProductClass() );
  echo 'Tax Classes '.$taxClasses.'
';
  // Extract the tax rate from the array
  $taxRate   = $taxClasses["value_".$taxClassId];
  echo 'Tax Rate '.$taxRate.'
';
 }
 ?>

Comment: Hey, thanks for answering. The thing is, I'm looking to get the price (discounted and with taxes in it) for EACH item of my cart (hence my foreach). Is there a way to do that with your method ? Thanks.
Comment: try, getStore('default');
    $request = Mage::getSingleton('tax/calculation')->getRateRequest(null, null, null, $store);
    $taxclassid = $item->getData('tax_class_id')
    $percent = Mage::getSingleton('tax/calculation')->getRate($request->setProductClassId($taxclassid));
?>
Answer: You can get the discount and tax value per item and make the calculation.
$_item->getDiscountAmount
$_item->getTaxAmount

$totalItemPrice = $_item->getPrice - $_item->getDiscountAmount + $_item->getTaxAmount