Problemas de conexão entre Hibernate com Banco MySQL

Question: Olá, estou iniciando os estudos em Hibernate e não estou fazendo uma conexão com o Banco de Dados MySQL. Segue abaixo o meu código:
import java.util.Calendar;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

@Entity
public class Tarefa {
    @Id
    @GeneratedValue
    private Long id;
    private String descricao;
    private boolean finalizado;
    @Temporal(TemporalType.DATE)
    private Calendar dataFinalizacao;

}

Método main:
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

public class GeraTabelas {

    public static void main(String[] args) {
        EntityManagerFactory factory = Persistence.
                createEntityManagerFactory("tarefas");
                factory.close();

    }

Arquivo Persistence
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd ">
  <persistence-unit name="tarefas">
  <provider> org.hibernate.jpa.HibernatePersistenceProvider </provider>
  <class>br.com.caelum.tarefas.modelo.Tarefa</class>
  <properties>
  <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />
  <property name="javax.persistence.jdbc.url" value="jdbc:mysql: //localhost:3306/fj21" />
  <property name="javax.persistence.jdbc.user" value="root" />
  <property name="javax.persistence.jdbc.password" value="*********" />
  <property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5InnoDBDialect" />
  <property name="hibernate.show_sql" value="true" />
  <property name="hibernate.format_sql" value="true" />
  <property name="hibernate.hbm2ddl.auto" value="update" />
  </properties>
  </persistence-unit>
</persistence>

Quando executo aparece essa mensagem de erro
jan 24, 2017 10:43:38 AM org.hibernate.jpa.internal.util.LogHelper logPersistenceUnitInformation
INFO: HHH000204: Processing PersistenceUnitInfo [
    name: tarefas
    ...]
jan 24, 2017 10:43:38 AM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {5.2.7.Final}
jan 24, 2017 10:43:38 AM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
jan 24, 2017 10:43:39 AM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
jan 24, 2017 10:43:39 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
WARN: HHH10001002: Using Hibernate built-in connection pool (not for production use!)
jan 24, 2017 10:43:39 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001005: using driver [com.mysql.jdbc.Driver] at URL [jdbc:mysql: //localhost:3306/fj21]
jan 24, 2017 10:43:39 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001001: Connection properties: {user=root, password=****}
jan 24, 2017 10:43:39 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001003: Autocommit mode: false
jan 24, 2017 10:43:39 AM org.hibernate.engine.jdbc.connections.internal.PooledConnections <init>
INFO: HHH000115: Hibernate connection pool size: 20 (min=1)
Exception in thread "main" org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:271)
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:233)
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:210)
    at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.configure(JdbcServicesImpl.java:51)
    at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:94)
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:242)
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:210)
    at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.handleTypes(MetadataBuildingProcess.java:352)
    at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.complete(MetadataBuildingProcess.java:111)
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.metadata(EntityManagerFactoryBuilderImpl.java:858)
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:885)
    at org.hibernate.jpa.HibernatePersistenceProvider.createEntityManagerFactory(HibernatePersistenceProvider.java:58)
    at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:55)
    at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:39)
    at GeraTabelas.main(GeraTabelas.java:8)
Caused by: org.hibernate.HibernateException: Unable to make JDBC Connection [jdbc:mysql: //localhost:3306/fj21]
    at org.hibernate.engine.jdbc.connections.internal.BasicConnectionCreator.createConnection(BasicConnectionCreator.java:60)
    at org.hibernate.engine.jdbc.connections.internal.PooledConnections.addConnections(PooledConnections.java:123)
    at org.hibernate.engine.jdbc.connections.internal.PooledConnections.<init>(PooledConnections.java:42)
    at org.hibernate.engine.jdbc.connections.internal.PooledConnections.<init>(PooledConnections.java:20)
    at org.hibernate.engine.jdbc.connections.internal.PooledConnections$Builder.build(PooledConnections.java:161)
    at org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl.buildPool(DriverManagerConnectionProviderImpl.java:109)
    at org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl.configure(DriverManagerConnectionProviderImpl.java:72)
    at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:94)
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:242)
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:210)
    at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.buildJdbcConnectionAccess(JdbcEnvironmentInitiator.java:145)
    at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:66)
    at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:35)
    at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.initiateService(StandardServiceRegistryImpl.java:88)
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:259)
    ... 14 more

Comment: Considerando-se a resposta aceita, votei para fechar isto como erro de digitação.
Answer: A exceção em questão, assumindo que suas credenciais estão corretas, se deve ao espaço extra na URL JDBC jdbc:mysql: //localhost:3306/fj21.
Para resolver o problema edite a URL no arquivo persistence.xml.
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/fj21" />

Comment: Deu certo, obrigado. Era o espaço extra mesmo.
Answer: Pelos códigos que mostrasse, pode ser o caminho do banco que você declarou name="javax.persistence.jdbc.url". Veja também se a biblioteca, conector, do mysql encontra-se na sua classpath.
Comment: O Conector está na classpath


Handle different language and target levels for sources and tests with IntelliJ IDEA

Question: I'm interested if someone has clue how to handle this pom in projects properties of IDEA:
<plugin>
   <groupId>org.apache.maven.plugins</groupId>
   <artifactId>maven-compiler-plugin</artifactId>
   <configuration>
       <source>1.3</source>
       <target>1.3</target>
       <testSource>1.5</testSource>
       <testTarget>1.5</testTarget>
   </configuration>
   <version>3.0</version>
</plugin>

