Ajuda com Select somando campos contas a pagar e receber para relatorio MYSQL

Question: Galera tenho duas tabelas campos iguais, CONTAS A PAGAR e CONTAS A RECEBER, preciso gerar um relatório pegando o valor Credito - Debito e saindo resultado, alguém consegue me ajudar, estou apanhando pra isso, abaixo o select que estou usando e o link com print do resultado de testes que tenho no banco de dados.
https://www.cloudvine.com.br/exemplo.png
SELECT
tb_cr.tb_cr_credito AS tb_cr_credito,
tb_cr.tb_cr_id_fornecedor AS tb_cr_id_fornecedor,
tb_cr.tb_cr_dt_Lancamento AS tb_cr_dt_Lancamento,
tb_cr.tb_cr_vencimento AS tb_cr_vencimento,
tb_cr.tb_cr_descricao AS tb_cr_descricao,
tb_cr.tb_cr_valor AS Credito,
'' AS Debito,
tb_cr.tb_cr_situacao AS tb_cr_situacao
FROM tb_cr
WHERE tb_cr.tb_cr_situacao = 'Recebido'

UNION

SELECT
tb_cp.tb_cp_debito AS tb_cp_debito,
tb_cp.tb_cp_id_fornecedor AS tb_cp_id_fornecedor,
tb_cp.tb_cp_dt_Lancamento AS tb_cp_dt_Lancamento,
tb_cp.tb_cp_vencimento AS tb_cp_vencimento,
tb_cp.tb_cp_descricao AS tb_cp_descricao,
'' AS Credito,
tb_cp.tb_cp_valor AS tb_cp_valor,
tb_cp.tb_cp_situacao AS tb_cp_situacao
FROM tb_cp
where tb_cp.tb_cp_situacao = 'Pago'

Comment: Veja se ajuda https://pt.stackoverflow.com/questions/305445/consultar-dados-de-duas-tabelas-diferentes-e-listar-sem-unir-dados
Answer: Você pode utilizar a seguinte estratégia:

Ao invés de usar uma String vazia para as Credito e Debito, utilize 0, assim você pode utiliza-los como atributo de cálculo;
Englobe toda a sua query em uma subquery;
Utilize a cláusula SUM para obter os valores totais de cada coluna;
Realize a operação baseada nessa soma;

Fazendo isso você terá algo como:
SELECT (SELECT SUM(tb_cr.tb_cr_valor) AS Credito
          FROM tb_cr
         WHERE tb_cr.tb_cr_situacao = 'Recebido') -
       (SELECT SUM(tb_cr.tb_cr_valor) AS Credito
          FROM tb_cr
         WHERE tb_cr.tb_cr_situacao = 'Pago') AS saldo

Veja functionando no SQL Fiddle.

SUM([DISTINCT] expr) [over_clause]
Returns the sum of expr. If the return set has no rows, SUM() returns NULL.

Em tradução livre:

Retorna a some de uma expressao. Se o conjunto retornado não contiver linhas, SUM() retornará NULL.
Comment: Obrigado, me esclareceu bastante.


How are basis defined in non-linear coordinate systems?

Question: A basis is defined as follows:
<code>
Given a basis of a vector space V, every element of V can be expressed uniquely as a linear combination of basis vectors, whose coefficients are referred to as vector coordinates or components.
</code>
How does this work if we have some non-linear manifold? What is the basis of that coordinate system? This definition doesn't seem to work anymore.
Comment: If your manifold is over $\mathbb{R}^n$ or $\mathbb{C}^n$ then you have a basis in each neighbhorhood of your manifold using the chart
Answer: You don't have a "basis" for any thing that isn't a linear space.  But, as Tony S.F. said, you can define the "tangent space" of a differentiable manifold and define a basis for that.
Comment: Fascinating. So we take the tangent plane at every point and define a basis for each of those? That's amazing.


Programmatically make a screenshot of a terminal window in Gnome/Wayland

Question: I work on a terminal font and I'd like to take screenshots of various terminals (at least xterm, gnome-terminal and konsole) running a rendering test application. Executing the command is not a problem, but the usual, portable X way of doing it, the xwd command, doesn't seem to be very script-friendly and only works on X apps (xterm, in this case) and (unsurprisingly) ignores events from Wayland windows.
Answer: Figured it out (ish). All that's needed is to add a gnome-screenshot -w to the program I want to run. In my specific case, I added a script that ran the rendering test, then slept for two seconds (so that Konsole drops the window size widget) and then ran the screenshot command:
#!/bin/sh

./test_font_rendering.py
sleep 2 # Needed for Konsole to clear the window size

# Capture the active window to a file given as a parameter
gnome-screenshot -w -f $1.png

So, in order to generate the samples, you'd need something like:
gnome-terminal -- bash -c './test_font_rendering.sh gnome-terminal'
xterm -e './test_font_rendering.sh xterm'


Spring 4 hibernate 4 JPA LazyInitializationException: failed to lazily initialize a collection of role

Question: I made a database connection with spring 4 used with hibernate 4 and JPA. When I try to get a lazy initializated field I got an LazyInitializationException.
My applicationContext.xml:
<context:annotation-config />
<context:component-scan base-package="xy" />

<jpa:repositories base-package="xy.repositories" />

<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
    <property name="persistenceUnitName" value="punit" />
    <property name="dataSource" ref="dataSource" />

    <property name="jpaVendorAdapter">
        <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
            <property name="showSql" value="true" />
        </bean>
    </property>
    <property name="jpaPropertyMap">
        <map>
            <entry key="hibernate.dialect" value="org.hibernate.dialect.MySQL5InnoDBDialect" />
            <entry key="hibernate.hbm2ddl.auto" value="update" />
            <entry key="hibernate.format_sql" value="true" />
        </map>
    </property>
</bean>

<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
    <property name="entityManagerFactory" ref="entityManagerFactory" />

</bean>

<tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true" />

<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="com.mysql.jdbc.Driver" />
    <property name="url" value="jdbc:mysql://localhost:3306/keysystem" />
    <property name="username" value="username" />
    <property name="password" value="password" />
</bean>

<bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"/>

