Visual Studio offline installation remove old versions

Question: Is there a possibility to remove the old versions of installation packages from the layout folder of Visual Studio 2017 offline installation? This folder needs a lot of memory on my HDD.
Comment: Microsoft link (using --clean param): https://learn.microsoft.com/en-us/visualstudio/install/create-a-network-installation-of-visual-studio?view=vs-2022#remove-older-versions-from-a-layout
Answer: You can use the new --clean option. You'll need the file path(s) to catalog manifest(s) that contain those obsolete packages. You can find the catalog manifests in an Archive folder in the offline layout cache.
They are saved there when you update a layout. In the "Archive" folder, there is one or more GUID named folders, each of which contains an obsolete catalog manifest. The number of GUID folders should be the same as the number of updates made to your offline cache.
A few files are saved inside each GUID folder. The two files of most interest are a catalog.json file and a version.txt file. The catalog.json file is the obsolete catalog manifest you'll need to pass to the --clean option. The version.txt file contains the version of this obsolete catalog manifest. Based on the version number, you can decide whether you want to remove obsolete packages from this catalog manifest. You can do the same as you go through the other GUID folders. After you make the decision on the catalog(s) you want to clean, run the --clean command by supplying the files paths to these catalogs.
Examples:
vs_enterprise.exe --layout <layoutDir> --clean <file-path-of-catalog1> <file-path-of-catalog2> …

vs_enterprise.exe --layout <layoutDir> --clean <file-path-of-catalog1> --clean <file-path-of-catalog2> …

You can also invoke vs_enterprise.exe inside the <layoutDir>. Here's an example:
c:\VS2017Layout\vs_enterprise.exe --layout c:\VS2017Layout --clean c:\VS2017Layout\Archive\1cd70189-fc55-4583-8ad8-a2711e928325\Catalog.json --clean c:\VS2017Layout\Archive\d420889f-6aad-4ba4-99e4-ed7833795a10\Catalog.json

When you execute this command, Setup analyzes your offline cache folder to find the list of files that it will remove. You will then have a chance to review the files that are going to be deleted and confirm the deletions.
Comment: Yes. This is a new feature.
No. You don't have to download the whole packages again. A new folder will be created under ```Archive``` folder after any update progress. You can clear old packages using that catalog.
Comment: Is this a recent feature?  I only have one GUID if if I select it to be cleaned, it says a whole bunch of current files will be deleted.  I guess I'll have to download the whole thing from scratch to use this feature in future.
Comment: @Arman Is it safe after that to delete that Archive folder? I see it has only JSON files inside that folder.
Comment: @LoneWOLFs I think yes, It is safe to delete that folder after cleaning operation.
Comment: Also after each layout operation, there are a bunch of JSON files (e.g.  _Response_20170609091955_backup.json_)which are generated.  Is it ok if we get rid of these as well?
Comment: I have removed the Archive folder before updating offline layout. after 100% completion there is no Archive folder and I can see there are packages with multiple versions on layout dir. How to clean old packages now?
Answer: I had created a small utility application for deleting old version folders from Visual Studio 2017 offline setup.
You can download the source from GitHub at https://github.com/deepak-rathi/VS2017OfflineSetupUtility
Or
Run the executable VS2017OfflineSetupUtility.exe from Release folder
https://github.com/deepak-rathi/VS2017OfflineSetupUtility/tree/master/VS2017OfflineSetupUtility/bin/Release
Comment: Nice tool, simple and easy
Comment: Thanks for your effort! I'm wondering why Microsoft as such a large company did not recognize to produce such simple, user friendly and absolutely required tool for downloading, updating and cleaning the Visual Studio after such a looooong time!?
Answer:
After you perform layout updates to an offline cache, the layout
  cache folder may have some obsolete packages that are no longer needed
  by the latest Visual Studio installation. You can use the --clean
  option to remove obsolete packages from an offline cache folder.

Microsft Docs: How to remove older versions from a layout
Comment: The docs say that there should be one GUID folder under Archive for each update you've run. I've run it multiple times since first release (and the folder has doubled in size) but only have one GUID folder after the latest update. The docs aren't clear on whether this first creation is sufficient to remove all obsolete files from historical updates.
Comment: A feature that should have been in from the beginning. Guess I'll have to do a fresh, full download to start taking advantage of this.
Comment: no don't do a fresh one ... it will work fine ... I am using the same layout folder from the first version
Comment: after the --layout finish the folder with the guid will be created
Comment: This doesn't remove all old versions, I could remove ~8GB after using `--clean` and could install VS without problem
Comment: I got 96 GB free space after use this way LOL, thanks


Switch between Mongo production and test database - Java Spring Boot

Question: I have the following model:
import org.springframework.data.annotation.Id;

@Document
public class Customer {

    @Id
    public String id;

    public String firstName;
    public String lastName;

    public Customer() {}

    public Customer(String firstName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }

    @Override
    public String toString() {
        return String.format(
                "Customer[id=%s, firstName='%s', lastName='%s']",
                id, firstName, lastName);
    }

}

And the following repository:
import java.util.List;

import org.springframework.data.mongodb.repository.MongoRepository;

public interface CustomerRepository extends MongoRepository<Customer, String> {

    public Customer findByFirstName(String firstName);
    public List<Customer> findByLastName(String lastName);

}

The development database contains the customers collections, which contains the real data - the information regarding real customers.
As a big fan of TDD, I created the following Unit test:
@RunWith(SpringRunner.class)
@SpringBootTest
@ContextConfiguration(classes = {CustomerTest.class})
public class CustomerTest {

    @Autowired
    private CustomerRepository repository;

    @Before
    public void setUp() throws Exception {
           // I want to delete the test database, not the production one
           repository.deleteAll();
    }

    @Test
    public void testCreateCustomer() {

       // save a couple of customers
       repository.save(new Customer("Alice", "Smith"));
       repository.save(new Customer("Bob", "Smith"));

       // fetch all customers
       System.out.println("Customers found with findAll():");
       System.out.println("-------------------------------");
       for (Customer customer : repository.findAll()) {
           System.out.println(customer);
       }
       System.out.println();

       // fetch an individual customer
       System.out.println("Customer found with     findByFirstName('Alice'):");
       System.out.println("--------------------------------");
       System.out.println(repository.findByFirstName("Alice"));

       System.out.println("Customers found with findByLastName('Smith'):");
       System.out.println("--------------------------------");
       for (Customer customer : repository.findByLastName("Smith")) {
           System.out.println(customer);
       }
    }
}

Of course I have a SpringMongoConfig.java
@Configuration
@PropertySource(value={"classpath:application.properties"})
public class SpringMongoConfig extends AbstractMongoConfiguration {

    @Value("${spring.data.mongodb.host}")
    private String host;

    @Value("${spring.data.mongodb.port}")
    private Integer port;

    @Value("${spring.data.mongodb.database}")
    private String database;

    public @Bean
    MongoDbFactory mongoDbFactory() throws Exception {
        return new SimpleMongoDbFactory(new MongoClient(this.host + ":" + this.port), database);
    }

    public @Bean
    MongoTemplate mongoTemplate() throws Exception {
        MappingMongoConverter converter = new MappingMongoConverter(new DefaultDbRefResolver(mongoDbFactory()),
                new MongoMappingContext());
        converter.setMapKeyDotReplacement("\\+");

        MongoTemplate mongoTemplate = new MongoTemplate(mongoDbFactory(), converter);

        return mongoTemplate;

    }

    @Override
    protected String getDatabaseName() {
        return this.database;
    }

    @Override
    public Mongo mongo() throws Exception {
        return new MongoClient(this.host, this.port);
    }
}

How can I switch between production and test databases while executing unit tests?
Comment: A note: what has your data model to do with the question, other that both are related to MongoDB somehow? Other than that, you can use environment variables for this.
Answer: Personally I prefer to use an embedded database for testing. You can use FakeMongo
package com.backend.configuration;

import com.github.fakemongo.Fongo;
import com.mongodb.Mongo;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.config.AbstractMongoConfiguration;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;

@Configuration
@EnableMongoRepositories(basePackages = "com.backend.repository")
public class MongoConfiguration extends AbstractMongoConfiguration {

  private static final String DB_NAME = "test";

  @Override
  protected String getDatabaseName() {
    return DB_NAME;
  }

  @Override
  @Bean
  public Mongo mongo() {
    return new Fongo(getDatabaseName()).getMongo();
  }

  @Override
  protected String getMappingBasePackage() {
    return "com.backend.domain";
  }
}

In test class :
package com.backend.repository;

import com.backend.configuration.MongoConfiguration;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = MongoConfiguration.class)
public class CustomerRepositoryTest {

}

For the other profiles like development and production, you can use spring boot profile (see doc) or you can use maven profile :
in application.properties add this property firstname.lastname@example.com@ then define it in pom.xmlaccroding to used profile :
    <profile>
        <id>dev</id>
        <activation>
            <activeByDefault>true</activeByDefault>
        </activation>
        <properties>
            <mongo.host>localhost</mongo.host>
        </properties>
    </profile>
    <profile>
        <id>prod</id>
        <properties>
            <mongo.host>mongo</mongo.host>
        </properties>
    </profile>

Answer: The most easy way to do it is just override desired properties in your test:
@RunWith(SpringRunner.class)
@SpringBootTest(properties = {
    "spring.data.mongodb.database=test_db"
})
@ContextConfiguration(classes = {CustomerTest.class})
public class CustomerTest {

In case you need  to redefine bean - for instance use in-memory fongo  implementation you can create CustomTestConfig and add it to your test:
@RunWith(SpringRunner.class)
@SpringBootTest(classes = TestConfig.class)
@ContextConfiguration(classes = {CustomTestConfig.class})
public class CustomerTest {

Answer: If you want to switch online database or test database, use test database when unit test. you can use @Conditional annotation on your datasource config.
Here is the way:

Add class to impl Conditional. One of the online condition, the other of the test condition.You can just impl this two conditional class by read yml config
Add those condition to your data source config:

    @Conditional(Online.class)
    @Component
    class OnlineDatasrouceConfig{
    }