Should I set project level 1.3 and module level 1.5 or wise verse around?
As well anytime when IDEA reloads maven project it sets language levels as it thinks from maven to 1.3 and after always complaints about test classes.
But this will go as bug report to JetBrains.
Comment: There is already an open bug report for this: http://youtrack.jetbrains.com/issue/IDEA-81494
Comment: Defect: https://youtrack.jetbrains.com/issue/IDEA-85478
Answer: Supporting test source/target levels is tracked by this request. Language level changed message is also a known issue.
Comment: Thank you Sergey, I hope Dev team will pick up this soon, since it's really annoying. But maybe there are not many people who supports ancient products
Comment: Six years have passed and the issue is still unresolved. :-( Looks like we have to use one of the proposed workarounds.
More relevant than ever, since certain test libraries depend on the latest language features and the release cycle of the Java language is now faster than back then.
Answer: As already mentioned different language levels for main and test sources are not yet supported by Idea.
There's a workaround to force Idea to use the language level defined in testSource when importing Maven project. You can create a separate Maven profile only for Idea with different compiler plugin settings:
<profiles>

    <profile>
        <id>default</id>
        <activation>
            <activeByDefault>true</activeByDefault>
        </activation>
        <build>
            <plugins>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <version>3.2</version>
                    <configuration>
                        <source>1.6</source>
                        <target>1.6</target>
                        <testSource>1.8</testSource>
                        <testTarget>1.8</testTarget>
                    </configuration>
                </plugin>
            </plugins>
        </build>
    </profile>

    <profile>
        <id>ide</id>
        <activation>
            <activeByDefault>false</activeByDefault>
            <property>
                <name>idea.maven.embedder.version</name>
            </property>
        </activation>
        <build>
            <plugins>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <version>3.2</version>
                    <configuration>
                        <source>1.8</source>
                        <target>1.8</target>
                        <testSource>1.8</testSource>
                        <testTarget>1.8</testTarget>
                    </configuration>
                </plugin>
            </plugins>
        </build>
    </profile>

</profile>


JavaScript para de funcionar e só volta com cache vazio?

Question: Ultimamente eu tenho tido muita raiva de JavaScript, o motivo é que eu escrevo meus códigos e funções em JavaScript e elas aparentemente não funcionam. Aí eu preciso abrir o navegador em aba anônima, aí elas funcionam. As vezes preciso limpar todo o cachê do navegador para as alterações que fiz no código voltar a funcionar. Tem vezes que mesmo limpando o cachê do navegador e abrindo no modo anônimo o código não funciona, aí para vê-lo funcionar eu preciso mandar ele no meu servidor em um domínio de testes para conseguir testá-lo.
Por que isso acontece? Porque toda vez que altero um código em JavaScript ele nunca funciona de primeira e me obriga a ter que ficar fazendo toda essa gambiarra pra fazer o código funcionar?
Quando finalmente eu consigo rodar um código em JavaScript após limpar o cache ou utilizar em aba anônima, ele permanece funcionando um bom tempo, mas de acordo com o que eu vou dando refresh na página (para testar alterações) ele volta a parar de funcionar. Isso me preocupa, pois e se isso acontecer com o usuário que acessa meu site e as funções pararem de funcionar de acordo com o número de acessos que ele faz no site?
Eu declaro todos os scripts no final do código antes de fechar body.
Comment: A questão do cache não é gambiarra, é o comportamento natural do navegador que te ajudará muito em ambiente de produção. Para contorná-lo, você pode ler [Forçar atualização de arquivo javascript sem desativar cache](http://pt.stackoverflow.com/questions/68382). Agora, para saber do porquê ele para de funcionar depois de alguns acessos, você precisará postar os códigos aqui.
Answer: O cache do navegador é justamente para otimizar uma aplicação web, aproveitando o conteúdo da página para que não seja necessário recarregar alguns recursos toda vez que a página for atualizada. O que eu sugiro para o ambiente de desenvolvimento, seria o uso do navegador Chrome. Aperte F12 para abrir a janela de Inspeção de Código, clique nos 3 pontinhos que fica no topo da janela e depois clique em Settings para abrir as configurações. Marque a opção Disable cache (while DevTools is open) como na imagem abaixo:

E sempre que estiver desenvolvendo e testando seu código, deixe aberto a janela de Inspeção de Código.
Answer: A solução lógica é o cache que feito no primeiro carregamento como você já deve saber. Isso explica o por que uma atualização no código não roda de primeira. Eu aperto umas 5 ou 6 vezes o F5 para ocorrer a atualização do cache. E assim vejo a minha atualização funcionar.


Textview doesn't display anything if the string is over 18175 characters long

Question: I have a textview that has its text set from a local xml file. Anytime the string is over 18175 characters long, the entire textview is blank. Anything at 18175 or under will display perfectly fine.
This only happens on OS 2.1 and under. I've tried looking around for a similar issue but have not had any luck. Does anyone know if this is a bug?
Answer: I'd assume that for OS 2.1 and below nobody thought of a device that would be able to display that many characters at the same time.
If you have a larger String or buffer, you might display parts of it via the public final void setText (char[] text, int start, int len) method.
There are various places where Android provides quite sharp resource limits - another example is the default stack size which is so small that it broke recursive methods for me.


What is the approporiate test?

Question: I have two variables ; First variable is ordinal and it represent years series from 2006 to 2015 and another variable which is interview score and I want to study if there a relationship between the graduation year and the interview score. What is the appropriate test I shall use ?
Thanks !
Comment: Welcome to CV. It would help your potential respondents if you were to say a bit more about your data. For instance, what is the sample size? What is the unit of analysis? What are the "interviews" about?
Comment: Thank you. My sample size is 34 for a small population (60).
Comment: The interviews are ; Interviews for hiring in a company where each applicant has a degree from 1.00 to 10.00 ( it's included values such as 2.50 etc.)
Comment: A "degree?" Do you mean a *rating* from 1 to 10? What is this a rating of? Candidate's qualifications for a position? Likelihood of future success? What is "graduation year?" Why is the sample size so low? With such a small sample size and large span of years the power of any analysis will be very low.
Comment: Yes . A rating from 1 to 10. Each applicant who apply to a position go thorough three interviews and the score of the interviews will qualify them to be accepted or not for the position.
Answer: A Kruskall-Wallis test would be suitable to test, whether ordinal scores are differing between different groups (years). Spearman correlation would be suitable to tell, whether older applicants tend to get higher oder lower scores. (Call that 'ANOVA' and 'Pearson' instead of 'Kruskall-Wallis' and 'Spearman' if you want to deal with problems like normality assumptions in your small sample - hint: you don't want to).

What is the approporiate test?


What is the proper way to align UITableViewCells when only some have an imageView?

Question: I am new to iPhone programming and working on my first real application (i.e. one not written in a book or online) and I've run into a small problem which I could solve a multitude of ways, but feel like there should be a good solution that perhaps I am just missing.
Here is the scenario: I have a UITableView with a bunch of standard UITableViewCells in it. What I want to do is toggle a green check mark when the cell is selected and I have that part working (note: I'm already using the accessoryType for something else, so I can't use it for the checkmark...besides, it's not as pretty). Unfortunately, when I toggle the checkmark like so:
if (...) {
  cell.imageView.image = [UIImage imageNamed:@"checkmark.png"];
} else {
  cell.imageView.image = nil;
}

It makes the cell's label bounce back and forth depending on whether it is checked or not. What is the proper way to align the cell's text (set via cell.textLabel.text) regardless of whether or not it has an image set? The solutions I have come up with are:

Create a blank 40x40 png image in Photoshop and set the unchecked to that
Create a blank 40x40 image solely in code
Set some setting that I don't know about that will align it for me
Create a subclass of UITableCellView that does what I need (which would be stupid, I'd just go with option 1...)

Suggestions? Thoughts? Comments? Thank you very much :-)
P.S. I'd like the solution to work with OS 3.0 and 4.0 if that makes any sort of difference.
Answer: Option 1 is the way to go for a standard cell.
Strictly speaking, you do not have to subclass UITableViewCell to customize the layout.  You can add any views you wish to the contentView.  So you can add a UILabel and UIImageView to the contentView instead of using the imageView and textLabel properties.
Comment: Thanks for the answer. @Shaji - Thanks for the comment, that question may help in the future.


How to convert a string into hexadecimal in Bash

Question: I've found many posts on StackOverflow which have covered this question in C++, C# and other languages, but none with Shell.
Using Bash/Shell, how do I convert a random String into a byte array?
I tried:
echo "some string" | xxd -r -p

but it didn't work.
I basically want a byte output - e.g. )?e?GV??vY?Ge?#G
Comment: A byte array with what encoding?
Comment: Byte output of "some string" is "some string".
Comment: @alecrosic : How does the example output you provided, relate to the input?
Answer:
If you want to get the hex values of some string, then this works:
$ echo "testing some values"$'\157' | xxd
0000000: 7465 7374 696e 6720 736f 6d65 2076 616c  testing some val
0000010: 7565 736f 0a                             ueso.

If you just need the "plain" string:
$ echo "testing some values"$'\157' | xxd -p
74657374696e6720736f6d652076616c7565736f0a

If you need to "reverse" an hex string, you do:
$ echo "74657374696e6720736f6d652076616c7565736f0a" | xxd -r -p
testing some valueso

If what you need is the character representation (not hex), you could do:
$ echo "testing:"$'\001\011\n\bend test'  | od -vAn -tcx1
  t   e   s   t   i   n   g   : 001  \t  \n  \b   e   n   d
 74  65  73  74  69  6e  67  3a  01  09  0a  08  65  6e  64  20
  t   e   s   t  \n
 74  65  73  74  0a

Or:
$ echo "testing:"$'\001\011\n\bend test'  | od -vAn -tax1
  t   e   s   t   i   n   g   : soh  ht  nl  bs   e   n   d  sp
 74  65  73  74  69  6e  67  3a  01  09  0a  08  65  6e  64  20
  t   e   s   t  nl
 74  65  73  74  0a

Comment: Can I ask why did you add "o" at the end ($'\157')? I thought these are some flags to this command and spent like 2 hours trying to figure out where is this extra "o" comming from.
Comment: Thank you for your answer regardless. It was very helpful.
Answer: Looks like you want to convert hex string to bytes. xxd needs a starting point (since it is used to patch binary files and such)
string="626c610a"
echo "0: $string" | xxd -r

xxd will also silently skip any invalid hex, so check your data if you get empty output.


jxBrowser support for SPNEGO / Kerberos

Question: We are evaluating to integrate jxBrowser in our desktop solution to handle authentication with an IDP (Keycloak).
In this integration we would like to support Kerberos authentication, and for that we would require support for SPNEGO.
Is this something that jxBrowser supports? Otherwise is it on the roadmap?
Answer: In JxBrowser you can configure HTTP server authorization whitelist that represents a string with comma/semicolon separated list of URLs. This feature allows you to use Integrated Windows authentication (IWA) and Kerberos authentication for the listed domains.

With IWA, Chromium can authenticate the user to a web server or proxy without even prompting the user for a username or password. It does this by using cached credentials which are established when the user initially logs in to the machine that the browser is running on. IWA is supported for Negotiate and NTLM challenges only.
The HttpAuthPreferences.serverWhitelist() method allows you to specify which servers should be whitelisted for integrated authentication. By default, integrated authentication is only enabled when there is an authentication challenge from a proxy or from a server which is in this permitted list. If this list is not set, Chromium engine will try to detect if a server is on the Intranet and only then will it respond to IWA requests. If a server is detected as Internet, then IWA requests from it will be ignored.
The HttpAuthPreferences.delegateWhitelist() method specifies the servers that Chromium may delegate to. If this list is not set, Chromium will not delegate user credentials even if a server is detected as Intranet.
If you specify multiple server names in the lists, separate them with commas. Wildcards (*) are allowed.
Example
Let's assume that IIS is running on 127.0.0.1. The NTLM/Negotiate authentication was enabled for the server.
By default, the server responds with 401 Unauthorized. After adding 127.0.0.1 to the whitelists, authentication passes without any additional requests.
<code>engine.network().httpAuthPreferences().serverWhitelist("http://127.0.0.1");
engine.network().httpAuthPreferences().delegateWhitelist("http://127.0.0.1");
</code>
We haven't tested this solution with Kerberos authentication, because we don't have the required infrastructure yet, but you can try using this approach to configure the server and delegate whitelists with the addresses that use the Kerberos authentication. Please try this approach and let me know if it helps.

jxBrowser support for SPNEGO / Kerberos


Configuring Rebus in a .net core Worker Service (or a Console App)

Question: I have seen that Adding rebus in the ASP.NET Core execution pipeline is very neat using Startup.cs.
I wonder if there is a same neat way to do the same for Worker service or generally a console app.
Most .net core console apps I have seen are very simple demo applications.
Kindly if there is any concrete sample configuration using .net core console application.
Regards
Amour Rashid
Answer: One way would be to add Microsoft's Microsoft.Extensions.Hosting package and build your background service as a BackgroundService:
public class MyBackgroundService : BackgroundService
{
    readonly IServiceCollection _services = new ServiceCollection();

    public MyBackgroundService()
    {
        // configure the bus

        services.AddRebus(
            configure => configure
                .Transport(t => t.Use(...))
        );
    }

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        using var provider = _services.BuildServiceProvider();

        // start the bus
        provider.UseRebus();

        while (!stoppingToken.IsCancellationRequested)
        {
            await Task.Delay(TimeSpan.FromSeconds(1), stoppingToken);
        }
    }
}

which you then add by going
public static IHostBuilder CreateHostBuilder(string[] args) =>
    Host.CreateDefaultBuilder(args)
        .ConfigureServices((_, services) =>
        {
            services.AddHostedService<MyBackgroundService>();
        });

in your startup.
Answer: Thanks Mogens,
Another way is to
var host =CreateHostBuilder(args).Build();
host.UseRebus();
host.Run();
Or in ConfigureServices method
....
var provider=services.CreateServiceProvider();
provider.UseRebus();
It helped me I could create Worker Services using rebus.


Adding dynamic and multiple fields for user profile using profile2 module in Drupal 7

Question: I am creating profile like linkedin.
Where user can have multiple education fileds and he can add/modify dynamically.
Is there any plugin which suits my requirements.
The nearest I found is profile2 which is promising but does not provide me multiple entry functionality.
Can Drupal help me out how to fix this problem?
Thanks in Advance.
Yatendra
Edit : I want profile types like linkedin education wizard. i.e. if user had entered education detail one time then there should be two option first one for editing education detail and second one for adding more education detail.
Comment: you can add field to the user account at `/admin/config/people/accounts/fields` and set the number of values to multiple (as per your req.), and if need the fields as collection than give try to field collection module
Comment: Thanks Ankit!!. Yes it works for fields but I have multiple profile types (forms for profile) and I want to open same form again and again for adding newer values of same profile type.
Answer: Old question, but I have to say that Ankit's comment was on the right track. Install and enable Field Collection, because you will use this to group each instance of your education details fields.
Depending on whether or not you use Profile 2, create a Field Collection-type field at /admin/config/people/accounts/fields or /admin/structure/profiles/manage/<profile_type>/fields. The number of values for the field collection field should be greater than one or unlimited. Finally, create your education details fields at /admin/structure/field-collections/<field_collection>/fields.
Answer: I'd probably go with a mixture of the Conditional Fields module and setting the various fields to 'Unlimited'. Here is an excerpt about it from the module's project page:

... allows you to manage sets of dependencies between fields. When a field is "dependent", it will only be available for editing and displayed if the state of the "dependee" field matches the right condition.
When editing a node (or any other entity type that supports fields, like users and categories), the dependent fields are dynamically modified with the States API.
You can, for example, define a custom "Article teaser" field that is shown only if a "Has teaser" checkbox is checked.


How can I slow down a YouTube video I'm trying to analyze or transcribe?

Question: Sometime I want to use a YouTube video to

figure out what notes/chords are being played,
figure out how (i.e., by what technique) the notes/chords are being played, or
transcribe a (part of) a song.

But there are cases where the passage goes too fast, and I can't stop the video in time. Or I stop and restart, but I can't hit the spot I'm trying to see.
Is there some way to slow down the video, so I can see what's happening?

Related question
Software that slows down music to help in transcribing
Comment: ..playback speed? It's been a thing for years.
Comment: Do you really need to **see** something?   That's not a good, or reliable, way to transcribe audio.  Why not extract the audio track and play it in any decent tool, such as  Audacity, where you can play back at any desired speed, and easily identify critical junctures via the sound-wave display.
Comment: @CarlWitthoft Audacity would make a good addition to the answers to this question; I don't see it mentioned yet. Regarding "seeing", it's helpful when questions of, say, piano fingering come up.
Comment: @Aaron I think the question as asked is fine as it's not asking for recommendations, but a general way to solve a problem musicians encounter. Talking about general methodologies using a specific software as an example is fine like in user66401's answer. Posting just a plugin or software alone is not. This question is currently on the Hot Network questions so there are uses from other site that may not be as familiar with our scope so I posed that comment as a reminder to them.
Comment: For slowing down and looping about sections of a YT video this might suffice already: https://agrahn.gitlab.io/ABLoopPlayer/
Comment: @AlexG Your (I presume) loop player would be a good answer addition, too. Possibly with instructions for use.
Comment: To all of our HNQ visitors please note: Software recommendations are off-topic on this SE. Please do not add any answers that are just software or plugin recommendations.
Comment: @Dom This may be my misunderstanding. Recognizing that software/plugin recommendations are off-topic, In this case, my intention in the question was to compile a set of resources to solve a common problem. Does that mitigate the off-topic-ness, or is my question ill-conceived to being with? Thanks.
Comment: The firefox plugin "Video Download Helper" will let you capture the video. Then VLC can let you loop over sections if you wish, the advanced controls used to be required for pitch correction when slowed down, but now I think it is the default. Among players I had tested it had the most dependable playback at very slow speeds. I used to be interested in ball room dance and full body positioning is quite important so I found VLC invaluable for both online videos as well as DVD content. VLCs controls seem very simple but few people realize that under the advanced options it can do a lot.
Answer: There are at least two options:
Option 1: You can slow down the video by changing the Playback Speed setting
Below are browser instructions (mobile instructions are here)

Click on the Settings menu icon.

Select Playback speed

Select the speed you want

Option 2: Go frame by frame
You can progress frame by frame using the ,
(backward) and . (forward) keys. (This is also discussed in the YouTube Help discussion How to advance video frame by frame.)
Additional YouTube keyboard shortcuts include

< (Shift + ,) and > (Shift + ,) = adjust playback speed
note: in some browsers (Shift + < and Shift + >)
j = rewind
k = pause
? = view all keyboard shortcuts

Thanks to @user66401 and @flawr for pointing these out in the comments
Comment: While the comma and period do in fact control frame-by-frame, the `<` and `>` keys (while using shift) control the playback speed. `j` (rewind), `k` (pause), and `l` (fast forward) are probably also of interest. Also pressing `?` will show you a list of all the keyboard shortcuts.
Comment: Frame by frame probably isn't going to help in this case since it doesn't play sound while doing that, and even it it did, 1 frame's worth of sound would be hard to catch for the purposes of transcription.
Comment: I use frame by frame sometimes to catch fingerings, not as in which _note_ is being played (aural) but which _finger_ is being used (visual). This is usually after I've figured out which note is being played so it's used in conjunction with and not in replace of playback speed.
Comment: There is also `[shift]+[,]` and `[shift]+[.]` (or in some browsers `[shift]+[>]` and `[shift]+[<]`) to change the speed using the keyboard.
Comment: Be a happier person and install the "Video Speed Controller" extension (for both Chrome and Firefox). I recommend setting the speed increment to 0.25 and the seeking speed to 2 or 3 seconds. That way you can quickly and easily go forwards and backwards with Z and X a sensible distance instead of 5 seconds, and can easily change the playback speed with S and D.
Answer: I'd probably recommend starting with the built-in YouTube controls. But for the sake of completeness here's another workflow that makes use of 3rd party software called a "phrase trainer" or "slow downer". Here's a list of them.
Typically, you'd download or otherwise record the audio from the video so that you have it locally. There are a lot of services that will let you download the audio from a YouTube video, but personally I like the command-line youtube-dl package because it works well for most popular video sites and can do audio or video.
Once you have the audio file, then the phrase trainer software will let you slow down the audio without changing the pitch, loop sections, transpose/tune, and other features that are useful for transcribing.
If you absolutely need the video as well, I know Transcribe! at least works with videos as well. So you could download the video file and it will provide the same transcribing tools for the audio but also show the video at the same time:

I find youtube-dl, Transcribe!, and MuseScore (if I need to actually write it down) to be a pretty good workflow. But it depends on your needs. For instance Transcribe! doesn't offer any kind notation feature so you'll either have to remember it or write it down somewhere else.
Some software, for instance Capo, provides built-in guitar tabbing by letting you click on the spectrogram view to add a note to the tab view. So you can then later look at what you tabbed to refresh your memory. Again, it depends on your instrument and the features that you need.
Comment: Having a local copy of the video also lets you view it with a local video player like https://mpv.io/ (Linux / Mac / Windows) with responsive seeks, better than youtube's sometimes-sluggish seeking.  And fine-graned speed controls, a/v sync in case a vid is out of sync, aspect ratio control if you need it.
 And pretty importantly for this, configurable keybinds for seeking fast or accurately, e.g. back by 5 seconds precisely, even if that means decoding many frames after a keyframe.  Also it can loop a timespan of a video.
Answer: A small web-app that may be useful when analyzing or practicing with YouTube videos and offline media files (I am its author):
https://agrahn.gitlab.io/ABLoopPlayer
It has A-B repeat, fast/slow motion and loop bookmarking facilities.
Some more features:

The A-B loop window can be adjusted using a double-handled slider, ← & → on the keyboard, or, more accurately, via two time input fields.
The entire A-B loop window can be moved pressing Ctrl and moving one of the slider handles.
A-B loops can be saved as bookmarks for the current or for later sessions on the same computer and in the same browser.
Bookmarked A-B loops can be annotated individually with short description texts.
playback rates from slow to fast motion
resizable video display
search videos on YouTube

If the player widget has the focus (after clicking on it) it can be controlled with the same keyboard keys as the player on the main YT web site, e. g. ,, . for seeking frame-wise
Answer: I have been using this extension called "Youtube Playback Speed Control" for a long time to speed up YouTube videos, but it can be used to slow them down too.
https://chrome.google.com/webstore/detail/youtube-playback-speed-co/hdannnflhlmdablckfkjpleikpphncik
From the description:

Youtube playback speed increase or decrease is just a mouse click or keyboard button away. Get more out of Youtube and control speed of youtube video easily either by clicking the speed overlay button on the top right hand corner or just keyboard button '+' and '-'. Keyboard button are configurable and if you want to use different key, you can change this default keys from settings tab.

It is quite flexible.
You can set the speed increment to as low as 0.001 (Might be lower, haven't tested it).

There is a similar extension for FireFox as well:
https://addons.mozilla.org/en-US/firefox/addon/videospeed/
Comment: @Dekkadeci Yes! Once upon a time, the only way to play a video at a different rate was to skip or extend frames with JavaScript, which was quiet tricky to get right. Now, the HTML 5 standard supports a `playbackRate` property on the video that is handled by the browser itself, so it is much smoother.
To answer your question, yes, you should get audio at any speed you choose.
Comment: Youtube's standard UI already has speed controls.  So this addon just makes the control more fine-grained, instead of additive increments of 0.25?
Comment: @PeterCordes Yes, this allows for finer control than increments of `0.25` of the playback speed, and it does not cap your speed. You can play the video at `0.05x`or `4x` if you want. This extension simply changes the `playbackRate` property on the video. You can open up the devloper console and [change it yourself](https://www.w3schools.com/tags/av_prop_playbackrate.asp) too, but this just makes it more convenient.
Comment: When the speed is lower than 0.25x the usual, do you still get audio? (YouTube's 0.25x speed setting didn't have audio for years, which was annoying for me as a transcriber.)


Default route action not working after upgrade to ASP.NET Core MVC 2.2

Question: After updating my app from asp.net core 2.1 to 2.2 it seems that default route action is not working for controllers that live in a separate class library.
For example I have a default route like this:
routes.MapRoute(
            name: "default",
            template: "{controller}/{action}"
            ,defaults: new { controller = "Home", action = "index" }
            );

and in my class library I have a controller SiteAdminController which has an Index action method.
When I visit the url /siteadmin I get the HomeController index and not the index action of the SiteAdminController
if I use /siteadmin/index then it works
How can I make it work without requiring the index action to be explicitly in the url? It worked fine in 2.1
Comment: Are you using the 2.2 compatibility level? `.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2)`? or the old 2_1 compatibility? (it determines if endpoint routing is used or the mvc router middleware). Can also be disabled separately via `MvcOption`'s `EnableEndpointRouting` property
Comment: yes 2.2 compatibility and in  process hosting
Comment: changing to 2.1 compatibility does solve the problem, but I want it to work with 2.2 compatibility
Comment: having trouble trying to replicate this issue in a new solution, can't figure out what is different in my main solution that could be causing this.
Comment: strangely I can't seem to reproduce this in other solutions than the main dev solution for cloudscribe core. If anyone wants to try to help figure it out the repo is here:https://github.com/cloudscribe/cloudscribe Note that even new projects created with our project template and using our nugets, when upgraded to netcoreapp2.2 work just fine. At the moment I'm stumped why this problem happens.
Comment: Is the class controller in the other solutions in a class library too? Try adding the class library via application part: Or maybe its just some case sensitivity issue with the new routing?
Comment: yes works fine with controllers in class libraries in other solutions. and even the class libraries in the problem solution when consumed as nugets work fine in other solutions. I should mention also that the class libraries reference 2.1 aspnet core libs even though the the main app references 2.2. But that doesn't seem to be a factor as I tried replicating that factor in other solutions but the issue doesn't happen
Comment: also I've tried different casing in the route declaration and no change. I'm forcing lower case routes.
Answer: Have you tried setting the defaults in the template?
app.UseMvc(routes =>
        {
            routes.MapRoute(
              name: "default",
              template: "{controller=Home}/{action=Index}");
        }
);

This worked for me in Core 2.2
Comment: I meant literally in the template, not as "defaults: new controller = .." The latter doesn't work if I try it. Defining it in the template does.


Send rate to Google Play Store from your application

Question: Is there a way to send "rating" from your application to Google Play store? How?
I made a pop-up dialog for my application where I get a comment and a rate from the user. How can I send that feedback to Google Play store?
I'd like to have an experience, where user does not have to leave my app for the rating.
Using this library.
Comment: Possible duplicate of [Rate Google Play application directly in app](https://stackoverflow.com/questions/11270591/rate-google-play-application-directly-in-app)
Comment: @Pater , there is way if you redirect playstore for ratting > check below url

https://stackoverflow.com/questions/10816757/rate-this-app-link-in-google-play-store-app-on-the-phone
Answer: It is not possible (as of now) to send the rating to the play store. You can have your own prompt, and then send an intent to the play store, where the user can rate your app.
Google is working on a solution, similar to the iOS implementation, to allow the user to rate your app without leaving.
Android Central posted an article about this new (and upcoming feature): https://www.androidcentral.com/check-out-play-stores-new-app-review-feature-pictures
Edit: Android has added the option to have an In-App Review Flow. See this documentation: https://developer.android.com/guide/playcore/in-app-review/kotlin-java
Answer: I think that what the OP is asking is if Android has a way to display a google play dialog to rate the app directly. Something like what iOS have:

I just did a quick research trying to figure out and I couldn't find anything. Let me know if you have found a way to do it.
Answer: now google add in-app-review for rate and comment in google play store.
you can use this link for extra details:
https://developer.android.com/guide/playcore/in-app-review/kotlin-java


Creating multiple rows in databases

Question: I'm not sure why I can't test my function. My desired output is ID, then Room, but if there are multiple rooms for the same ID, then put it in a new row, like
  ID   Room
  1   SW128 SW 143
  into
  ID Room
   1  SW128
   1  SW143

This is some of the data in the file.
   1,SW128,SW143
   2,SW309
   3,AA205
   4,AA112,SY110
   5,AC223
   6,AA112,AA206

but I can't even test my function. Can anyone please help me fix this?
def create_location_table(db, loc_file):
'''Location table has format ID, Room'''

con = sqlite3.connect(db)
cur = con. cursor()
cur.execute('''DROP TABLE IF EXISTS Locations''')
# create the table
cur.execute('''CREATE TABLE Locations (id TEXT, Room TEXT)''')

# Add the rows
loc_file = open('locations.csv', 'r')
loc_file.readline()
for line in loc_file:
    d = {}
    data = line.split(',')
    ID = data[0]
    Room = data[1:]
    for (ID, Room) in d.items():
        if Room not in d:
            d[ID] = [Room]
            for i in Rooms:
                cur.execute(''' INSERT INTO Locations VALUES(?, ?)''', (ID,
                 Room))
     # commit and close cursor and connection
con.commit()
cur.close()
con.close()

Answer: The problem is, that d is always an empty dict, so the for (ID, Room) in d.items() won't do anything. What you need to do is looping over Room. And you don't need the d dict.
def create_location_table(db, loc_file):
    '''Location table has format ID, Room'''

    con = sqlite3.connect(db)
    cur = con. cursor()
    cur.execute('''DROP TABLE IF EXISTS Locations''')
    # create the table
    cur.execute('''CREATE TABLE Locations (id TEXT, Room TEXT)''')

    # open the CSV
    csv_content = open(loc_file, 'r')

    for line in csv_content:
        data = line.strip().split(',')
        # made lowercase following PEP8, but 'id' is a built in name in python
        idx = data[0]
        rooms = data[1:]
        # loop through the rooms of this line and insert one row per room
        for room in rooms:
            cur.execute(''' INSERT INTO Locations VALUES(?, ?)''', (idx, room))
            # for debug purposes only
            print('INSERT INTO Locations VALUES(%s, %s)' % (idx, room))
    # commit and close cursor and connection
    con.commit()
    cur.close()
    con.close()

# call the method
create_location_table('db.sqlite3', 'locations.csv')

Note: Following PEP 8 I made your variables lowercase.
EDIT: post full code example, use loc_file parameter
Comment: Comments are not for extended discussion; this conversation has been [moved to chat](http://chat.stackoverflow.com/rooms/160137/discussion-on-answer-by-masterfloda-creating-multiple-rows-in-databases).

Creating multiple rows in databases


pass custom variable for image field from preprocess node to twig

Question: I have a content type (gallery) with an image field which is unlimited: field_picture.
I have a logic which calculates custom css classes to their HTML containers, like: grid-item--width1, grid-item--width2, grid-item--height1, grid-item--height2.
I store these in the grid_class.
I can't merge these classes with the item class, because I want to style different HTML containers by them.
I tried to add this new variable (grid_class) to the image elements from the mytheme_preprocess_node__gallery and I thought drupal8 will pass them to the twig template.
function mytheme_preprocess_node__gallery(&$variables)
{
  foreach (Element::children($variables['elements']['field_picture']) as $key) {
    // here is my logic which calculates the classes for the image elements' containers
    $grid_class = "grid-item--width1 grid-item--height1";
    $variables['elements']['field_picture'][ $key ]['grid_class'] = $grid_class;
  }
}

but in my twig template (themes/custom/mytheme/templates/field/field--node--field-picture--gallery.html.twig) when I loop through the items, the grid_class isn't available.
{% for key, item in items %}

    {{ (dump(item)) }}

{{ item.content }}

{% endfor %}

I also tried to add it from mytheme_preprocess_field(). I saw the array of the field_picture element, but I didn't find the items in there.
any help or hints?
Answer: I found that I have to use the mytheme_preprocess_field hook.
function mytheme_preprocess_field(&$variables) {
  if ($variables['field_name'] == "field_picture") {
    foreach ($variables['items'] as $key => $item) {
      $grid_class = "grid-item--width1 grid-item--height1";
      $variables['items'][ $key ]['grid_class'] = $grid_class;
    }
  }
}


Expected value and variance of ratio of two sums of two sets of random variables

Question:
Let $X_1,X_2,\ldots,X_n$ be iid $\operatorname{Gamma}(\alpha,\beta)$ random variables. Suppose that, conditionally on $X_1,X_2,\ldots,X_n$, the random variables $Y_1,Y_2,\ldots,Y_n$ are independent and $Y_{i}\mid X_{i}\sim \operatorname{Gamma}(\alpha,\beta X_i)$. Show that $$E\left(\frac{\bar{Y}}{\bar{X}}\right)=\alpha\beta$$ and $$\operatorname{Var}\left(\frac{\bar{Y}}{\bar{X}}\right)=\alpha\beta^2E\left(\frac{\sum X_i^2}{(\sum X_i)^2}\right).$$

It is a question from a past comprehensive exam. The hint says "use the iterated expectation and variance formulas". But I do not see anywhere can use this hint.
Comment: This is as if the author of the exercise was trying hard to hide the fact that $Y_i=X_iZ_i$ where all the random variables $X_i$ and $Z_j$ are i.i.d. Gamma$(a,b)$. With this remark in mind, the rest follows easily, using nothing more than $E(X_i)=E(Z_j)=ab$ and var$(Z_j)=ab^2$ (compare with the accepted answer).
Comment: If $\xi=(X_1,X_2,\ldots,X_n)$ and $U=n\bar X$, then $E(Z_i\mid\xi)=E(Z_i)=ab$ and $E(X_i\mid\xi)=X_i$ for every $i$ hence $$E(\bar X^{-1}\bar Y\mid \xi)=U^{-1}\sum_iE(X_iZ_i\mid\xi)=U^{-1}\sum_iX_iE(Z_i)=U ^{-1}\sum_iX_iab=ab.$$
Comment: @Did. Do we still need to use iterated expectation and variance formulas?
Comment: Iterated expectation, if you want to call it this, yes. Iterated variance, no.
Comment: @Did. I was trying to use the result "$E(\frac{Y_i}{X_i})=E(Z_i)=ab$" to calculate $E(\frac{\bar{Y}}{\bar{X}})$. But once I use iterated expectation, I did not see where I can use this result. Can you tell me more about which step we can simplify?
Answer: If $X_i \backsim \operatorname{Gamma}(\alpha,\beta)$ where $\alpha$ is the shape and $\beta$ is the scale parameter then
$$ \mathbb{E}\left[ X_i \right] = \alpha \beta \quad \quad \mbox{and} \quad \quad  \mathbb{V}\mbox{ar}\left[ X_i \right]  = \alpha \beta^2 $$
From the properties of the gamma distribution
$$ \overline{X} \backsim \operatorname{Gamma}\left(n \alpha, \beta/n \right) $$
which means
$$ \mathbb{E}\left[ \bar{X}\right] =  \alpha\beta \quad \quad \mbox{and} \quad \quad  \mathbb{V}\mbox{ar}\left[\bar{X}\right]  = \alpha \beta^2/n   $$
Then for
$$ Y_i | X_i \backsim \operatorname{Gamma}\left(\alpha, \beta X_i \right) $$
$$ \mathbb{E}\left[ Y_i | X_i \right] =\alpha \beta X_i  \quad \quad \mbox{and} \quad \quad  \mathbb{V}\mbox{ar}\left[Y_i | X_i \right]  = \alpha (\beta X_i )^2  $$
From the law of total expectation we have
\begin{equation}
\begin{split}
\mathbb{E}\left[\frac{\bar{Y}}{\bar{X}}\right]&= \left.
\mathbb{E}\left[ \mathbb{E}\left[ \frac{\bar{Y}}{\bar{X}} \right| X_1, \ldots, X_n \right]  \right] \\
&=
\mathbb{E}\left[ \frac{1}{\bar{X}} \frac{1}{n} \sum_{i=1}^n\mathbb{E} [ Y_i \big| X_1, \ldots, X_n ]  \right] \\
&=
\mathbb{E}\left[ \frac{1}{\bar{X}} \frac{1}{n} \sum_{i=1}^n\mathbb{E}[ Y_i \big| X_i ]  \right] \\
& = \mathbb{E}\left[ \frac{1}{\bar{X}} \frac{1}{n} \sum_{i=1}^n \alpha \beta X_i  \right] \\
& =  \alpha \beta \mathbb{E}\left[ \frac{1}{\bar{X}} \frac{1}{n} \sum_{i=1}^n X_i  \right] \\
& =  \alpha \beta \mathbb{E}\left[ \frac{1}{\bar{X}} \bar{X}  \right] \\
& =  \alpha \beta \mathbb{E}\left[ 1 \right] \\
& =  \alpha \beta  \\
\end{split}
\end{equation}
From the law of total variance we have
\begin{equation*}
\begin{split}
\mathbb{V}\mbox{ar}\left[\frac{\bar{Y}}{\bar{X}}\right] &= \left.
\mathbb{V}\mbox{ar}\left[ \mathbb{E}\left[ \frac{\bar{Y}}{\bar{X}} \right| X_1, \ldots, X_n \right]  \right] + \left. \mathbb{E}\left[   \mathbb{V}\mbox{ar} \left[ \frac{\bar{Y}}{\bar{X}} \right| X_1, \ldots, X_n \right]  \right] \\
&= \left.
\mathbb{V}\mbox{ar}\left[ \frac{1}{\bar{X} } \frac{1}{n}   \mathbb{E}\left[  \sum_{i=1}^nY_i\right| X_1, \ldots, X_n \right]  \right] + \left. \mathbb{E}\left[   \frac{1}{\bar{X}^2 } \frac{1}{n^2}   \mathbb{V}\mbox{ar} \left[ \sum_{i=1}^nY_i \right| X_1, \ldots, X_n \right]  \right] \\
&=
\mathbb{V}\mbox{ar}\left[ \frac{1}{\bar{X} } \frac{1}{n}    \sum_{i=1}^n \mathbb{E}\left[ Y_i\big| X_i\right]  \right] +  \mathbb{E}\left[   \frac{1}{\bar{X}^2 } \frac{1}{n^2}   \sum_{i=1}^n \mathbb{V}\mbox{ar} [ Y_i \big| X_i]  \right] \\
&= \mathbb{V}\mbox{ar}\left[ \frac{1}{\bar{X} } \frac{1}{n}   \sum_{i=1}^n  \alpha \beta X_i  \right] +\mathbb{E}\left[   \frac{1}{\bar{X}^2 } \frac{1}{n^2}   \sum_{i=1}^n  \alpha (\beta X_i )^2  \right] \\
&= \alpha^2 \beta^2 \mathbb{V}\mbox{ar}\left[ \frac{1}{\bar{X} } \bar{X}  \right] +\mathbb{E}\left[   \frac{n^2}{ (\sum_{i=1}^n X_i)^2 } \frac{\alpha \beta^2}{n^2}   \sum_{i=1}^n   X_i^2  \right] \\
&= \alpha^2 \beta^2 \mathbb{V}\mbox{ar}\left[ 1 \right] + \alpha \beta^2 \mathbb{E}\left[   \frac{1}{ (\sum_{i=1}^n X_i)^2 }    \sum_{i=1}^n   X_i^2  \right] \\
&= \alpha \beta^2 \mathbb{E}\left[   \frac{    \sum_{i=1}^n   X_i^2 }{ (\sum_{i=1}^n X_i)^2 }   \right] \\
\end{split}
\end{equation*}


Translate Wilson Score Confidence SQL Code to Codeigniter active record

Question: I can't seem to translate the Wilson Score Confidence SQL code to Codeigniter active record code. Here is the ordinary SQL for the Wilson Score Confidence:
SELECT *, ((likes+ 1.9208) / (likes + dislikes) -
                   1.96 * SQRT((likes * dislikes) / (likes + dislikes) + 0.9604) /
                          (likes + dislikes)) / (1 + 3.8416 / (likes + dislikes))
       AS ci_lower_bound FROM widgets WHERE likes + dislikes > 0
       ORDER BY ci_lower_bound DESC;

This was taken from: http://www.evanmiller.org/how-not-to-sort-by-average-rating.html
Here was my attempted translation which didn't seem to work:
        $this->db->select('*, ((likes + 1.9208) / (likes + dislikes) - 1.96 * SQRT((likes * dislikes) / (likes + dislikes) + 0.9604) / (likes + dislikes)) / (1 + 3.8416 / (likes + dislikes)) AS ci_lower_bound');
        $this->db->where('likes + dislikes >', 0);
        $this->db->order_by("ci_lower_bound", "desc");
        $query = $this->db->get('posts', $config['per_page'], $this->uri->segment(1));
        $data['results'] = $query->result();

The results always end up as empty.
Answer: 1.the table name has not been specified in code "widgets"
try:
        $this->db->from('widgets');

Answer: Hmm... Turns out my code was right after all. There was just some glitch with MySQL:
$this->db->select('*, ((likes + 1.9208) / (likes + dislikes) - 1.96 * SQRT((likes * dislikes) / (likes + dislikes) + 0.9604) / (likes + dislikes)) / (1 + 3.8416 / (likes + dislikes)) AS ci_lower_bound');
$this->db->where('likes + dislikes >', 0);
$this->db->order_by("ci_lower_bound", "desc");
$query = $this->db->get('posts', $config['per_page'], $this->uri->segment(1));
$data['results'] = $query->result();


Passing calculated value to Django template

Question: I'm pretty new to Django and I'm having trouble with passing a variable to a Django template.  My code finds the average of an Integer field from the database (using Django's AVG) then perform a calculation on the result. Ultimately I would like to pass the result of this calculation to a template.
My model.py is:
from django.db import models

class Post(models.Model):
    fname = models.CharField(max_length=20)
    lname= models.CharField(max_length=25)
    reading=models.IntegerField(default=100)
    entrytime=models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self

The view is:
from django.views.generic import TemplateView, ListView
from django.db.models import Avg
from .models import Post

class ShowCalcView(ListView):
    model=Post
    template_name = 'calc.html'

    def calca1c(request):

        context = Post.objects.aggregate(Avg('reading'))
        r=context['reading__avg']
        rs = (46.7 + r) / 28.7
        context['calc']  = rs
        return context

The template is:

Approximate A1C

Approximate A1c:  {{ calc }}

I have tried using {{ calc }}, {{ calc.rs}}, {{ calc['rs'] }}, and just about every other combination I can think of but the value is not being passed.  I have checked the function in the shell, and it produces the desired result.  I'm probably missing something obvious but I cannot figure it out.
Thank you for your assistance.
Answer: The context for a view is generated from a get_context_data() method. This is what you need to override to inject additional context into the view. As it is currently your getca1c() method will never be used because it is not something that Django looks for.
So you would do something like this:
def get_context_data(self, **kwargs):
    context = super().get_context_data(**kwargs)
    context['calc'] = self.getca1c(self)
    return context

You would then modify getca1c() to return just a number that is the average you want to display:
def calca1c(self):
    result = Post.objects.aggregate(Avg('reading'))
    r = result ['reading__avg']
    return (46.7 + r) / 28.7

(side note - the first argument to this method is self - i.e., the view class instance - and not a request object).
And then in your template:

Approximate A1c:  {{ calc }}

Comment: Thank you!  This worked with one tweak.  self.gatcalc(self) returned an error (takes 1 positional argument but 2 were presented), so I removed the (self) from this call and it now works perfectly.  Thank you so much!!!


Using variable in another function Javascript

Question: Hello I have a problem with AJAX I got my data from the url but I want to use the variable IsochroneData into the function geo_json_add. How can I do this? I can console log the data that works fine. But getting the variable to the other function is my problem.
$.getJSON("/isochrone", function (data) {
 var isochroneData = data
 console.log(data);
 function geo_json_add(isochroneData) {
   geo_json
   .addData(isochroneData)
   .addTo(map);
 }
 geo_json_add(isochroneData);

Comment: The code you've posted is not valid JavaScript. If the `geo_json_add` function is nested within the `getJSON` callback, it will work just fine as-is.
Answer: When you want to make a variable global, you've to declare it outside the function then set its value in the function, without the declaratory keyword then it'd be global.
var isochrone; - Outside the function
isochrone = data - In the function
Answer: Fix your syntax and indentation
$.getJSON("/isochrone", function (data) {
 var isochroneData = data
 console.log(data);
 function geo_json_add(isochroneData) {
   geo_json
   .addData(isochroneData)
   .addTo(map);
 }
 geo_json_add(isochroneData);
})

if you want to use geo_json_add elsewhere, declare it ouside of the getJSON.
function geo_json_add(isochroneData) {
  geo_json
  .addData(isochroneData)
  .addTo(map);
}

$.getJSON("/isochrone", function (data) {
  var isochroneData = data
  console.log(data);

  geo_json_add(isochroneData);
})


How to get the data of field collections

Question: I have one field collection with 4 fields. How to get the data of field collection in views tpl file
I am trying to load data as
field_collection = entity_load('field_collection_item', array($node->field_suppliers_value['und'][0]['value']));
print_r($field_collection);

The fields in field collection are one is text field and another one is entity reference and one more is term reference and last one is date type.
I am able to retrieve the data only for text data type and for other data types it was showing as [target_id]=some number.
How can i retrieve the data for other data types except text.
Comment: Your approach is correct. I would recommend to use dpm($field_collection) (a function bundled with devel module) to inspect the object. It even gives you the PHP expression needed to load any particular item from the object / array.
Answer: These are the field data types and their column names:

Text - value
Entity Reference - target_id
Term Reference - tid

Combine that with field_get_items(), e.g.:
$items = field_get_items('node', $node, 'field_suppliers_value');

if ($items) {
  // Or $items[0]['target_id'], etc
  $fc = field_collection_item_load($items[0]['value']);
}

Hopefully that'll give you enough to go on.
Comment: In $fc i can see the target_id with some number, how can i get the data for that target_id. Please can you clarify me...If i print the $fc , the field array is like `[field_technology_supplier] => Array
        (
            [und] => Array
                (
                    [0] => Array
                        (
                            [target_id] => 19417
                        )

                )

        )`


Column editor in Oracle Sql Developer

Question: Anyone knows if there is a column editor function in Oracle SQL Developer?
I have to modify the same column in a large number of insert statement and it would be really useful to have a column editor.
To explain better which is my problem i am searching a function similar to Eclipse ones when you type Alt + Shift + A (How do I enable the column selection mode in Eclipse?), and it allow you to edit in one time a lot of columns.
There is something similar or i have to do it manually?
I am using 18.104.22.168 version.
Thanks
Comment: You can add extra cursors by ctrl+shift+click, but I can't find column editing in SQL Developer so would recommend UltraEdit instead.
Comment: i know that, but it's not like others software column editing. I don't think it's possible right now, maybe in the future. Thank you anyway for the suggestion!
Answer: If you're using a newer version of Oracle Sql Developer (at least 18.3.x but perhaps before) there is an even easier way.
Simply go to the "Edit" menu and then choose "Block Selection":
Comment: Legend. Thanks @risingTide. This answers my problem!
Answer: Edit/Wrap Selection (enable it):
https://www.thatjeffsmith.com/archive/2012/07/how-to-block-select-text-in-oracle-sql-developer/
Just press Shift and move cursors up and down, etc.
Be careful to press Esc after each edition as it seems to "stick" or something and it keeps adding cursors and modifying where you don't expect it.
Trick: The multi-cursor is useful to edit several parts in the same line.

Column editor in Oracle Sql Developer


Import database with SSDT programmatically

Question: I have a situation where I need to copy everything out of a database (except data) and deploy it to a new database. I am currently doing this by importing from the existing database into SSDT and then publish the project to the new database.
I want to know if there is a way I can do this programmatically. Ideally I would like to have a process in place where I can give the process the name of the database to copy from, the name of the database to copy to, and then the process  would just automatically carry out the import and export.
What might be a good way to do this?
Answer: SSDT is powered by a library called the Data-Tier Application Framework (also known as DacFX).  DacFX is a public API that you can use to extract and publish dacpac files.  You can find a copy of DacFX in Program Files under Visual Studio or SQL Server in a directory something like this:

C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\Extensions\Microsoft\SQLDB\DAC\130
C:\Program Files (x86)\Microsoft SQL Server\130\DAC\bin

You can download the latest version of DacFX here:
https://www.microsoft.com/en-us/download/details.aspx?id=51672
Note that when you install DacFX it's also necessary to install its dependencies, SqlSysClrTypes and SqlDom, which can be found in the System Requirements section of the above download page.
To use DacFX to extract and publish a dacpac file, you can use SqlPackage.exe, like so:
C:\Program Files (x86)\Microsoft SQL Server\130\DAC\bin\SqlPackage.exe /a:extract /scs:"Data Source=YOURSERVER;Initial Catalog=YOURDB;Integrated Security=true" /tf:C:\temp\yourdb.dacpac
C:\Program Files (x86)\Microsoft SQL Server\130\DAC\bin\SqlPackage.exe /a:publish /tcs:"Data Source=YOURSERVER;Initial Catalog=YOUROTHERDB;Integrated Security=true" /sf:C:\temp\yourdb.dacpac
Alternately, you can use DacFX programmatically using the Microsoft.SqlServer.Dac API, like so:
using Microsoft.SqlServer.Dac;
class Program
{
    static void Main(string[] args)
    {
        DacServices ds = new DacServices("Data Source=YOURSERVER;Initial Catalog=YOURDB;Integrated Security=true");
        ds.Extract(@"C:\temp\yourdb.dacpac", "YOURDB", "AppName", new System.Version());
        using (DacPackage dp = DacPackage.Load(@"C:\temp\yourdb.dacpac"))
        {
            ds.Deploy(dp, "YOUROTHERDB");
        }
    }
}
Answer: You could do it programatically but I would say the easiest would be to buy a license for redgate sqlcompare and using the command line version of that.
Answer: Database Create Script
[2]: Run this Script in code
I hope It Help
Comment: Thanks, but I'm wanting to this programmatically


How to break long lines in grakn console?

Question: Is there a kind of soft-break or line-continuation character for breaking longer lines into 2 or more short lines before submitting a graql statement?
Found nothing about this issue in the docs.
Answer: You can use the editor command to open your default editor (normally vim) and prepare multi-line queries there.


Prevent Carousel scroll within scrollable Container (Sencha 2)?

Question: I've got a Container with a header, content (Carousel) and a footer. The Container itself is therefor scrollable (vertical) to be able to scroll down to the footer. The Carousel can be swiped horizontally to change active item. I want to lock it to do only two thing:

If starting to move vertically, only scroll Container
If starting to move horizontally, only scroll Carousel

If you now grab the Carousel you are able to scroll both ways at the same time. Example code:
Ext.define('MyApp.view.MyContainer', {
    extend: 'Ext.Container',

    config: {
        scrollable: true,
        items: [
            {
                xtype: 'container',
                items: [
                    {
                        xtype: 'label',
                        html: 'abc'
                    }
                ]
            },
            {
                xtype: 'carousel',
                height: 200,
                scrollable: false,
                items: [
                    {
                        xtype: 'label',
                        html: 'x'
                    },
                    {
                        xtype: 'label',
                        html: 'y
y
y
y
y
y
y
y'
                    }
                ]
            },
            {
                xtype: 'container',
                items: [
                    {
                        xtype: 'label',
                        html: 'def'
                    }
                ]
            }
        ]
    }

});

Using Sencha Touch 2.
Answer: You might need to block the over scrolling .This will help to prevent both vertical scrolling and carousel item change happening at the same time.Try this code inside your scrollable of container.
 scrollable: {
           directionLock: true,
            direction: 'vertical',
            momentumEasing:  {
             momentum: {
               acceleration: 30,
               friction: 0.5
             },
             bounce: {
                acceleration: 0.0001,
                springTension: 0.9999,
             },
             minVelocity: 3
          },
          outOfBoundRestrictFactor: 0
        },

Answer: If starting to move horizontally, only scroll Carousel
Just add this to the config of your container :
config: {
  scrollable: {
    direction: 'vertical',
    directionLock:true
  }
}

I still haven't figured out how to lock the carousel when you scroll vertically. I'll let you know if I find out.
Answer: Try this one.It is working fine for me.
Ext.define('MyApp.view.MyContainer', {
    extend: 'Ext.Container',

    config: {
        scrollable: {
            direction: 'vertical'
        },
        items: [
            {
                xtype: 'container',
                items: [
                    {
                        xtype: 'label',
                        html: 'abc'
                    }
                ]
            },
            {
                xtype: 'carousel',
                height: 200,
                direction: 'horizontal',
                directionLock: true,
                items: [
                    {
                        xtype: 'label',
                        html: 'x'
                    },
                    {
                        xtype: 'label',
                        html: 'y
y
y
y
y
y
y
y'
                    }
                ]
            },
            {
                xtype: 'container',
                items: [
                    {
                        xtype: 'label',
                        html: 'def'
                    }
                ]
            }
        ]
    }
});


Egorov's theorem and Baire class $1$ function

Question: Suppose $f$ is Baire class 1. Then there exists $f_n$ each one is continuous and that $f_n \to f$. By Egorov's theorem, a measurable $\mu(B) < \varepsilon$, and $(f_n)$ converges to $f$ uniformly on the relative complement $A \setminus B$.
(1) Can we make the set $B$ to include the set of discontinuous point of $f$?
(2) Can we construct $g_n$ where the rate of convergence on $B$ is slowest?
Comment: Then what additional assumption will be needed?
Answer: The answer to the first question is no. Say $K$ is compact, has empty  interior, no isolated points, and positive measure (for example a fat Cantor set). Let $f=\chi_K$. Then $f$ is in Baire class 1. But $f$ is discontinuous at every point of $K$. So you can't include all the discontinuities of $f$ in $B$ if $\epsilon<m(K)$.
The second question doesn't make much sense, since you don't give any relation between $g_n$ and $f_n$. Were the $g_n$ supposed to be a subsequence of $f_n$ or something? (Once we make sense of the question the answer will be no - there's never a slowest anything...)
Comment: Then what condition on $f$ is needed to make (1) true?
Comment: It's obvious true if and only if $f$ is continuous almost everywhere.
Comment: Then how about (2)? want to show existence of such $g_n$.
Comment: ??? I _said_ in my answer that I didn't understand what you meant by (2). When you say "how about (2)?" that doesn't really clarify things much...


Linguagem C - Loop infinito, não esta fazendo a comparação de vetores como planejei

Question: Boa tarde.
Estou fazendo um exercício, desenvolvi uma solução porem não esta funcionando, estou há alguns dias tentando resolver porem empaquei.
Escreva um programa que leia a idade e o primeiro nome de 10 pessoas. Seu programa
deve terminar quando uma idade negativa for digitada. Ao terminar, seu programa deve
escrever o nome e a idade das pessoas mais jovens e mais velhas.
<code>#include <stdio.h>
#include <string.h>
#include <conio.h>

int main()
{
    int i=0;
    int idade[10];
    int troca_idade;
    char nome[10][20];
    char troca_nome[20];

    for (i=0;i<10;i++){
        printf("Digite o %i nome: ",i);
        fgets(nome[i],20,stdin);
        setbuf(stdin,NULL);
        printf("Digite a idade: ");
        scanf("%i",&idade[i]);
        setbuf(stdin,NULL);
        if (idade[i]<0){
            break;
        }
    }

    for(i=0;i<10;i++){
        if (idade[i]<idade[i+1]){ // Se a posição atual for menor que a seguinte não faz nada, se for diferente começa.Lembrando que estou espelhando a posição da idade com os nomes.

        }
        else{
            troca_idade=idade[i];//troca_idade esta com maior valor
            // troca_nome=nome[0];
            strcpy(troca_nome, nome[i]);

            idade[i]=idade[i+1];//idade[i] esta com o valor menor
            //nome[i]=troca_nome[0];
            strcpy(nome[i],nome[i+1]);

            idade[i+1]=troca_idade; //A posição a frente (i+1) esta com o maior vetor
            //nome[i+1]=troca_nome[0];
            strcpy(nome[i+1],troca_nome);

            printf("\n%i",i);
            i=0; //Se for feita uma alteração zera o contador, para refericação de todo o vetor novamente, só sai do loop quando na mudar nada de lugar.
        }
    }

    for (i=0;i<10;i++){
        printf("idade: %i nome: %s ",idade[i],nome[i]);
    }
    return 0;
}
</code>
A logica e a seguinte, se a posição posterior for maior que a atual ambas trocam de valor, a cada vez que troca zera o contador, para reverificar tudo, só sai do Loop quando não fizer mais nenhuma modificação !
Acredito que o problema esteja no contador i do FOR, quando mando imprimir so aparece o valor 2.
Sei que é um problema simples e banal, mas fiquei alguns dias tentando resolver. E as soluções que tento esta dando perigo no compilador, nem chego a testa-las.
Comment: Note que o índice de seu array varia de 0 a 9. Você faz o loop ` for(i=0;i<10;i++){` mas logo a seguir o if `if (idade[i]<idade[i+1]){`, ou seja para i = 9 tentará acessar idade[10] que está fora do limite de seu array.
Answer: Muito obrigado !
Consegui deixar o código um pouco mais certo! A partir do momento que liberou o Loop vi alguns erros a mais e corrigi. Está praticamente funcionando.
Só estou com um pequeno problema as vezes quando tem que realizar muitas mudanças a primeira posição fica com valor errada, só troca de posição umas 2x.
<code>#include <stdio.h>
#include <string.h>
#include <conio.h>

int main()
{
    int i=0;
    int idade[10];
    int troca_idade;
    char nome[10][20];
    char troca_nome[20];

    for (i=0;i<10;i++){
        printf("Digite o %i nome:",i);
        scanf("%s",&nome[i]);
        setbuf(stdin,NULL);
        printf("Digite a idade:");
        scanf("%i",&idade[i]);
        setbuf(stdin,NULL);
        if (idade[i]<0){
            break;
        }
    }

    for(i=0;i<9;i++){
        if (idade[i]<idade[i+1]){ // Se a posição atual for menor que a seguinte não faz nada, se for diferente começa.Lembrando que estou espelhando a posição da idade com os nomes.

        }
        if(idade[i]>idade[i+1])
            {
            troca_idade=idade[i];//troca_idade esta com maior valor
            strcpy(troca_nome, nome[i]);

            idade[i]=idade[i+1];//idade[i] esta com o valor menor
            strcpy(nome[i],nome[i+1]);

            idade[i+1]=troca_idade; //A posição a frente (i+1) esta com o maior vetor
            strcpy(nome[i+1],troca_nome);

            i=0; //Se for feita uma alteração zera o contador, para refericação de todo o vetor novamente, só sai do loop quando na mudar nada de lugar.
        }
    }
    printf("\n");
    for (i=0;i<10;i++){
        printf("idade:%i nome:%s\n",idade[i],nome[i]);
    }
    return 0;
}
</code>
Eu consigo corrigir mas com gambiarra com outro loop ou aumentando o vetor, mas quero entender oque acontece. Para da próxima vez saber como reagir !
Sugestão de valores pra teste nessa ordem: 987,98,688,65,65,699,44,323,33,8.


Significance test with four categorical predictors?

Question: I'm analysing the following data:

I'm interested in the difference between the "CONT" control group, and PPS/PWS (which I'll collapse to one group), on the Normal/Abnormal measurements. I'm not interested in sex or age differences.
I thought I might be able to analyse this with a factorial ANOVA, or by using multiple regression.
What would be the best way to proceed? Are there any guides I could follow? I can use R or SPSS.
Comment: Just to clarify, you are interested in knowing if the "CONT" group differs from "PPS/PWS" group on all four variables (500R, 500L, 1000R, 1000L)?
Comment: That's a good question – I should have been more precise :-)
Comment: I'd be interested in both differences on the individual measures, and on the measure of all four variables (500R, 500L, 1000R, 1000L).
Comment: Interpretation would be easier if there was a significant difference on all four measures. But a significant difference on just one measure would also be of interest. However, there is little reason to suspect laterality effects. So, R&L (right and left) could be combined for 500Hz, and for 1000Hz – if I was working with continuous data, I'd be inclined to average them.
Comment: thanks for the clarification. I asked for the clarification because your title is inconsistent with your question. The title outlines there to be four predictors while it seems that you have four outcome variables and only one predictor (the grouping variable).
Comment: Ah yes. Sorry about that. I've managed to confuse myself by looking at latent variable analysis (in which my control and PWS groups are the outcomes). So, it's quite likely I'm using the wrong terminology for a smaller scale analysis where the focus is on group differences.
Answer: It seems that you have four questions of interest:

are group assignment and 500R independent of each other?
are group assignment and 500L independent of each other?
are group assignment and 1000R independent of each other?
are group assignment and 1000R independent of each other?

In addition, group assignment and outcome variables are all categorical variables. In this case, it seems to me that Chi-squared test would be appropriate to help answer those questions.
Furthermore, if you do decide to run four chi-squared test, correction for multiple testing would be highly recommended. Bonferroni correction can be applied, that is, your alpha level should be divided by the number of tests you run. In this case, since you are running four tests, if p<.05 is your usual threshold of significance, in each of the four tests, your threshold of significance should become p<.0125 in order to preserve a family type I error rate under .05.
Comment: Thanks, that is brilliant :-).

None of the comparisons reach significance. 500Hz Right was at p=.04 before the Bonferroni correction.
Comment: You can probably report that as like a trend or marginally significant. :)


A theme in a custom distribution isn't found

Question: For our Drupal sites we develop our own distribution. In the distribution are two themes (administration theme and custom base theme). The administration theme works, but the custom base theme cannot be found. When I try to install the theme with drush theme:enable our_base_theme -y, I get this error.

In ThemeInstaller.php line 136: Unknown themes: our_base_theme.

In admin/appearance, under the custom theme, which depends on the base custom theme, I see:

Requires: our_base_theme (missing)
This theme requires the listed modules to operate correctly.

With $themeHandler->getTheme('our_base_theme'); in Drupal Shell, I get:

Drupal\Core\Extension\Exception\UnknownExtensionException with message 'The theme our_base_theme does not exist.'

The themes are located at:

web/profiles/custom/our_profile/themes

our_admin_theme
our_base_theme

When I move the theme to web/themes/custom/our_base_theme, the theme can be found and works correctly.
I have already tried:

Clearing the cache
drush cr

Reinstalling the Drupal files
rm composer.lock
composer install
# or composer update

Setting file and folder permissions to avoid issues
chmod -R 777 web/profiles/custom/our_profile/themes

Refreshing the theme data
$themeHandler = \Drupal::service('theme_handler');
$themeHandler->reset();
$themeHandler->rebuildThemeData();
$themeHandler->refreshInfo();

Changing the path in
SELECT * FROM `key_value` WHERE `collection`='state' AND `name`='system.theme.files';

There is a similar issue, where the solution is to delete the hook_install() implementation, but we don't use that hook in our distribution.
I have found also a troubleshooting article, but none of the suggestions solved the issue.
Comment: Thanks @apaderno
Answer: This issue has been created during the migration of the old site (without the distribution) to the new site (with the distribution). Because of a lot of dependencies in the configurations, the migration has been divided in two stages. In the first stage (in old git repository) all new distribution modules and themes have been enabled, but without any configurations (the modules and themes in the old repository have only info files). In the second phase of the migration (in new git repository) have been the configurations imported.
The path to the installation profile in the old repository was: "web/profiles/our_profile", in the new repository: "web/profiles/custom/our_profile". After changing the path in the old repository to : "web/profiles/custom/our_profile", the theme works and can be found also after the migration.
I do not understand, why the issue effected only one theme and none of the modules.


Page not found in drupal 7

Question: I am new to Drupal. I added a new content type and a view that points in the google map for the locations I entered
This worked fine in my local site. I implemented the same in the live site. But that gave a page not found error for every page and all the pages are redirected to some another unneccessary page.
Please let me know if adding a view can cause this kind of errors.
I used these modules: Location Map, Geocoder, geoPHP , Geofield and Geomap.
Or did this effect occure because of using these modules?
Comment: Have you tried clearing cache ..?
Answer: Check if anything in this list of typical things might help:

Make sure "clean urls" is enabled. Refer to "Clean URL leads to duplicate URL after migration to another hosting" for more details on that.
Make sure the value of "base_url" is set correctly (in your settings.php).

Another option is to check the logs. If you find errors there (like PHP Fatal errors), then try to narrow down that error to the module that causes the error and disable that module (and report it in its issue queue on Drupal.org). If you don't know which module is causing it, then first disable all modules, and enable them one by one again. If at some point the error then comes back, then that must be the problem module causing your problem. Then disable that module again and re-enable all others.
Comment: Hi..thank you for the reply.I checked the logs and found the error that reported as below    "     PHP Fatal error:  [] operator not supported for strings in ..../../includes/common.inc  at the line that contains code below  $options['attributes']['class'][] = 'active'; "
Comment: I enhanced my answer related to the error you mentioned.
Answer: 'Page not found' is exactly what it refers to. That means that particular url is still not created. There are multiple ways to do that in Drupal 7 depending on your approach.
Since you indicated views, for views you would set the page at Path: under the Page Settings tab incase a Page Level view is being added.
Here is a link that can introduce some of those concepts.
If this does not help, please add the link where you would like to display the view at?
Comment: .Thank you for the reply.I have added \path  for the view in the page settings tab only.I tried that in local which worked fine ..I am facing the issue when i am doing the same in the production site.
Comment: Are you able to share the link that you are trying to load? Additionally a screenshot of the view and the error page would help as well

Page not found in drupal 7


Jmeter loop though CSV Data set config - Ajax flow

Question: I am new to Jmeter and trying to carry out the following flows:

User Login with username and password
Page 1 is displayed with 10 invoices - User select ten invoices -
10 ajax call is executed (invoice1, invoice2,invoice3..  json file is generated with invoices as request)
Page 2 is displayed to view  invoices
User log out

I have recorded the flow with blazemeter plugin on chrome.
The thread group in Jmeter has the following tasks:

I have 10 users in a file called users.txt and i am using CSV Data
set config to load them.
For each user  I will load only 10 invoices from invoices.txt using
CSV Data set config to load them.
Since I have 10 users and each user needs 10 invoices, my
invoices.txt has 100 unique invoices.

Please find csv config for invoice below:

The problem is that I need each user to be assigned with 10 unique invoices and those 10 invoices cannot be allocated to another user.
Any idea how I can load 10 unique invoices for each user and make sure those invoices are not assigned again to another user?
Comment: invoices.txt have unique IDs? is its CSV Data Set sharing mode is All Threads?
Comment: yes they are unique and sharing mode is All threads. I have updated my post with this info
Answer: invoices.txt should have only unique IDs before test start, you can share the IDs using:
CSV Data Set Config inside loop of users with attributes:
Sharing mode - All Threads - ID won't be repeated

Recycle on EOF? - False - for not to get invalid Id (<EOF>)

Stop thread on EOF? - True - Stop when file with unique IDs ends

Answer: You can consider using HTTP Simple Table Server instead of 2nd CSV Data Set Config.
HTTP Simple Table Server has KEEP option, given you set it to FALSE each used "invoice" will be removed, it will guarantee uniqueness even in case when you run your test in Distributed (Remote) mode
You can install HTTP Simple Table Server (as well as any other JMeter Plugin) using JMeter Plugins Manager


Solving $z^3 =-1$

Question: I need to find the solution of $z^{3} =-1$.
Let$$z=[ r,\theta ]$$
then using de Moivre's theorm$$ z^{3} =\left[ r^{3} ,3\theta \right] $$
write the number $-1$ in modulus argument from,
$$[ 1,( 2n-1) \pi ]$$
the we can write$$\left[ r^{3} ,3\theta \right] =[ 1,( 2n-1) \pi ]$$
Therefore,$$ r^{3} =1 \space \text{and} \space \theta =\frac{( 2n-1) \pi }{3}$$
Then$$z_{n} =1\left( \cos\frac{( 2n-1) \pi }{3} +i\sin\frac{( 2n-1) \pi }{3}\right)$$
\begin{align}
&n=0 \quad z_{0} =\frac{1}{2} -i\frac{\sqrt{3}}{2}\\
&n=1 \quad z_{1} =\frac{1}{2} +i\frac{\sqrt{3}}{2}\\
&n=2 \quad z_{1} =-1\\
\end{align}
Comment: Note that unity means 1,  not (-1).
Comment: @Lazy No, the answer is not correct. The first red flag is that the complex roots should be conjugates, while OP's are not.
Comment: @dxiv Oh yeah, I didn't read closely enough to spot that there is a big modulus error (that's what being tired does for you). Basically the error is that you do not want $(-1,n\pi)$ but $(-1,n2\pi)$, as $e^{it}$ is $2\pi$-periodic. So then $\theta = 2n\pi/3$.
Comment: @Lazy The canonical modulus-argument representation is $\,\big(1, (2n+1)\pi\big)\,$.
Comment: @dxiv I think it is correct now. Thank you sir
Comment: @dxiv That is correct, but irrelevant for the construction.
Comment: Your answer is correct. You can see this from: Your three solutions are clearly solutions and distinct. As this *can* only have three distinct solutions, these are all solutions.
Comment: "*write the number −1 in modulus argument from ...*" $\;-\;$ Except the modulus must be a non-negative number, and the argument is *not* $\,n \pi\,$.
Comment: You have mentioned complex root of unity, but then solved z^3=-1. If you want the complex roots of unity, shouldn't it be z^3=1.
Comment: I'm following the lecture note, It has not any examples. It noted that Complex root of unity. @Starlight I'm sorry, I don't know much about that.
Comment: @dxiv, thanks sir
Comment: @Lazy now is it correct? updated
Answer: You can find the complex roots of unity as below. The equation you have solved is not the one that will give you complex roots of unity.
$$z^3=1 \implies z^3-1=0$$
Factor the LHS (using any of a variety of methods):
$$(z-1)(z^2+z+1)=0$$
Use the zero-product property:
$$z-1=0\implies z=1$$
$$z^2+z+1=0\implies z=\frac{-1\pm i\sqrt{3}}{2}$$
(where we used the quadratic formula above)
Comment: Thanks for your effort, But I need to solve above equation by using complex complex number de moivre's theorem.
Answer: $z=re^{i\theta}$
$z^3 = -1$
$r^3 (e^{3 i \theta})= 1\cdot e^{i\pi}$
Hence, $  r=1$ and $\theta= \frac{i(\pi + 2k\pi) }{3}$ for $k=0, 1,2$
$z= e^{\frac{i\pi}{3}} , e^{i\pi}, e^{\frac{5i\pi}{3}}$

Solving $z^3 =-1$


Div slide from the left side after a button is clicked

Question: The picture explains it better than I do.
Before I click on it - screenshot1
After: screenshot2
It's a fixed button on the side of a window and it slides out when it's clicked.
I've been searching the web for so long and can't find the solution. Could you guys help me please?
Comment: you should put some code here. jsfiddle.net is your friend :)
Comment: may be the problem of space from right side when button clicked then one panel is open.so we guess that then panel doesn't have enough space from right side.so it slide left side with button..
Comment: I think you are asking like this : http://www.jqueryscript.net/demo/Simple-jQuery-Plugin-For-Slide-Out-Tab-Feedback-Widget-Feedback-Me/

From here you can download fixed forms : There are lots of fixed forms are there : http://www.jqueryscript.net/tags.php?/Contact%20Form/
Answer: below code can help you.
HTML

   <

CSS
#hiddenPanel {position:fixed; top:0; right:-200px; width:200px; background-color:grey; height:250px;}
#close-bar { position:absolute; left:-20px; background:red; color:white; width:20px; height:250px;}

jQuery Code
var speed = 300;
    $('#close-bar').on('click', function(){

        var $$ = $(this),
            panelWidth = $('#hiddenPanel').outerWidth();

        if( $$.is('.myButton') ){
            $('#hiddenPanel').animate({right:0}, speed);
            $$.removeClass('myButton')
        } else {
            $('#hiddenPanel').animate({right:-panelWidth}, speed);
            $$.addClass('myButton')
        }

    });

http://jsfiddle.net/Rxsd5/
Answer: basically i do in jquery, however i given a code for css.. i used hover instead of click. And changes these css values and play with it..

     //content or form goes here..

.wrapper {
    position: relative;
    overflow: hidden;
    width: 100px;
    height: 100px;
    border: 1px solid black;
}

#slide {
    position: absolute;
    left: -100px;
    width: 100px;
    height: 100px;
    background: blue;
    transition: 1s;
}
.wrapper:hover #slide {
    transition: 1s;
    left: 0;
}


When editing a node, some markup disappears

Question: I'm using Drupal 7 and my page loads and looks fine when I add a new node and insert HTML markup. When I edit the page, some of the markup either disappears or it's replaced.
For example, if I add
, the node saves and it's displayed fine. When I edit the node,
 is replaced by
. If I add ,  is replaced by
.
Do you know why this would happen? How can I fix it?
Comment: sounds like the standard operation of an input filter... which ones do you have installed and are you using a WYSIWYG editor or just plain text entry?
Answer: I have the same issue, and this is caused by the WYSIWYG editor: When you try to edit a node created with a input format with WYSIWYG enabled, the HTML markup will be changed by the editor.
To solve it, you have two options.

Disable the WYSIWYG editor by default, unselecting the checkbox as shown in the screenshot.

Create a node using an input format that doesn't use the WYSIWYG editor (for example Full HTML, or Filtered HTML). If the Full HTML format is already associated with a WYSIWYG profile, try to create a custom format from /admin/config/content/formats, and use it to create new nodes. Remember to not associate a WYSIWYG profile.


Extract a field if it is accompanied by specific key-value pairs

Question: //test.json
{
"RED":
  [
    {
      "attr1": "aaaa",
      "attr2": "bbbb",
      "attr3": "cccc"
    },
    {
      "attr1": "aaaa",
      "attr2": "dddd",
      "attr3": "eeee"
    }
  ],
"WHITE":
  [
    {
      "attr1": "aaaa",
      "attr2": "bbbb",
      "attr3": "cccc"
    },
    {
      "attr1": "aaaa",
      "attr2": "dddd",
      "attr3": "eeee"
    }
  ]
}

I want to get a value that meets (key=RED && attr1="aaaa" && attr2="bbbb")
So I have written jq command like this :
jq -r 'with_entries(select([.key] | inside(["RED"]))) | .[] | .[] | select(.attr1=="aaaa") | select(.attr2=="bbbb") | .attr3' test.json

this command works well. but I think that command is a little long.
How can I shorten the command without reducing readability?
(* This is my first time using JQ)
Comment: Next time, do clarify all the details beforehand. https://jqplay.org/s/WumRKjvHyn In case you wanted my answer (deleted) as reference
Comment: Is `RED` always going to be present? do you want it hardcoded or by dynamically selected?
Comment: @Inian I checked your answer. In the case I ask, RED is always present. I think your answer is very useful when i need to make a dynamic select. Thank you.
Answer: You don't need with_entries or multiple selects there. The following program does exactly the same thing and is way shorter.
.RED[] | select(.attr1 == "aaaa" and .attr2 == "bbbb") .attr3


Self-Adjoint Transformation in Visualization

Question: Self-adjoint transformations obey $\langle T v, w\rangle=\langle v, T w\rangle$
What is a simple example and visualization of a self-adjoint matrix where everything is on $\mathbb{R}^{2}$? The book I am using is very algebraic and does not present any examples.
Comment: It's a stretch/squeeze in one direction and also in the perpendicular direction.
Comment: Could you please elaborate a bit? If $w$ is a fixed vector, then we take some $v$ to $Tv$ and this dot product happens to be the same if we took $w$ to $Tw$ instead. So I am guessing the magnitude and angle shift from $v$ to $Tv$ has to be made up by $w$ to $Tw$. But how ?
Comment: Self-adjoint maps in spaces with positive-definire inner products are diagonalizable. Do you know how to interprete the action of a diagonal matrix? That's it (up to change of basis).
Answer: Theorem : $T : V \longrightarrow V$ is a self-adjoint operator if, and only if, its matrix relative to a (and therefore to any) orthonormal basis $B = \lbrace v_{1}, \cdots, v_{n} \rbrace \subset V$ is a symmetric matrix.
Let $T : \mathbb{R}^{2} \longrightarrow \mathbb{R}^{2}$ be a linear operator defined by: $T(x,y) = (x, 2y)$
So, for all $v = (x,y)$, we have:
1) $\langle e_{1}, T^{*}v \rangle = \langle Te_{1}, v \rangle = \langle e_{1}, v \rangle = x$
2) $\langle e_{2}, T^{*}v \rangle = \langle Te_{2}, v \rangle = \langle 2e_{2}, v \rangle = 2y$
From the above theorem, we have: $T^{*} = T$.


Does this multivariable non-negative function only have minima points?

Question: Consider multivariable functions of the form: $$\left(\sum_{i=1}^n a_ix_i\right)^2$$ Can they only have minima points? If so, why?
I tried to plot some functions on Desmos and it looks like my hypothesis is correct, but maybe I'm missing something.
Edit: I removed the first question, as I realized it was too naïve.
Comment: Can you clarify a bit more? Are you looking to see whether other extrema than minima are possible with such functions, or do you want functions that only consist of minimal points?
Comment: Do you mean functions like $f(x) = e^x$? That's a non-negative function, but it doesn't have a smallest value.
Answer: The function $x^2 e^{\left(-x^2\right)} + 1$ has global maxima at $x = \pm 1$. https://www.desmos.com/calculator/llxnomd24q
Comment: Thanks, but you didn't answer my second question
Answer:
No.  One example is constant functions : every point is simultaneously a global maximum and a global minimum.  A less degenerate example is

having a local maximum at $x = 0$.  Another is

In fact $\mathrm{e}^{P(x)}$, where $P(x)$ is a polynomial in $x$ having a global maximum (respectively, local maximum), is an everywhere positive function having a global maximum (resp., local maximum).

Yes or maybe, depending on your definitions.  Compute the various first partial derivatives to discover that the only possible critical point is at the origin, $x = (0,\dots, 0)$.  Here, the function is $0$, so there is both a local minimum and a global minimum at the origin.  However, note that if all the $a_i = 0$ then every point is simultaneously a global minimum and a global maximum.


How to open saved event log archive in .NET?

Question: I have used the System.Diagnostics.EventLog to view the logs on the local computer.  However, I would like to open a saved event log archive (.evt or .evtx) and view the logs that are contained in the saved file.  I just need to view timestamps, messages, sources, etc. associated with the logs in the file.  Can this be done in C#?
Answer: Check out the System.Diagnostics.Eventing.Reader namespace. Specifically the EventLogQuery class.
http://msdn.microsoft.com/en-us/library/bb671200(v=VS.90).aspx
Answer: Try LogParser tool from Microsoft. It can fetch any data from logs of any log format using SQL-like selecting language. It can also be used from any .NET application. The example parsing of CSV logs (I believe you can use this code for EVT files with small modifications):
        public IList<LogRow> GetLog()
        {
            return Load("SELECT *, OUT_ROW_NUMBER() FROM logfile*.log WHERE Field2='Performance' ORDER BY Field1 ASC");
        }

    private static IList<LogRow> Load(string sql)
    {
        IEnumerable<string[]> log = ParseLog(sql);

        return Convert(log);
    }

    private static IList<LogRow> Convert(IEnumerable<string[]> log)
    {
        return log.Select(logRecord => new LogRow
                                           {
                                               TimeStamp = logRecord[2],
                                               Category = logRecord[3],
                                               Machine = logRecord[4],
                                               ThreadId = logRecord[5],
                                               ProcessId = logRecord[6],
                                               ProcessName = logRecord[7],
                                               DomainName = logRecord[8],
                                               Message = logRecord[9],
                                               Number = logRecord[10]
                                           }).ToList();
    }

        private static IEnumerable<string[]> ParseLog(string query)
        {
            var records = new LogQueryClassClass().Execute(
                query,
                new COMCSVInputContextClass { headerRow = false, iTsFormat = "yyyy-MM-dd HH:mm:ss.fff" });
            var entries = new List<string[]>();

            while (!records.atEnd())
            {
                entries.Add(records.getRecord().toNativeString("CSVseparator").Split(
                                new[] { "CSVseparator" },
                                StringSplitOptions.None));
                records.moveNext();
            }

            records.close();
            return entries;
        }

Answer: If your intention is to read the saved logs, we can do it using EventLogReader. It basically takes two parameters - filename (as in file path), and second parameter specifying path type. For your reference, say you have a saved .evtx file - temp.evtx, you can read it as in:
new EventLogReader(filepath, PathType.Filepath);

This gives you an event log reader, which can be used to read events. And further more, if you would want to read content out of it, we can use Properties which is basically a list of string. Can read it, parse it, and get whatever information you need.
I agree that we don't have the provision to directly get all the details as like what we get using EventLogEntry. Never the less, we just need to have some parsing done to get what we need using event record.


Url rewriting issue on azure

Question: I have a subdomain, test1.test.com, i want to do a url rewriting on that subdomain to rewrite all requests to point other domain. For example i want to rewrite all request to test1.test.com to point http://www.AAA.com
here is my rewrite rule.
<rewrite>
      <rules>
        <rule name="Rewrite sample">
          <match url="(.*)" />
          <action type="Rewrite" url="http://www.AAA.com" />
        </rule>
      </rules>
    </rewrite>

the result is not what i expected.
"The resource you are looking for has been removed, had its name changed, or is temporarily unavailable."
Answer: It's not possible to rewrite to another domain. Rewrite deals only with the last part of the url (after the domain) so the only way to change domain is to use redirect like this:
<rewrite>
  <rules>
    <rule name="Test" stopProcessing="true">
      <match url="test1.test.com" />
      <action type="Redirect" url="http://www.AAA.com"/>
    </rule>
  </rules>
</rewrite>

Comment: i want rewrite instead of redirect, i want user to keep seeing test1.test.com in the address bar, while the content is from AAA.com
Comment: @AndrejKovalksy is not possible to rewrite to another domain. Rewrite deals only with the last part of the url (after the domain) so the only way to change domain is to use redirect.
Comment: thanks, you can edit your answer with your comment, that i can mark it as an answer.

Url rewriting issue on azure