Model:
@Entity
@Table
public class Employee {
    @Id
    @GeneratedValue
    private long employeeId;
    private String firstName;
    private String lastName;
    @OneToMany(fetch = FetchType.LAZY, mappedBy = "employee")
    @Cascade(CascadeType.ALL)
    @Fetch(FetchMode.SELECT)
    private Set<Legitimacy> legitimacies;
    ...

I found only MVC filter solution, but I don't use MVC. I tried Hibernate.initialize(...) and @Transational, @Fetch annotations but these didn't solved my problem.
Here is the stacktrace:
Caused by: org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: xy.Employee.legitimacies, could not initialize proxy - no Session
    at org.hibernate.collection.internal.AbstractPersistentCollection.throwLazyInitializationException(AbstractPersistentCollection.java:575)
    at org.hibernate.collection.internal.AbstractPersistentCollection.withTemporarySessionIfNeeded(AbstractPersistentCollection.java:214)
    at org.hibernate.collection.internal.AbstractPersistentCollection.initialize(AbstractPersistentCollection.java:554)
    at org.hibernate.collection.internal.AbstractPersistentCollection.read(AbstractPersistentCollection.java:142)
    at org.hibernate.collection.internal.PersistentSet.iterator(PersistentSet.java:180)
    ... 64 more

Comment: http://stackoverflow.com/questions/33318404/jpa-how-to-return-null-instead-of-lazyinitializationexception/33325493#33325493
Accepted answer explains why it happens and how to solve it. There's no trick to it, if you try to access the contents of `legitimacies` Set outside of a transaction while it still has not been fully initialized, you will get this exception.
Comment: The @Transactional annotation didn't work for me, and I don't want to use Eager initialization because of the performace.
Comment: Then I think you should provide two more parts of code so we can identify the exact problem and how to solve it. Please add the code you use to fetch  the Employee object, and the code where you try to access the legitimacies Set content. What you could do is to initialize the Set while the hibernate session is still open.
Comment: Also, saying "this didn't solve my problem" is not helpful at all. Instead, you should explain why it didn't solve your problem. For example, why Hibernate.initialize didn't work for you? This method has only one intent, to initialize the collection, if it's called within a transaction it should initialize your Set and you should not have any problems accessing its contents later on.
Answer: Guillaume is right, you are using a proxy managed by Hibernate in some location in your code which is outside a transactional context.
Because of that, when you call getLegitimacies() that has not been initialized yet, Hibernate try to populate its proxy by graping a session and make a database call.
If you are in a controller for example and no session is available, an exception is thrown. You have to fetch your legitimacies set at some point in your dao (by using FETCH keyword in your HQL query for example) :
FROM Employee e LEFT JOIN FETCH e.legitimacies WHERE <your_predicate>;

You should also not manipulate your entities if not in service/dao layer but use a DTO instead to avoid those problems.
Answer: Lazy exceptions occurs when you try to access a referenced object outside of the original session.
Basically, you are doing this :
* Open a session
* Fetch an object, let's say X
* Close the session
* Try to access X.getY()

A solution is to fetch X and Y at the same time, while the session is open.


Version of Drupal is no longer supported [Using the latest 7.42 release]. After automatic update

Question: I use Drupal with Commerce Kickstarter profile installed. After automatic update from Installatron in my Direct Panel i get an error of unsupported Drupal Core version:

There's no way to make update using Drush or Installatron from that state.
The only way to make it work, that I have found, is to revert to the backup before update. Can anyone help me to understand what's happening, and why  Installatron updates to the 7.42 version (7.41 -> 7.42) while Drupal Report state of 7.41 v. states that it is up-to-date?
Comment: You question is slightly vague. I suggest you edit it otherwise it might get closed.
Comment: Please ask the people who support that platform @maszynka, we couldn't know what they've done to your site
Comment: What is "automatic update from Installatron in my Direct Panel" ?
Comment: It is an web-app automatic installer, with build in backup & update functions. It supports Drupal, Joomla, WP and more.

I have ticked an option for automatic updates with backups, and it caused that mentioned situation.
Comment: you might also check /update.php to see if there are update scripts that need to be run (?)
Answer: You updated Drupal core outside of updating the entire distribution. You're seeing this message because of the Distribution Update module and having upgraded outside of the distribution.
On that note, CK 2.32 uses Drupal 7.41. I will roll CK 2.33 with 7.42


Size of Complier Group (Instrumental Variables) - Mostly Harmless vs. Abadie Kappa

Question: Focusing solely on the case with a binary endogenous explanatory variable $D$ and binary instrument $Z$ and control variables $X$, Angrist & Pischke 2009 ("Mostly Harmless Econometrics") show that the size of the complier group can be given by the Wald first stage
$P[D_{1i}>D_{0i}]=E[D_i|Z_i=1]-E[D_i|Z_i=0]$
However, it is unclear to me whether this holds true once we add the covariates to the first stage. In contrast to the above, Abadie 2003 (top of page 237) shows that the size of the complier group is given by
$$
P[D_{1i}>D_{0i}]=E[\kappa_i] \\
\textrm{where} \quad  \kappa_i = 1 - \frac{D_i(1-Z_i)}{1-P(Z_i=1|X_i)} - \frac{(1-D_i)Z_i}{P(Z_i=1|X_i)}
$$
In simulations, it's easy to show that when X is independent (or is an intercept only) these two measures are equivalent. Otherwise, they seem to differ. In at least one paper (Maestas, Mullen, Strand 2013), the authors claim that the first stage coefficient with controls gives the number of compliers, but the two measures above also differ from the coefficient on $Z$ in the full first stage, i.e. $D_i=\alpha + X_i'\beta + Z_i'\gamma + \varepsilon_i$. The simulation results are attached at the bottom of this post.
I am unsure about which of these gives the correct measure of the complier group. I feel similarly unsure about the intuition for the size of the complier group with controls. It seems that the degree to which covariates predict $Z$ can dramatically affect the size of the complier group, but any intuition about why this makes sense, what this means for external validity, etc. is greatly appreciated.
The simulation is in the following R script. Please do point out if these differences are due to errors in implementation.
<code>### simulate the data generating process
set.seed(2839)
n <- 20000

endo <- rnorm(n)
endo2 <- rnorm(n)
z <- as.integer(endo2 + rnorm(n)>0)
d <- endo2 + endo + z + rnorm(n)
d <- as.integer(d > median(d))
x <- rnorm(n)+endo2
# x <- rep(1,n) # can confirm that if x is just an intercept these are equivalent
# x <- rnorm(n) # similarly if x is independent these are equivalent

y <- 1.5+ 2*d - 4*x + 1.5*endo + rnorm(n)

## make sure you've simulated estimable model coefficients
mod_1st <- lm(d ~ z + x)
dhat <- fitted(mod_1st)
mod_2nd <- lm(y ~ dhat + x)

mod_ols <- lm(y ~ d + x)

### wald 1st stage implied size of complier group
mean(d[z==1]) - mean(d[z==0]) # roughly .49

## kappa version
zmodel <- fitted(lm(z~x))
kappa <-
    1 -
    (d * (1-z)) / (1 - zmodel) -
    ((1-d)*z)/zmodel
mean(kappa) # roughly .65
</code>
Answer: In the same paper, Abadie shows (Lemma 2.1.) that $$\mathbb{P}(D_1>D_0|X) = \mathbb{E}[D|Z=1, X] - \mathbb{E}[D|Z=0, X]$$ so the conditional variant of this holds even if you add covariates.
Comment: Thanks so much for this additional detail. Can you explain more about how this detail could rationalize the fact that the Wald first stage differs from the (unconditional) expectation of Kappa in the example? And why the first stage coefficient controlling for X is different from both? I guess ultimately I still don't know which of these would be an appropriate measure of the unconditional "size of the complier population." I guess would also be interested to understand how this relates to accurately measuring the size of the complier population conditional on X. Thanks again!
Answer: In the script you write $X$ and $Z$ as jointly determined.
This is equivalent to there being selection into instrument on endo2 in your script, confounding the estimates of the estimation.
The LATE framework requires the instrument, $Z$, be independently assigned to unit (or conditionally so).
This is violated in your script by determining both $Z$ and $X$ by endo2.
To see this, note that the $\kappa$-weight gets the average rate of compliance correct if you estimate $\Pr(Z_i = 1)$ without conditioning on $X_i$:
<code>### simulate the data generating process
set.seed(2839)
n <- 20000
endo <- rnorm(n)
endo2 <- rnorm(n)
z <- as.integer(endo2 + rnorm(n)>0)
d <- endo2 + endo + z + rnorm(n)
d <- as.integer(d > median(d))
x <- rnorm(n)+endo2
y <- 1.5+ 2*d - 4*x + 1.5*endo + rnorm(n)
### wald 1st stage implied size of complier group
mean(d[z==1]) - mean(d[z==0]) # roughly .49
zmodel <- fitted(lm(z~1)) # This is where the change is, Z ~ 1
kappa <- (1 -
    (d * (1-z)) / (1 - zmodel) -
    ((1-d)*z)/zmodel)
mean(kappa) # roughly .49
</code>
Though, if you're interested in further practical details on the Abadie (2003) weights approach, new research in the area is fairly interesting.

https://doi.org/10.2139/ssrn.4093467
https://doi.org/10.48550/arXiv.1909.05244
Comment: Thanks for your response! Is it true that LATE requires $Z$ to be independent of all observed covariates $X$ in the model? The 2SLS estimates in the original code do recover the correct coefficient after all. If independence of $Z$ and $X$ were required, what would be the point of including $P(Z_i=1|X_i)$ in the calculation of $\kappa$ (as opposed to $P(Z_i=1)$)?
Comment: I also understand that the Wald first stage coincides with the $\kappa$ weights when conditioning on $X$ is omitted. However, I am most interested in understanding the rate of compliance when conditioning on $X_i$. Could you provide more intuition (or simulation) on that front?


Neater version of print_r($_POST)

Question: I'm trying to creating a php program that simply does the same thing as print_r(), but in a neater format.  I created a form that just has some checkboxes and radio buttons and when the user hits the submit button, it takes them to another page that shows them the values of what they picked.  I planned on using a foreach statement, but I'm having trouble with the syntax.  Here's what I came up with in my pseudocode
foreach($_POST as X=>Y)
    echo ("For ".X." you entered ".Y."
");

What I'm unsure of is what X and Y would be.  Is there a way I can read the print_r($_POST) into a variable and display it how I want to?
Comment: `foreach` is described pretty well in manual. Check it.
Comment: "Is there a way I can read the print_r($_POST) into a variable and display it how I want to?" — In to a variable as what? As a string of not-very-well-structured data that you'd have to parse to figure out which parts were formatting and which parts were data?!
Comment: you can also just wrap print_r in `` tags so it's easier to read.
Comment: I ended up going with Kai's suggestiong.  Thank you.  I think I'm trying to get too fancy with something I don't have enough of an understanding of.
Comment: "What I'm unsure of is what X and Y would be" — variables … with normal variable syntax.
Comment: I know X and Y would be variables, but I'm not sure what I'm setting them as.  Sorry for the poor wording.  I'd like one to be a variable for each field, and the other to be a variable for each value entered.  I'm very new new to php (to put it lightly) so I think I'm missing the syntax for this.
Answer: A nicer way is to get xdebug module and turn on HTML display (see http://xdebug.org/docs/display) and it will make it look nicer.
You could also look at kurmo http://krumo.sourceforge.net which is a nice tree view of print_r

Neater version of print_r($_POST)


Inserir input somente se ainda não existir

Question: Estou trabalhando em um form com campos inseridos dinamicamente. Mas quero que os campos sejam inseridos apenas se não existirem ainda. Meu html:
<!DOCTYPE html>

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

Milho <input type="checkbox" class="check">

Sorgo <input type="checkbox" class="check">

Monenzina <input type="checkbox" class="check">

Calcário Calcítico <input type="checkbox" class="check">

Farelo de Soja <input type="checkbox" class="check">

Farelo de Algodão <input type="checkbox" class="check">

Aromatizante <input type="checkbox" class="check">

Farelo de Arroz <input type="checkbox" class="check">

    <button id="add-button" type="submit">Adicionar</button>

        <form id="form-receiver">
            <fieldset>

            </fieldset>
        </form>

Meu javascript:

Assim a inserção funciona perfeitamente. No entanto, é possível que campos repetidos sejam adicionados caso o usuário decida marcar mais checkboxes e clicar no botão adicionar. Devem ser adicionados somente se não existirem.
Tentei da seguinte forma:
$('#add-button').click(function(){
        $('.check').each(function(){
            if($(this).is(':checked')){
                if(!$('#form-receiver').has("input[name='" $(this).parent().text().toLowerCase() "']"){
                    $('#form-receiver fieldset').append("
" +$(this).parent().text()+ "<input name='" + $(this).parent().text().toLowerCase() + "'>
")
                }
            }
        })
    });

Mas ainda não funcionou. Alguém poderia dar uma ajudinha aqui? :D
Answer: Resolvi seu problema da seguinte forma, embora acho que de pra resolver de outra maneira.
Adicionei ao checkbox um attibuto data-add que irá garantir se o campo foi inserido ou não, ficou desta forma.
JQuery
$(function(){
    $('#add-button').click(function(){
            $('.check').each(function(){
                if($(this).is(':checked'))
                    if(!$(this).data('add')) {
                        $('#form-receiver fieldset').append("
" +$(this).parent().text()+ "<input name='" + $(this).parent().text().toLowerCase() + "'>
");
                        $(this).attr('data-add', true);
                    }
            });
        });
});

Pode acompanhar o resultado nesta DEMO
Caso não queira utilizar atributos data- pode fazer dessa maneira usando uma variável para controle do mesmo.
var checked = [];

$(function(){
    $('#add-button').click(function(){
            $('.check').each(function(index){
                if($(this).is(':checked'))
                    if(!checked[index]) {
                        $('#form-receiver fieldset').append("
" +$(this).parent().text()+ "<input name='" + $(this).parent().text().toLowerCase() + "'>
");
                        checked[index] = true;
                    }
            });
        });
});

Pode acompanhar o resultado também nesta DEMO
Comment: Disponha @PedroVinícius implemente também a solução do amigo ali referente aos nomes do campo, um grande abraço e boa sorte com os projetos.
Comment: Cara!! Valeu demais! Não tinha nem cogitado essa possibilidade! Resolveu meu problema. Muito, muito obrigado! ;-)
Answer: Eu evitaria usar nomes com espaços.
Assim sugiro uma função para fazer CamelCase fonte aqui:
function camelCase(input) {
    return input.toLowerCase().replace(/[-\s](.)/g, function (match, group1) {
        return group1.toUpperCase();
    });
}

Depois podia usar este código:
$('#add-button').click(function () {
    $('.check').each(function () {
        if (this.checked) {
            var nome = $(this).parent().text();
            if (!$('#form-receiver').find("input[name='" + camelCase(nome) + "']").length) {
                $('#form-receiver fieldset').append("
" + nome + "<input name='" + camelCase(nome) + "'>
")
            }
        }
    })
});

Exemplo: http://jsfiddle.net/ULLD9/2/
De qq maneira a unica diferença relevante entre o meu código e o seu é que eu usei
 if (!$('#form-receiver').find( .... ).length. O length é só por precaução mas o find é para procurar se existe o elemento dentro da form. Mudei também para this.checked pois não precisa de jQuery para fazer essa verificação.
Comment: @PedroVinícius, a ideia do "Camelize" é remover espaços brancos e fazer a primeira letra de cada palavra ficar em "Capital". Ou seja: `border-width` fica `borderWidth`
Comment: Muito obrigado. Sua resposta foi de grande utilidade! Poderia me explicar o que está acontecendo ali na função replace? Só mesmo pra eu saber exatamente o que estou fazendo e garantir o aprendizado :-)
Comment: Ahh sim. Obrigado! :D
Answer: Na verdade, apesar de já haverem boas resposta, o erro em sua solução e falta de concatenação no seletor de verificação:
// adicionei os operadores de concatenação de string '+'
if(!$('#form-receiver').has("input[name='" + $(this).parent().text().toLowerCase() + "']")

E também o método .has() do jQuery não retorna um boolean, e sim o resultado de uma seleção, então você teria que verificar se retornou alguém no seletor:
$('#form-receiver fieldset').has("input[name='" + $(this).parent().text().toLowerCase().trim() + "']").length == 0

E não recomendaria criar tags name com espaços em branco, eu faria um trim():
$(this).parent().text().toLowerCase().trim();

Acompanhe sua solução em funcionamento aqui.
Mas ainda assim recomendo utilizar a solução do @Diego Vieira, por ser mais limpa.
Comment: Mas o trim não remove apenas os espaços anteriores e posteriores à string?
Comment: @PedroVinícius, sim, mais havia espaços depois, os do meio nem tava citando, mas também é interessante fazer um `replace` em todos os espaços. Boa colocação.
Comment: Ahh sim. Eu nem tinha notado os espaços depois kkk
Valeu mesmo cara! Sua resposta foi muito útil!


join list with linq-to-sql query

Question: I have list of MyObject that looks like this:
public class MyObject{
  public int FruitID {get;set;}
  public string FruitName {get;set;}
}

List<MyObject> TheList = new List<MyObject>();

This list is populated with a linq-to-sql query. I'm looking to create a join between this list and a table that contains FruitID as its foreign key.
The table HarvestTimes looks like this:
FruitID   |   HarvestDatetime  |   RipeFactor
   3      |        3/4/2011    |       2
   3      |        4/5/2011    |       4
   3      |        5/5/2011    |       3
   4      |        3/21/2011   |       2
   4      |        4/10/2011   |       2
   4      |        5/10/2011   |       2

This is what I have so far:
var TheQuery = (from list in TheList
                join fruit in MyDC.HarvestTimes on
                list.FruitID equals fruit.FruitID
                where ....
                select new MyObject{... }).ToList();

I'm have some trouble with the Where clause. How do I get only the Fruit where the RipeFactor was always 2. For instance, Fruit 3 has a RipeFactor of 2 but also has 4 and whereas only Fruit4 has only 2s. I tried with Contains but both fruits come up.
Thanks for your suggestions.
Comment: Not sure if it's possible, buy try grouping by FruitID, Ripe factor, then count the number of rows on each FruitID group, if the count is 1 and Ripe factor is what you want then select it...
Comment: Is TheList filled from the same DataContext as HarvestTimes exists in?
Answer: Assuming there is a Relationship between the tables HaverstTime and Fruit:
var TheQuery = MyDC.HarvestTimes
    .Where(p => TheList.Select(q => q.FruitID).Contains(p.FruitID))
    .GroupBy(p => p.Fruit)
    .Where(p => p.All(q => q.RipeFactor == 2))
    .Select(p => p.Key);

This will create a IEnumerable<Fruit> which I think can be easily converted to MyObject.
Update:
Oops I forgot to add TheList.Select(q => q.FruitID). That's why it didn't compile.
Sorry =)
Update2:
Do the same, considering Ripefactor = 2 and 3
var TheQuery = MyDC.HarvestTimes
    .Where(p => TheList.Select(q => q.FruitID).Contains(p.FruitID))
    .GroupBy(p => p.Fruit)
    .Where(p => p.All(q => q.RipeFactor == 2 || q.RipeFactor == 3))
    .Select(p => p.Key);

Comment: Should it be .GroupBy(p => p.FruitID) ?
Comment: For some reason, the .Where(p => TheList.Contains(p.FruitID)) statement is underlined red.
Comment: It depends. I thought you wanted to select the Fruit object, not the FruitID. In that case you can do GroupBy(p => p.FruitID), it should work too.
Comment: ok, what if I want to select the RipeFactor where it's only 2 AND 3 (but never 1, 4 or any other value)?
Answer: I think this would work
var fruit = (from list in TheList
             join fruit in
               (from fr in MyDc.HarvestTimes
                group fr by fr.FruitID into fg
                where !fg.Any(f => f.RipeFactor != 2)
                select fg)
             on list.FruitID equals fruit.Key
             select new MyObject{... }).ToList();

Update - If you only want to return the distinct list of FruitIDs you need to select fg.Key instead of fg
var fruit = (from list in TheList
             join fruit in
               (from fr in MyDc.HarvestTimes
                group fr by fr.FruitID into fg
                where !fg.Any(f => f.RipeFactor != 2)
                select fg.Key)
              on list.FruitID equals fruit
              select new MyObject{... }).ToList();

Comment: Yes, that works in the sense that it only returns Fruit4. I looked at it again and then I realized that it was returning all the Fruit4 records instead of just one. I think I wasn't clear on that, my bad. Would .Single work i this case?
Comment: @frenchie - Updated the answer. Is that what you are looking for?
Comment: I'll just take the one with duplicates and delete the dups with a linq-to-object query. Thanks for your help and if you figure out why duplicates are showing then please let me know.
Comment: Quick follow-up: what if I want results where RipeFactor is only 2 AND 3? Should this do it: where !fg.Any(f => f.RipeFactor != 2 && f => f.RipeFactor != 3) ?
Comment: @frenchie - not sure why duplicates are being shown. Yes you are right

join list with linq-to-sql query


C write number digits, one by one and in extension, in a new line

Question: I'm new in C and I can't do a simple exercise for school.
I want to do something like this:
 Please insert a number: 12345
 five
 four
 three
 two
 one

Basically, the user inputs a number and them the program writes, in a new line, the number from the last significant number to the most.
This is to do with the switch function and only basic programming skills.
I have this:
#include <stdio.h>
#include <stdlib.h>

int main()
{
    int num; printf("Please insert a number: "); scanf("%d", &num);
    switch(num){
    case 1:printf("One\n");break;
    case 2:printf("Two\n");break;
    case 3:printf("Three\n");break;
    case 4:printf("Four\n");break;
    case 5:printf("Five\n");break;
    case 6:printf("Six\n");break;
    case 7:printf("Seven\n");break;
    case 8:printf("Eight\n");break;
    case 9:printf("Nine\n");break;
    case 0:printf("Zero\n");break;
    }
}

I I use a number between 0 and 9 it works ok but a number bigger then that it does not do nothing.
The first problem i cant solve is to, in a number, get the digit position.
I believe that In my code, the break isn't doing nothing...
Sorry if I can't explain me better but English is not my native language.
Regards,
Favolas

############################## In Progress Solution (does not work if number % 10 gives 0¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int num; printf("Please insert a number: "); scanf("%d", &num);
    int i,digit;
    for (i = 0; num%10!=0;i++){
        digit = num % 10;
        switch(num){
        case 1:printf("One\n");break;
        case 2:printf("Two\n");break;
        case 3:printf("Three\n");break;
        case 4:printf("Four\n");break;
        case 5:printf("Five\n");break;
        case 6:printf("Six\n");break;
        case 7:printf("Seven\n");break;
        case 8:printf("Eight\n");break;
        case 9:printf("Nine\n");break;
        case 0:printf("Zero\n");break;
        }
        num = num / 10;
    }
}

Comment: +1 for a well worded question
Comment: Your so-called solution is a wrong solution. What happens if the number is 666 or 1000?
Comment: Ok.  Found the error. Thanks. Will try to fix that
Answer: The number 123 is 100 + 20 + 3 or 1*10^2 + 2*10^1 + 3*10^0.
You need to isolate the individual digits from the input.
Hint: use the / and % operators
 12345 % 10 ==> 5
 12345 / 10 ==> 1234

 1234 % 10 ==> 4
 1234 / 10 ==> 123

 123 ... ... ...

Answer: If you enter a bigger number, num holds exactly that number, i.e. none of your cases (0 to 9) matches the value of num.
So you have to "traverse" the number digit by digit. You can extract the last digit if you take modulo 10: 12345 % 10 == 5. Moreover, you can cut off the last digit by dividing by 10: 2345 / 10 == 234 (due to integral division).
So, you have to write a loop that extract the single digits from num and then apply your case distinction for each digit.
Answer: In base 10, the number 12345 is in fact 1 * 10000 + 2 * 1000 + 3 * 100 + 4 * 10 + 5 * 1. So you can get the last digit of a number by computing the remainder of the division of the number by 10. And the dividend will be the most significant par of the number. So, '12345 = 1234 * 10 + 5. InC, the%operator is used to compute the remainder of the division, so12345 % 10is equal to5`.
Then, you just have to loop while the number is non-zero, taking the remainder at each step, displaying the digit and then dividing the number.
Answer: void main (void){
    int num;
    int factor=10;
    printf("Please insert a number: "); scanf("%d", &num);
    while(num>0){
        switch(num%factor){
            case 1:printf("One\n");break;
            case 2:printf("Two\n");break;
            case 3:printf("Three\n");break;
            case 4:printf("Four\n");break;
            case 5:printf("Five\n");break;
            case 6:printf("Six\n");break;
            case 7:printf("Seven\n");break;
            case 8:printf("Eight\n");break;
            case 9:printf("Nine\n");break;
            case 0:printf("Zero\n");break;
        }
        num=num/factor;
    }
}

Comment: As the question is tagged `Homework` please consider not giving the code out so much as providing pointers to help the questioner write the code.
Comment: By the way, what if the user enters the number `0`?
Comment: -1: If you are going to write code for homework questions, at least write good code so the student learns something even by just copying: `main` should return `int`; output is line buffered by default so you should terminate the string with a line break or `fflush(stdout);` after printing; `scanf` return value should be checked; you missed a validation for num <= 0; and there's no default case for the switch. Also you use very little whitespace.


Quais os benefícios de usar struct?

Question: Como que variáveis do tipo struct ficam alocadas na memória, por exemplo:
struct livro{
char autor[10];
float preco;
};

//como essas variaveis fica alocado na memória?
struct livro livro1;
strcpy(livro1.autor, "Deitel");
livro1.idade = 320.25;

Aliás, o conceito de struct é muito semelhante a orientação a objetos, ou é impressão minha?
O que acontece dentro da memória ao usar struct?
Comment: Struct e class são essencialmente a mesma coisa mudando apenas o nível de acessibilidade padrão dos membros. Struct tem como padrão public, class é private.
Comment: É [isso](https://pt.stackoverflow.com/q/16181/112052)? Sugiro que veja [aqui](https://pt.stackoverflow.com/search?q=diferen%C3%A7a+struct+class) também, tem bastante coisa sobre o assunto...
Comment: Alguma das respostas resolveu sua dúvida? Acha que pode aceitar uma delas? Veja o [tour] como fazer isso, se ainda não o fez. Você ajudaria a comunidade identificando qual foi a melhor solução para você. Pode aceitar apenas uma delas. Mas pode votar em qualquer pergunta ou resposta que achar útil no site todo.
Answer: Toda vez que quiser manter organizado dados diversos, provavelmente de tipos heterogêneos, agrupados de forma lógica como uma coisa só ela é útil. Existem casos que até um dado pode ser útil fazer assim como uma abstração.
Quando você declara uma struct está apenas mapeando como esses dados estão configurados na memória e você poderá acessar cada dado individual através dos nomes de seus membros. Ela só existe no código, durante a execução não existe nada que indique que aquilo é uma struct, apenas tem dados, um atrás do outro.
Se acha que isto é semelhante a orientação a objetos é porque não tem ideia do que é orientação a objetos. Mas não se preocupe, quase todo mundo programa assim, ou pensa que programa e também não sabe o que é. Juntar dados em uma estrutura única nunca foi orientação a objetos, mas realmente muitas pessoas acham que é isto. E ainda ela usa a notação de objeto (substantivo, ponto, adjetivo), aí confunde mais ainda.
De fato quando cria uma struct está criando um modelo de como um objeto será composto, assim como um int é um objeto composto por bits de uma certa forma que representa um número inteiro e tem um único membro acessado de forma direta para facilitar, ou seja, objeto sempre existiu em tudo e as pessoas acham que objeto é algo ligado à uma classe, não é, isto é um conceito universal independente de paradigma. Já respondi sobre isso em Em programação, o que é um objeto?.
O resto eu já respondi em Como uma "struct" é organizada na memória?.
Answer: Respondendo sua pergunta de uma maneira mais empírica, podemos recorrer ao utilitário objdump.  Usando sua struct como exemplo e compilando com a flag "-g" para fornecer informações de debug, obtemos:
<1><2e2>: número abbrev: 8 (DW_TAG_structure_type)
    <2e3>   DW_AT_name        : (cadeia indirecta, desvio: 0xed): livro
    <2e7>   DW_AT_byte_size   : 16
    <2e8>   DW_AT_decl_file   : 1
    <2e9>   DW_AT_decl_line   : 4
    <2ea>   DW_AT_decl_column : 8
    <2eb>   DW_AT_sibling     : <0x30a>
 <2><2ef>: número abbrev: 9 (DW_TAG_member)
    <2f0>   DW_AT_name        : (cadeia indirecta, desvio: 0x18): autor
    <2f4>   DW_AT_decl_file   : 1
    <2f5>   DW_AT_decl_line   : 5
    <2f6>   DW_AT_decl_column : 6
    <2f7>   DW_AT_type        : <0x30a>
    <2fb>   DW_AT_data_member_location: 0
 <2><2fc>: número abbrev: 9 (DW_TAG_member)
    <2fd>   DW_AT_name        : (cadeia indirecta, desvio: 0xda): preco
    <301>   DW_AT_decl_file   : 1
    <302>   DW_AT_decl_line   : 6
    <303>   DW_AT_decl_column : 7
    <304>   DW_AT_type        : <0x31a>
    <308>   DW_AT_data_member_location: 12

Os parâmetros mais relevantes acima evidenciam as seguintes informações:

DW_TAG_structure_type, DW_TAG_member e DW_AT_name evidenciam os tipos das informações que estão sendo tratadas, sendo as mesmas a própria struct, seus campos e nomes respectivamente.
DW_AT_byte_size: Fornece o número em bytes usados pela struct.
DW_AT_data_member_location: Fornece a posição em bytes onde os dados de um campo se localizam. Aqui fica evidenciado o fenômeno de "padding" (bytes inseridos no meio do caminho) para alinhar os campos.

Quais os benefícios de usar struct?


Symfony2 redirect to an externel url in new tab

Question: I have a function that redirect to an external URL with parametre, but I want to redirect it to a new tab ,
This my code
<code> public function urlAction(){

    $directory= $user->getDirectory();
           return $this->redirect('http://localhost/sound/index.html?directory='.$directory );

}
</code>
I want to open the link in new tab. any suggestion please?
Comment: Use `target="blank"` on a link. There is no such thing as "redirecting into a new tab/window".
Comment: AFAIK, the user decides whether he wants to open a link in a tab. Just like I CTRL+clicked this question to open it in a separate tab.
Comment: `target site`
Comment: @PietervandenHam I'm not sure how many common users even know that key combination
Answer: The only answer possible here is that you can't redirect in a new tab.
You can provide links that open in a new tab or window using the target in html or a function in php, but you can't have a redirect.


Where can I find the source for springloaded-core jar?

Question: I can't seem to find this anywhere and am assuming that this jar is built as part of something else. Anyone know where I can get the source? I am using version 1.0.2.
Comment: Interesting. It's mentioned a few places but springsource and grails don't seem to have the source anywhere public. If you just want one or two classes you could try decompiling them with Jad or something similar.
Answer: I found it on GitHub here....
https://github.com/SpringSource/spring-loaded


How do I programmatically set the view title?

Question: In D8, I have a need to dynamically set the title of a views page display.
I've tried implementing both hook_views_pre_render and hook_views_post_build and setting the value of $view->build_info['title'], but Drupal seems to be ignoring it when setting the page title.
It seems like the code in Views where the title is set is in Drupal\views\Plugin\views\display\Page::execute()
The #title property on the render array in that method IS receiving my overwritten value from one of my hooks, but it's still ignore and is using the manually specified title on the display config.
What is going on!?
Comment: What is going on!? The title is set in the route definition. See http://drupal.stackexchange.com/questions/224217/change-view-title-programmatically
Comment: Do you have the [metatag](https://www.drupal.org/project/metatag) module enabled? It is still missing Views integration (https://www.drupal.org/node/2563647) so perhaps it overrides your title with the global default?
Comment: I do, but if that were the case, then specific views title I specify in the views config would not work either, but it does.
Comment: Is this view using a custom template file?
Answer: If someone else is looking for an answer, this is how I achieved this.
I implemented hook_views_pre_render() where I called ViewExecutable::setTitle(). This allowed me to set the page title.
function MYMODULE_views_pre_render(ViewExecutable $view) {
  if ($view->id() == 'ABC') {
    $view->setTitle('MY CUSTOM TITLE');
  }
}

Comment: Just to appreciate you that this answer worked.
Comment: This will only change the title on the page (i.e. h1) and not the title in the head of the document (i.e Please work!).
Comment: @serverjohn this somehow changed. Working for me in 9.4.7.
Answer: If you want to change page title too you can use this snippet
\Drupal::routeMatch()->getRouteObject()->setDefault('_title', $title);

Hope this helps.
Comment: This no longer works. :-(
Comment: This works, but you also have to override the `_title_callback` to keep your changes, see below
Comment: `$route->setDefault('_title_callback', NULL);`
Comment: There is no need to edit an existing answer to repeat what another answer already said. If you want the other answer to be on top (which helps only with the default sorting), give to the other answer enough votes.
Answer: Setting only the _title property to set the page title tag was not enough in my case.
Overriding the title_callback property did the trick :-)
$title = 'something';
$route = \Drupal::routeMatch()->getCurrentRouteMatch()->getRouteObject();
$route->setDefault('_title_callback', function() use ($title) {
  return $title;
});

Comment: Did not work. D9.4.5
Answer: Implemented using hook_views_post_render(). In this example the contextual filter is just added to the title.
/**
 * Implements hook_views_post_render().
 */
function THEME_views_post_render(&$view) {
    /** @var \Drupal\views\ViewExecutable $view */
    if ($view->id() === 'events' && isset($view->args[0])) {
        // Get year from contextual argument of the view.
        $year = $view->args[0];

        // Prefix year to title.
        $title = (string) t('@year Events', ['@year' => $year]);

        // Set view and page titles.
        $view->setTitle($title);
        \Drupal::routeMatch()->getRouteObject()->setDefault(
            '_title',
            $title
        );
    }
}


Finding alternate transformation matrix for similarity transformation

Question: A pair of square matrices $X$ and $Y$ are called similar if there exists a nonsingular matrix $T$ such that $T^{-1}XT=Y$ holds. It is known that the transformation matrix $T$ is not unique for given $X$ and $Y$. I'm just wondering whether those non-unique transformation matrices would have any relation among themselves, like having column vectors with same directions...
What I want to mean is: Given $X$ and $Y$ a pair of similar matrices, if $S$ and $T$ are two possible transformation matrices satisfying $S^{-1}XS = T^{-1}XT = Y$, is there any generic (apart from scaling) relation between $T$ and $S$ (e.g., direction of column vectors)?
For a specific example, consider $X = \begin{bmatrix} A & BK\\ C & 0 \end{bmatrix}$ and $Y = \begin{bmatrix} A+A^{-1}BKC & -A^{-1}BKCA^{-1}B\\ KC & -KCA^{-1}B \end{bmatrix}$. Assuming $K$ to be invertible it can be shown that $X$ and $Y$ are similar with transformation matrix $T = \begin{bmatrix} I & -A^{-1}B\\ 0 & K^{-1} \end{bmatrix}$. Can there be any other matrix $S$ which will be independent of $K$, and would result $S^{-1}XS=Y$?
Answer: You can always use $S=\alpha\,T$ with $\alpha$ some non-zero scalar not equal to one. Another way of finding more solutions is by using the Kronecker product, which allows you to write the transformation as
\begin{align}
X\,T &= T\,Y \\
(I \otimes X)\,\text{vec}\,T &=
(Y^\top \otimes I)\,\text{vec}\,T \\
(I \otimes X - Y^\top \otimes I)\,\text{vec}\,T &= 0
\end{align}
Using any (non-zero) vector which lies in the null space of $I \otimes X - Y^\top \otimes I$ for $\text{vec}\,T$ will satisfy the equation (however I am not sure if every $T$ would be invertible). If the dimension of the null space is one then you can only do the scalar multiplication. If the dimension is bigger then one you can also take a linear combinations of linear independent solutions (this both holds for $\text{vec}\,T$ and $T$, since the vectorization transformation and its inverse are also linear).
Comment: Apart from the trivial case of scaling by nonzero scalars, can we have any relation between the different transformation matrices? Can you please address it in terms of the example I've given in the question?
Comment: @neelarnab I suspect that you will have multiple solutions if $X$ and $Y$ have repeated eigenvalues/Jordan blocks.
Comment: are you saying that it would be a necessary condition for having multiple transformation matrices (excluding the scaling)?
Given a transformation matrix $X$, can we then find an alternate transformation matrix $Y$, like in the case of the mentioned example?
Comment: @neelarnab I did some testing and it seems that when $X,Y,T\in\mathbb{R}^{n \times n}$ you always seem to have that the dimension of the null space is equal or greater then $n$. But I haven't found an intuitive explanation for this.


name is not defined - nome/variavel não definida, tkinter e slite3 help

Question: estou começando a estudar sqlite3 na marra, e esta sendo difícil, mas já consegui algumas coisa, o problema é que na hora de compilar o programa aparece o seguinte erro:
"name 'adic' is not defined".

Segue o código:
from tkinter import*
import sqlite3

class Principal:
    def __init__(self):
        janela_principal = Tk()
        janela_principal.geometry("400x400+50+50")
        #janela_principal.overrideredirect(True)

        lb0 = Label(janela_principal)
        lb0.grid(row=0, column=0, padx=13)

        lb1 = Label(janela_principal, text="Digite um número:")
        lb1.grid(row=1, column=1, sticky=E)
        digite_numero = Entry(janela_principal, width=35)
        digite_numero.grid(row=1, column=2, sticky=W)
        separador = Frame(janela_principal, height=2, bd=3, relief=SUNKEN, width=340)
        separador.grid(row=2, column=1, columnspan=2)

        lb2 = Label(janela_principal, text="Assunto:")
        lb2.grid(row=3, column=1, sticky=E)
        digite_assunto = Entry(janela_principal, width=35)
        digite_assunto.grid(row=3, column=2, sticky=W)

        separador = Frame(janela_principal, height=2, bd=3, relief=SUNKEN, width=340)
        separador.grid(row=4, column=1, columnspan=2)

        add = Button(janela_principal, text="ADICIONAR NOME", relief=SOLID, border=1, foreground="BLUE", command=adic)
        add.grid(row=5, column=2, columnspan=2, sticky=W)
        apagar = Button(janela_principal, text="APAGAR NOME", relief=SOLID, border=1, foreground="RED", command=apag)
        apagar.grid(row=5, column=2, sticky=E)

        lb3 = Label(janela_principal)
        lb3.grid(row=6, column=0)

        rolagem = Scrollbar(janela_principal)
        rolagem.grid(row=7, column=2, sticky=N+S+E)

        caixa_exibição = Listbox(janela_principal, relief=SOLID, border=1, width=45, height=15, font=("Gentium Basic", 11))
        caixa_exibição.grid(row=7, column=1, columnspan=2, sticky=W)

        #for i in range(100):
        #    caixa_exibição.insert(END, i)

        # attach listbox to scrollbar
        caixa_exibição.config(yscrollcommand=rolagem.set)
        rolagem.config(command=caixa_exibição.yview)

        #Banco
        conectar = sqlite3.connect("numeros.db")
        cursor = conectar.cursor()
        cursor.execute("CREATE TABLE IF NOT EXISTS nomes(numeros TEXT, assunto TEXT)")
        conectar.commit()
        lista = cursor.execute("SELECT * FROM nomes")
        for i in lista:
            caixa_exibição.insert(END, i)

    def adic():
        numerosx = digite_numero.get()
        assuntox = digite_assunto.get()
        cursor.execute("INSERT INTO nomes values(?, ?)", (numerosx, assuntox))
        conectar.commit()
        caixa_exibição.insert(END, numerosx)
        caixa_exibição.insert(END, assuntox)

    def apag():
        numerosy = str(caixa_exibição.get(ACTIVE))[3:-3]
        assuntoy = str(caixa_exibição.get(ACTIVE))[3:-3]

        cursor.execute("DELETE FROM nomes WHERE name=?, ?", (numerosy, assuntoy))
        conectar.commit()
        caixa_exibição.delete(ANCHOR)

        janela_principal.mainloop()

Principal()

Comment: Seu código está bastante confuso: as funções `adic` e `apag` estão indentada, como se fossem métodos da classe `Principal`, mas foram definidas como funções, sem o parâmetro `self`. Elas deveriam ser métodos da instância, métodos da classe ou funções fora da classe? Além disso, dentro da função `adic` você utiliza o objeto `digite_numero` que foi definido em `__init__` e, portanto, não existe dentro desta função. Este objeto deveria ser um campo de instância? Perceba que isso nem tem relação com o SQLite ainda.
Comment: como assim? Você pode me dar um exemplo?
Answer: Nesse caso é bem simples: você está fazendo uma classe, não com funções soltas - então ao declarar o command=..., em vez de command=adic, você deve usar command=self.adic.
E, claro, já que são métodos, coloque o parâemtro self na definição delas.
Se quiser usar só como função, tudo bem - nesse caso é só retira-las do corpo da classe (identando-as na coluna zero), aí não precisa do self.adic nem do parâmetro self, mas aí você também não tem como compartilhar variáveis entre as suas funções.
A vantagem de fazer tudo como classe (sem herdar de nenhuma classe do tkinter, exatamente como está no seu código), é que você pode definir  variáveis no __init__  que serão atributos da classe - então, a sua função adic precisa acessar a caixa_exibicao por exemplo - ela pode fazer isso, se  tanto no __init__ quanto no método você sempre usar self.caixa_exibicao. Acrescente  o self. em todas as variáveis que precisar acessar de todas as funções do seu código.
(o self. vale para o cursor e todas as outras variáveis que você compartilha, claro).
Comment: jsbueno Meu Muito obrigado pelo excelente explicação, desejo sucesso na sua carreira, valeu.
Answer: Por indicações de profissionais, indico sempre definir os métodos antes do resto do programa (embora não seja necessário, faça como quiser).
Por estar utilizando classes, é necessário utilizar self. para poder acessar as variáveis dentro da classe, por esse motivo "adic" aparecia como "não definido", pois estava fora de seu escopo.
Segue o código mostrando algumas aplicações nesse sentido, não é necessariamente obrigatório utilizar tudo como utilizei:
from tkinter import*
import sqlite3

class Principal:
    def adic(self): #Métodos antes, com o paramentro self para receber variáveis do __init__
        numerosx = self.digite_numero.get() #Por ser uma variável utilizada apenas dentro dessa função, não existe a necessidade do self.
        assuntox = self.digite_assunto.get()
        self.cursor.execute("INSERT INTO nomes values(?, ?)", (numerosx, assuntox)) #Cursor é uma variável do método __init__, por esse motivo, precisamos utilizar self. para acessá-la
        self.conectar.commit()
        self.caixa_exibição.insert(END, numerosx+" "+assuntox) #Aqui você irá inserir: 'numerox assuntox', do modo como estava fazendo, você inseria um por vez, fazendo com que um ficasse abaixo do outro
        #self.caixa_exibição.insert(END, assuntox)

    def apag(self):
        selecionada = str(self.caixa_exibição.get(ACTIVE)).replace('(','').replace(')','').replace("'","").split(',') #Coleta a linha selecionada, e por ser uma string, eu faço o tratamento da linha, removendo varias coisas como "(')". Além disso, estou fazendo um array, separando os elementos por ",".
        try:
            self.numerosy = selecionada[0]
            self.assuntoy = selecionada[1][1:]
        except:
            selecionada = str(self.caixa_exibição.get(ACTIVE)).split(" ")
            self.numerosy = selecionada[0]
            self.assuntoy = selecionada[1]

        self.cursor.execute("DELETE FROM nomes WHERE numeros='"+self.numerosy+"' AND assunto = '"+self.assuntoy+"'") #Corrigi a Query
        self.conectar.commit()
        self.caixa_exibição.delete(ANCHOR)
    def __init__(self):
        janela_principal = Tk()
        janela_principal.geometry("400x400+50+50")
        #janela_principal.overrideredirect(True)

        lb0 = Label(janela_principal)
        lb0.grid(row=0, column=0, padx=13)

        lb1 = Label(janela_principal, text="Digite um número:")
        lb1.grid(row=1, column=1, sticky=E)
        self.digite_numero = Entry(janela_principal, width=35)
        self.digite_numero.grid(row=1, column=2, sticky=W)
        separador = Frame(janela_principal, height=2, bd=3, relief=SUNKEN, width=340)
        separador.grid(row=2, column=1, columnspan=2)

        lb2 = Label(janela_principal, text="Assunto:")
        lb2.grid(row=3, column=1, sticky=E)
        self.digite_assunto = Entry(janela_principal, width=35) #Usar self. para tornar a variável acessível
        self.digite_assunto.grid(row=3, column=2, sticky=W)

        separador = Frame(janela_principal, height=2, bd=3, relief=SUNKEN, width=340)
        separador.grid(row=4, column=1, columnspan=2)

        add = Button(janela_principal, text="ADICIONAR NOME", relief=SOLID, border=1, foreground="BLUE", command=self.adic)
        add.grid(row=5, column=2, columnspan=2, sticky=W)
        apagar = Button(janela_principal, text="APAGAR NOME", relief=SOLID, border=1, foreground="RED", command=self.apag)
        apagar.grid(row=5, column=2, sticky=E)

        lb3 = Label(janela_principal)
        lb3.grid(row=6, column=0)

        rolagem = Scrollbar(janela_principal)
        rolagem.grid(row=7, column=2, sticky=N+S+E)

        self.caixa_exibição = Listbox(janela_principal, relief=SOLID, border=1, width=45, height=15, font=("Gentium Basic", 11))
        self.caixa_exibição.grid(row=7, column=1, columnspan=2, sticky=W)

        #for i in range(100):
        #    caixa_exibição.insert(END, i)

        # attach listbox to scrollbar
        self.caixa_exibição.config(yscrollcommand=rolagem.set)
        rolagem.config(command=self.caixa_exibição.yview)

        #Banco
        self.conectar = sqlite3.connect("numeros.db")
        self.cursor = self.conectar.cursor()
        self.cursor.execute("CREATE TABLE IF NOT EXISTS nomes(numeros TEXT, assunto TEXT)")
        self.conectar.commit()
        self.lista = self.cursor.execute("SELECT * FROM nomes")
        for i in self.lista:
            self.caixa_exibição.insert(END, i)

        janela_principal.mainloop()

Principal()

Comment: Um detalhe: a ordem que é definido os métodos não importa, então não fará diferença definir `adic` antes de `__init__`.
Comment: eu ficaria mais confortável, se você não conhece bem a linguagem, que testasse o que fez, antes de responder com um código de mais de 30, 40 linhas feito no chute.
Comment: "Por indicações de profissionais, indico sempre definir os métodos antes do resto do programa " aqui você tem um outro profissional **não indicando** isso. Em Python, a recomendação é definir o `__init__` antes dos outros métodos.
Comment: @NathanSchroeder Cara muito obrigado, eu consegui concluir meu projeto. Daqui a um tempo vou fazer um projeto maior, espero que na próxima se eu ficar com alguma dúvida você possa me ajudar de novo. :D, Thank You Man
Comment: @NathanSchroeder desculpa ser chato, mas preciso de um detalhe. É porque vou fazer algo maior depois, então preciso saber pelo menos a base, vamos lá. Quando adicionamos o item na linha e excluir está tudo ok, do jeito que eu queria, só que depois que o item é salvo, e o programa é executado pela segunda vez a coluna 1 e 2 vem com chaves, por exemplo:
'{ 1819 - P1/2018} {Informação}', respectivamente colunas 1 e 2, ambas com { }, como faço para consertar isso?
Comment: @VictorS' Se você inserir '1' e 'teste' isso não acontece, se você apenas apertar adicionar, com os campos vazios, isso acontece, creio que sejam caracteres em que o DB não leia corretamente, creio que você deva dar uma pesquisada sobre isso.
Comment: Mais uma vez obrigado @NathanSchroeder


Algebraic structures with one binary operation

Question: I need your help.I am studying about algebraic structures.I have a question that I can't solve ..
Let $G=\langle A,*\rangle$ be a monoid with the identity $e$. Let $a\in A$.
İs it possible that $a$ has two different left-inverses, $L_1$ and $L_2$?
Thank you very much for your answers.
Answer: Hint: For an example of such a thing consider the monoid of set maps $\mathbb{N \to N}$ with composition as the operation.  A function has a left-inverse if and only if it's injective, so pick an injective map (for example $x \mapsto 2x$) and try and find two different left-inverses.
Comment: thanks Jim for help.
Answer: Yes, it certainly is possible.  For example, if $X$ is any set, the set of functions $A=\{f:X\to X\}$ form a monoid under composition.  If $f\in A$ is injective but not surjective, then $f$ always has more than one left inverse.  This is because a left inverse $g$ can do anything it wants with the elements that are not in the image of $f$.
In particular, let $X$ be the integers, $X=\mathbb Z$, and consider the function $f:\mathbb Z\to\mathbb Z$ that is multiplication by 2.  Two natural choices for a left inverse of $f$ are "divide by two and then round down" or "divide by two and then round towards 0."  These will behave differently on negative numbers, but they are both left inverses of $f$.
Comment: thank you very much SMoore


Laravel-mix - BrowserSync throwing an error at event.js:160

Question: Not sure if the problem is related to laravel-mix, but I am having problem with Browsersync package. Here is my mix.js:
mix.js('resources/assets/js/app.js', 'public/js')
.browserSync({proxy: 'localhost:8000'})
.sass('resources/assets/sass/app.scss', 'public/css');

When I run npm run watch-poll ( watch doesn't pick up the changes, hence the watch-poll see here ) I get the following error on the console:
[Browsersync] Watching files...
events.js:160
      throw er; // Unhandled 'error' event
      ^

Error: watch resources/views/auth/passwords ENOSPC
    at exports._errnoException (util.js:1020:11)
    at FSWatcher.start (fs.js:1443:19)
    at Object.fs.watch (fs.js:1470:11)
    at createFsWatchInstance (/home/tanmay/LVProjects/learningdemo/node_modules/chokidar/lib/nodefs-handler.js:37:15)
    at setFsWatchListener (/home/tanmay/LVProjects/learningdemo/node_modules/chokidar/lib/nodefs-handler.js:80:15)
    at FSWatcher.NodeFsHandler._watchWithNodeFs (/home/tanmay/LVProjects/learningdemo/node_modules/chokidar/lib/nodefs-handler.js:228:14)
    at FSWatcher.NodeFsHandler._handleDir (/home/tanmay/LVProjects/learningdemo/node_modules/chokidar/lib/nodefs-handler.js:407:19)
    at FSWatcher.<anonymous> (/home/tanmay/LVProjects/learningdemo/node_modules/chokidar/lib/nodefs-handler.js:455:19)
    at FSWatcher.<anonymous> (/home/tanmay/LVProjects/learningdemo/node_modules/chokidar/lib/nodefs-handler.js:460:16)
    at FSReqWrap.oncomplete (fs.js:123:15)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! @ watch: `cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --watch --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js "--watch-poll"`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the @ watch script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/tanmay/.npm/_logs/2017-08-07T07_02_31_677Z-debug.log
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! @ watch-poll: `npm run watch -- --watch-poll`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the @ watch-poll script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/tanmay/.npm/_logs/2017-08-07T07_02_31_725Z-debug.log

I am on: Ubuntu 16.04.3 (Not a VM). Running: Nodejs v6.11.2, NPM v5.3.0
When I comment out the .browserSync() call from my mix.js:
mix.js('resources/assets/js/app.js', 'public/js')
   // .browserSync({proxy: 'localhost:8000'})
   .sass('resources/assets/sass/app.scss', 'public/css');

however, the error no longer persists. How do I get around the problem? Please feel free to ask any other necessary information.
Here is my package.json file
UPDATE: This error doesn't occur on a new laravel project. To get the same result as a new project, this is what I did:
I removed the node modules: rm -rf node_modules I removed the package-lock.json file: rm package-lock.json I re-run: npm install, npm run dev, npm run watch-poll
Result: still same error :(
Comment: Same error here; just a quick question you say in your update "This error doesn't occur on a new laravel project", but you end the statement with "Result: still same error :(" !? Do you mean no error with these steps in a new project, but still in your existing one? Thanks
Comment: @retrovertigo No error in a new project "if" I run `sudo npm run watch` instead of `npm run watch`. And as you can probably guess, after 4 months of this post, I have again encountered this issue on a new machine. I am really depressed with this issue.
Comment: A solution that works for me is switching to "watch-poll" instead of "watch"
Comment: I use `laravel-mix` with `4.0.7` version. I just remove `node_modules`, then `npm install` and all is ok. I saw so many variants of this error and there is no universal solution.
Answer: This might be due to another task running on port 4040 already.
You can try killall -9 node
Source/more details: https://github.com/parse-community/parse-dashboard/issues/401#issuecomment-224007436
Comment: `node: no process found`
Answer: I suspect it's the same problem that is shown & with working solution from Gulp Error: watch ENOSPC

Try this: Why this issue occured? There is the limit in the number of
  files that can be watched in a system. We have to increase this
  number. The below command can be used to increase this number.

$ echo fs.inotify.max_user_watches=582222 | sudo tee -a /etc/sysctl.conf && sudo sysctl -p


Best storage engine for high volume, static analytics data

Question: I'm building an application that requires storage and querying of very large amount of timestamped data. Specifically, this is analytics type data whereby a particular "set" can contain up to 100 separate data points tied together via a shared timestamp. This data is static, in that it will never change once stored but may be queried multiple times before it is expunged from the database (we currently only store 12 weeks of data).
At the moment, we're storing this data within MySQL with several tables of around 100 million rows each (we add roughly 3 million rows daily). This is fine when storing and querying the data only by timestamp, but it becomes tedious when performing SELECTs with sorts and especially when trying to remove old stale data from the tables. A DELETE query using for example WHERE timestamp < $12weeksago often takes several hours to complete.
We would also like to keep some of the data beyond the 12 week period, which adds another WHERE clause to the DELETE against another column. This slows things up further.
What storage engine would you recommend based on this use case, bearing in mind the high volume of reads/writes and querying needs?
Answer: It all depends on the kind of selects that you do. If a NoSQL database can do it than that might be your best guess.
However, I think you can probably improve your performance a lot by partitioning the database. Since it's already time based you can easily create a partition per day/week/month, that way you only have to query the tables that are relevant for your current query. And deleting old data is a simple drop table instead of a slow delete.
Answer: Try Redis or MongoDB. They were both designed for this sort of use case.


Digital home organ bass resonance

Question: I got a home organ in my living room, and I get a lot of bass resonance. I'm looking for easiest ways how to get rid of these. The room is 350x590cm and 260cm high, the organ stands in the corner, about 8cm from each wall.
Experimentally, the most noticable resonance seems to be vertical and in the range low G--low B on 16' ranks.
I would of course prefer something effective that can be hid behind the organ, if possible, but I understand that this can be difficult. Second reasonable option is arranging some (book)shelves above the organ, if this helped, but I have no idea how effective this could be.
Comment: What frequency range (in Hz) is low G to low B? A bookshelf or a thin wall ornament isn't going to absorb much bass frequency; but a strategically placed wardrobe or cupboard full of blankets or towels might. Look up "bass traps", and how they are placed in home studios (in the corners mostly).
Comment: Polystyrene will be much too lightweight for bass frequencies. You're probably better off using (closed) bags of sand. Even then, the location of the traps is crucial; putting them in the wrong spot may lead to them having no effect at all. You'll have to experiment with objects that are both heavy and slightly malleable, like sand, rubber, vinyl, dense rockwool... A large plant pot may work (the earth in the pot, not the plant itself). Rigid objects or lightweight heat insulation materials won't work.
Comment: @YourUncleBob That would be 42Hz (704cm) to 62Hz (560cm). Thanks for bass traps tip, but the thing is, I don't want my living room spoiled by these things all around the place, obviously :)
Comment: Those low frequencies will be very tough to do anything about, especially if it has to fit in visually in a living room. There's a reason why bass traps are so big, and that's because you need a lot of mass to absorb low frequency energy. You may have to look at removing some of the low end at the source, by adding some sort of equalisation or filtering or using smaller speakers.
Comment: @YourUncleBob I realize this is a tough job. Fortunately the volume of specific "pipes" (specific keys in a specific register) can be modified, so this is an option. Still, I would prefer to do as much as possible to kill the resonance. I consider trying to dump the polystyrene parcel fillers behind the organ as the mass that can be put there is actually quite large; however, I have no idea how efficient that would be.
Answer: Your basic problem is that you have a sound source in one corner of what looks like a box-shaped room. That in itself will boost the sound output at low frequencies, by reflecting the sound coming from the back of the instrument into the room.
If the organ amplifier has some type of "tone control" or "equalizer," simply reducing the bass response may fix the problem. The picture looks like a Johannus organ, so you probably already have a separate amplifier and speaker channel for the pedals. You may be able to adjust the balance between the divisions, or route the pedal to an external speaker somewhere else in the room which avoids the resonance problems. In a fairly small room the bass sound will be almost completely non-directional, so the speaker could be positioned  anywhere to minimize problems with the room acoustics.
The walls and floor are effectively forming a "corner cube" reflector which will return sound waves approaching from any angle back in the exact opposite direction. That is very desirable property of a corner cube if you are putting a radar reflector on a small boat for example, but not if you want good room acoustics.
Assuming the other walls are similar to the one in the picture (i.e. flat and reflecting sound well) you are probably creating a standing wave as the sound is reflected back and forth between the parallel walls.
The most effective solution would be relocate the organ somewhere in the middle of the room, but that might not be practical. If you can turn it through an angle of say 30 degrees from the wall while keeping it in the corner, that might help. You may have to move the yellow seat slightly out of the way, but not by much.
Another line of attack is to damp out the reflections. Covering the opposite wall with something that absorbs sound, like a decorative curtain, will help. A cheap way to experiment with that idea is to "borrow" a duvet from your bedroom and see how much effect it has held up against the wall. An open door is also a good way to avoid reflected sound by removing it from the room completely, if the layout of the house is suitable.
Breaking up the reflective surface with bookshelves or something similar will also help, but they will be most effective on the opposite wall, not behind the organ. The idea is not so much that the books and shelves will absorb the sound, but that the irregular surface of different sized books(or any other objects that you might want to display on shelves) will disrupt the standing wave between the two parallel walls.
If you are in a house, a really radical solution (which has been built, and does work!) would be to move the pedal speaker out of the room completely, and install a speaker in the roof space above stair well, using the whole ceiling as an "infinite baffle". This doesn't involve designing a speaker cabinet - you literally just have a speaker with the cone facing downwards and the back open into the roof space, with a lightweight dust shield protecting the back of the speaker from dirt falling onto it. If there is a removable panel in the ceiling to allow access into the roof space, that can be used to mount the speaker cone without any structural alterations to the building.
The speaker will then be operating into an air column about 16 feet long from the top of the stair well to ground level, which is of course the same length as the longest open organ pipe of 16' pitch. A surprisingly low power amplifier (only a few watts) will be enough to produce a very smooth bass response through the entire house, if the other residents apart from the organist don't have any objections!
Comment: Hello and thanks. Just couple things: Note that there is no "pedal speaker" for the organ, the built-in speakers (placed below the manuals, close to the organist's knees) deliver way enough power to make the organ loud. Also note that this is an appartment house, so there is nothing like roofs and stuff. The idea with bookshelves on the opposite wall is interesting; there is one just now, but I plan an upgrade, so I hope it will help. Relocating the organ is really the least thing I'd like to do. Well, I'll try couple things and see what works, and I'll return here to report :) Thanks again!

Digital home organ bass resonance


Continuous downvote on some questions at a time

Question: Yesterday I found the reputation changed on my account.
I checked in the reputation bar. Then I found that my questions got downvotes at a seconds gap.
https://magento.stackexchange.com/users/33000/teja-bhagavan-kollepara?tab=reputation
Comment: someone has some issue with you then
Comment: Contact the mods, on other SE sites they tend to reverse these things, as it tends to be against the rules.
Comment: @Teja Bhagavan Kollepara, we are looking this downvotes and will get back to you.
Comment: @AmitBera, Hi, Okay sure please check thanks
Comment: @MarshallTigerus, Hello dear. Thanks for the followup. One of the moderator responded.
Answer: Teja, we have checked the activity on your account, we don't find enough proof of targetting down votes over your account and also, does not find this type of downvote activity over your account at past also. So, we don't take any action right now.
But, We still observing over your account and will take the right action, if anything comes at rader.
Comment: I also checked the same thing and can confirm that I came up with the same result.
Comment: Yeah Okay, thanks for the update. #Amit and @Marius


hook_library: if two libraries share common file, might this cause files to get loaded in wrong order?

Question: I am using hook_library to define two libraries:

mymodule_views_plugin_style_library
mymodule_views_plugin_row_library

The "style" library gets loaded in my custom style template:  drupal_add_library('mymodule', 'mymodule_views_plugin_style_library')
The "row" library gets loaded in my custom row template:  drupal_add_library('mymodule', 'mymodule_views_plugin_row_library')
Each library contains 3 javascript files, which must be added in the specified order.
The style library contains these 3 files:

mymodule_views_lib.js
mymodule_views_style1.js
mymodule_views_style2.js

The row library contains these 3 files.

mymodule_views_lib.js
mymodule_views_row1.js
mymodule_views_row2.js

Note that both the "style" and "row" library have a file in common (mymodule_views_lib.js) and that this file needs to load first.
Here is my hook_library code:
function mymodule_library() {
  $path = drupal_get_path('module', 'mymodule');
  $libraries = array(
    'my_views_plugin_style_library' => array(
      'js' => array(
        $path . '/mymodule_views_lib.js' => array('group' => JS_LIBRARY),
        $path . '/mymodule_views_style1.js' => array('group' => JS_LIBRARY),
        $path . '/mymodule_views_style2.js' => array('group' => JS_LIBRARY),
      )
    ),
    'my_views_plugin_row_library' => array(
      'js' => array(
        $path . '/mymodule_views_lib.js' => array('group' => JS_LIBRARY),
        $path . '/mymodule_views_row1.js' => array('group' => JS_LIBRARY),
        $path . '/mymodule_views_row2.js' => array('group' => JS_LIBRARY),
      )
    ),
  );
  return $libraries;
}

My problem:
The file mymodule_views_lib.js does not load before mymodule_views_row1.js.  It does not load until the "style" library (which happens to load after the "row" library) is loaded.
Question #1:
I see here that there is a solution to my problem:  I can create a separate library for the common js file, and then add this library as a dependency.  I am wondering, though, whether this is the only solution.  Is it possible to specify the relative load order when two different libraries share a common file?
Question #2:
Assuming my libraries do not share any js files, is it safe to assume that the library files will be loaded in the same order in which they are listed, in hook_library?  Or must I explicitly specify a weight?
UPDATE
I added a weight to each js file, as suggested by tenken below, and that solved the problem.  The javascript files now load in the desired order:
   function mymodule_library() {
      $path = drupal_get_path('module', 'mymodule');
      $libraries = array(
        'my_views_plugin_style_library' => array(
          'js' => array(
            $path . '/mymodule_views_lib.js' => array('group' => JS_LIBRARY, 'weight'=>1),
            $path . '/mymodule_views_style1.js' => array('group' => JS_LIBRARY, 'weight'=>2),
            $path . '/mymodule_views_style2.js' => array('group' => JS_LIBRARY, 'weight'=>3),
          )
        ),
        'my_views_plugin_row_library' => array(
          'js' => array(
            $path . '/mymodule_views_lib.js' => array('group' => JS_LIBRARY, 'weight'=>4),
            $path . '/mymodule_views_row1.js' => array('group' => JS_LIBRARY, 'weight'=>5),
            $path . '/mymodule_views_row2.js' => array('group' => JS_LIBRARY, 'weight'=>6),
          )
        ),
      );
      return $libraries;
    }

Answer: For question #1 --
$options in hook_library() supports all the options in drupal_add_js.
$options in drupal_add_js supports a weight value to determine ordering:
From hook_library:

'js': An array of JavaScript elements; each element's key is used as
  $data argument, each element's value is used as $options array for
  drupal_add_js(). To add library-specific (not module-specific)
  JavaScript settings, the key may be skipped, the value must specify
  'type' => 'setting', and the actual settings must be contained in a
  'data' element of the value.

From drupal_add_js:

weight: A number defining the order in which the JavaScript is added
  to the page relative to other JavaScript with the same 'scope',
  'group', and 'every_page' value. In some cases, the order in which the
  JavaScript is presented on the page is very important. jQuery, for
  example, must be added to the page before any jQuery code is run, so
  jquery.js uses the JS_LIBRARY group and a weight of -20,
  jquery.once.js (a library drupal.js depends on) uses the JS_LIBRARY
  group and a weight of -19, drupal.js uses the JS_LIBRARY group and a
  weight of -1, other libraries use the JS_LIBRARY group and a weight of
  0 or higher, and all other scripts use one of the other group
  constants. The exact ordering of JavaScript is as follows:

For question #2 -- the safest thing todo is to always specify the inclusion order; eg weight.


What should I be careful when using the word "supervised" in paper writing?

Question: I am a biologist using machine learning tool for my research. I modified matrix decomposition ($V \approx WH$) to fit my data and wanted to describe about that in my paper.
If I fixed one matrix factor ($W$), can I write the following sentences?

The dictionary ($W$) is supervised
This is a supervised method

I think 1. is correct because the dictionary is given/supervised. However, 2. is wrong because I do not aim to train the method with the labeled data. So, here is unsupervised learning but the dictionary is provided (as hyperparameter?).
What should I be careful when writing the word "supervised" in interdisciplinary research paper?
Answer: "Supervised" usually means you have labeled response/target. I would say the matrix $W$ is "given" or "provided" or "fixed", rather than "supervised".

As a tool to recognize patterns or predict observations, machine learning models are "supervised" if they are given correct labels to try to predict. Compared to "unsupervised" models which try to recognize the patterns on their own. Supervised/unsupervised is the adjective that describes the model, not the (hyper)parameter. Hyperparameters are either searched for optimal values, or given based on empirical knowledge.


Calculus Long division integral

Question:
I started out doing long division and got

which is where im a little confused.
Do i then do partial fractions? or am i approaching this problem the wrong way?
Answer: In fact ,we have $x^4-x^3-7x^2+13x-6=(x-1)^2(x-2)(x+3)$,maybe this can help you!
Answer: It's a good start (but I haven't checked your calculations). Yes, you do need to do partial fractions, but first you must factorize the denominator. To that end, you have been given a useful hint: A zero of the denominator. So you have at least one factor, and can divide it out. Which leaves you with a third degree polynomial. If you know how to find the roots of those, you're good to go. If not, then hope that you can find another root. Or maybe $1$ is a double root; I don't know.
Comment: so i can factor out a x-1 from the denominator?
Comment: Yes, that's right.

Calculus Long division integral


Save attachment from IMAP on networkdrive

Question: I'm looking for a solution to save automatically attachments of an e-mail for a specific mailbox on an network drive. Mails are stored on cyrus imap server.
Does anyone know a script or something like this. Maybe there is a way to do this with sieve?!?
I searched on the web, but didn't find anything.
Thanks in advance!
Answer: AFAIK Sieve (the scripting language Cyrus loves) does not support attachment extraction. What you can do though is that you create a Sieve script which identified the e-mails having attachments (from sender, message size, whatever criteria you'd like to use), and automatically file those messages to some specific IMAP folder, say TemporaryAttachmentsFolder.
Then you can put in cron a shell script, which periodically polls that TemporaryAttachmentsFolder directory, and extracts the attachments with a tool like ripmime and saves them elsewhere. Or, if you are truly l337, you can replace the traditional cron with incron and make the extraction happen in real-time.
Answer: Take a look at the following script: https://github.com/auino/mail-attachments-archiver, allowing you to store received mails attachments into a specific directory.


Adding ResourceDictionary to Application.Current.Resources.MergedDictionaries (Avalonia UI)

Question: I want to add resources through code, but I can't do it.
In WPF, I would have done that:
Application.Current.Resources.Clear();
Application.Current.Resources.MergedDictionaries.Add(Application.LoadComponent(
    new Uri(@"Resources\Style\light.xaml", UriKind.Relative)) as ResourceDictionary);

But Avalonia doesn't have an Application.LoadComponent.
I try to do it, but it doesn't work:
Application.Current?.Resources.MergedDictionaries.Clear();
Application.Current?.Resources.MergedDictionaries.Add( new ResourceInclude
{
    Source = new Uri(@"/Assets/icons/LightIcons.axaml", UriKind.Relative)
});

If you know how to do this, please help.
Thank you in advance.
Answer: I found the answer, it's the right thing to do:
Application.Current?.Resources.MergedDictionaries.Clear();
Application.Current?.Resources.MergedDictionaries.Add(new ResourceInclude
    {
        Source = new Uri("avares://MyApplication/Assets/icons/DarkIcons.axaml")
    });

Comment: As it's currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer).


Pinch/zoom within a div but not whole page

Question: Is it possible to enable pinching/zooming of a specific div on a page?  I don't want to pinch/zoom the entire page, just a specific element.
I am using jQuery, jQuery Mobile and viewing the project on an iPad.
Comment: Possibly related: http://stackoverflow.com/q/11517086/472495
Comment: Interesting (and also found with a ten-second search engine search): https://forum.jquery.com/topic/detect-pinch-zoom-on-an-image
Answer: You can use Zoomooz. It's a jQuery library which is very interesting:
Comment: Zoomooz does not support multi-touch pinching events. Its only a library for zooming into elements on a page, but has no support for pinching behavior, so far as I can see in the documentation.


HAproxy configuration file rebinding

Question: Is it possible for HAproxy to reload its configuration at runtime, without dropping existing connections?
I've looked high and low in the documentation for some mention of this but have been unsuccessful. Does anybody know off hand?
Thanks.
Answer: I am not sure about how perfectly this handles a reload, but the command line option for this to haproxy is -sf:

-sf  Send FINISH signal to the pids in pidlist after startup. The
  processes which receive this signal
  will wait for all sessions to finish
  before exiting. This option must be
  specified last, followed by any number
  of PIDs. Technically speaking, SIGTTOU
  and SIGUSR1 are sent.

This is what the reload argument does in my Ubuntu init scripts:
haproxy_reload()
{
        $HAPROXY -f "$CONFIG" -p $PIDFILE -D $EXTRAOPTS -sf $(cat $PIDFILE) \
                || return 2
        return 0
}

Comment: I've just noticed that the docs for v1.2 contain a lot more detail around this subject: http://haproxy.1wt.eu/download/1.2/doc/haproxy-en.txt But the docs for v1.4 seem to have removed all references to it! Confusing...
Comment: Turns out that `/etc/init.d/haproxy reload` is sufficient :) Seems that newer versions have got this so well catered for on a stock install that the extensive documentation for it in previous versions is no longer required.

HAproxy configuration file rebinding


[__NSCFDictionary objectAtIndex:]: unrecognized selector sent to instance

Question: I am trying to parse a Json file into the Table view and I am getting this error
[__NSCFDictionary objectAtIndex:]: unrecognized selector sent to instance
and the app is crashing. Please help me, I am new to iOS development.
My Code
@implementation ViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
    // Custom initialization
}
    return self;
}

- (void)viewDidLoad
{
    self.title = @"Feeds";
    [super viewDidLoad];
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;

    NSURL *url = [NSURL URLWithString:@"http://little-people.blogspot.com/feeds/posts        /default?alt=json"];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    [[NSURLConnection alloc] initWithRequest:request delegate:self];
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    data = [[NSMutableData alloc] init];
    NSLog(@"Data Data , %@", data);
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)theData
{
    [data appendData:theData];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;

    feed = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
    NSLog(@"Data  , %@", feed);
    [mainTableView reloadData];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    UIAlertView *errorView = [[UIAlertView alloc] initWithTitle:@"Error" message:@"The download   could not complete - please make sure you're connected to either 3G or Wi-Fi." delegate:nil cancelButtonTitle:@"Dismiss" otherButtonTitles:nil];
    [errorView show];
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}

- (int)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (int)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [feed count];
    NSLog(@"Data Data , %@", feed);
 }
  - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath    *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MainCell"];

    if(cell == nil){
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"MainCell"];
}
if (([feed count] - 1) >=indexPath.row) {

    cell.textLabel.text = [[feed objectAtIndex:indexPath.row] objectForKey:@"feed"];
    cell.detailTextLabel.text = [[feed objectAtIndex:indexPath.row] objectForKey:@"title"];
}

    return cell;
}

Comment: The problem is that you expect your data to be an array, but in reality is a dictionary and that's why is crashing. Check your `feed` object...
Answer: The problem is that feed is not a NSArray, but a NSDictionary.
Looking at the JSON, you likely want to access this array: [feed objectForKey:@"entry"]
Answer: The top level object in your feed is a JSON object, not a JSON array.  So the deserialisation gives you an NSDictionary, not an NSArray.
Comment: @user2192724 - Good!  Sounds like you've made great progress!  (Hint: NSLog)


Time Series Anomaly Detection Overfitting

Question: If the goal is anomaly detection on time series data, then over-fitting my forecast model on the data is just what I want. If the historical data is fit really well, then I should expect some error from this over-fit model to be large enough to signal an anomaly. Is this true? If not, why so?
Answer: No. You can easily overfit without any presence of anomalies in the series. Think of FFT, if you don't smooth it, then the output is a perfectly overfitted series.
Comment: This does not answer the question.


Show that the given curve is normal to the given surface at the given point).

Question: Show that the curve $r(t) = (t^2, t, 5t − 4)$ is normal to the surface $2x^2 +y^2 +5z^2 = 8$ at the point $(1, 1, 1)$.
My thought is that find the derivatives of $r(t)$ and the gradient of the surface. Then make these two have a dot product is $0$. But I found that after my calculations. The result is not $0$.
Hope someone can help with my confusion
Thanks.
Comment: If $r(t)$ is normal to the given surface, then it derivative is along the gradient and not perpendicular to it.
Comment: You can find the normal vector N at the surface in that point, and check if vectors N and r(1,1,1) are collinear
Comment: In connection with the remark of @Glorious Nathalie, you do a common error because people associate the gradient in 2D to the tangent : the gradient of a surface defined implicitly by $f(x,y,z)=0$, i.e., the vector of partial derivatives is *orthogonal* to the surface.
Answer: We can use this statement for definition of normal plane:
A plane P passing through a point M of a curve L and perpendicular to the tangent MT is called a normal plane to the curve L. The direction vector of the tangent $r'=x', y' z')$, is a normal vector to the plane P.The equation of a normal plane is:
$(X-x)x'+(Y-y)y'+(Z-z)z'=0$
Now we have:
$r(t)=f(x, y, z)=(x=t^2, y=t, z=5t-4)$
So the equation of normal plane on curve L is:
$(X-t^2)2t+(Y-t)\cdot 1+(Z-5t+4)5=0$
$2tX-2t^3+Y-t+5Z-25t+20=0$
Or:
$2yX-2y^3+Y-y+5Z-25y+20=0$
$\Rightarrow 2yX-2y^3+Y-26y+5Z+20=0$
At point $(x, y, z)=(1, 1, 1)$ we have:
$2X+Y+5Z-8=0$
So the direction vector (normal vector of plane) is:
$N=(2, 1, 5)$
The  vector of a tangent plane on surface is:
$(2x^2+y^2+5z^2)'=4x +2y+10z=2(2x+y+5z); N'=(2, 1, 5)$
So $N=N'$
That is normal plane is tangent on surface, so the surface is perpendicular on the curve at point $1, 1, 1$.
$L: $
Answer: The surface is a plane in canonical form so its normal vector is $(2,1,5)$.
The derivative of the curve is $(2t,1,5)=(2,1,5)$ at $(1,1,1)$
Therefore, ...


will logout failed when TGT expires on cas server, but session on client system is active

Question: 1 cas client and 1 cas server.
cas client login success, then user use the client system over 2 hours, so the session never timeout on client system.
but cas server TGT may timeout, because TGT expires after 2 hours in inactivity.
then the user try logout the system. browser will send a logout request with TGT to cas server,
but the TGT has already expires, so the logout will be failed, the cas server won't send logout request to the client
system too, so the session in client system will still active.
is this a problem?
Answer: No. Log out does not fail. When tgt expires on CAS, CAS will automatically reach out to client apps if u have SLO turned on


All zero values passed in the table

Question: When I execute this code, I only get zeroes inserted into my database. Why? What can I do to solve this problem?
<select class="date" name="year"> <option value="">Year</option>
<?php $i=1; while($i<=31) { ?>
<option value="<?php $i ?>"> <? echo $i; ?> </option>
<?php $i++; } ?> </select>

And this is my mysql code:
$sql="INSERT INTO information ( Year )
VALUES ('$_POST[year]')";

Comment: nothing is right , both the code and the sql are wrong
Comment: what data type is the column "Year" in your database table?
Comment: You're showing a query to insert the (uncleaned) year, but your HTML is for the day. Wha?
Comment: That's a mistake, I fixed it now. @Josh
Comment: Please don't name your table "information".  That is about as undescriptive a name as could possibly exist, along with "data".  All tables contain information and data.  What is in the table?  What does that year represent?  Think of the next programmer who has to maintain your code.
Comment: http://pastebin.com/LZwDMEsW please check it
Answer: <select class="date" name="day"> <option value="">Day</option>
<?php $i=1; while($i<=31) { ?>
<option value="<?php echo $i; ?>"> <?php echo $i; ?> </option>
<?php $i++; } ?> </select>

Always use <?php and ?> so your browser recognizes PHP
also, with your first <?php $i ?>
I changed this to echo $i;  and on the same line I changed <? echo $i; ?> </option> To <?php echo $i; ?> </option>
and it worked for me.
With Your Insert:
$sql="INSERT INTO information (COL_FOR_DAY)
VALUES ('{$_POST['day']}')";

Comment: so your **browser** can parse php? :P
Answer: here how it will be your code
     <select class="date" name="year">
       <option value="">Year</option>
         <?php  for($i=1;$i<=31 ;$i++ ) { ?>
       <option value="<?php $i ?>"> <? echo $i; ?> </option>
         <?php } ?>
     </select>

EDIT :
    <input type ="submit" value =" submit me"/>
    <?php  if (isset($_POST['year']))  // check if isset the year
       {
       $year = $_POST['year']  ;
       } else {}

    $sql="INSERT INTO information ( Year ) VALUES ('".$year."')";
       ?>

edit 2 :
your code is right but you should escape value to prevent sql injection
do like that
insert into ....
    VALUES
       ('mysql_real_escape_string($_POST[user])','mysql_real_escape_string($_POST[email])'.........

Comment: Just judging by the OPScode, the `$i<=31` Represents the day. There is a maximum of `31 days in a month` Not the year
Comment: That's not the real problem Daryl. It's just an example.
Comment: @user1902462  if u mean the month , just replace the year by the month
Comment: @user1902462 i think u still miss some code to submit and code to define the POST . and then insert to mysql
Comment: @user1902462 this the whole code to submit and define post year and then insert it to mysql
Comment: Yes, all time I got zero till now :(
Comment: as i told u make submit button , hidden fields if it needs , define post variables and then insert them to mysql
Comment: yes your code is right but missing to work , just do what i told u and it will work . ur html is right , ur sql right but just escape variables to prevent from sl injection .and then do what u are missing
Comment: something doesn't quite look right here: `` with no echo? and `mysql_real_escape_string()` php function in quotes as part of the SQL statement?
Comment: `` it will be read ,better with ``.and  `mysql_real_escape_string()` yes i have tried it and it works , and he can also make `$var = mysql_real_escape_string($var);` and then use $var in his sql . if he uses `'$var'`  mean that he can also use `'mysql_real_escape_string($var)'`.

All zero values passed in the table


jqueryui 1.10.3 datepicker format using . as separator

Question: I have inherited some code that appears to use jqueryui 1.10.3 to incorporate a datepicker.
When I click the textbox to bring the datepicker up and choose a date, the format looks like
21.03.2020
However, if I click on the textbox again the format is
21/03/2020
The slash is the desired functionality. When the initial date is selected I want it to display as dd/mm/yyyy. How can I stop the date parts being separated by .
I have tried examining the jquery-ui-1.10.3 file to see if I can work out where the . separator is being applied but I haven't been able to come up with anything.
Comment: Please see https://jqueryui.com/datepicker/#date-formats
Answer: Somewhere in your web page or script section you should have code that looks like the code below.
This is where you can set your date time picker format. Look at the format date section.
$(document).ready(function () {
             $("#<%= TextBoxName.ClientID %>").datetimepicker({
                 dayOfWeekStart: 1,
                 lang: 'en',
                 startDate: '<%= TextBoxName.Text %>',
                 step: 30,
                 formatTime: 'H:i',
                 formatDate: 'Y.m.d'
             });
         });

See more help here: jquery datetime picker