    @Conditional(OnTest.class)
    @Component
    class TestDatasrouceConfig{
    }

Then, spring will create the bean only when conditional is true.
Here is the condition document:
http://docs.spring.io/spring-boot/docs/1.4.1.RELEASE/reference/htmlsingle/#boot-features-condition-annotations
And, there is some other way to switch test database when you are running unit test.
Add @ActiveProfile("test") to your test class. spring will use test.yml to init this test class. And, you just need to put your test database config in test.yml(I AM USE THIS WAY)


Construction based on circumcenter and incenter

Question: Construct a triangle given the exact location of its circumcenter and its incenter, and the position of its angle bisector (including its direction), but not its length.
I tried to consider the angles between the points.
Comment: I am thinking of dropped the circumcenter to one of the angle bisectors...
Comment: Is both the endpoints of the angle bisector given, or just its length?
Comment: @Sawarnik, please check updated question
Comment: You mean that the line (and not a segment) is given but not any endpoint or length? :)
Answer: There is not a unique triangle with that information.
General argument: A triangle has $6$ degrees of freedom: $x$ and $y$ coordinates for each vertex. Since the given angle bisector goes through the given incenter, you have only $5$ pieces of information: the two centers ($2$ each) and the direction of the angle bisector ($1$).
Specific example: Consider an equilateral triangle. The circumcenter and incenter are identical, with the angle bisector going through both. Expand the triangle with respect to the circumcenter/incenter, and none of your given information changes, despite the changes in all the vertices.
Possible modification: Would it be acceptable to find just one of the triangles that have the given circumcenter, incenter, and angle bisector? This could probably be done by fixing one more datum, such as the location of the vertex on the angle bisector.
Answer: Given: Incenter $(I)$, its radius $r$, circumcenter $(O)$ and slope $m$ of line $t$ (angle bisector); ?: translation point; $R$ by the Euler's relation, equation of the circle ($μ$) with center $O$ and radius $R$; Points $A$ and $Z$: intersection of the circle ($μ$) with the line $t$; circle ($ψ$) with center $Z$ and radius $IZ$; Points $B$ and $C$: intersection of the circles $ψ$ and $μ$; translation point.
$\begin{array}{} I=(X_{I},Y_{I}) & O=(X_{O},Y_{O})  \end{array}$
$\begin{array}{} \text{translation point} & k=X_{I} & h=Y_{I} \end{array}$
$\begin{array}{} I=(0,0) & O=(a=X_{O}-k,b=Y_{O}-h)  \end{array}$
$\begin{array}{} \text{Euler's relation} & IO=\sqrt{a^2+b^2}=\sqrt{R(R-2r)} & R=r+\sqrt{a^2+b^2+r^2} \end{array}$
$\left\{ \begin{array}{} (x-a)^2+(y-b)^2=R^2 \\ y=m·x  \end{array}  \right.\ $
$\begin{array}{} x_{A}=\frac{a+b·m+\sqrt{(1+m^2)R^2-(a·m-b)^2}}{1+m^2} & y_{A}=m·x_{A} \\ x_{Z}=\frac{a+b·m-\sqrt{(1+m^2)R^2-(a·m-b)^2}}{1+m^2} & y_{Z}=m·x_{Z} \\ \end{array}$
$\begin{array}{} \text{Eq.1 (Ψ)} & x^2+y^2-2x_{Z}·x-2m·x_{Z}·y=0 \\ \text{Eq.2 (μ)} & x^2+y^2-2a·x+2b·y+a^2+b^2-R^2=0 \\ \end{array}$
$\begin{array}{} \text{Eq.2 - Eq.1} & y=p·x+q & \text{where:} \\ p=\frac{x_{Z}-a}{b-m·x_{Z}} & q=\frac{a^2+b^2-R^2}{2(b-m·x_{Z})}   \\ \end{array}$
replacing in Eq.2, solving, we get
$\begin{array}{} x_{B}=\frac{a+bp-pq+\sqrt{(1+p^2)R^2-(ap-b+q)^2}}{1+p^2} & y_{B}=p·x_{B}+q \\ x_{C}=\frac{a+bp-pq-\sqrt{(1+p^2)R^2-(ap-b+q)^2}}{1+p^2} & y_{C}=p·x_{C}+q \\ \end{array}$
$\begin{array}{} X_{A}=x_{A}+k & Y_{A}=y_{A}+h  \\ X_{B}=x_{B}+k & Y_{B}=y_{B}+h  \\ X_{C}=x_{C}+k & Y_{C}=y_{C}+h  \\ \end{array}$


Most appropriate simple IP direct for Drupal 7

Question: Having looked at the descriptions provided for the following modules

ip2cc
ip2country
geoip
smart_ip

I'm having trouble identifying which module would be the simple solution to my scenario.
I have established 'Landing Pages' which represent the different countries for my website. (initially)
e.g:
 - www.example.com/au (Australia)
 - www.example.com/us (United States)
 - www.example.com/uk (United Kingdom)
If a user lands at the www.example.com url and they are from IP addresses in Australia, United States or the UK, I'd want it to direct them to the appropriate landing page.
I'm not sure which module is the most appropriate for this scenario and how it would be applied.
Many thanks for your help.
Answer: All of the modules you have listed only provide APIs, choose one for which you need least maintanence. For geoIp you need to keep updating County List DAT file manually once in 3~4 months, I am not sure about others. Once you choose your module you have to write logic for your scenario, something like this
<code>$cc = geoip_country_code();
if($cc == "AU"){
  drupal_goto(MY_AUSTRALIAN_SITE_URL);
}
</code>
You can use page--front.tpl.php or make use of drupal_is_front_page() in page.tpl.php to write your own logic.
Comment: While this is correct, might I suggest that it would be much simpler to put the code in template.php and limit it to a simple drupal_goto('/' . $cc); There should be no need to do if/switches on every country code since Marcus already has the url structure set up.
Comment: @nowarninglabel I am not sure if they are correct/final URLs he s gonna use so the IF/ELSE ladder I just gave a hint on how to use APIs.


How to fit a multiple membership model when the factor is nested?

Question: The accepted answer to this question explains how to fit a mixed effects model where there is multiple membership. I would like to know how to proceed when the multiple membership factor itself is nested in another random factor.
Comment: Can you provide an example dataset for this ?
Answer: lmerMultiMember is an R package that implements multiple membership models in lme4. To use nested multiple membership factors in lmerMultiMember, you pre-generate an indicator matrix for the nested factor. For example, let's say we have a model where we try to predict journal article citations based on word count, while accounting each articles' authors and the scientific field the articles were published in. One possible (toy) model for this would be to nest authors in scientific fields, because authors don't necessarily have the same reputation in every field they publish in.
The usual formula for such a model might be lmer(citations ~ wordcount + (1 | author/field))
However, journal articles will have often have multiple authors, so in order to properly account for the authorship effects, we'll need a multiple membership model. Assuming a dataframe df with a single membership factor field and a multiple membership factor authors which contains the authors for each article, separated by commas, we specify the nested model as follows:
library(lmerMultiMember)

Wa <- weights_from_vector(df$authors, sep = ",")  # create multimembership matrix
Wf <- Matrix::fac2sparse(df$field)  # make single membership matrix using fac2sparse()
Waf <- interaction_weights(Wa, Wf)  # pre-generate interaction matrix

lmer(citations ~ wordcount + (1 | author) + (1 | authorXfield),
     memberships = list(author = Wa, authorXfield = Waf))

The interaction_weights() function creates an indicator matrix Waf as described in this answer, but for the interaction between two other indicator matrices, Wa (multimembership matrix for authors) and Wf (single membership matrix for scientific field). We just have to tell lmerMultiMember to use these indicator matrices by specifying the random effects using dummy (non-existent) variable names in the model formula, and then tell it which dummies map to which indicator matrices by passing a named list through the memberships argument.
lmerMultiMember is not yet on CRAN, but can be installed from https://github.com/jvparidon/lmerMultiMember


Como alterar o cache do google para site reformulado

Question: Existe um site aonde as suas opções estão nos resultados de pesquisa do Google, só que acontece que o site foi todo reformulado, assim como também as suas opções e conteúdos.
Quando a pesquisa é realizada, aparecem as informações do antigo site no resultado do google e não do novo.
Como faço para alterar os resultados?
Comment: Um dos melhores jeitos é manter o _sitemap_ atualizado, e usar as ferramentas para _webmaster_ do google pra deixar tudo em dia. Reenviar o site pode ajudar, se o Google não mudou de novo as regras do jogo. https://www.google.com/webmasters/tools/submit-url
Comment: Obrigado vou fazer as verificações do google.
Answer: Se com cache você quer dizer as páginas indexadas pelo Google que ficam como cópias por exemplo:

O Google não atualiza ou indexa imediatamente as páginas quando você faz uma atualização no site, o máximo que ele faz é recolher o conteúdo e agendar pra prepara-lo, isto pode levar semanas ou meses, depende de quantas visitas ou o rank do site e não tem como "controlar" ou forçar o Google reindexar.
Não tem como afirmar o tempo em média, o Google vive mudando, hoje eles fazem de uma maneira e amanhã pode ser de outra.
Essas páginas de "cache" ao qual se refere que aparecem junto ao resultado de busca levam algum tempo pra atualizarem, assim como com a indexação.
Redirecionamento de links antigos
Se os links que aparecem no cache são antigos e mudaram de estrutura, por exemplo:
http://examplo/siteantigo/?pag=produto&id=1

E agora ele é acessado assim:
http://examplo/sitenovo/produto/1

Uma boa estratégia é reaproveitar links antigos já indexados, claro que não é garantido, vai depender do rank do link especifico dentro de um determinado site. Para reaproveitar e até aportantar para páginas que representam o mesmo conteúdo de páginas especificas será necessário fazer um redirecionamento permanente pelo HTTP, por exemplo criar um script assim em siteantigo/index.php:
<?php
if (isset($_GET['pag'], $_GET['id'])) {
    /* Isto direciona para: http://exemplo/sitenovo/{pagina}/{id} */
    header('Location: /sitenovo/' . $_GET['pag'] . '/' . $_GET['id'], false, 301);
    exit;
}

Claro que isso é só um exemplo pra explicar o redirecionamento, não tem uma formula pronta, vai depender de como você fez o site antigo e como você fez o novo, se forem tecnologias conhecidas como Joomla ou Wordpress é provável que existam plugins pra isto, mas isto é bastante amplo.
Note que se você não fizer o redirecionamento de URLs antigas é provável que no painel Google/webmaster comece a aparecer uma série de erros Not found ou o Soft 404, o Soft 404 ocorre quando a página emite outro código como o 200, mas a página retorna uma resposta vazia, ou uma página que não parece ter conteúdo (o Google consegue identificar mesmo que a página tenha menus e rodapé, mas não tenha um razoável conteúdo ou tenha uma mensagem de erro talvez).
META tag revisit-after
Até existe uma tag <meta> que deveria ser usada pra isto, seria a revisit-after, por exemplo, visitar a cada 15 dias:
<meta name="revisit-after" content="15 days">

Você poderia colocar 1 dia, mas o Google geralmente desconsidera, pois muitas pessoas usam isto pra tentar manter atualizado e no entanto a taxa de atualização era bem baixa ou demorada e isto seria péssimo pra eles se todos sites do mundo quisessem atualizações de 1 dia, portanto eles analisam o trafego feito através de "buscas" e eles calculam quais precisam de maior atualização ao invés de usar o valor da tag que você definir.
Conforme este link https://developer.mozilla.org/pt-PT/docs/Utilizando_meta_tags na verdade é o uso de revisit-after deve ser pra servidores proxy.
Sitemap.xml
Você pode usar as tags:

<priority> pra determinar a importância da página.
<lastmod> define a data da ultima atualização.

Mas note que isso não é garantia de agilizar indexação ou renovação do cache. Se necessita forçar remover uma URL você pode usar a tag <expires> pra remover urls que não deseja mais, exemplo:
<url>
    <loc>http://www.examplo.com/expired.html</loc>
    <expires>2011-06-21</expires>
</url>

Answer: Você pode usar o link abaixo para solicitar ao Google que atualize o cache do seu site nas pesquisas:
https://www.google.com/webmasters/tools/removals
Espero ter ajudado :)
Answer: Siga os passsos abaixo:

Para colocar seu site na fila prioritária de espera você deve
primeiro criar uma conta no Google Search e adicionar o seu site lá.
Siga os passos nesse [link][1]
[1]: https://support.google.com/webmasters/answer/34592?hl=pt-BR
Após isso vai no sidebar do lado esquerdo e procure um menu chamado
"inspeção de URL", click nele e coloque a URL do seu site. Exemplo "huebr.com.br"
Após a inspeção aparecerá um relatório do seu site, caso tenha algum erro o Google mostrará o porquê.
Após corrigir o erro se houver, faça uma nova solicitação de indexação, para fazer isso basta clicar em "Solicitar indexação"

Lembre-se! leva uma tempo até que seu site seja indexado novamente, então seja paciente. No meu caso leva em média só 10min, mas tem casos que lavam até 2 dias
Espero ter ajudado!
Att,


Como fazer Collapse e Expand de um texto usando apenas HTML5?

Question: Escrevi o seguinte código que vi num video tutorial de Bootstrap mas não está a funcionar:

Column3

Bacon ipsum dolor amet pancetta  fatback ground round, bresaola strip steak boudin filet mignon turkey kevin drumstick sirloin swine pork belly. Corned beef shankle ham hock drumstick capicola short loin ball tip tri-tip kevin turkey chuck pork belly venison bacon. Fatback turkey swine tongue, chuck jerky doner pork belly pork corned beef rump leberkas. Ham hock fatback bresaola tri-tip salami.

Comment: Sabes que o Bootstrap tem JavaScript certo?
Comment: Sim mas no video é possivel fazer collapse e expand do texto com apenas estes codigo
Comment: Eu acho que eu já respondi uma que faz isso, mostrar o texto expandido ao clicar (a solução é checkbox se for um item só, e radiobutton se forem vários, mas para mostrar um só por vez). Enquanto não acho o link, segue outra variante: http://pt.stackoverflow.com/questions/99108/como-clicar-e-descer-uma-parte-oculta
Answer: Não estou a ver como isso pode ser feito sem JavaScript. O mais perto é usar o :active mas que só funciona no momento em que o mouse é pressionado:

.collapse {
 height: 0px;
 overflow: hidden;
 transition: height 0.8s;
}

h4:active + .collapse {
 height: 200px;
}

Faz um clique longo...

Bacon ipsum dolor amet pancetta  fatback ground round, bresaola strip steak boudin filet mignon turkey kevin drumstick sirloin swine pork belly. Corned beef shankle ham hock drumstick capicola short loin ball tip tri-tip kevin turkey chuck pork belly venison bacon. Fatback turkey swine tongue, chuck jerky doner pork belly pork corned beef rump leberkas. Ham hock fatback bresaola tri-tip salami.

Para fazer isso sem JavaScript podes usar o truque da checkbox, que basicamente usa a lógica do adjacent sibling no CSS que referi em cima mas usando o estado da checkbox como interruptor:

label input[type="checkbox"] {
    display: none;
}

label h4 {
 cursor: pointer;
 text-decoration: underline;
}

.collapse {
    height: 0px;
    overflow: hidden;
    transition: height 0.8s;
}

input:checked + .collapse {
    height: 200px;
}

Clica aqui

        <input type="checkbox" />

Bacon ipsum dolor amet pancetta fatback ground round, bresaola strip steak boudin filet mignon turkey kevin drumstick sirloin swine pork belly. Corned beef shankle ham hock drumstick capicola short loin ball tip tri-tip kevin turkey chuck pork
            belly venison bacon. Fatback turkey swine tongue, chuck jerky doner pork belly pork corned beef rump leberkas. Ham hock fatback bresaola tri-tip salami.

Existe ainda uma tecnologia nova no HTML5 que faz isso, sem JavaScript e sem CSS, usando os elementos  e :

  Clica aqui...

Bacon ipsum dolor amet pancetta fatback ground round, bresaola strip steak boudin filet mignon turkey kevin drumstick sirloin swine pork belly. Corned beef shankle ham hock drumstick capicola short loin ball tip tri-tip kevin turkey chuck pork belly
    venison bacon. Fatback turkey swine tongue, chuck jerky doner pork belly pork corned beef rump leberkas. Ham hock fatback bresaola tri-tip salami.


Self-learning how to play the piano

Question: I'd like to start learning to play the piano from scratch, and I would like to know how many hours of practice will it take me to:

master the basics like scales, technique, fingering, theory, and sight reading.
be able to play a piece and not sound bad
be able to sight read a piece which is not complex, but also not too easy
be able to approach a complex piece (you name it, as long as you explain what will it demand, and why do you see it as complex)
be able to sight read a complex piece.

Are there any pieces or exercise that I can treat as "goals", that I know I reached a certain level when I am able to play them? Also, if you have any good advice, a good place to start from and good excercise, and a place (maybe books or sites or YouTube channels) which have everything.
I need to start about theory, techniques, scales, fingerings, note reading, etc. I would love to hear it from you! i am going to have a few free months with absolutely nothing to do very soon, so I plan to put my willpower to the test and try practicing 6 days a week for 5-10 hours (one day a week for being lazy, and maybe practicing a bit more), and when I get busy again, practice about 1 hour at least. I used to have a teacher for six years and I quit playing the piano, it's been about 4 years since and I've recently fallen in love with classical music, so this time i would like to try and go solo, without a teacher.
And last question, just out of interest, because I don't really think it is going to happen, I'm 18 years old, can I still become a professional player or is it too late? At what age do the pros begin? And how do they practice?
update: thank you very much for all your amswers, i have decided to go with a r
Teacher for those six months to gain independence and restore the abillities i used to have (i played the piano six years from age 7 to 13 practicing 3 hours a week + one weekly hour with a teacher), afterwards, if my timetable will allow it i will continue taking lessons and if not, i will continue practicing ajd making progress on my own in the free time i have
Comment: 10,000. It's the industry standard.
Comment: @nath Popularised by https://en.wikipedia.org/wiki/Outliers_(book), goes back to a study by Ericsson, K. Anders on expertise in general.
Comment: @Tim is there any reference where the "10,000" comes from? I have seen this number being quoted here a couple of times and asking just because of further interest...
Answer: Starting with the last question, if you can you still become a professional, it's risky and presumptuous to give a definitive answer, but not to let you end on a complete blank I'll give you my opinion. It's highly improbable that you may acquire the technical proficiency required, for example, to become a classical concert pianist, but other than that everything is possible.
As a committed adult learner your learning curve can be much speedier than a child's normal development, but a good teacher makes all the difference, and finding one is the best thing you can if you're so motivated to learn quickly.
Beware of too much and/or ill guided practice, as it may be harmful, reinforcing mistakes or even causing physical injury. Don't forget that playing the piano is also a physical, muscular activity, don't expect to be able to compress in a few months the work of years, no matter how many hours a day you practice.
And it will be a waste to dedicate such amount of effort and then let it fade away for lack of continuity. Your motivation is commendable, but try to plan for a more sustained effort in the long run.
Anyway, regarding the request for self learning resources, this answer may give you a starting point.
Comment: Thank you for your answer, I think that what imight do is just take a few lessons with a teacher to go over the technique and then continue by myself
Answer: If you don't mind some dissonance in your sound repertoire, I'd recommend Bartok's Mikrokosmos as your learning tool. It is the only progressive piano method written by a compositional genius. It will introduce you to a huge range of piano textures and sounds. And it gets quite difficult. By the time you are through with Volume 6, you have the technique to handle a wide range of repertoire and can start to think about simpler mainstream pieces (i.e. not the big bravura stuff) by Chopin, Mozart or Beethoven.
Of course you'll probably want to pair it with some different sounds as you go. During volume 2, you can explore Bach's AM Bach notebook, or Albums for the Young by Schumann and Tchaikowsky; during volumes 3, 4, and 5, you might enjoy Debussy's Children's Corner and Schumann's Kinderszenen.
That should do you!
And no, you will never become a professional pianist, the neural nets need to start early. :)
Answer: In general, 2000 hours of focused practice will get you to a professional level.  The "10000 hours of practice" number comes from an article studying Olympic athletes and thus is reserved for becoming the best musician possible given your innate limitations.  As Josh Kaufman has demonstrated, even 20 hours of focused practice on a well-defined goal can produce results that you can demonstrate.
Answer: My personnel suggestion is to Start from a Teacher.It will good to have a teacher for guidance.Later you can do self learning. For self learning lot of resources are available in internet like
L&M Piano. http://www.learnandmaster.com/piano/  etc.
Answer: I suggest starting with 20 minutes and gradually work yourself up to an hour.  I did it step-wise with two 25 minute sessions and gradually adding a minute to the time.
You can also consider watching training videos, such as on youtube, in addition to your keyboard time.
Answer: It is better to practice in shorter sessions but ensure you do so every day. Music is supposed to be fun, so if you push yourself too hard it can rapidly become a chore.
Reading music is part of the challenge but a surprising number of talented musicians never learn to read - I know a gospel keyboardist who is simply amazing but he cannot read - he envies me (with my much inferior talents as a musician) because I can read, but I can't play like he does.
So if you find improvising or copying what you hear is fun, than don't worry too much about the 'proper' way to learn.
As a late beginner (I did not start until the age of 13) it took me about a year of lessons, 1 hour per week, to get to grade 3 level and by then I felt reasonably confident that I could proceed on my own from that point. I also subsequently played in a band and learned valuable skills about improvising and reading chord charts as opposed to proper sheet music.
You do not say what styles of music you enjoy. However learning in the classical idiom I think is best initially, even if you want to actually play modern music. Jazz in particular requires a sophisticated rhythmic touch which isn't intuitive for many people - a lot of classical musicians never quite figure out how to 'swing', so listen to stuff and make an aspirational list. Mine, for instance, is to one day be able to play Debussy's Images - but I'm much older than 13 now, so I don't know if I'll ever be able to do that. Still, it's a goal....

Self-learning how to play the piano


If $r+r'\leq d(a,a')$ then $B(a,r)\cap B(a',r')= \emptyset$.

Question: I have to prove this assertion :
Suppose that $r+r'\leq d(a,a')$
Show that $B(a,r)\cap B(a',r')= \emptyset$.
What I have to prove is that if I have $p \in B(a,r)\cap B(a',r')  $ then $p=0$.
If $p \in B(a,r)\cap B(a',r')$ then :
$$d(a,p)<r $$
$$d(a',p)<r'$$
Then :
$$0\leq d(a,p)+d(a',p)\leq r+r' \leq d(a,a') \leq d(a,p)+d(p,a')$$
Know I'm stuck, can I Say that $d(a,a')=d(a,p)+d(a',p)$ according to the last inequality ? If yes, I don't know I to prove that $p=0$...
Comment: Being empty does *not* mean the only element is $0$. It means the *number* of elements id $0$. Does $B(a,r)$ denote the *open* ball centred at $a$?
Comment: Oh yes, absolutly ! Thank you !
Answer: I assume the balls are open, otherwise the statement is not true.
Let $p\in B(a,r)$, i.e. $d(a,p)\lt r$. Then the triangle inequality states that
$$d(a,p)+d(p,a')\ge d(a,a')\ge r+r'$$
Hence
$$d(p,a')\ge (r-d(a,p))+r'>r'$$
Hence $p\notin B(a',r')$.
Therefore, $B(a,r)\cap B(a',r')=\emptyset$.

Note that it's absolutely not true that you have to show that if $p \in B(a,r)\cap B(a',r')$ then $p=0$. If $p=0$ were in $B(a,r)\cap B(a',r')$, then obviously the intersection would not be empty.
Comment: Yes that is true, the empty set is not the set which contains $0$... Thank you Jean Claude !
Answer:
"What I have to proove is that if I have $p \in B(a,r)\cap B(a',r')  $ then $p=0$."

That is a wrong route and can only be marked as an effort to prove the weaker statement : $$B(a,r)\cap B(a',r')=\varnothing\text{ or } B(a,r)\cap B(a',r')=\{0\}$$
It must be shown that the assumption $p \in B(a,r)\cap B(a',r')$ leads to a contradiction.
If $p \in B(a,r)\cap B(a',r')$ then  $$d(a,a')\leq d(a,p)+d(p,a')<r+r'$$ contradicting that $r+r'\leq d(a,a')$.

If $r+r’\leq d(a,a’)$ then $B(a,r)\cap B(a’,r’)= \emptyset$.


JavaScript Div Annimation

Question: I would like to know if there is any specific way to get javaScript code to stop executing at some point so as to allow another called function to execute, for example in a sorting algorithm using Div's you call a function which annimates the swapping of the two Div's so you can visually see the sort taking place. I have tried using the setTimeout(c,t); however it does not seem to be be waiting and the Divs do not seem to be moving, if I however place an alert(""); within the moving code it seems to allow the move to take place with thousands to alerts popping up.
The code I have is as follows:
var q;
var w;
function move(x,y)
{
    q = x.style.top; // Keep a reference to the Top divs top element
    w = y.style.top; // Keep a reference to the Top divs top element
    doMove(x,y);
}
function doMove(topDiv, bottomDiv)
{
    //alert("in doMove " + topDiv);
    topDiv.style.top = parseInt(topDiv.style.top)+2+'px';
    bottomDiv.style.top = parseInt(bottomDiv.style.top)-2+'px';
    //alert("hi");
    if(bottomDiv.style.top != q && topDiv.style.top != w) // Check if the Top and Bottom divs have finally swapped
    {
        setTimeout(doMove(topDiv,bottomDiv),20); // call doMove in 20msec
    }
}

Answer: One problem with your code is that in this line:
setTimeout(doMove(topDiv,bottomDiv),20);

You are calling doMove immediately and passing the value undefined as the first parameter to setTimeout.  Not entirely sure that the following will solve your problem, but I would recommend trying this:
setTimeout(function() { doMove(topDiv,bottomDiv); }, 20);

JavaScript Div Annimation


How to $\int \sqrt{10x-x^2}dx$

Question: Theres a hint to use $x=5+5\sin{t}$. Ok, but how do I know what substitution to use if a hint wasn't given? Is it "trivial" or perhaps, its very unlikely that that will appear?
Anyways, I did:
$\int \sqrt{10(5+5\sin{t}) - (5+2\sin{t})^2} dx \\
= \int \sqrt{50+50\sin{t} - (25+50\sin{t} + 25\sin^2{t})} dx\\
= \int \sqrt{ 25-25\sin^2{t} } dx \\
= 5 \int \sqrt{1-\sin^2{t}} dx \\
= 5\sin^{-1}{\sin{t}} \\
= 5t \\
= 5 \sin^{-1}{\frac{x-5}{5}}$
But the answer was:
$$\frac{25}{2}\sin^{-1}{\frac{x-5}{5}}+\frac{x-5}{2}\sqrt{10x-x^2}+c$$
What did I do wrong? Or is the answer wrong perhaps?
Comment: If you substitute $x=5+5sin(t)$, then you must note that $dx=5cos(t)dt$, which you forgot from your calculations. Right now you're integrating $t$ respect to the variable $x$.
Comment: I don't think that was so much a "hint" as an "Apply x as $5+5\sin{t}$".
Answer: What you "did wrong" in making the subsitution was forget to take into account the
$$\frac{dx}{dt} = 5\cos t.$$
Continuing,
$$\begin{align}
\int \sqrt{10x-x^2}dx & = \int \sqrt{10(5 + 5\sin{t}) + (5+5\sin{t})^2}5\cos{t}dt\\
& = 5\int \sqrt{25 - 25\sin^2t}\cos{t}dt\\
& = 25\int \cos^2tdt\\
& = \frac{25}{2}\sin{t}\cos{t} + \frac{25}{2}t\\
& = \frac{25}{2}\frac{(x-5)}{5}\sqrt{1-(\frac{x-5}{5})^2} + \frac{25}{2}\sin^{-1}(\frac{x-5}{5})\\
& = \frac{x-5}{2}\sqrt{25 - (x-5)^2} + \frac{25}{2}\sin^{-1}(\frac{x-5}{5})\\
& = \frac{x-5}{2}\sqrt{10x-x^2} + \frac{25}{2}\sin^{-1}(\frac{x-5}{5}).
\end{align}$$
Not the easiest method, but it does work.
Comment: Hmm ... so am I right to say:

$$5 \int \sqrt{1-\sin^{-1}{t}} \cdot \cos{t} dt$$

Then I do integration by parts,

Let $u = \cos{t} \Rightarrow du = -\sin{t} dt$
Let $dv = \sqrt{1-\sin^2{t}} dt \Rightarrow v=t$

$$= 5[t\cos{t} + \int t\sin{t} dt]$$

Then integration by parts again, this time ...

Let $u=t \Rightarrow du = dt$
Let $dv = \sin{t} dt \Rightarrow v = -\cos{t}$

$$=-t\cos{t}+\int \cos{t} dt = -t\cos{t} + \sin{t}$$

$ori eq = 5\sin{t} +c$? Yet another answer?
Comment: Let's start from $\int \sqrt{25-y^2}\, dy$, as I told you. Put $y=5\sin t$, $dy=5 \cos t \, dt$. Now $$\int \sqrt{25-y^2}\, dy = \int \sqrt{25-25\sin^2 t} \cdot 5 \cos t \, dt = 25 \int \cos^2t \, dt.$$ Try to complete.
Answer: Try to complete the square: $10x-x^2=10x-x^2+25-25 = -(x-5)^2+25$. After a change of variables $y=x-5$, your integral becomes $\int \sqrt{25-y^2}\, dy$. And yhis should be familiar to you.
Answer: For these types of problems, try to substitute the variable $x$ so that the integral reduces into a form that is easier to integrate.
For this integral, I would start by completing the square in the integrand:
$\sqrt{10x-x^2} = \sqrt{-(x^2-10x)}= \sqrt{-((x-5)^2-25)}=\sqrt{25-(x-5)^2}$.
Note that, so far, I have made no substitution... I have just fiddled around with the integrand.
Now I am ready to substitute. Let $x-5 = t$.
Then the integrand turns into $\sqrt{25-t^2} = 5\sqrt{1-\frac{t^2}{5^2}}$ (which you ought to know how to integrate... either off hand or by further substitution)
and also
$\frac{dx}{dt} = 1 $ which implies $dx = dt$.
Comment: Ok, So I have ...

$$5\int\sqrt{1-(\frac{t}{5})^2}=5\sin^{-1}{\frac{x-5}{5}}$$

Is it right? I also tried letting $t=\frac{x-5}{5}, dx=5 dt$

$$5 \int \sqrt{1-t^2}\cdot 5 dt=25 \sin^{-1}{\frac{x-5}{5}}$$

They appear different? I must me making some very stupid mistakes again?

$$$$
Comment: @Jiew Check your integral tables. You're confusing the integral you want to solve with

$$\int \frac{dx}{\sqrt{1-x^2}}=\sin^{-1} x+C$$
Answer: As Thomas said $\displaystyle \frac{dx}{dt} = 1$ not $5dt$.
If $\displaystyle x - 5 = t$ then $\displaystyle x = t - 5 \therefore \frac{dx}{dt} = 1$.
But what you really should do, is use the sustitution originally suggested and remeber to integrate with respect to $t$.
Comment: I get $dx = 5dt$ when I let $t=\frac{x-5}{5}$. Thats 1 possible substitution too?
Comment: Yes you're right, I didn't see that, but I'm not sure that's the way to go.
Answer: put dx = 5cost dt
from your fourth step,
<code>5∫cost * 5cost dt = 25∫(cos^2)(t) dt
                  = 25∫(1 + cos2t)/2 dt
                  = (25/2)∫(1 + cos2t)dt
                  = (25/2)(t + (sin2t)/2) + c
                  =(25/2)(t + (2 sint cost)/2) + c
</code>
and substitute the value of t and sint and cost in above. Then you will get your answer.

How to $\int \sqrt{10x-x^2}dx$


How to limit the quantity of a product to 1?

Question: Some stores sell products that can only be purchased once (for example, on iTunes, you can only buy a song for yourself once, or on Steam, you can only buy a game for yourself once).
So for products like this, how can I limit the quantity to 1 in Commerce?  (Users should never be able to order 2+ of any individual product of type myproducttype.)
There are some answers for doing this in Drupal 7:

Using rules to restrict anonymous users to quantity of 1
Limiting order quantity

Unfortunately, these solutions use Rules, which is still in alpha for D8.
So how can I programatically restrict the product quantity to 1 for a given product type?
Answer: For me, simply skipping to checkout does not address my desired workflow. I still want users to be able to shop around and use a cart.
But some of my products are subscriptions, for which it doesn't make any sense to have multiple. For this purpose, I'm using https://www.drupal.org/project/commerce_xquantity module.
Answer: As pointed out in this question, there is an issue on Drupal.org for a "skip cart" feature that will create something similar to a "Buy it now" button, which means that the user will automatically be transferred to the checkout page as soon as the product is clicked.
This is effectively limiting the quantity to one.
Thanks to @Berdir for writing the code for this.
How to use the patch

Apply the patch.
Go to the Product Types -> Edit Display page for your product type that you want to skip the cart for (<code>/admin/commerce/config/product-types/my-product-type/edit/display</code>).
Look for the Product Variations field, the format of which should be Add to cart form. Click the little gear icon on the right.
Check the box for Skip cart and press Update.


The frequency in histograms

Question: My question is trivial, but the problem is that I found contradictory answers on internet.
So I have the following sample data:
31/08/2015, Monday, 'Seat Ibiza', 3
31/08/2015, Monday, 'Ford Focus', 2
01/09/2015, Tuesday, 'Seat Ibiza', 3
02/09/2015, Wednesday, 'Toyota', 1
07/09/2015, Monday, 'Honda', 2
08/09/2015, Tuesday, 'Volkswagen Golf', 1
08/09/2015, Tuesday, 'Seat Ibiza', 1

1) Now I want to build a classical histogram. I wonder if the frequencies should be absolute or relative numbers??
For instance, I would build the following frequency table, but I'm not sure if it's a must to use relative numbers (i.e. divide each number by total - 7):
Monday, 3
Tuesday, 3
Wednesday, 1

2) Another question is: can I call such graphic as a histogram, though discrete values are used? I read that the term 'histogram' refers only to continuous space.
3) Final question is: how the probability distribution would be estimated for these data?
Answer: You have a discrete variable with, in your example, very small frequencies. It would be fine to show relative frequencies so long as you made clear the small sample size. I suggest that it would be nevertheless be simpler to show sample frequencies directly:

In this case we hope that people are able to look at the graph and think (e.g.) 3 out of 7 were on Monday, and so forth. Small children are often encouraged to do this, which presumably explains why it is sometimes thought too challenging for business people.
I am happy, personally, with the idea that this is a histogram, as it shows the frequency distribution of a numeric variable. The fact that the variable is discrete and not continuous does not worry me. As a convention to underline discreteness many people like to leave some space between the bars. Some even like to show spikes. I have often done either. Here there is no signal what the data are, beyond showing car makes. Suppose that the data are daily sales or numbers of cars serviced. If there is an idea that some business is open for part of the day only, then spaces between bars convey a fair picture. Conversely, if the days were touching 24 hour periods, then I think the bars are better shown as touching.
Do not be surprised if some people prefer to call this a bar chart, not a histogram. Graphically a histogram is just a bar chart, but in many statistical discussions pedagogic tradition and minor snobbery join forces to insist that a histogram showing a frequency distribution is not a bar chart at all!
All that said, I imagine that your real data set is larger than your example, so it might well be in order to show relative frequencies as well as frequencies (counts).
It is hard to get people to agree on whether the numeric information should be given (a) on the graph (b) in a table (c) in accompanying text, and indeed any or even all could make sense, depending on the data, the readership and the goals of he analysis.
Without more said, the underlying probabilities are to be estimated as the sample proportions.
Answer:
I would show absolute counts, not relative frequencies.  Absolute counts make the total weight of the evidence (which is not much!) clear.
It's a "bar chart" you want, not a "histogram".  Although many people say "histogram" for both discrete and continuous data, you may as well head-off any complaints by using the correct terminology.
If you have categorical data (e.g. counts for days of the week or types of car) and want to estimate the underlying probabilities then, well, "it depends".  You can use the observed frequencies, e.g. $(\frac{3}{7},\frac{3}{7},\frac{1}{7})$, as a point estimate; or, to allow the possibility of currently-unseen values, add a small flattening pseudo-observation of size $\epsilon$ to everything to get say $(\frac{3+\epsilon}{7+4\epsilon},\frac{3+\epsilon}{7+4\epsilon},\frac{1+\epsilon}{7+4\epsilon},\texttt{other=}\frac{\epsilon}{7+4\epsilon})$; and you might want to put some sort of confidence interval around your estimates.  It all comes down to your "loss function", or the penalty you'd pay for being wrong.  It's a bit of a black art, to be honest.  How about starting with the observed frequencies and clarifying your question if you want a more problem-specific answer?

The frequency in histograms


what is the best way to update a timer UI

Question: My app draws a timer (with detail to .1 seconds), for which I am currently using a NSTime which fires every .1 seconds. This feels like an absolutely terrible idea, but I'm not sure how else to do it. I don't really care about the .1 seconds updating always, but I would like it to update more than once per second. Is there a good way to do this?
Answer: NSTimer doesn't strike me as a bad approach. NSTimer is generally a very regular way to keep track of time (indeed it was used for animation timing before CADisplayLink came along). Unless you are seeing unacceptable performance of your timer display updating, I would stick with this approach.
If you are having issues with delays and inaccurate time readings, you could store the start time in NSDate, and continue to use the NSTimer but only to update the display. On each timer event firing, you then update the display by finding the NSTimeInterval from the start time to now. This way even if there is a performance issue, at least the time being display should remain accurate at the time of display.
Comment: I actually ended up using using a GCD timer source just for fun, but after doing more research I realized my fear of NSTimer was a bit irrational. Thanks.


How find $\int(x^7/8+x^5/4+x^3/2+x)\big((1-x^2/2)^2-x^2\big)^{-\frac{3}{2}}dx$

Question: How can I compute the following integral:
$$\int \dfrac{\frac{x^7}{8}+\frac{x^5}{4}+\frac{x^3}{2}+x}{\left(\left(1-\frac{x^2}{2}\right)^2-x^2\right)^{\frac{3}{2}}}dx$$
According to Wolfram Alpha, the answer is
$$\frac{x^4 - 32x^2 + 20}{2\sqrt{x^4 -8x^2 + 4}} + 7\log\bigl(-x^2 - \sqrt{x^4 - 8x^2 + 4} + 4\bigr) + C$$
but how do I get it by hand?
Answer: Perform the substitutions $y=\frac{x^2}{2}, y=2+\sqrt{3}\sec{\theta}$ to get:
\begin{align}
&\int{\frac{\frac{x^7}{8}+\frac{x^5}{4}+\frac{x^3}{2}+x}{((1-\frac{x^2}{2})^2-x^2)^{\frac{3}{2}}} dx} \\
& =\int{\frac{y^3+y^2+y+1}{(y^2-4y+1)^{\frac{3}{2}}} dy} \\
&=\int{\left(\frac{y+5}{\sqrt{(y-2)^2-3}}+\frac{20y-4}{\sqrt{((y-2)^2-3)^3}}\right) dy} \\
&=\int{\left[\frac{7+\sqrt{3}\sec{\theta}}{\sqrt{3}\tan{\theta}}+\frac{36+20\sqrt{3}\sec{\theta}}{3\sqrt{3}\tan^3{\theta}}\right](\sqrt{3}\sec{\theta}\tan{\theta}) d\theta} \\
&=\int{\left(7\sec{\theta}+\sqrt{3}\sec^2{\theta}+12\csc{\theta}\cot{\theta}+\frac{20}{\sqrt{3}}\csc^2{\theta}\right) d\theta} \\
&=7\ln{|\tan{\theta}+\sec{\theta}|}+\sqrt{3}\tan{\theta}-12\csc{\theta}-\frac{20}{\sqrt{3}}\cot{\theta}+c \\
&=7\ln{|\frac{\sqrt{y^2-4y+1}+y-2}{\sqrt{3}}|}+\sqrt{y^2-4y+1}-\frac{12(y-2)}{\sqrt{y^2-4y+1}}-\frac{20}{\sqrt{y^2-4y+1}}+c \\
&=7\ln{|\frac{\sqrt{y^2-4y+1}+y-2}{\sqrt{3}}|}+\frac{y^2-16y+5}{\sqrt{y^2-4y+1}}+c \\
&=7\ln{|\sqrt{x^4-8x^2+4}+x^2-4|}+\frac{x^4-32x^2+20}{2\sqrt{x^4-8x^2+4}}+c'
\end{align}
where $c,c'$ are arbitrary constants of integration.


How can i smooth data in Python?

Question: I'm using Python to detect some patterns on OHLC data. My problem is that the data I have is very noisy (I'm using Open data from the Open/High/Low/Close dataset), and it often leads me to incorrect or weak outcomes.
Is there any way to "smooth" this data, or to make it less noisy, to improve my results? What algorithms or libraries can I use for this task?
Here is a sample of my data, which is a normal array:
DataPoints = [6903.79, 6838.04, 6868.57, 6621.25, 7101.99, 7026.78, 7248.6, 7121.4, 6828.98, 6841.36, 7125.12, 7483.96, 7505.0, 7539.03, 7693.1, 7773.51, 7738.58, 8778.58, 8620.0, 8825.67, 8972.58, 8894.15, 8871.92, 9021.36, 9143.4, 9986.3, 9800.02, 9539.1, 8722.77, 8562.04, 8810.99, 9309.35, 9791.97, 9315.96, 9380.81, 9681.11, 9733.93, 9775.13, 9511.43, 9067.51, 9170.0, 9179.01, 8718.14, 8900.35, 8841.0, 9204.07, 9575.87, 9426.6, 9697.72, 9448.27, 10202.71, 9518.02, 9666.32, 9788.14, 9621.17, 9666.85, 9746.99, 9782.0, 9772.44, 9885.22, 9278.88, 9464.96, 9473.34, 9342.1, 9426.05, 9526.97, 9465.13, 9386.32, 9310.23, 9358.95, 9294.69, 9685.69, 9624.33, 9298.33, 9249.49, 9162.21, 9012.0, 9116.16, 9192.93, 9138.08, 9231.99, 9086.54, 9057.79, 9135.0, 9069.41, 9342.47, 9257.4, 9436.06, 9232.42, 9288.34, 9234.02, 9303.31, 9242.61, 9255.85, 9197.6, 9133.72, 9154.31, 9170.3, 9208.99, 9160.78, 9390.0, 9518.16, 9603.27, 9538.1, 9700.42, 9931.54, 11029.96, 10906.27, 11100.52, 11099.79, 11335.46, 11801.17, 11071.36, 11219.68, 11191.99, 11744.91, 11762.47, 11594.36, 11761.02, 11681.69, 11892.9, 11392.09, 11564.34, 11779.77, 11760.55, 11852.4, 11910.99, 12281.15, 11945.1, 11754.38]

plt.plot(DataPoints)

Answer: Smoothing is a pretty rich subject; there are several methods each with features and drawbacks.  Here is one using scipy:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy.signal import savgol_filter

# noisy data
x = [6903.79, 6838.04, 6868.57, 6621.25, 7101.99, 7026.78, 7248.6, 7121.4, 6828.98, 6841.36, 7125.12, 7483.96, 7505.0, 7539.03, 7693.1, 7773.51, 7738.58, 8778.58, 8620.0, 8825.67, 8972.58, 8894.15, 8871.92, 9021.36, 9143.4, 9986.3, 9800.02, 9539.1, 8722.77, 8562.04, 8810.99, 9309.35, 9791.97, 9315.96, 9380.81, 9681.11, 9733.93, 9775.13, 9511.43, 9067.51, 9170.0, 9179.01, 8718.14, 8900.35, 8841.0, 9204.07, 9575.87, 9426.6, 9697.72, 9448.27, 10202.71, 9518.02, 9666.32, 9788.14, 9621.17, 9666.85, 9746.99, 9782.0, 9772.44, 9885.22, 9278.88, 9464.96, 9473.34, 9342.1, 9426.05, 9526.97, 9465.13, 9386.32, 9310.23, 9358.95, 9294.69, 9685.69, 9624.33, 9298.33, 9249.49, 9162.21, 9012.0, 9116.16, 9192.93, 9138.08, 9231.99, 9086.54, 9057.79, 9135.0, 9069.41, 9342.47, 9257.4, 9436.06, 9232.42, 9288.34, 9234.02, 9303.31, 9242.61, 9255.85, 9197.6, 9133.72, 9154.31, 9170.3, 9208.99, 9160.78, 9390.0, 9518.16, 9603.27, 9538.1, 9700.42, 9931.54, 11029.96, 10906.27, 11100.52, 11099.79, 11335.46, 11801.17, 11071.36, 11219.68, 11191.99, 11744.91, 11762.47, 11594.36, 11761.02, 11681.69, 11892.9, 11392.09, 11564.34, 11779.77, 11760.55, 11852.4, 11910.99, 12281.15, 11945.1, 11754.38]

df = pd.DataFrame(dict(x=data))
x_filtered = df[["x"]].apply(savgol_filter,  window_length=31, polyorder=2)

plt.ion()
plt.plot(x)
plt.plot(x_filtered)
plt.show()

Answer: If you can plot it, use the moving average/rolling mean and identify the window size which suites your data.
from scipy.ndimage.filters import uniform_filter1d

data = [6903.79, 6838.04, 6868.57, 6621.25, 7101.99, 7026.78, 7248.6, 7121.4, 6828.98, 6841.36, 7125.12, 7483.96, 7505.0, 7539.03, 7693.1, 7773.51, 7738.58, 8778.58, 8620.0, 8825.67, 8972.58, 8894.15, 8871.92, 9021.36, 9143.4, 9986.3, 9800.02, 9539.1, 8722.77, 8562.04, 8810.99, 9309.35, 9791.97, 9315.96, 9380.81, 9681.11, 9733.93, 9775.13, 9511.43, 9067.51, 9170.0, 9179.01, 8718.14, 8900.35, 8841.0, 9204.07, 9575.87, 9426.6, 9697.72, 9448.27, 10202.71, 9518.02, 9666.32, 9788.14, 9621.17, 9666.85, 9746.99, 9782.0, 9772.44, 9885.22, 9278.88, 9464.96, 9473.34, 9342.1, 9426.05, 9526.97, 9465.13, 9386.32, 9310.23, 9358.95, 9294.69, 9685.69, 9624.33, 9298.33, 9249.49, 9162.21, 9012.0, 9116.16, 9192.93, 9138.08, 9231.99, 9086.54, 9057.79, 9135.0, 9069.41, 9342.47, 9257.4, 9436.06, 9232.42, 9288.34, 9234.02, 9303.31, 9242.61, 9255.85, 9197.6, 9133.72, 9154.31, 9170.3, 9208.99, 9160.78, 9390.0, 9518.16, 9603.27, 9538.1, 9700.42, 9931.54, 11029.96, 10906.27, 11100.52, 11099.79, 11335.46, 11801.17, 11071.36, 11219.68, 11191.99, 11744.91, 11762.47, 11594.36, 11761.02, 11681.69, 11892.9, 11392.09, 11564.34, 11779.77, 11760.55, 11852.4, 11910.99, 12281.15, 11945.1, 11754.38]

plt.figure(figsize=(15,15))
plt.plot(data)
for i in range(3, 100, 10):
  y = uniform_filter1d(data, size=i)
  plt.plot(y, '--', label=f"{i}")

plt.legend()

Output:
Answer: As mentioned in the comments, you can take the moving average, which sort of works like a convolutional layer. It averages the values from 0 to n and sets that as point 0. Then it averages values 1 to n+1, and sets that as point one. the larger the n, the less points you will have, yet the smoother it will be. You can get the moving average using the code below:
import numpy as np
def moving_avg(x, n):
    cumsum = np.cumsum(np.insert(x, 0, 0))
    return (cumsum[n:] - cumsum[:-n]) / float(n)

I found that code snippet here.
With a n of 10, I got the following plot:

How can i smooth data in Python?


Explanation of line element formula $dl^2 = dx^2 + dy^2$

Question: I found this in a physics textbook without justification: $$dl^2 = dx^2 +dy^2,$$
where I presume that $l = \sqrt{x^2+y^2}$.
Why is this so?
By my calculations I obtain $$ dl = \dfrac{\partial l}{\partial x} \, dx + \dfrac{\partial l}{\partial y} \, dy= \dfrac{x \, dx + y \, dy}{\sqrt{x^2+y^2}},$$
and squaring
$$ dl^2 = \dfrac{x^2 \, dx^2 + y^2 \, dy^2 +2xy \, dx \, dy}{x^2+y^2}. $$
Are they the same? Am I doing something wrong?
Comment: The basic idea is to picture a tiny triangle and use the Pythagorean theorem.
Comment: see this image (replace $ds$ with $dl$) http://abe-research.illinois.edu/faculty/dickc/mathematics/arclengtha_files/image002.jpg
Answer: Your presume wrong: if $dl^2=dx^2+dy^2$, you can't conclude $l=\sqrt{x^2+y^2}$. You're talking about differentials here.
All that you can say starting from
$$dl^2=dx^2+dy^2$$
is that
$$dl=\sqrt{dx^2+dy^2}$$
This is the result of considering the differential length of arc $dl$ as the hipotenuse of a triangle made of sides $dx$, $dy$, and $dl$ in the cartesian plane.
Comment: $dl$ is often written $ds$ in math texts. It is the "element of arclength."
Comment: I'm not presuming $dl^2 = dx^2+dy^2$, I'm trying to understand what it means and why is it so. I think that $$df(x,y):=\dfrac{\partial f}{\partial x} dx + \dfrac{\partial f}{\partial y} dy.$$ Is this true?
Comment: you are presuming $l = \sqrt{x^2 + y^2}$, which may or may not be true. If you post a little more context in which you came across this equation, we may be able to help you more.
Answer: You have interpreted $dl$ as the differential of some function $l(x,y)$ defined over
some domain in $\mathbb{R}^2$. The truth is it isn't. It is true that we can view $dl$ as a differential. However, it is one "living" on a one-dimension curve instead over some two-dimension domain.
Let $C \subset \mathbb{R}^2$ be any geometric figure in the plane that resemble our
geometric notion of what a segment of a curve should be. If $C$ is regular enough
and we can parametrize it by two differentiable functions $x(t), y(t)$:
$$[0,T] \ni t \quad\mapsto\quad \gamma(t) = (x(t),y(t)) \in C \subset \mathbb{R}^2$$
We can define the length of $C$ as an integral.
$$L \stackrel{def}{=} \text{length}(C) = \int_0^T \sqrt{\left(\frac{dx(t)}{dt}\right)^2 + \left(\frac{dy(t)}{dt}\right)^2} dt$$
As a geometric figure, $C$ admits many different parametrization. The key point
is above definition of length is essentially independent of choice of parametrization.
Among all these parametrization, there is one more or less natural. It is called
arc-length parametrization.
For any point $p \in C$, let $t_p = \gamma^{-1}(p)$. The length of that portion of $C$
between $\gamma(0)$ and $p = \gamma(t_p)$ is once again given by an integral:
$$s(t_p) \stackrel{def}{=} \text{length}( \{\;\gamma(t) : 0 \le t \le t_p\; \} ) = \int_0^{t_p}
\sqrt{\left(\frac{dx(t)}{dt}\right)^2 + \left(\frac{dy(t)}{dt}\right)^2} dt$$
We can view this length as a function of $p$ and the correspondence map
$$[ 0, L ] \in s \quad\mapsto\quad p \in C \;\text{ such that }\; s(t_p) = s$$
gives us the arc-length parametrization.
By defintion, we have
$$\frac{ds}{dt} = \frac{d}{dt} \int_0^t \sqrt{\left(\frac{dx(t)}{dt}\right)^2 + \left(\frac{dy(t)}{dt}\right)^2} dt
= \sqrt{\left(\frac{dx(t)}{dt}\right)^2 + \left(\frac{dy(t)}{dt}\right)^2}$$
Since this relation is essentially independent of choice of parametrization $t$,
we usually drop the $t$ and $dt$ in the formula and write it as
$$ds = \sqrt{dx^2 + dy^2}\quad\text{ or }\quad ds^2 = dx^2 + dy^2$$
Some authors also perfer to use $l$ instead of $s$ to denote the parameter in arc-length parametrization. As you can see, the $dl$ ( or $ds$ ) here is really the differential
for the function $l(t)$ ( or $s(t)$ ) living on the "curve" $C$ for some arbitrary parametrization $t$.
Comment: very detailed answer!
Answer: Just picture a tiny right triangle with width $dx$ and height $dy$ and hypotenuse $dl$.  By the Pythagorean theorem, $dl^2 = dx^2 + dy^2$.


Are my answers correct? (Graphs; paths; path lengths; circuits)

Question:
My answers
a) Yes, this forms a path.  This is a simple path.  The length of this path is 4.
b) Yes, this forms a path.  This is a circuit.  The length of this path is 4.
c) Yes, this forms a path.  This is a circuit.  The length of this path is 6.
d) Yes, this forms a path.  This is a circuit.  The length of this path is 7.
Comment: I think c) and d) are not paths as the directed edges $(d,b)$ and $(b,d)$ do not exist in the graph shown.
Comment: @positiveimpact, no because you don't know which way is being taken to get from b to d.  Is it b,e,d or b,a,d?  There are multiple paths here which is why the list of vertices specifies the edges to be used to make the path.
Comment: Note that a) is not simple, since vertex $b$ is repeated.
Comment: What are your definitions of "path", "simple", "circuit" and "length"?
Comment: @Adraino Can you explain what a simple path is then?
Comment: @dtldarek path is "a sequence of edges that begins at a vertex and travels from vertex to vertex along edges of a graph" - "a simple path is denoted by its vertex sequence" - "a circuit starts and ends at the same vertex" - "length is the number of edges"  and "A path or circuit is simple if it does not contain the same edge more than once
"
Comment: @adriano isn't a) simple because it does not contain the same edge more than once?
Comment: Wikipedia says that simple paths have no repeated vertices (http://en.wikipedia.org/wiki/Path_(graph_theory)#Different_types_of_paths).
Comment: @Daniel but because b can be reached from d, isn't it still a path?
Comment: Makes sense; thanks.
Answer: According to your definitions:

path is a sequence of edges that begins at a vertex and travels from vertex to vertex along edges of a graph
"a circuit starts and ends at the same vertex"
"length is the number of edges"
"A path or circuit is simple if it does not contain the same edge more than once "

If I guess correctly the intention of the authors of this question, your answers to a) and b) are ok, however, c) and d) are not since $db$, $ea$ and $bd$ are not edges.
Also, please be aware (as @Adriano already pointed out) that usually "a simple path" means that you cannot enter vertex more than once or exit it more than once (in case of cycles you do both, but only once, i.e. one entry and one exit, so it's still ok). With such definition a) would not be a simple path (but according to your definition it is).
I hope this helps $\ddot\smile$
Comment: That is why I don't like such questions, the authors weren't precise enough to tell, however, I guess that their intention was that those sequences of vertices should be the immediate neighbors in a path. In fact your graph is strongly connected, so with your interpretation _any_ sequence of vertices would be a path and as such, the question would be pointless (not to mention it would be rather hard to describe length, more like "possible lengths").
Comment: My definitions may be wrong.  That's why I'm asking here.  Will you tell me whether or not my answers are correct based on YOUR definitions?
Comment: Also, I think c) and d) are paths because it is possible to reach b from d, and d from b across two edges.  Doesn't that satisfy my definition of a path?


Galeria com PHP e Javascript não funcionando corretamente

Question: Tenho uma função em JavaScript que monta uma galeria de imagens. Tinha essa função toda em Javascript e funcionava perfeitamente, agora eu preciso inserir o PHP para que o usuário possa fazer alterações nas imagens, e estou passando o parametro para essa função através do resultado da query em PHP. Ela deveria funcionar desta maneira: Titulo da galeria em cima, e abaixo 4 imagens diferentes do resultado da query. Abaixo outro titulo, e outras imagens. O problema é que PHP está passando o mesmo parametro para a função, fazendo com a função retorne: Titulo da galeria e abaixo 4 imagens identicas(o primeiro valor da query), Outro titulo da galeria e outras imagens identicas(o segundo valor da query). Como posso fazer para que a galeria carregue 4 imagens diferentes em uma galeria, e não 4 imagens iguais em diferentes galerias ?
Minha função em JS está assim:
function galerias(query){
    var galeria = new Array();
        //aqui eu pego a div que armazena as galerias
        var imgs = document.querySelector("#gallery");
        var x = 1;

            imgs.innerHTML += "
";
            imgs.innerHTML += "
";
            imgs.innerHTML += "
Galeria "+x+"
"

        //passo o valor da query para o array galeria
        for(var i = 0; i <= 3; i++){
            galeria[i] = query;
        }

        e insiro dentro da div
        for(var i = 0; i < galeria.length; i++){
            imgs.innerHTML += "";
        }

        imgs.innerHTML += "
";
        imgs.innerHTML += "
";
        imgs.innerHTML += "

Veja mais

";
        x++;

}

Minha função em php:
function consultarDados($query){
    $dbResult = array();
    $conexao = mysql_connect($this->host, $this->usuario, $this->senha);
    mysql_select_db($this->banco, $conexao);
    $rs = mysql_query($query, $conexao);
        while($rows = mysql_fetch_assoc($rs)){
            array_push($dbResult, $rows);
        }
    return $dbResult;
    mysql_close($conexao);
}

Insiro este php no window.onload da página:
<?php
    foreach($galeria_1 as $result){
        echo'galerias("'.$result['nome'].'");';
    }
?>

O resultado visual é este:

e deveria ser este:
Answer: Verifica se este array ($galeria_1) tem realmente todas as posições, por que parece que ele só tem uma posição.
Comment: Sim, ele tem todas as posições !
Comment: Qual o resultado da variável $result ?
Comment: $result['nome'] retorna os valores da coluna do meu banco de dados: foto1_1.jpg foto1_2.jpg foto1_3.jpg foto1_4.jpg, e apenas o $result retorna Array Array Array Array... está parte está perfeita, aparentemente
Comment: Então ai é que está o erro meu amigo,  perceba que não função galerias você recebe "query" que era pra ser um array e não um nome de umas das imagens, por que no decorrer da função você faz um for para montar as imagens passando "query" como nome da imagem no "src" mas essa "query" é um único valor que você passou em "echo'galerias("'.$result['nome'].'");';"
Não sei se deu pra você entender bem.
Comment: Na verdade deu sim ! Mas como eu poderia passar o array como parametro para a função...?
Comment: Cria um Json!!!
Comment: Obrigado pela resposta !
Comment: De nada, estamos aqui uns para ajudar os outros!
Forte abraço meu amigo.


jQuery PHP Collapse repetitive line breaks into a single one

Question: I know that there are similar questions to this but I couldn't help noticing that this question has never been asked or may be it is impossible but I need to set a maximum line break for text entered in a textarea or any other html element.
example one

    Lorem ipsum dolor sit.
    Lorem ipsum dolor sit.

    Lorem ipsum dolor sit.
    Lorem ipsum dolor sit.

On a web page that preserves the blank lines no matter the gap between the text lines.
I know there are some css3 functions but they can only control whitespaces  and not sure they can limit blank line length.
I would like the code above to look like this.
example two.

    Lorem ipsum dolor sit.
    Lorem ipsum dolor sit.
    Lorem ipsum dolor sit.
    Lor

the
 tags are just for reference. Any help will be greatly appreciated. Thanks.
Comment: How much is "maximum"? 10? maybe you want just `white-space: pre` (a [link](https://developer.mozilla.org/en-US/docs/Web/CSS/white-space))?
Comment: no, am talking about empty lines not pre tags
Comment: Okey, let me fix the title...
Comment: If such an html is being generated by server, then I would recommend to process it on server side. Does it came from DB? if yes, maybe it would be a good option to process it before setting to DB... only once.
Comment: yes, that is the reason why i wonna reduce the multiple empty lines before DB processes take place
Comment: So, if it's initially some user input, then the UX should be taken into the account: maybe it would be better to show him (the user) that the extra lines are being collapsed right during the input?
Comment: True, but then again I allow upto I blank line which is pretty standard
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/156867/discussion-between-dennisrec-and-dhilt).
Answer: Try to regex on your PHP while load the content before echo it
$thecontent = "YOUR_CONTENT_HERE";
preg_replace('/(?:(?:\r\n|\r|\n)\s*){2}/s', "\n\n", $thecontent);

Comment: Thanks for this hack.
Answer: In javascript you can split() the string at line breaks into an array then filter() out empty lines and join() array using line break as delimiter

let str = `
Lorem ipsum dolor sit.
Lorem ipsum dolor sit.

Lorem ipsum dolor sit.
Lorem ipsum dolor sit.`;

let res = str.split('\n').filter(line => line.trim()).join('\n');

document.getElementById('result').value = res;
textarea{ width:100%; height:200px}
<textarea id="result"></textarea>


Components cannot be accessed after migrating from ionic3 to ionic4

Question: I have migrated from ionic v3 to ionic v4 with the help of Migration from ionic3 to ionic4 documentation.
As per the documentation i have installed newer version of angular by doing
$npm install @ionic/angular
Now in all my pages if my try to import the following statement
<code>import { IonicPage, NavController, NavParams, ViewController, LoadingController } from '@ionic/angular';
</code>
IonicPage and ViewController is underlined with red line suggesting the error as `Module has no exported member
How to overcome this issue, i am not able the revert back to older version of ionic-angular
Answer: They cant be assessed because ionic 4 does support 'Pages' like they used to. Now they just use angular components which you use the router to jump between. I'd advice generating your pages components using the ionic cli that will make a page like component for you, then migrate your logic over.


preg_match: nothing to repeat / no match

Question: I am using this: if(!preg_match('/^+[0-9]$/', '+1234567'))
and am getting:

Warning: preg_match()
  [function.preg-match]: Compilation
  failed: nothing to repeat at offset 1

any ideas why?

update: Now using this: if(!preg_match('/^\+[0-9]$/', '+1234567'))
and am getting no match.
any ideas why?
Answer: + is a special character that indicates 1 or more of the previous character, and by not escaping it you are applying it to the caret. escape it with \ and it will match a literal plus sign.
if(!preg_match('/^\+[0-9]$/', '+1234567'))

EDIT:
The reason why it didn't match is because you specified 1 digit from 0-9 and the end of the string with $. You need to make it a variable amount of digits.
if(!preg_match('/^\+[0-9]+$/', '+1234567')) {

Shorter version:
if(!preg_match('/^\+\d+$/', '+1234567')) {

Comment: Cheers,

Have edited the question now to reflect the current problem.
Comment: Hailwood, you shouldn't remove the old problem, but should show both together. (just edited to do that).
Comment: Also, the current problem is correct behavour - you are asking regex to match a single plus, a single 0..9, then find the end of line position, which your input does not do. To match your supplied input you want either `^\+[0-9]+$` or `^\+[0-9]{7}$` or similar.
Comment: @peter Thanks, will keep that in mind
@meder Cheers, Perfect.

i actually know about the d flag, but use [0-9] for personal preference as i think it increases readability at a glance,

are there any speed benefits to using the flag vs [0-9]?
Answer: '/^\+[0-9]$/' means that begining of the line has to be plus sign folowed by a number then end of line.
'/^\+[0-9]+$/' means that begining of the line has to be plus sign folowed by a one or more  numbers then end of line.


Detect when 'Remove' is clicked on a file widget form element?

Question: I have a handful of file fields that have the following default Drupal behavior:

User can upload a file
User can upload another file in place
User can remove file

Standard config. Whats happening is the user wants the file being replaced to be deleted before the new one is uploaded, and thus, avoiding the issue where files have their names replaced with _N identifiers to ensure unique filenames.
This is because they are referencing physical file paths from the menu and WYSIWYG fields - which means the old replaced file is being referenced instead of the new one. Since these are core file fields and over 100 files have been uploaded, I cannot switch out to a Media field. I'm also not sure if that would even solve the problem at hand, anyway.
Is there any way I can hook into this widget via form alter, detect a click on the upload field, and if a new file is being added, delete the old one in place so that the file being uploaded the name stays intact and thus preserving link targets?
I have looked at the form with both hook_form_alter and hook_field_widget_form_alter - but I am not really seeing anything I can use to hook into.
Comment: Reacting to the "Remove" being clicked is to early. If the user does not commit to the action (click save) you have now lost the file.

This does feel like the time for a custom submit handler. Perform the file_copy() yourself and set the $replace parameter to FILE_EXISTS_REPLACE.
Comment: We can rename the file using hook_file_insert(Drupal file FileInterface $file).
Comment: I would add submit handler to the file widget/element that would, after removing usage, physically delete the file.
Comment: hook_file_insert would be too late. Need to delete it when Remove is clicked.
Comment: @Ivan where are you seeing this?
Comment: Be very careful with that approach, if there is any caching in front of your Drupal site (like browsercache, varnish or basically anything that caches static resources) you might get cached results due to same file name.
Comment: Islinet that was the first thing that popped in my head, actually. But we promised to explore if a solution can be done.
Comment: Also it would seem that if you uploaded the same file elsewhere you can overwrite one in the system with the same name unintentionally.
Comment: I think this is a bad idea. What if the user uploads a new image but then doesn't save the form. The old image is gone but the new one it not there. All permanent actions should only take place after the user has clicked Save.
Comment: Have a look at this module for Drupal 7. https://www.drupal.org/project/upload_replace

You might be able to see how its done for D7 and then implement in D8.
Answer: You can use this approach.
/**
 * Implements hook_field_widget_form_alter().
 */
function insights_analyst_field_widget_form_alter(&$element, FormStateInterface $form_state, $context) {
    if($element['#field_name'] == 'field_figure'){
        $element['#process'][] = 'removeFile';
    }
}

function removeFile(&$element , \Drupal\Core\Form\FormStateInterface $form_state, &$complete_form){
    $element['remove_button']['#submit'][] = 'markupRemove';
    return $element;
}

function markupRemove($form , \Drupal\Core\Form\FormStateInterface $form_state){
    $parents = $form_state->getTriggeringElement()['#array_parents'];
    $button_key = array_pop($parents);
    //print_r($button_key);
    if($button_key == 'remove_button'){
       //Write your logic here
    }
}


Look for documentation about how precisely modules parts are loaded (Drupal 7)

Question: Developping my custom module, I ran several times into misunderstood issues regarding the precise order used by Drupal when loading parts of a module.
Each time, I finally got rid of it after any disabled and suppressed then recreated, but this is obviously not satisfying.
So I'm now looking for sufficient information to be able to understand what happens in those circumstances.
This time the problem I have is as follows:

Having my module working fine on a site under D-7.34, I upgraded it to D-7.35, following all necessary steps.
After successfully executing update.php (which notified that no update was needed), I clicked to go to front page: this one was properly displayed.
NOTE: necessarily, my module was already involved at this stage, since it works during output rendering (so whatever the path indicated by the URL)
But from there, then, any attempt to access another page (either public or administrative one) fires a PHP error "Call to undefined function myfunction()...", where myfunction() belongs to my module.

I can't figure out how it is possible, since my code schematically looks like:
file: mymodule.module
<?php

module_load_include('inc', 'mymodule', 'mymodule.core');

function mymodule_some_hook() {
    # ...
    myfunction();
    # ...
}

file: mymodule.core
<?php

function myfunction() {
    # ...
}

In other words, in my eyes:

when the error fires, it necessarily means that mymodule.module was loaded, since it is where myfunction() call resides
then if mymodule.module was loaded, it should have first executed module_load_include(), so loading mymodule.core and defining myfunction()

Yet it is clear that, in this case, something is happening differently!
But why this behaviour now, and not at the first access to front page?
And why this behaviour with D-7.35 (where no changes seem to be involved here), and not with D-7.34?
NOTE: I suspected something wrong with caching, so I tried flushing it. But flushing process failed with the same "Call to undefined function".
Then I used directly PhpMyAdmin to truncate all cache tables, without success: behaves the same after that.
Comments greatly welcome, and notably if pointing to any documentation about detailed process of modules load.
Thanks in advance.
Comment: Are you employing a PHP opcode caching tool, like APC, on your server?
Comment: @ShawnConn: no, I don't. Nothing about documentation? TIA.
Comment: I don't know off-hand of a resource on d.o. I believe .module gets parsed when Drupal rebuilds its system module/theme cache. A simple solution to your problem is to add module_load_include inside your hook function.
Comment: @ShawnConn: great idea, so now it works! In the other hand, it doesn't seem right to have to do that, especially as I have a number of hooks invoking that function. And most of all because i keep wondering why my initial, global scoped, module_load_include() is not executed? Anyway, thanks for the tip.
Comment: I believe the solution there is to use files[] = definition in you .info file. I believe that makes the included file available in your module (not sure if global).
Comment: @ShawnConn: files[] definitions are already in my .info file. I included them early when developping my module, merely because the docs told it - but furtherly learned I had to call module_load_include() in spite of that. Not really sure what is necessary and what is enough. But for now I have file[] definitions PLUS module_load_include() in global scope PLUS module_load_include in function - really should work :-)
Answer: After a lot of tests, I'm now pretty convinced that, despite it is not mentioned in the release notes page, a change happened in 7.34, which consists in that, now, the full-bootstrap condition is not reached yet when the MODULE.module file is loaded.
According to module_load_include() page, this function requires Drupal to be fully bootstrapped: this clearly relies to the use of drupal_get_path() (see the function code in this page), which is not available without full-bootstrap.
It is why my (global-scoped) module_load_include() calls are executed but without result (see 'file: mymodule.module' in my question above).
I had to modify my module, including a dedicated module_load_include() call inside each function which needed it, like this:
<?php

function mymodule_some_hook() {
    module_load_include('inc', 'mymodule', 'mymodule.core');
    # ...
    myfunction();
    # ...
}

This way, now all works fine anew.
I verified it is the same with Drupal 7.36: my module doesn't work in its original implementation, then it does with this modification.
Hope this helps.


How to stop auto encoding of <%= strings %> with Rails 3

Question: I'm using rails 3. In my  index.html.erb and in my index.js.erb, if I have:
<%= "string with unsafe characters' like <" %>

It will automatically be encoded to:
string with unsafe characters" like &

just the same as if I had used:
<%=h "string with unsafe characters' like <" %>

How do I get it to stop? I have stored some short bits of JavaScript that I need to insert into the template without it automatically encoding the string?
Comment: Just for reference, this is a feature of Rails 3.0 called SafeBuffers, http://yehudakatz.com/2010/02/01/safebuffers-and-rails-3-0/
Answer: Just use the raw method like this:
<%=raw "string with unsafe characters' like <" %>


How can I remote into my machine from outside the LAN without touching anything at the router?

Question: I'm looking to remote into my windows 7 machine (looking to connect to terminal services, not just at a command prompt) from outside my LAN but I currently do not have access to my routers admin page to configure any sort of port forwarding or rules.
Does anyone know if/how I can accomplish this?
Edit: I'm looking for a free solution to do this, if possible.
Cheers,
Comment: Be sure to get written permission to do this from your IT/HR people as this kind of thing can be a really good way of finding your belongings in a box at some/many companies :)
Comment: Talk to your system administrator. We're not here to help you circumvent security measures imposed by one of our own.
Comment: Ill be going into my home machine using this service. Are there any security/other issues when going FROM a work/other machine?
Comment: Why the downvote?
Answer: Use logmein
https://secure.logmein.com/
Comment: Logmein offers a free version  https://secure.logmein.com/US/products/free/
Comment: Sorry, forgot to mention I'm looking for a free solution - will update the question
Comment: I am a happy customer of logmein pro...
Answer: windows live mesh will work and its free!
Answer: The Windows Live Essentials beta includes a Live Sync feature that combines Live Mesh and Remote Desktop capabilites. There is a video on Channel 9 with more information on Windows Live Sync and how it differs from Live Mesh.
Answer: From the same folks who give you the (free) LogMein, check out LogMeIn Hamachi. Slick little "hosted" (brokered may be a better term) VPN solution that makes it very easy for you to get to your PCs regardless of the firewalls in between them.
I've been using it for years for just what you're after.
Answer: I've used OpenVPN for this in the past.  Set up an OpenVPN tunnel outwards from the PC you want to access to a machine somewhere (like a VPS) that you do have access to.  I'd then set ssh from the machine I'm at to the open/3rd machine and forward a port (like 3000) to the behind-the-router machine's VPN IP, and connect RDP to localhost:3000.
Machine-behind-router ---OpenVPN--> VPS-or-something <---- Some-client-you're-at
Answer: GoToMyPC works much in the same way, and is really easy to install at both ends (remote host and the client) as everything works over port 80, which is more-often-than-not the default port available.
They also have a decent 30-day trial of it too.  Give it a whirl.


Consider the following differential equation$ y'' + 5y' + 4y = 0$.

Question: a) Determine a system of equations $x' = Ax$ that is equivalent to the differential equation.
b) Suppose that $y_1, y_2$ form a fundamental set of solutions for the differential equation,
and $x(1), x(2)$ form a fundamental set of solutions for the equivalent system. Show that
$$W[y_1, y_2](t) = k W[x(1), x(2)](t)$$ for some $k$ in $R$.
(Hint. You don't have to solve for $y_1, y_2$ or $x(1), x(2)$, but you can if you want to)
Comment: thx for your help
Comment: For $(a)$ see [here](http://math.stackexchange.com/questions/381528/express-differential-equations-as-system-of-first-order-equations/381538#381538).
Answer: Part a): The easiest way is to let $x_1 = y, x_2 = y'$. Then $x_1' = x_2$ and
$x_2' = -5 x_2 -4 x_1$. The $A$ matrix is straightforward to compute from these equations.
Part b): Show that $t \mapsto y_1(t)y_2'(t)-y_1'(t)y_2(t)$ and $t \mapsto x_1(t)x_2'(t)-x_1'(t)x_2(t)$ satisfy the same differential equation.


Copy and Paste using Range.Copy Method

Question: I am trying to paste values from a bunch of tables into one long list. I have the tables spread across different sheets and the number of rows changes, but the columns do not. Then I am also trying to paste a string value that tells what sheet it came from, but having trouble with the active cell part of the code.
When I first tried it, it did not compile, hence why I came here, to figure out why it did not compile. Going back and forth with urdearboy, below, I was able to get the correct code working here.
I have the following:
sub copypaste()
  Dim ws1 as worksheet
  dim ws2 as worksheet
  dim mas as worksheet
  Set ws1 =ThisWorkbook.Sheets("Sheet1")
  Set ws2=ThisWorkbook.Sheets("Sheet2")
  Set mas=ThisWorkbook.Sheets("Master") 'where I create my list

     For Each ws In Worksheets
    If ws.Name <> mas.Name Then
        LRow = mas.Range("A" & mas.Rows.Count).End(xlUp).Offset(1, 0).Row
        wsLRow = ws.Range("A" & ws.Rows.Count).End(xlUp).Row
        ws.Range("A2:A" & wsLRow - 1).Copy
        mas.Range("A" & LRow).PasteSpecial Paste:=xlPasteValues
        ws.Range("B2:B" & wsLRow - 1).Copy
        mas.Range("B" & LRow).PasteSpecial Paste:=xlPasteValues
        mas.Range(mas.Cells(LRow, 4), mas.Cells(wsLRow + LRow - 2, 4)) = ws.Name 'I need my sheet value in the fourth column, not the third, but simply change the col coordinate in the Cells equation above

    End If
Next ws

'In order to figure out the sheet name, I used the following:
Dim rng As Range
Set rng = mas.Range("D2", Range("D2").End(xlDown))
For Each Cell In rng
    If Cell.Value = "Sheet 1" Then
        Cell.Value = "S1"
    ElseIf Cell.Value = "Sheet 2" Then
        Cell.Value = "S2"
    End If
Next Cell

end sub
Comment: @JackArmstrong you have syntax issues with your range on the error line. You can see one correct method on the solution below.
Comment: Please don't add the answer in the question; this breaks the question.
Comment: This doesn't compile right now. Syntax errors
Comment: hence my issue with the copy and paste. It is not supposed to compile.
Comment: please see **how to include a [mcve]** with your question
Comment: Please explain what isn't working. Indicate any errors and on which lines they occur. Some sample data with expected output often helps.
Comment: I indicated where my error occurs within the code. There is no sample data as it is a values in excel.
Comment: `Sheets("Sheet1").whatever` is how you access a sheet via string.
Answer: This will loop through all sheets, with the exception of Master, and import the values on Column A to Master accompanied by the origin of the data (sheet name).
Option Explicit for good measure.

Option Explicit

Sub copypaste()

Dim mas As Worksheet: Set mas = ThisWorkbook.Sheets("Master")
Dim ws As Worksheet, LRow As Long, wsLRow As Long

Application.ScreenUpdating = False
    For Each ws In Worksheets
        If ws.Name <> mas.Name Then
            LRow = mas.Range("A" & mas.Rows.Count).End(xlUp).Offset(1).Row
            wsLRow = ws.Range("A" & ws.Rows.Count).End(xlUp).Row
            ws.Range("A2:A" & wsLRow).Copy mas.Range("A" & LRow)
            mas.Range(mas.Cells(LRow, 2), mas.Cells(wsLRow + LRow - 2, 2)) = ws.Name
        End If
    Next ws
Application.ScreenUpdating = True

End Sub

To paste values change
ws.Range("A2:A" & wsLRow).Copy mas.Range("A" & LRow)

to this
ws.Range("A2:A" & wsLRow).Copy
mas.Range("A" & LRow).PasteSpecial xlPasteValues

Comment: That is a separate ask from your original question. Give it a shot yourself and post a new question if you cannot figure it out! IF this does solve your initial ask, please clear question from unanswered queue by validating solution
Comment: anyway to add the sheet name as a string insteal of a variable? I have string names, but really need a short name for them, i.e. Sheet1=S1, Sheet2=S2. Sorry.
Comment: Sounds like you know the sheet name references you want to use. Record a macro using the basic feature `CTRL + F` with Find / replace all
Comment: That's fair. What if I need to paste only the values? see edited above.
Comment: How did I change the question? Cause I asked to paste values instead? That's an update to the question, not changing it. There is no need to create a whole new thing for that. I edited the code. I will put down you as a contributor. Sorry about that.

Copy and Paste using Range.Copy Method


Update all references to an object when the object is updated(reference to a reference)

Question: I want to declare an object in java that is like a a pointer to a pointer in C++, let me show you an example :
//*** At the application startup

//Initialize a settings container class
Settings settings = //Load settings

//Declaring static Application class that contain a reference to the settings container
Application.setSettings(settings);

//Get sub settings from settings container class
DatabaseSettings dbSettings =  settings.getDbSettings();
LogSettings logSettings = settings.getLogSettings();

//Initialize components
DatabaseConnector dbConn = new DatabaseConnector(dbSettings);
Logger logger = new Logger(logSettings);

In the above code i have created a settings container class that contain all settings of my application components, then i have assigned each sub settings class to the related component, at this point during the execution of the program i want to update the settings and let the component of the application to see the updated settings, so for example during the execution i can update the settings container in this way :
//Update settings through Application static class
Settings newSettings = //assign updated settings
Application.setSettings(newSettings);

Now the problem is that when i update the settings container at runtime the application static class will contain the updated reference to the newSettings instance while each sub Settings instance keep referencing the old sub settings, so :
dbConn      ---> settings.getDbSettings()
logSettings ---> settings.getLogSettings()

While i want that the two reference automatically reference to the new instance of the settings, so :
dbConn      ---> newSettings.getDbSettings()
logSettings ---> newSettings.getLogSettings()

It is like a pointer to pointer ... Is it possible in Java ? How can it be done ?
Comment: What you can do is use a singleton pattern to ensure you use the one setting object, or an observer pattern to update the observers to your observable (the settings class)
Comment: Even the singleton pattern isn't guaranteed to work, it depends on what the constructor of DatabaseConnector and Logger do. If they copy the fields from the config, then even if you update the config those objects will never see a change. In that case the only option is the observer.
Comment: If you pass the same object it will reference the same object in memory, effectively it is a pointer.
Answer: Well, instead of setting new settings in Application, update the existing ones.
Or simply document the fact that these settings could change, and that any code interested in having the new settings must always go through Application.getSettings().
Comment: +1 The first statement is what I was going to write as an answer to this question.
Answer: In Java, you only have references to objects.  To have a reference to a reference you need some sort of indirection. e.g.
AtomicReference<DatabaseSettings> refDatabaseSettings = new AtomicReference<DatabaseSettings>();

refDatabaseSettings.set(dbSettings);

DatabaseSettings dbSettings = refDatabaseSettings.get();

You can pass the ref around and change it in one place.  However, this won't notify any of the references that it has changed, just allow all references to see the same thing when they check next time.
Answer: You need to use some form of notification system to accomplish what you are trying to do.  An observer/observable or some event based system with listeners that are interested in the changes is really the only way to go.
You could certainly create threadsafe settings objects (like DatabaseSettings) that can be updated, and therefore the consumer of the object will get the new values, but this will only work in the simplest of cases.  The problem with this approach is that the results of multiple calls to the settings instance will become inconsistent.  Assuming that there are multiple settings in the settings object that are related to one another, if one settings is retrieved, the object is updated, and then the next setting is retrieved, you have no way of knowing that the two calls have produced inconsistent (to each other) values.
For Example:
dbSettings.getConnectionUrl();
dbSettings.getUsername();

If dbSettings is updated between these 2 calls, then the username and connection will no longer match.
The other issue is that if anyone extracts specific values from a settings object and stores them in another variable or class, they will have no way of knowing that it changed.
It makes the way in which these classes are used very rigid and error prone.


Find the side of an equilateral triangle given only the distance of an arbitrary point to its vertice

Question: Triangle ABC is an equilateral triangle and P is an arbitrary point inside it. The distance from P to A is 4 and the distance from P to B is 6 and the distance from P to C is 5. How to find the side of an equilateral triangle from this information?
$$\frac{a^2+x^2-y^2}{2xa} = \frac{\sqrt{3}}{2}\frac{a^2+x^2-z^2}{2xa}+\frac{1}{2} \sqrt{1- \Big(\frac{a^2+x^2-z^2}{2xa}\Big)^2}$$
@Aditya
based from that equation where did you get
 that square root of 3 over 2 ....up to   ...... plus one half then square root of 1 minus something and so on.. pls explain further
Comment: But in http://math.stackexchange.com/questions/329761/equilateral-triangle-geometric-problem the three distances were a Pythagorean triple, a fact that was used in the accepted answer. Here the distances are not a Pythagorean triple.
Comment: [this](http://math.stackexchange.com/questions/937327/equilateral-triangle-problem-with-trig/937418#937418) explains it all
Answer: The geometry of equilateral triangles is often best dealt with in 3 dimensions.
Consider points on the plane
$$
x+y+z = K = s/\sqrt{2}
$$
where $s$ is the side of the equilateral triangle with vertices at $(K,0,0), (0,K,0), (0,0,K)$.
If $X, Y, Z$ are the distances between P on the plane and these vertices, then
$$
X^2 = (K-x)^2 + y^2 + z^2
\\Y^2 = x^2 + (K-y)^2 + z^2
\\Z^2 = x^2 + y^2 + (K-z)^2
$$
which after some strenuous manipulation yields
$$
s^2 = 2K^2 = \tfrac{1}{2}\left( X^2 + Y^2 + Z^2 \pm \sqrt{3\left((X^2 + Y^2 + Z^2)^2 -2( X^4 + Y^4 + Z^4))\right)}\right)
$$
Comment: i believe you have one lose bracket at the end of the equation


Different rankings in a view based on geolocation

Question: I'm currently building a site which has a ranking table.
I'd need the rankings to be different based on geolocation so what i'v done so far is building a different view for each country.
So the question is - how do i display them based on the session's location? (different home page and navigation for different countries)
Any explanation would be more than welcomed.
Edit: I'm using Zen theme.
Answer: I think Smart IP module is help you to solve your query.
OR
Check IP Geolocation Views & Maps or Session Cache API module.
Comment: Any tutorial video you might pull out of your sleeve? I'm a rather new drupalholic.
Comment: Check **README.TXT** file of these modules. I think txt file help you to understand.