Como mudo a cor do switch do bootstrap?

Question:

  <input type="checkbox" class="custom-control-input" id="teste">

Answer: O switch do bootstrap é feito criando dois elemento dentro da label com a classe "custom-control-label", você pode criar algumas regras de CSS para se aplicar a eles, como por exemplo:
.custom-switch .custom-control-label::after{
    background-color: red;
}

.custom-switch .custom-control-label::before {
    border-color: red;
}

Comment: Até fiz dessa forma, mas nada está dando certo, mas sua ajuda já foi um pontapé inicial amigo vlw
Comment: Perfeito Sergio Carvalho, muito obrigado, me salvou!
Comment: Só uma dúvida, ele ativo como mudo a cor?
Comment: Ao ser ativo o input recebe uma propriedade "checked". Você pode criar a seguinte regra CSS para aplicar quando ele estiver ativo:

.custom-control-input:checked~.custom-control-label::before {
    color: #fff;
    border-color:  red;
    background-color :red;
}

.custom-switch .custom-control-input:checked~.custom-control-label::after {
    background-color: #c55d5d;
}`

Aqui o CSS já não é tão básico, mas é o gerado pelo próprio bootstrap, um ótimo material de estudo
Comment: Adicionei a propriedade, mas infelimente continuou padrão, teria uma outra solução amigo?
Comment: Pronto não, recomendo você utilizar a função de inspecionar elemento e ver como o css do bootstrap é aplicado, e ir mudando até encontrar o resultado diário. Assim você saberá quais classe mudar

Como mudo a cor do switch do bootstrap?


Can we use Markov Chain for forecasting a time series?

Question: I have a dataset which contains information about monthly visitors go to a particular website from Google News. Basically there are two columns - one is Month and another is Unique Visitors. There are 30 observations in the dataset. Can I apply Markov Chain to the data in any manner? Will it give any good result?
Answer: I suppose you can use a Markov Chain for forecasting. However, you only have 30 data points, just two years and a half. This is very little data to use such a complicated method. I'd suggest you start with far simpler methods, like Exponential Smoothing. This textbook gives a good introduction to forecasting.
Answer: A Markov chain process and a time series process are two completely different kinds of stochastic processes, though all methods behind stochastic processes have similar features. You should distinguish different stochastic processes first by looking at the following table, which is taken from juan2013integrating. [2]

You can try to convert a Markov chain process to a time series process by normalising, which makes the state space relatively continuous. But I don't see the point of any conversion.
Usually, time series analysis focuses on dynamics regarding many lags, while the main idea behind Markov chains is to omit the history and focus on the current state. Also, time series analysis has been applied widely, while theoretical approaches for other three kinds are emphasised most of the time.

[2]: Morales, J.M., Conejo, A.J., Madsen, H., Pinson, P. and Zugno, M., 2013. Integrating renewables in electricity markets: operational problems (Vol. 205). Springer Science & Business Media.
Comment: please add full reference for your link, in case it dies in the future, thanks!
Comment: It's in the appendix of that book. Also, I think there is no need to reference basic concepts. But I will remember to add full reference next time.


MLB rule on subs for injuries after you used the entire roster

Question: Major league rules. What happens if team used the entire roster and now a player gets hurt ???
Answer: MLB rule 7.03(b) (2021 edition):

A game shall be forfeited to the opposing team when a team is
unable or refuses to place nine players on the field.

So if it's really the case that all but 8 players on your roster have already been used or are injured, your team loses the game by forfeit.
Comment: You can maybe imagine some narrow loopholes.  Say you are the home team and you come to bat in the bottom of the 17th with only 9 players left.  The scheduled leadoff batter trips on his way up the dugout steps and injures himself.  You could perhaps avoid a forfeit by sending one of your remaining 8 players to the plate, and let him be called out for batting out of order.  Then hope you can get a walkoff win before making 2 more outs, because if it goes to the top of the 18th, you'll forfeit when you can't field 9 players for defense.
Answer: When a player leaves the game he is done.   There are high school rules that are subject to locality that allow a pitcher to reenter the game in a non-pitching role.   However in MLB you get taken out, you are out - I think rule 303.
What happens when the manager is in the 17th inning and a player gets hurt and there is no one else?   Well this basically can never happen in reality.
Why?
Because there are 4 other starting pitchers.   So right fielder gets hurt, starting pitcher (that did not pitch this game) plays right field.   If all of your other 4 starting pitchers enter the game and get taken out or if they are hurt... You play with 8 - bylaws will include an automatic out in the lineup.
Comment: MLB rules state that if you cannot field 9 players, you forfeit the game (7.03(b)); they do not have an "automatic out" rule as far as I can tell.
Comment: @YannisDran - Great question - 8 is the minimum.   You cannot play with less than 8 players.   So at most you could have one auto out in your lineup.   Really good stats question would be when was the last time this happened in a MLB game.   When I used to umpire youth games I would see it once a year.
Comment: I don't get the "bylaws will include an automatic out in the lineup" phrase. Does it mean that on their turn they will start with an out against three to end the inning?
Comment: @YannisDran - if you are down to 8 players the "missing player" is still in your lineup.   When they come to bat it is an automatic out.
Comment: So that means if (theoretically) we had a three consecutive players missed from our lineup, then a whole inning would not be played in defense, right?
Comment: Thank you for the answer. In other countries out of US, due to unpopularity of the game it is difficult to have same rules sometimes , but we are trying mantain MLB rules as much as possible.
Comment: @YannisDran -  Here is the deal.   If you run a youth league, will teams abuse this rule and only play with their best 7-8 hitters.   Yes it is a problem not having fielders but you can usually shift around it.   Also what do you do if a team has 13 kids and their worst 6 hitters go down with an injury in the bottom of the last inning?


Integration of ccavenue payment gateway in ionic android mobile app

Question: I need integration steps for implementing ccavenue payment gateway in ionic android app. Please help me out.
Answer: Iframe solution is not working for https links.
Need to use RSA key encryption method provided by ccavenue mobile integration KIT.
Use the non-seamless mobile kit integration of php.
Add inappbrowser in application to visualize the ccavenue response.
<code>$ cordova plugin add cordova-plugin-inappbrowser
</code>
After successful installation write the following code in the controller -
<code>$scope.data = {
    orderId: 1,
    amount: 1,
};

$scope.ref = null;
$scope.getStateSecondWindow = function()
{
    $scope.ref.executeScript(
        {code: "localStorage.getItem('isCloseSelf')"},
        function(data)
        {
            if (data == 'yes')
            {
                $scope.ref.close();
            }
        }
    );
}
$scope.onSubmit = function(){
    $scope.ref = window.open(CONFIG.BASE_URL + 'getRSA.php?orderId=' +     $scope.data.orderId + '&amount=' + $scope.data.amount,'_blank','location=no');
    $scope.ref.addEventListener('loadstart', function(event) {  });
    $scope.ref.addEventListener('loadstop', function(event) {
    setInterval($scope.getStateSecondWindow, 5000);
    });
    $scope.ref.addEventListener('exit', function(event) {  });
}
</code>
Refer the link for php code: https://github.com/manjitlatthe/ionic-php-ccavenue-integration


Please any one can tell me How to filter an array from array using predicate.?

Question: I have an array
NSArray *arry = [[NSArray alloc]initWithObjects:@"1322",@"13222",@"13322",@"14322",@"13522",@"21322",@"11322",@"13212" ,nil];

and I want to get array having object
@"1322",@"13222",@"13322",@"13212"

can you please tell me how to use predicate for this filter.
Comment: Any criteria for this?
Comment: It is unclear how you want to filter. For example, why is `@"13222"` included in the result, but `@"11322"` is not??
Comment: let i have four objects(a,b,g,d) and i want to retrive only those four(a,b,g,d) objects from array of all objects(a,b,c,d,e,f,g,h,....z).NOTE:-it is not like retrieving first four objects.
Comment: Are you aware of having written a question and three comments without  explaining what you need?
Answer: I am not sure if I understand your question (and the comments) correctly.
To find all objects in array that are contained in another array wanted,
you can use the "SELF IN %@" predicate:
NSArray *array = [[NSArray alloc] initWithObjects:@"1322",@"13222",@"13322",@"14322",@"13522",@"21322",@"11322",@"13212" ,nil];
NSArray *wanted = [[NSArray alloc] initWithObjects:@"1322", @"13522", @"999", nil];

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF IN %@", wanted];
NSArray *filtered = [array filteredArrayUsingPredicate:predicate];
NSLog(@"%@", filtered);

Output:

(
1322,
13522
)
Answer: Try to use this one
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF like [c]'1*1*1'"];
NSArray *arry = [NSArray arrayWithObjects:@"1322",@"13222",@"13322",@"14322",@"13522",@"21322",@"11322",@"13212", nil];
NSArray *resltArry = [array filteredArrayUsingPredicate:predicate];

Answer: NSPredicate *p = [NSPredicate predicateWithFormat:@"SELF like [c]'13***'"];
NSArray *array = [NSArray arrayWithObjects:@"11321", @"13121", @"23121", @"1111", nil];
NSArray *resultArray = [array filteredArrayUsingPredicate:p];
NSLog(@"%@",resultArray);

o/p
(
    13121,
)
you can also refer this link
thisone
Answer: NSArray *yourArray = [[NSArray alloc]initWithObjects:@"1322",@"13222",@"13322",@"14322",@"13522",@"21322",@"11322",@"13212" ,nil];
NSArray *filter = [[NSArray alloc] initWithObjects:@"1322", @"13522", nil];

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF IN %@", filter];

NSArray *filteredArray = [array filteredArrayUsingPredicate:predicate];

This filteredArray will contain your filtered data. I think it will work as well.
Comment: Why do you need to copy the accepted answer and answer again..?


Doubt trying to understand the product in category theory?

Question: I'm reading Walters' Categories and Computer Science, here we have the definition of product:

I made a Mathematica code just to "see the definition working" but am confused with the following issue:

I defined my objects as elements of $A=\{\{\},\{1\},\{2\},\{3\},\{1,2\},\{1,3\},\{2,3\},\{1,2,3\}\}$.
I defined my arrows as $a\to b$ if $a \subset b$.
I want to find the product of $X=\{1, 2\}$ and $Y=\{1, 3\}$, looking at the definition, I think I need to collect all $i\in A$ such that we have $X\times Y \to X$ and $X\times Y \to Y$, there are two possibilities: $\{\},\{1\}$.
Now I think that we need to check if for all $Z\in A$, we have the arrows: $Z\to X\times Y, Z \to X, Z \to Y$ for $X\times Y=\{\}$ and then for $X\times Y=\{1\}$.

The trouble I am facing is the following: The code I made takes each possibility for $X\times Y$ and highlights the following edges:

$X\times Y \to X$
$X\times Y \to Y$
$Z\to X\times Y$
$Z \to X$
$Z \to Y$

For all $Z\in A$ if all them exist for some $Z$. It returns me the following graphs:

Question: I am a bit confused, what is the actual product here? Is it $\{\}$?Is it $\{1\}$? Is it both? I may be confusing something really silly but I am really lost here. I suspect $\{\}$ is not a product here but I don't know why.
Comment: Hint: $\{1\}$ is a subset of both $\{1,2\}$ and $\{1,3\}$, but not a subset of $\{\}$. What does that tell you about $\{\}$ being a product? On the other hand, any subset of both $\{1,2\}$ and $\{1,3\}$ is a subset of $\{1\}$. What does that tell you?
Comment: That's the most spectacular way to compute the intersection of two 2-element sets I've ever seen... May I suggest Rydeheard & Burstall's "Computational Category Theory"? I'm pretty sure they provide runnable code, and I'm also pretty sure that they use posets as examples.
Comment: @AndreyTyukin Hahaha, I like to write code for things in math (when possible) and generate figures of them, I guess it helps me understand things better. Also, thanks for the book, by the title I'm pretty sure I'm gonna love it!
Comment: Side note: For the identity arrows to exist you need $a \subseteq b$ (instead of $a \subset b$).
Comment: @MichaWiedenmann Many use $a\subset b$ to include the case $a=b$
Comment: @RedBanana Can you please share the Mathematica code / code you used for those diagrams, please? Thanks.
Comment: @JuliusHamilton Of course. [Here it is.](https://pastebin.com/ZEnvD7yB) It's a bit messy and I don't remember the code too well but in the variable `Obj` you set the objects in the category, the function `p[x,y]` is where you define the predicate so that it creates the arrows for the category and in `X` and `Y`, you define what objects you are computing the product. They are already in a convenient form: `X = Obj[[5]];` Where you can just change the numbers to obtain products between other objects in the category. If you need any help, contact me.
Answer: In your case the product corresponds to the intersection.
Things you have:

$p_1 : \{1\}\rightarrow \{1,2\}$
$p_2 : \{1\}\rightarrow \{1,3\}$
$q_1 : \{\} \rightarrow \{1,2\}$
$q_2 : \{\} \rightarrow \{1,3\}$

Two candidates for a product with their respective projections. However $\{1\}$ has something stronger, and it's that for $\{\}$ and its projections $q_1$ and $q_2$, there is a unique map $\{\}\rightarrow\{1\}$ call it $f$ such that $q_1 = p_1\circ f$ and $q_2 = p_2\circ f$.

I think of it this way:
We say an object is a "candidate for a product" if it has the projections. (Formally we call it a "cone".)
Then, a product is a candidate for a product with "maximal information".
As you can see, we can "recover" $q_1$ from $p_1$ and $q_2$ from $p_2$ assuming $f$. So in a sense $p_1$ and $p_2$ "contain more information". And that's what's so fundamental about this definition of product.

Importantly, you don't have a map from $\{1\}$ to $\{\}$ that has the same effect. Else it could happen that both were products.
Comment: But assuming the product is $\{\}$ doesn't it also have this unique map? In this case:

$$f = \{\}\to \{\} \\ q_1=p_1 = \{\}\to \{1,2\}\\ q_2=p_2 = \{\}\to \{1,3\}$$

The code I wrote gives me these five arrows (when I don't throw off the repetitions).
Comment: @RedBanana what you say is correct but not what we want, maybe I wasn't clear. The definition would be that $\{\}$ is a product of $\{1,2\}$ and $\{1,3\}$ if *for every* cone $x$, there is a morphism $x\rightarrow\{\}$ that factors the projections. In our case $\{1\}$ is a cone but fails to have such a mapping. (It doesn't have *any* mapping $\{1\}\rightarrow\{\}$ to begin with.)
Comment: @RedBanana For a product of $a$ and $b$ you can collect all cones (objects with a map to both $a$ and $b$) and then check for every arrow between every cone to see if there's an object with exactly one arrow that factors nicely through the projections of every other cone. It's really bad computationally in general, although for your example it is alright.
Comment: @RedBanana Instead, to make it algorithmically friendlier, you can consider a product as a function that takes cones as inputs and outputs arrows. So for instance in this case the product would be the function that when evaluated at $\{1\}$ gives the identity, and at $\{\}$ gives the arrow $\{\}\rightarrow\{1\}$. If you keep studying category theory you may see this written as $\Delta\dashv lim$.
Comment: I guess I understood it in my own crooked(?) way: First we collect all Z's that obey the definition, in this case: $\{\},\{1\}$, then we look for the arrows $\alpha$ **between the Z's** we found before?
Answer:
Now I think that we need to check if for all $Z\in A$, we have the arrows: $Z\to X\times Y, Z \to X, Z \to Y$ for $X\times Y=\{\}$ and then for $X\times Y=\{1\}$.

I think this is where your confusion lies, since you don't have these arrows in logical order. We don't need universally arrows $Z \to X \times Y$, $Z \to X$, and $Z \to Y$. Instead, we have an arrow $Z \to X \times Y$ whenever there are arrows $Z \to X$, and $Z \to Y$ (subject to a uniqueness condition).
As you correctly surmise, $X \times Y$ in your example can only be either $\{\}$ or $\{1\}$ because those are the only objects with arrows to both $\{1, 2\}$ and $\{1, 3\}$. Let's prove that $\{\}$ is not the product.
For $\{\}$ to be the product, we need for every object $Z$ and every pair of arrows $f : Z \to X$ and $g : Z \to Y$, an arrow $\langle f, g \rangle : Z \to \{\}$. As pointed out before, if we have these arrows $f$ and $g$, $Z$ must be either $\{\}$ or $\{1\}$. Let's check with $Z = \{1\}$. $f$ and $g$ can only be one thing, so let's check that there is an arrow $Z \to \{\}$. But since $Z$ is $\{1\}$ and there is no arrow $\{1\} \to \{\}$, $\langle f, g \rangle$ can't exist. This proves that $\{\}$ cannot be the product.
Spoilers below

 You might try proving that in general, the product of two sets in your category are their intersection. Similarly, the coproduct is the union.
Comment: I guess I'm starting to see it: First we collect all $Z$'s that obey the definition, in this case: $\{\},\{1\}$, then we look for the unique arrow $\alpha$ **between the Z's** we found before?


Why val() value is not working in function?

Question: This code is not working. but if inValue in function, it works well.
I want to know why this happens.
$('#id').on('input', something);
var inValue = $('#id').val();

function something () {
    console.log(inValue);
}

Comment: "This code is not working." You should [edit] the question and tell us _how_ it isn't working.
Comment: Most likely your code is executed before the DOM is fully rendered.
Answer: It is about scope, moving the val() inside the function fixes that:

$('#id').on('input', something);

function something () {
    var inValue = $('#id').val();
    console.log(inValue);
}

<input id="id" type="text" placeholder="Type in here" />
Comment: Thanks^________^ have a nice day!


Como fazer livebindings com objetos e pegar os objetos contidos?

Question: Estou com um problema que não consigo resolver de jeito nenhum. Com o Delphi XE8, já fiz livebindings para ligar componentes de tela TEdit com objetos não visuais, porem não consigo ligar componentes de tela com objetos contidos em outros objetos:
Exemplo:
TEstado = class
  FUF: string;
end;

TCidade = class
  FNome: string;
  FEstado: TEstado;
end;

Neste caso consigo ligar o nome da cidade com algum componente da tela, mas não consigo pegar cidade.estado.uf para mostrar na tela.
Comment: Quando eu precisar editar essa lista? No caso eu tenho um botão que atualiza essa lista com outros valores, qual função eu chamo pra atualizar o componente visual? Pois se eu só atualizar a grid dessa forma ai não vai atualizar o componente visual pra mostrar os dados.
Answer: Para disponibilizar a estrutura da sua classe para a LiveBinding utilize o componente "DataGeneratorAdapter". Crie as propriedades da sua classe nele, a partir daqui vc poderá ligar seus componentes visuais a esta estrutura.
Depois disso, utilize o componente "AdapterBindSource" para vincular a sua classe a essa estrutura criada no "DataGeneratorAdapter". Programe o evento "CreateAdapter" da seguinte forma:
procedure TForm1.AdapterBindSource2CreateAdapter(Sender: TObject;
  var ABindSourceAdapter: TBindSourceAdapter);

begin

     FLista := TObjectList<TPessoa>.Create;
     FLista.Add(TPessoa.Create('Filipe', 25, 'email@example.com'));
     FLista.Add(TPessoa.Create('Cíntia', 27, 'email@example.com'));
     FLista.Add(TPessoa.Create('Julio', 32, 'email@example.com'));
     ABindSourceAdapter := TListBindSourceAdapter<TPessoa>.Create(Self,     FLista);

end;


One tailed or two tailed test?

Question: I have a simple question. I'm not sure which one to use, whether it should be one tailed or two tailed test.
I have two sets of data - any type of measurements. First test is in perfect conditions and the second one is where the measurements are slightly different, some noise has been introduced.
Comparing two second set of data to the first one I need to answer the following questions:

Is the mean value of the second data significantly different?
Is the second data significantly nosier?

For the first one I decided to use two-tailed t-test to compare the means, the reason why I chose two tailed test is the fact that we are not asked whether one is higher/lower/better than the other.
However with the second question I've got a little dilemma. I want to use F-Test to compare the variances, but I am slightly confused in deciding, which one to use - two or one tailed test? I think it should be one tailed test, as I am testing whether the second data is worse than the first one, what that means I am checking whether the variance in the second one is a lot higher.
Am I correct or am I misunderstanding something here?
Thank you.
Answer: It is possible to use a one-tailed test since only deviations in one direction are expected in this case and because it is essentially an interpretation problem. More importantly, however, is that if you reject the second hypothesis, a different test needs to be chosen for the first, because t-test has an assumption of equality of variances. Finally, F-test for inequality of variances is extremely sensitive to data meeting distributional assumptions (normality), Levene's test is a more robust alternative.

One tailed or two tailed test?


How to make navbar overlap other contents in tailwind css

Question: When I open my nav bar(for mobile version) on my first page it works fine and overlaps the contents (picture): https://cdn.discordapp.com/attachments/916242216211595264/1001057465795874906/unknown.png
And when I open my navbar on the second page(forms page) the forms overlap the navbar.(picture): https://cdn.discordapp.com/attachments/916242216211595264/1001057531591929876/unknown.png
How could I fix that?
My code for my navbar is:
import React, {useState} from 'react';
import {GiHamburgerMenu} from 'react-icons/gi';
import {AiOutlineClose} from 'react-icons/ai';
import {NavLink} from 'react-router-dom';

const NavBar = () => {
  const [isOpen, setIsOpen] = useState(true);
  const toggle = () => {
    setIsOpen(!isOpen);
  }

  return (

            <NavLink to="/" activeClassName="active" >
Home
</NavLink>
            <NavLink to="/details" activeClassName="active" >
About
</NavLink>
            <NavLink to="https://www.google.com" activeClassName="active" >
Host
</NavLink>
            <NavLink to="/info" activeClassName="active">
Tutorial
</NavLink>

          {!isOpen ? <AiOutlineClose size={20}/> : <GiHamburgerMenu size={20}/>}

Home

About

Host

Tutorial

  )
}

export default NavBar;

First page:
import React from 'react'
import Typed from 'react-typed';
import { Link } from 'react-router-dom';
export const Welcome = () => {
  return (

              Web

            <Typed
              className="md:text-7xl sm:text-6xl text-4xl font-bold md:py-6 text-indigo-600"
              strings={["site", "Adam"]}
              typeSpeed={70}
              backSpeed={100}
              loop
            />

          A website  that is focused on design and
             simplicity

          <Link to="/details"><button className="bg-white text-black w-[200px] transition-[0.5s] rounded-lg font-bold my-6 mx-auto py-3 ring-2 ring-white hover:ring-indigo-600 hover:bg-indigo-600  hover:shadow-xl hover:shadow-indigo-700 hover:text-white hover:scale-110">
            Create
          </button></Link>

  )
}

Forms Page:
Code from: https://tailwindui.com/components/application-ui/forms/sign-in-forms (First Form). So how could i make my navbar overlap my forms page?
Answer: You'll have to work with relative absolute and z-index tailwind classes to overlap the navbar on the contents of the page.
Logic:
Have parent relative having z-index value less than the child absolute div which will be used for navbar.
Output in large device:

Output in smaller device:

Code:

          Desktop Navbar

        The main content of the file and it has it's content all over the page
        and i want to build a navbar on top of this

          Mobile Navbar

Further more you can use this tailwind play link

Extra. Toggle mobile navbar using hamburger menu
Output on large devices

Output in small device with hamburger menu

When clicked on hamburger menu

Code:

          Desktop Navbar

        The main content of the file and it has it's content all over the page
        and i want to build a navbar on top of this

          Mobile Navbar

Answer: Increase the z-index of the nav bar so that it is higher than that of the form.


SpringBoot with Ehcache

Question: I'm using spring boot and i have configured ehcache in my program. My Application Class looks like
SprinbootApplication.Class
@SpringBootApplication
@EnableJpaRepositories(basePackages = { "in.secondlevelcache.persistance"})
@EntityScan(basePackages = { "in.secondlevelcache.entity"})
@ComponentScan(basePackages = { "in.secondlevelcache.*"})
@EnableCaching
public class SpringApplicationClass  extends SpringBootServletInitializer{

@Autowired
StudentInter studentInterfaceService;

@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {

    return application.sources(SpringApplicationClass.class);
}

public static void main(String args[]) throws Exception{

    SpringApplication.run(SpringApplicationClass.class, args);
}

@Bean
public ServletRegistrationBean jerseyServlet(){
    ServletRegistrationBean register = new ServletRegistrationBean(new ServletContainer(),"/*");
    register.addInitParameter(ServletProperties.JAXRS_APPLICATION_CLASS, JerseyInitialize.class.getName());
    return register;
}

@Bean
public CacheManager getEhCacheManager(){
    return  new EhCacheCacheManager(getEhCacheFactory().getObject());
}

@Bean
public EhCacheManagerFactoryBean getEhCacheFactory(){
    EhCacheManagerFactoryBean factoryBean = new EhCacheManagerFactoryBean();
    factoryBean.setConfigLocation(new ClassPathResource("ehcache.xml"));
    factoryBean.setShared(true);
    return factoryBean;
}

@Bean
public List<Student> getAllStudentData(){
    System.out.println("Inside the GetAllStudentData of Spring Initalize");
    return studentInterfaceService.getUser();
}

Ehcache.xml
<?xml version="1.0" encoding="UTF-8"?>

<ehcache>
<defaultCache eternal="true" maxElementsInMemory="100" overflowToDisk="false" />
<cache name="empcache" maxElementsInMemory="10" eternal="true" overflowToDisk="false" />
</ehcache>

My Interface Class
@Service
 @Cacheable("empcache")
public interface StudentInter {

public List<Student> getUser();

public List<LabelMaster> getAllLabelValue(String language);

public List<LabelMaster> getAllLocaleLabelValue();
}

My Entity Class
@Entity
@Table(name="Student")
@Access(AccessType.FIELD)
@Cacheable(value = true)
@Cache(usage=CacheConcurrencyStrategy.READ_ONLY)

public class Student {

@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="roll")
private int rollId;

@Column(name="name")
private String name;

@Column(name="address")
private String address;

@Column(name="telephone")
private long phone;

public int getRollId() {
    return rollId;
}

public void setRollId(int rollId) {
    this.rollId = rollId;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getAddress() {
    return address;
}

public void setAddress(String address) {
    this.address = address;
}

public long getPhone() {
    return phone;
}

public void setPhone(long phone) {
    this.phone = phone;
}

}

I call the entity class using the repository
I call the method get user() during the server startup, i can see the query executes in my log and after that i try to call the same method by using a rest service i can see the same query fires in my log,but after that i call the same method using rest service i dint see any query
My question is
1) I load the data from db to second level cache during my server start up, then why the query is executes while I'M calling the same method using rest service ?
Answer: First of all, you can remove all the ehcache setup since as of Spring Boot 1.3 it is auto-configured automatically. Since you are using the default "ehcache.xml" location, Spring Boot will auto-detect that and create the cache manager for you. If you are using a different location for the config, there is a property to teach Spring Boot where to find the configuration for the cache (spring.cache.ehcache.config)
Second, you can't rely on that feature in @PostConstruct as there is no way to ensure that all the post processing is already done (this is the same for pretty much every interceptors, including @Transactional for instance).
Try to move that code to afterSingletonInstantiated (from the SmartInitializingSingleton interface). If you don't want to do that, another idea is to move that code to an event listener that is invoked when the app has fully loaded:
@EventListener(ContextRefreshedEvent.class)
public void yourCacheStuff() {
   ///
}

Comment: how about invoking `yourCacheStuff()` inside `main()` after the `SpringApplication.run()`?

SpringBoot with Ehcache


10 year old homework ABCDE +BCDE =

Question: Kids maths homework -

ABCDE +
 BCDE +
  CDE
______
74915

We're told A = 7.  I don't even know how to go about working this out.  Help?!
Comment: To be honest, when I read the title, I understood it as "I've been stuck on this homework problem for 10 years".
Comment: Go from back to front. As a start, note that $E$ is $5$ and $D$ is $0$.
Answer: As noted by Andre Nicholas in the comment: start from the back.
Note that $E+E+E$ gives a value which ends with 5. Only the number 5 has such a property.
Now we know that $E+E+E=15$. Since $DE+DE+DE$ gives a value which ends with a 15 at the end. That means D is 0.
$DE+DE+DE$ is 15, which doesn't carry any value to the next number, so, $C+C+C=9$ and $C=3$.
Similarly, $C+C+C=9$ doesn't carry any value to the next number. Hence, $B+B=4$ and $B=2$.
Therefore $ABCDE=72305$.
Answer: I'll set the problem up. I trust you can follow and apply the logic to the rest of the problem. From the rightmost column, we have that $E+E+E = 5$ (maybe after carrying) - equivalently $E+E+E \equiv 5 \pmod {10}$. The only way for this to happen is if $E = 5$.
Then $E+E+E = 15$ and so we have to carry, giving that $1+D+D+D = 1$ or equivalently $D+D+D = 0$ (again, maybe after carrying). What value(s) of $D$ give you that $3D$ is a multiple of $10$? (Go case by case, starting at $0$ to see what the values of $D$ have to be if you're not sure.) Can you take it from here?
Answer: Instead from the back, you can also start from the front!
Since $A$ is given to be $7$, the condition is equivalent to
$$2000 \times B + 3 \times \underline{CDE} = 4915$$
Now looking at everything modulo $3$, we get
$$2 \times B \equiv 4915 \equiv 1 \pmod 3$$
Since $B \le \frac{4915}{2000} = 2.4575$, $B$ can only be $2$. This leaves us $3 \times \underline{CDE} = 915 \implies \underline{CDE} = 305$.
Combine all this, we have $\underline{ABCDE} = 72305$.

10 year old homework ABCDE +BCDE =


If $k\geq3$ then $\binom{\lfloor2^{k/2}\rfloor}{k}2^{1-\binom{k}{2}}<1$.

Question: How can we show that
$\binom{\lfloor2^{k/2}\rfloor}{k}2^{1-\binom{k}{2}}<1$ when $k\geq 3$? I tried using Stirling approximation but it turned out to be a mess, do you see a smarter proof?
More generally, this inequality arises when we want to decide for which natural numbers $n$ $$\binom{n}{k}2^{1-\binom{k}{2}}<1$$ how might one even think of something like $n=\lfloor2^{k/2}\rfloor$ and $k\geq 3$?
Answer: Just use the upper bound ${n \choose k}\leq (en/k)^k$. Applying this here with $n=\lfloor 2^{k/2}\rfloor$ gives
\begin{equation}
{\lfloor 2^{k/2}\rfloor \choose k}2^{1-{k \choose 2}}\leq 2\cdot \frac{e^k}{k^k} \cdot 2^{(k^2/2)-k(k-1)/2}=2\left(\frac{e\sqrt{2}}{k}\right)^k.
\end{equation}
This is less that $1$ for $k\geq 5$. For $k=3,4$, one can check your inequality holds by hand pretty directly.
As for how you see this quantity, the above inequality suggests you should take $n$ such that $n^k\approx 2^{k(k-1)/2}$, which suggests taking $n\approx 2^{k/2}$.
Comment: $\binom nk \le (\frac{en}{k})^k$ is overkill; just with $\binom nk \le \frac{n^k}{k!}$ and $\lfloor k/2 \rfloor \le k/2$ this inequality reduces to $2^{k/2+1} < k!$.
Comment: @MishaLavrov Oof, that's much cleaner--I typically default to the weaker bound and didn't even think to check the sharper one directly works...


Export content in features using UUID features

Question: I read the UUID feature description and it says it is used to export content in feature. I installed the module but did not know how to export the content.
Answer: The uuid module has been reworked, and, as of 2012.05.25, uuid_features has not been updated to address those changes (though there is a patch RTBC).
In the meantime, to export nodes using uuid_features in Drupal 7:

Install features version 7.x-1.0-rc2.
Install uuid version 7.x-1.0-alpha1. (Not the latest version.)
Install uuid_features version 7.x-1.0-alpha1.
Enable the features module, the uuid module, the uuid_node module, and the uuid_features module
Go to Configuration > System > Universally unique identifiers, and click the "Create missing UUIDs" button
Go to Structure > Features > Create feature, and from the "Edit components" dropdown, select "Content: uuid_node", then pick the nodes you'd like to export into your Feature
Comment: Thanks, it's really helpful!!I have spent a lot of time trying to find what was wrong in my drupal installation and know it's working fine!Thanks
Comment: It seems uuid_node isnt required anymore, it was probably merged into one of the above modules
Comment: Do you know if there are working to integrate the uuid_features with the newer uuid version?
Comment: It looks like on http://drupal.org/node/1245582#comment-6226436, Rob Loach committed the change to the 7.x-1.x branch of UUID Features, so the latest 7.x-1.x-dev version should work with the current UUID module.  (I haven't tried it though.)
Comment: This answer could be updated and expanded, as it only addresses nodes and ignores entitie bundles such as fielded taxonomy terms.  The UUID features interface has also changed a bit, and there's a configuration step missing (Features > Configure UUID Export tab).  That's the step where you can select entity bundles for export in features.
Answer: Another way is using defaultcontent module
Comment: But it does not use the uuid. It forces you to have a machine name for all nodes.
Comment: This has been deprecated


Weird Apache problem with file

Question: There is a problem with apache2. It does not let me see images in a spesific directory. There are images in for instance directory X and Y. I have uploaded new ones and all of a sudden Apache started to say "Error 404" to files at X but it shows the files in Y. I could not solve it. I have already restarted the apache.
I cannot find how to solve it :(
Comment: Can you be more specific, show some logs, give names of directories and what you did exactly?
Comment: Please provide logs, configuration, and any .htaccess files you may have.
Comment: chmod -R 777 *  might fix it.  It's not secure but if it is urgent then you can clean up later on
Answer: Probably a permissions issue.
Identify Apache User:
You first need to see what User apache is running as by looking at the User directive in the apache configuration files.
Check Permissions:*
You then need to make sure that this user can access those files, has read access to the directory itself, and execute to that directory and all the directories under it leading up to root (/). See this question, I have an answer in there :-),  for more permissions help.
* Assumes unix based OS
Answer: perhaps your file permissions are wrong after the upload. Have you checked the permissions?
Christian
Answer: it could be permissions, like some other people mentioned - or it could be something silly like case sensitivity or bad file names.
I have seen lots of people with windows machines upload files where windows capitalizes the image to "Mypic.jpg" where you may have expected it to be accessed as /mypic.jpg
Having a space in the filename will also cause problems.
Do an "ls" in the directory and verify that the filenames are as expected.
Answer: Thanks to you all for those answers. I have done all of those things and couldn't solve it. But somehow I figure out that one of our programmers changes the file extentions xxx.jpg to xxx.JPG . And because of case sensitivity those images were invisible.
I have looked everywhere even filenames but did not think to look at extensions.
Thank you very much all of you, you were very helpful.
Thanks :)
Comment: Please update the original question instead of "add an answer", it makes it much easier for people to see what etra information you can give to make it easier to answer.

Weird Apache problem with file


how to remove the italic behaviour of font. If the button is TILT?

Question: I have a problem that if i skew the button to -15deg. Its tilt like itlaic font style but when the button tilt the text inside the button also got tilt(italic).
I want to know that how is it possible that if the button is tilt(italic)  then the text should be in normal font style.
now its showing like this  . I want button should be like this but text shouldn't be like this it should be normal.
i follow this answer but this is not working for me. font style should be normal
Is there any problem in my code below:
HTML:
<input id="btn" type="submit" value="BUTTON IS THIS">

CSS:
#btn{
background-color:#29b6f6;
color:#fff;
transform: skewX(-15deg);
font-style:normal;
}

Comment: Possible duplicate of [How to skew element but keep text normal (unskewed)](https://stackoverflow.com/questions/17947565/how-to-skew-element-but-keep-text-normal-unskewed)
Comment: I'd suggest using `BUTTON IS THIS` instead; since you can then wrap the text inside with another tag and style that tag to give it a skew opposite of the one applied to the button itself; so it will look how you want
Comment: @IvanS95 u are right . gonna try this. Thanks
Comment: @IvanS95 Thanks dude. Your suggestion work :-)
Comment: Glad to help :)
Answer: You may add a transformation to a nested element:
HTML:
<button id="btn" type="submit">BUTTON IS THIS</button>

CSS:
#btn{
background-color:#29b6f6;
color:#fff;
transform: skewX(-15deg);
}
#btn span {
  display: block;
  transform: skewX(15deg);
}


Expanding the Hyper-Parameter Search Grid in Caret

Question: I was wondering if there was a way to expand the hyper-parameter search within caret package or with slight modification. For example, evtree can currently only take alpha in caret but the evtree.control can take many more arguments. I doubt that I can just pass it through method = "evtree".
ctrl <- trainControl(method = "repeatedcv", number=10, repeats = 5,classProbs=TRUE,summaryFunction = twoClassSummary)

# Set up the cross-validated hyper-parameter search
EVTREE_GRID= expand.grid(pmutatemajor=c(0.2,0.2), pmutateminor=c(0.2,0.2), pcrossover=c(0.2,0.2),
                     psplit=c(0.2,0.2), pprune=c(0.2,0.2), minbucket=c(5L,10L), minsplit=c(15L,25L),
                     maxdepth=c(5L,15L),alpha=c(1L,5L))

EVTREE_fit_bayes <- function(pmutatemajor, pmutateminor, pcrossover,
  psplit,pprune,minbucket,minsplit,maxdepth,alpha) {
    txt <- capture.output(
      mod <- train(Creditability~ ., data =XY_train,
                  method = "evtree",
                  preProc = c("center", "scale"),
                  metric = "AUC",
                  trControl = ctrl,
                  tuneGrid = EVTREE_GRID))

 list(Score = getTrainPerf(mod)[, "TrainAUC"], Pred)
 }

 library(rBayesianOptimization)
   EVTREE_Search <- BayesianOptimization(EVTREE_fit_bayes,

             bounds = list(pmutatemajor=c(0.2,0.2), pmutateminor=c(0.2,0.2), pcrossover=c(0.2,0.2),
                           psplit=c(0.2,0.2), pprune=c(0.2,0.2), minbucket=c(5L,10L),
                           minsplit=c(15L,25L), maxdepth=c(5L,15L), alpha=c(1L,5L)),

             init_grid_dt =NULL,
             init_points =10,
             n_iter = 10,
             acq = "ucb",
             kappa =1,
             eps = 0.0,
             verbose = TRUE)

Answer: you can create your own model so basically you redefine the parameters for evtree, basically redefining the existing one for evtree, the elements of the list to change are under parameters, grid and fit (where you pass in evtree.control) :
evtree_ext <- list(label = "Tree Models from Genetic Algorithms",
                  library = c("evtree"),
                  loop = NULL,
                  type = c('Regression', 'Classification'),
                  parameters = data.frame(parameter = c("maxdepth","alpha"),
                                          class = rep('numeric',2),
                                          label = c('maxdepth','alpha')),
                  grid = function(x, y, len = NULL, search = "grid") {
                    if(search == "grid") {
                      out <- data.frame(alpha = seq(1, 3, length = len),maxdepth=seq(1,20,len=len))
                    } else {
                      out <- data.frame(alpha = runif(len, min = 1, max = 5),maxdepth=sample(1:20,len=len))
                    }
                    out
                  },
                  fit = function(x, y, wts, param, lev, last, classProbs, ...){
                    dat <- if(is.data.frame(x)) x else as.data.frame(x, stringsAsFactors = TRUE)
                    dat$.outcome <- y
                    theDots <- list(...)

                    if(any(names(theDots) == "control"))
                    {
                      theDots$control$alpha <- param$alpha
                      ctl <- theDots$control
                      theDots$control <- NULL
                    } else ctl <- evtree::evtree.control(alpha = param$alpha,maxdepth=param$alpha)

                    ## pass in any model weights
                    if(!is.null(wts)) theDots$weights <- wts

                    modelArgs <- c(list(formula = as.formula(".outcome ~ ."),
                                        data = dat,
                                        control = ctl),
                                   theDots)

                    out <- do.call(evtree::evtree, modelArgs)
                    out
                  },
                  levels = function(x) x$obsLevels,
                  predict = function(modelFit, newdata, submodels = NULL) {
                    if(!is.data.frame(newdata)) newdata <- as.data.frame(newdata, stringsAsFactors = TRUE)
                    predict(modelFit, newdata)
                    },
                  prob = function(modelFit, newdata, submodels = NULL) {
                    if(!is.data.frame(newdata)) newdata <- as.data.frame(newdata, stringsAsFactors = TRUE)
                    predict(modelFit, newdata, type = "prob")
                    },
                  tags = c("Tree-Based Model", "Implicit Feature Selection", "Accepts Case Weights"),
                  sort = function(x) x[order(x[,1]),])

Using an example (sorry not familiar with this package, might be nonsense):
library(MASS)
library(caret)
library(evtree)
library(rBayesianOptimization)

mod <- train(type~ ., data =Pima.tr,method=evtree_ext,
tuneGrid=data.frame(alpha=c(1,2),maxdepth=c(5,10)),
trControl=trainControl(method="cv",number=2))

mod$results

  alpha maxdepth Accuracy     Kappa  AccuracySD    KappaSD
1     1        5    0.715 0.3511444 0.007071068 0.04724272
2     2       10    0.725 0.3273370 0.007071068 0.01357389

Comment: Thank you so much. Im going to try running the Bayesian optimization algorithm.
Comment: you're welcome .. happy modeling :)


Java POI - anyone been able to extract numbers from formula cells?

Question: I've been using Java POI for some time now, but have encountered a new problem, and I'm wondering if anyone has found a solution.
When you read a spreadsheet, you need to know the type of cell in order to use the proper read method.
So you get the cell type, then call the appropriate read method to get the cell's contents.
This works for all cells except for the FORMULA cell, where the value is a number. If it's text, you can read it just fine. But if the resulting value is a number, then all you get from the cell is a blank string.
I've been through the javadocs for POI, and am using the correct data type (HSSFRichTextString), but still no joy.
Anyone have a solution?
P.S. this behavior of POI does bug me as there should be a default cell.toString() method that would return the string representation of ANY cell type, say defaulting to the cell's value property. (sort of like the paste-special where you can choose "value").
PPS: As asked - I'm using Java 6 (1.6.0_06) and poi-3.0.2-FINAL-20080204.jar
Comment: What version of POI are you using?
Answer: <code> FileInputStream fis = new FileInputStream("c:/temp/test.xls");
    Workbook wb = new HSSFWorkbook(fis); //or new XSSFWorkbook("c:/temp/test.xls")
    Sheet sheet = wb.getSheetAt(0);
    FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator();

    // suppose your formula is in B3
    CellReference cellReference = new CellReference("B3");
    Row row = sheet.getRow(cellReference.getRow());
    Cell cell = row.getCell(cellReference.getCol());

    CellValue cellValue = evaluator.evaluate(cell);

    switch (cellValue.getCellType()) {
        case Cell.CELL_TYPE_BOOLEAN:
            System.out.println(cellValue.getBooleanValue());
            break;
        case Cell.CELL_TYPE_NUMERIC:
            System.out.println(cellValue.getNumberValue());
            break;
        case Cell.CELL_TYPE_STRING:
            System.out.println(cellValue.getStringValue());
            break;
        case Cell.CELL_TYPE_BLANK:
            break;
        case Cell.CELL_TYPE_ERROR:
            break;

        // CELL_TYPE_FORMULA will never happen
        case Cell.CELL_TYPE_FORMULA:
            break;
    }
</code>
Copied shamelessly from here
Comment: Be aware that the evaluator.evaluate(cell) can throw a RuntimeException if the formula is invalid.
Comment: Have you actually tried this? I too can read the docs. I'm looking for actual "yes, I've tried this and it works" info. Thanks.
Answer: Just convert that cell into text .. using copy-"paste special" ... I did it as follows ....
Read from Point # 2 at :
http://www.asif-shahzad.com/2010/12/how-to-read-numbers-as-string-value-in.html
Answer: If POI doesn't work out for you, try Andy Khan's JExcel.  I prefer it.
Answer: An alternative to using createFormulaEvaluator is to use SetCellType(CellType.STRING) and then access StringCellValue. I ran into problems using a formula evaluator (using NPOI) when it contains the WORKDAY() function.


What is the name of $E(XY)$?

Question: If $X,Y$ are random variables, what is the name of the term $E(XY)$? (which if we subtract $E(X)E(Y)$ gives the covariance)
Answer: Moments of the form $\mu'_{rs}=E(X^rY^s)$ are called "product moments" or more specifically "$r,s$ product moments"; you have the $1,1$ product moment, $\mu_{11}$. They may also be called raw product moments (to distinguish from central ones like covariance).
Some people might call it a 'first order product moment', though 'first order' can be somewhat ambiguous (some people might interpret that to mean $\mu_{01}$ or $\mu_{10}$, perhaps).
They are also sometimes called mixed moments (since they involve more than one variable) but the term can apply to moments in more than two variates; in this case we have mixed raw moments.
Comment: @StubbornAtom I should have a ' on $\mu_{rs}$ there (but not on $\mu_{1,1}$)
Comment: I have also heard people call $\mu_{rs}$ the $(r,s)$th order bivariate moment/product moment about zero. They denote it by $\mu_{r,s}'$.
Comment: Isnt there an abbreviation for the 1,1 moment? Similar to "mean" for the first moment?
Comment: @Programmer2134 There's going to be several names, I think. Did you have a particular name in mind?
Comment: If I had a name in mind I wouldnt have asked this question
Comment: Sorry, it just sounded like maybe you already had an idea of what it might be from your comment (more of an idea than was in your comment). There will be names for it that I don't have here (including perhaps simpler or more evocative terms than I've used); I'm dragging terms up out of memory and putting them in when they come to me (I haven't had to put a name to these in decades). I figured if you had part of a term or some notion about it (maybe you thought you remembered the first letter or something) that it might jog the memory better.
Comment: Oh that makes sense. Well hmm, not really. I was thinking about something like cross-mean or something like that

What is the name of $E(XY)$?


Falha de segmentação ao tentar inicializar lista encadeada

Question: #include <stdlib.h>
#include <stdio.h>
#define MAX 10

typedef struct
{
  int codigo;
  /*
     outros componentes
     de produto
  */
} TProduto;

typedef struct celula
{
  TProduto item;
  struct celula* prox;
} TCelula;

typedef struct
{
  TCelula* primeiro;
  TCelula* ultimo;
  int tamanho;
} TLista;

void FLVazia(TLista *Lista)
{
  Lista -> primeiro = (TCelula *) malloc(sizeof(TCelula));
  Lista -> ultimo = Lista -> primeiro;
  Lista -> primeiro -> prox = NULL;
  Lista -> tamanho = 0;
}

int Vazia(TLista Lista)
{
  return (Lista.primeiro == Lista.ultimo);
}

void Inserir(TProduto x, TLista *Lista)
{
  Lista -> ultimo -> prox = (TCelula *) malloc(sizeof(TCelula));
  Lista -> ultimo = Lista -> ultimo -> prox;
  Lista -> ultimo -> item = x;
  Lista -> ultimo -> prox = NULL;
  Lista -> tamanho++;
}

TCelula* Pesquisar(TLista Lista, TProduto Item)
{
   TCelula* Aux;
   Aux = Lista.primeiro;
   while(Aux->prox != NULL)
   {
      if(Aux->prox->item.codigo == Item.codigo)
         return Aux;
      Aux = Aux->prox;
   }
   return NULL;
}

void Excluir(TLista *Lista, TProduto *Item)
{
  /* Obs.: o item a ser retirado e o apontado por p */
  TCelula *Aux1, *Aux2;
  Aux1 = Pesquisar(*Lista, *Item);
  if (Aux1 != NULL)
  {
     Aux2 = Aux1->prox;
     Aux1->prox = Aux2 -> prox;
     *Item = Aux2->item;
     if (Aux1->prox == NULL)
        Lista->ultimo = Aux1;
     free(Aux2);
     Lista->tamanho--;
  }
}

void Imprimir(TLista Lista)
{
  TCelula* Aux;
  Aux = Lista.primeiro -> prox;
  while (Aux != NULL)
  {
    printf("%d\n", Aux->item.codigo);
    Aux = Aux -> prox;
  }
}

int main ()
{
    //1
    TLista *Lista1;
    TProduto Item;
    //2
    FLVazia(Lista1);

    return 0;
}

Estou tentando inicializar esta lista encadeada mas quando eu chamo a função "FLVazia" para fazer isso, ocorre um erro de falha de segmentação.
Eu tentei inicializar Lista1 como NULL (Lista1 = NULL;) antes de chamar a devida função mas como esperado, nada mudou e obtive o mesmo erro.
O que está causando isso?
Isto é uma parte de um trabalho da faculdade cujo só estou responsável pela função main, todo o resto foi feito pelo meu professor de Algoritmos e Estrutura de Dados 1.
Desde já, obrigado!!
Answer: Você está derreferenciando um ponteiro nulo quando faz:
Lista -> primeiro = ...

Na função FLVazia você deve verificar se Lista é ponteiro para nulo e, se for, fazer esse ponteiro apontar para algo:
void FLVazia(TLista *Lista)
{
  if (Lista == NULL) Lista = (Lista *) malloc(sizeof(Lista));
  Lista -> primeiro = (TCelula *) malloc(sizeof(TCelula));
  Lista -> ultimo = Lista -> primeiro;
  Lista -> primeiro -> prox = NULL;
  Lista -> tamanho = 0;
}

Mas se você já espera uma lista vazia nessa função, então não precisa do if, apenas alocar memória para o ponteiro (Lista) apontar.


How to find list of application accessed by user in a Interval using a background job?

Question: I want to find out the list of apps accessed by user in a particular time interval (ex: 5min), from a background job?
Is this possible on a non-rooted android phone? If possible I'm very much interested in knowing the answer as it will be a great learning about android.
Comment: Would it suffice to record the accessed apps during that interval?
Comment: I just need application names accesed in that interval.
Comment: Did you check my answer? The application though have a bug. not in the approach but it get destroyed after opening a lot of programs. calling the method from a service would solve the problem. and to be sent directly to a web service. or saving it on the device some where. my app display them on list view for testing purpose. it will get lost any way from the UI. even if we have a service. we need to store them.
Comment: @hasan83 thanks for your answer, but at android 5 `getRecentTasks()` is deprecated for user privacy. Is there any other solutions for this.
Comment: Ya thats true I know about that. so far I didn't investigate. but i don't' think so. I will investigate and update my answer regarding.
Answer: Update:

In android 5.0 an alternative of getRecentTasks() method is getAppTasks.

Code Sample:
private void listTasks() throws PackageManager.NameNotFoundException {
  ActivityManager mgr = (ActivityManager)getSystemService(Context.ACTIVITY_SERVICE);
  List<ActivityManager.AppTask>  tasks = mgr.getAppTasks();
  String packagename;
  String label;
  for (ActivityManager.AppTask task: tasks){
    packagename = task.getTaskInfo().baseIntent.getComponent().getPackageName();
    label = getPackageManager().getApplicationLabel(getPackageManager().getApplicationInfo(packagename, PackageManager.GET_META_DATA)).toString();
    Log.v(TAG,packagename + ":" + label);
  }
}

Original Answer:
Introduction
The ActivityManager class provides two methods that returns such an information. Choosing getRecentTasks or getRunningTasks method would be appropriate since the returned tasks list is not our goal anyway. but, It will be used as a reference point on the way to determine the desired list.
Code Sample:
ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
List<RecentTaskInfo> activitys = activityManager.getRecentTasks(Integer.MAX_VALUE, ActivityManager.RECENT_IGNORE_UNAVAILABLE);
for (int i = 0; i < activitys.size(); i++) {
    RecentTaskInfo activity = activitys.get(i);
    activity.baseIntent.getComponent().getPackageName();
}

Filtering: This list includes all type of tasks including system tasks.
Code Sample:
if (activity.baseIntent.getCategories().contains(Intent.CATEGORY_LAUNCHER)) {
    // This is an application.
    getPackageManager()
        .getApplicationLabel(getPackageManager()
        .getApplicationInfo(activity.baseIntent.getComponent()
        .getPackageName(), PackageManager.GET_META_DATA)); // application name
}

This is the same list that will display on long pressing the home button.
Abstract Approach: (Explanation comes later)

To determine the desired list within the specified time that we will
  call (period). The recent tasks list will be asked for in the
  beginning of the period and after each smaller period within the
  period that we will call interval.
The recent apps. list fetched after the first interval will contain
  three type of apps. Old-apps, which are not in our interest,
  New-launched and Re-launched apps. The reason behind choosing the
  abstract approach is detecting the Re-launched apps.
Detecting New-launched Apps:
Those are the apps. that simply didn't appear in the very first
  fetched list. (before the period).

Explanation by examples why this approach:

It would be a great idea to consider any app. appeared before your app. in a later fetched list a re-launched app. since when we started the operation, which is from inside the app, your app. was on top of the list.

But, your app. may step down from top and gets back to it within the interval time. (Facebook > Twitter > Your App).

In a later fetched list another app. may get on top. taking it as a reference will fail too for the same reason your app. failed as a reference.

Winning Approach:

The list fetched before an interval will be the reference for the list
  fetched after the interval. the re-launched apps. would be the apps.
  appeared before the first-ordered-sub-list(fosl).

All the apps. before the fosl are re-launched not only What's app. And, It can be proven easily. There is no way to rearrange the apps on top of the fosl in a way that some of them may have been re-launched without the fosl get changed (get bigger to include more apps). you can exercise it.
fosl approach will work too even if user removed some of the apps. from the list manually within the interval. only removed apps will not be detect if they didn't got detected in a previous interval. but, it will not affect the fosl approach for the rest in the list. same thing if user cleared all the list, only the cleared apps. will not detected and not the ones launched after within the same interval.
Why intervals? because for such a long period user can open and relaunch apps. then, clear the list or remove some.
Small intervals would also make it so hard on the user to open any top sublist with the same order again which is the only weakness of the fosl approach.
Sample Code: (fosl)
public int getIndexOfFirstAppBeforeFOSL(ArrayList<App> recentApps) {
    int i=previousRecentApps.size()-1, j = recentApps.size()-1;
    for (; i>=0 && j>=0 ; i--) {
        App app = previousRecentApps.get(i);
        if (app.equals(recentApps.get(j))) {
            j--;
        } else {
            // this application got re-launched and therefore it changed it place in list.
            // or removed manually by user.
        }
    }

    return j;
}

I created a GitHub project for the application. check it out, and report bugs if any.
Missing to detect one or two apps for the weakness we mentioned want really going to effect the research result your are getting from collecting apps. getting launched from a big number of user. if that what are you doing anyway. Otherwise, your app. can frequently get new launched app. and notify the user about it.
Comment: Note that your technique will no longer work as of Android 5.0, when `getRecentTasks()` no longer does what you need it to do.
Comment: Check this out, It's late night here. I made last minutes modifications to code project. all well as I can say. The approach theoretically looks perfect. report me with bugs in the project code. I will fix. interesting question anyway.
Comment: Yes that's true. but It will still work for like 80% of devices for maybe a year and less percentage later. I will update my answer if there a solution on 5.0 or not.
Comment: Thank you very much for not forgetting to assign the bounty :) but, I don't see the green check mark that indicate that the answer is accepted!
Answer: Yes.It is possible.Your service needs to be run for every 5 secs.In that service,you have to write the logic for  whichever apps is accessed by user.You have to use ActivityManager class for getting running applications.


What is this alternating notes called?

Question: Reading the works of Bach, there's an unusual pattern I keep seeing. Consider, for example, the opening of the fugue from the infamous BWV 565:

It constantly alternates between A, which doesn't move, and a lower note, which does move. Obviously this is a fugue, so this exact phrase appears again and again — but Bach seems to do this constantly, in just about every organ piece I've looked at. Sometimes the moving note is higher than the stationary note, sometimes it's lower. (In the toccata, one actually crosses the other at one point!)
Is there a name for this perculiar structure?
I know the general name for playing the notes of a chord sequentially is arpeggio. But this clearly isn't a chord, it's a melody. And there's always exactly 2 notes. And they always strictly alternate; never any more complex pattern. And one note stays stationary, and the other moves. And it only ever seems to move in fairly small steps, apart from the odd isolated jump. That all seems quite specific... like it should have a name. Also, as far as I know, only Bach does this. (Having said that, I've only ever tried to play Bach and pop songs, so...)
Comment: @Dekkadeci That answer just says it's called arpeggio. I'm not convinced that really describes this figure.
Comment: It doesn't matter whether any of its answers are correct - it asks pretty much the same question as yours, as far as I can tell. This website's precedent is to flag newer questions as duplicates and funnel viewers to older questions.
Comment: And the answer by RosieF there is correct in my opinion. I think the key concept is 'internal pedal point'.
Answer: In the case shown, the "A" is termed an "organ point" or a "pedal point." (Usually pedal point is used for such an occurance in the bass, but I've seen it used for any voice.) It's a sustained tone with (usually) dissonant harmony being sounded against the sustained tone. It's the same case here but the tone is repeated alternately rather than being sustained; the harmonic effect is identical. The use of alternate repitition indicates that this fugue was probably originally conceived for violin or another stringed instrument rather than for the organ.
Answer: You might be looking for 'bariolage'. This term is more often used for string writing. As an aside, scholars are not in full agreement as to whether this is actually by Bach. One of the arguments is that the toccata 'looks' like a simple arrangement of an Italianate violin piece.

What is this alternating notes called?


Polynomial equations in $p$ and $q$ with $p,q$ primes

Question:
Is there a non zero polynomial $R \in \mathbb{Z}[X,Y]$ such that there exists an infinite number of pair $(p,q)$ with $p$ and $q$ primes, $p \neq q$ and $R(p,q)=0$ ?

I know the curve must be of genus $0$ (Faltings-Mordell).
My question is related to Polynomial equations in $n$ and $\phi(n)$

 that has been solved.
Comment: Conjecturally, $R(x, y) = x - y + 2$ or $R(x, y) = x - 2y - 1$...
Comment: For the record, the conjectures mentioned in Qiaochu Yuan's comment are about [twin primes](http://en.wikipedia.org/wiki/Twin_prime) and [safe primes](http://en.wikipedia.org/wiki/Safe_prime) or [Sophie Germain primes](http://en.wikipedia.org/wiki/Sophie_Germain_prime).
Comment: Conjecturally, there are infinitely many primes $p$ such that $p^2-2$ is prime, so $R(x,y)=x^2-y-2$ will do. More generally, it is widely believed that if $f$ and $g$ are irreducible polynomials with integer coefficients, and if there is no $d\gt1$ such that $d$ divides $f(n)g(n)$ for all $n$, then there are infinitely many $n$ such that $f(n)$ and $g(n)$ are both prime. But the proofs are way out of reach. See Schinzel's Hypothesis H.
Comment: Less trivially, (p-q-2)(p-q-4)(p-q-6)(p-q-8)(p-q-10)(p-q-12)(p-q-14)(p-q-16)(p-q-18)(p-q-20) is zero infinitely often under Elliott-Halberstam.
Comment: @GerryMyerson: Thanks.
Answer: Meanwhile, we know the answer is yes. As of 2013 we know (thanks to Y. Zhang) that there is some $C\leq7\cdot10^7$ such that there are infinitely many prime pairs that differ by $C$. So we can take $R(x,y)=x-y-C$, or, if you want an explicit example, take $\prod_{\substack{C=2\\C\text{ even}}}^{7\cdot10^7}(x-y-C)$. As of april 2014 it is known that we can have $C\leq246$.
See here for more information.


Virtualbox PXE Boot Failing with a Windows Server 2008 R2 Server

Question: Some fast help on this would be good, I have been on this problem for 14 hours.
In a Virtualbox test environment I have 2 virtual machines networked together using a internal network (no traffic runs though the host, it is all at a software level). One is a fresh client with 512mb of ram and a dual core set-up, the other is the server with 1.5GB of ram and running server 2008 r2. The server is configured as a dns server, dchp server, domain controller and also serves PXE booting though WDS (Windows Deployment Services). Both machines can see each other and I am able to start a network boot.
The issue comes at the second to last stage of the pre windows PE install. On TFTP download of boot.sdi it starts it but stops during the boot process.
Comment: Is there any more info you can provide to help diagnose the fault? How you configured ther server, for example. What happens when it fails? Which boot image you're using, etc...
Answer: You need more than 512 MBs of RAM to boot a wim. WIM files are RAMdisk files so they need at least as much RAM as the file is big. Look at your WIM file and use that as the base amount of RAM to use with your machine. You should always add buffer space to the VM for processing at boot time. Some configurations are made and the only place to store them in a RAM OS is the RAM.
I add ~ 100 MBs as buffer but you should experiment around to get a good feel for you buffer. You might need more but most likely you would need less.
Comment: 512 MBs of RAM would most likely work with Windows XP because it does not load into a full GUI.
Answer: Check the Windows Firewall setting. Make sure that the Incoming and Outgoing rules for the TFTP server is allowed for all profiles (public, private, work/domain).
Important: Double check the process referred in the rules! Yesterday, I nearly tore my hair out trying to get an L3 switch pick up its IP address from tftpd32.exe on my computer... only to find that the rule explicitly matched d:\tools\tftpd32.exe, while I've actually moved tftpd32 to d:\tools\tftpd32\tftpd32.exe. As soon as I changed the path in the rule, the L3 switch saw my TFTP server, and all is well.
Comment: I can though see in my event logs that downloads do start and complete without a problem. Also I tend to open the entire port instead of just the process for services. Also I have turned the firewall off with no effect
Comment: @Vbitz downloads initiated by the VM or the host will not get affected because the destination of the initial TCP connection establishment is not directed to the host. And as to turning the firewall off: That's what I did with my tftpd32 woe. The firewall *was* turned off (got scary warnings from Windows), but the rule still stupidly gets applied. Try double-checking if Incoming *and* Outgoing rules for local UDP ports 67, 68, 69 (all UDP - DHCP and TFTP both use UDP) are all allowed.
Comment: And still I have the same problem I currently have a rule allowing all traffic to go though on UDP ports 67-69. Still I have the same issue.
Comment: @Vbitz ... okay, that stumped me ... can the DHCP and TFTP server be accessed from other VM? Say, boot using a LiveCD and access those ports.
Comment: Just booted into Ubuntu 11.04, I was able to download the file no problems, also this is not a part file, they are both the same size down to the byte, also the whole file was downloaded in 3 seconds.
Comment: @Vbitz ahh... something's wrong with the client then... what's the client?
Comment: The client is also a vm, all of this is being done in virtual machines
Comment: @Vbitz um, I meant, what's the client's OS supposed to be? Windows?
Comment: I am deploying Windows 7 Enterprise.
Comment: @Vbitz I'm scratching my head here, also... although truth be told, I haven't tried booting Windows via PXE... maybe the following TechNet article can help? : http://technet.microsoft.com/en-us/library/dd744541%28WS.10%29.aspx
Comment: That is more on building a image. My image was made using original install media and the wizard given.
Comment: If you can start the image stream then it is not a firewall issue. if you could not start the stream then it would most likely be an issue with the firewall.
Answer: Add more RAM to the client. Virtual NICs often behave strangely with tight memory.


Why is this XAML invalid?

Question: This XAML compiles and runs without any runtime errors:
<Window
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:Custom="http://schemas.microsoft.com/wpf/2008/toolkit" x:Class="WpfApplication1.Window1"
    Title="Window1" Height="300" Width="300" mc:Ignorable="d">
    <StackPanel Orientation="Vertical" d:LayoutOverrides="Height" DataContext="{Binding Source={StaticResource booksDataSource}}">
        <Custom:DataGrid ItemsSource="{Binding Mode=Default, XPath=/catalog/book}" AutoGenerateColumns="False">
            <Custom:DataGrid.Resources>
                <ControlTemplate x:Key="TemplateLoverBirds">
                    <StackPanel Orientation="Horizontal">
                        <TextBlock Text="Great book!" />
                        <TextBlock x:Name="textBlock" Text="{Binding Mode=Default, XPath=title}" />
                    </StackPanel>
            </ControlTemplate>
            </Custom:DataGrid.Resources>
            <Custom:DataGrid.Columns>
                <Custom:DataGridTextColumn Binding="{Binding Mode=Default, XPath=author}"/>
                <Custom:DataGridTemplateColumn>
                    <Custom:DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <Control x:Name="TitleControl">
                                <Control.Template>
                                    <ControlTemplate TargetType="{x:Type Control}">
                                        <TextBlock Text="{Binding Mode=Default, XPath=title}" />
                                    </ControlTemplate>
                                </Control.Template>
                            </Control>
                            <DataTemplate.Triggers>
                                <DataTrigger Binding="{Binding XPath=title}" Value="Lover Birds">
                                    <Setter TargetName="TitleControl" Property="Template" Value="{StaticResource TemplateLoverBirds}" />
                                </DataTrigger>
                            </DataTemplate.Triggers>
                        </DataTemplate>
                    </Custom:DataGridTemplateColumn.CellTemplate>
                </Custom:DataGridTemplateColumn>
            </Custom:DataGrid.Columns>
        </Custom:DataGrid>
    </StackPanel>
</Window>

But at design time in Blend this is marked as invalid XAML---and in Visual Studio design time the "Load Cancelled" screen shows (but loads properly after clicking Resume loading the designer).
Answer: Blend only supports a subset of WPF. I have noticed that EventSetters kill blend as well. I have the same problem as you. I have many windows which run fine, but cant be viewed in blend for odd reasons.
Strategy to diagnose Expression Blend 2 failure to open Window
I think maybe the Custom:DataGrid might not be supported. I dont know, just guessing. If your window instantiates and runs fine, then i guess blend is bugged.
Answer: Allright I fixed the issue like follows:
Change:
xmlns:Custom="http://schemas.microsoft.com/wpf/2008/toolkit

To:
xmlns:Custom="clr-namespace:Microsoft.Windows.Controls;assembly=WpfToolkit"

Make sure you have a good version of the WpfToolkit. Make a reference to the Toolkit and you can work with it.
Comment: My project has an explicit reference to `C:\Program Files (x86)\WPF Toolkit\v3.5.40619.1\WPFToolkit.dll` and this is not working for me...

Why is this XAML invalid?


Scraping HTML and JavaScript

Question: I am working on a project in which I need to crawl several websites and gather different kinds of information from them. Information like text, links, images, etc.
I am using Python for this. I have tried BeautifulSoup for this purpose on the  HTML pages and it works, but I am stuck when parsing sites which contains a lot of JavaScript, as most of the information on these files is stored in the

Scraping HTML and JavaScript


How to move local directories to Alibaba Cloud OSS using ossutil tool?

Question: I want to move a local directory to Alibaba Cloud OSS bucket using ossutil tool.
The command I used to upload the video directory to OSS bucket - testbucket is ossutil cp -r video oss://testbucket but it throws no such keyword error.
Comment: I've never used this tool, but after a quick google, the answers I found all use a different order for the arguments. They use `ossutil cp video oss://testbucket -r`
Answer: Be aware of that [/] in the end of source dir.
Try this:
ossutil cp -r folder_name/ oss://bucket-name

Refer:
https://github.com/aliyun/ossutil/issues/45#issuecomment-448818209
Answer: try this
ossutil cp -r video/ oss://bucket testbucket
Refer: https://help.aliyun.com/document_detail/50452.html?spm=a2c4g.111866220.127.116.11e5751a1SrXLBo
Answer: This worked for me.
Note: -r has to be at the end.
aliyun oss cp folder_name/ oss://bucket-name -r


Physical meaning of a function from $\mathbb{R}^2$ to $\mathbb{R}^3$ and its Jacobian matrix

Question: What exactly does it mean when it says:
For
\begin{align*}
f: \mathbb{R}^2 &\rightarrow \mathbb{R}^3,\\
f\pmatrix{x\\ y} &= \pmatrix {xy\\ \sin(x+y)\\ x^{2} - y^{2}},\\
Jf\pmatrix{x\\ y}
&= \left[\matrix{y&x\\ \cos(x+y)&\cos(x+y)\\ 2x&-2y}\right].
\end{align*}
My question is, what does this physically mean?
And also, what does the first bit mean? We have a function of two variables that is represented by three separate expressions?
Comment: Does the first bit make more sense if you replace the $n$ by the correct numbers? The given function is $f:\mathbb{R}^2\to \mathbb{R}^3$. When you say "what does this physically mean?" are you asking for a physical interpretation ... like an example from physics or something more along the lines of "how do you find $Jf$"?
Comment: Physical example. I'm a first year physics student, I'm just trying to get a head start on some of the mathematical topics for the 2013-2014 academic year (although I have a lot of interest in pure math).

how is this ${R}^2\to \mathbb{R}^3$ ? f is represented with three seperate expressions (why?), and after the Jacobian is taken, we get a 3X2 matrix as a result.
Comment: The Jacobian is formed by the matrix columns $[f_x | f_y]$, that is the partial $f_x(x,y)$ and $f_y(x,y)$. Does that make sense?
Comment: Like the derivative in one variable allows you to approximate a function by a degree one polynomial, the jacobian yields an affine approximation.
Answer: The Jacobian is made up of the partial in respect to $x$ and $y$ for each function as the columns of the matrix:
$$Jf{x \choose y} = \left[ \matrix {
f_x (xy) & f_y (xy) \\
f_x(\sin(x+y)) & f_y(\sin(x+y)) \\
f_x(x^2-y^2) & f_y(x^2-y^2)
}
\right]= \left[ \matrix {
y&x \\
cos(x+y)&cos(x+y) \\
2x&-2y
}
\right]
$$
Comment: Nice and concise and directly to the point! +1
Comment: $+1$ from my pocket to our friend.
Comment: @BabakS.: Nice to see you and thank you my friend!
Answer: The first two lines define your application $f$, which is here non-linear (sine function, quadratic terms ..). There is clearly a mistake in the first line: it is not $\mathbb{R}^n \to \mathbb{R}^n$, but $\mathbb{R}^2 \to \mathbb{R}^3$.
These two lines usually go together with a left bracket enclosing them, it reads: "We define the application named $f$, defined over $\mathbb{R}^2$ (vectors of two real numbers), and taking values in $\mathbb{R}^3$ (vectors of three real numbers). This application associates to any element $(x,y)\in \mathbb{R}^2$, the element of $\mathbb{R}^3$ defined by ... (the right member of the second line)".
The third part does not define $f$ per say. As Amzoti clearly explained, it is the Jacobian matrix of the corresponding application. In this case, if we denote formally:
$$
f\begin{pmatrix} x\\ y \end{pmatrix} = \begin{pmatrix} a\\ b\\ c \end{pmatrix}
$$
then the Jacobian of $f$ (provided it exists) would correspond to:
$$
Jf\begin{pmatrix} x\\ y \end{pmatrix} = \begin{pmatrix} \frac{\partial a}{\partial x} & \frac{\partial a}{\partial y}\\ \frac{\partial b}{\partial x} & \frac{\partial b}{\partial y} \\ \frac{\partial c}{\partial x} & \frac{\partial c}{\partial y}\end{pmatrix}
$$
Is it a sufficient explanation? I have to say, like the others, I don't know where to draw the line for "physical enough" :)
Comment: Yes, thanks, I think I'm understanding it a bit better. I'm still a bit confused by f having three expressions attached to it though. Does it mean to represent three vectors in $R^{2}$?
Comment: is $f\begin{pmatrix} x\\ y \end{pmatrix}$ a linear transformation? Maybe that's what I'm not understanding?
Comment: @user6777 I'm not quite sure what you mean by "three expressions attached to it"? If you are refering to $(a,b,c)$, it is simply the value taken by $f$, which has three coordinates. Let's take another example; consider a 2D plane, and a cone which generatrix is orthogonal to that plane. Now let $g$ be the function that associates to any point on the cone, it's orthogonal projection on the plane. Then $g^{-1}$ takes values in $\mathbb{R}^3$, and is defined on $\mathbb{R}^2$, just like $f$. As I said in my first sentence, $f$ is not a linear transformation.
Comment: I', sorry, I'm not understanding, I'll start another question about  this.
Comment: Why start another question when you can point to what it is you don't understand right here? We're only here to help, just say what exactly isn't clear in the explanations you received?
Comment: Ok, $$ f\pmatrix{x \\ y} = \pmatrix {xy \\ sin(x+y)\\ x^{2} - y^{2}}  $$

What does this mean? We have a function of two variables, x and y, which is equal to $$\pmatrix {xy \\ sin(x+y)\\ x^{2} - y^{2}} $$

These three expressions are equal to three separate coordinates? What does that mean? What does a graph of this function look like?

Because this is a function of two variables, the function is in 3D (I know this is a 2D function, but I don't really understand *why*).
Comment: For starters, you should think of $f$ as a function of _one variable_ in $\mathbb{R}^2$ (two coordinates). Then, you can't think about the graph of $f$ as you could visualize a surface in 3D, this would be wrong; we don't have an equation like $z = f(x,y)$ here, $f$ takes _values_ in $\mathbb{R}^3$, not $\mathbb{R}$ like $z$ does. Really, think about the cone/plane projection thing I told you, it's easy to see.
Comment: Hang on, is $f\pmatrix{x \\ y} $ a vector valued function?

If it IS, wouldn't that mean that it's in $\mathbb{R}^3$?
Comment: Yes it is, and no that's not what it means; it means that it is in $\mathbb{R}^n$. Yes, here it happens that $n=3$. But if it is your way to "prove" that you can draw $f$ in 3D, I think we might be touching at the core of your misconception.
Comment: I think I've understood it. f(x,y) = (a,b,c) is a function that will turn two values in $R^{2}$ and give a result in $R^{3}$. The result is a vector field in $R^{3}$.

So, for example $f\pmatrix{x \\ y} = \pmatrix {xy \\ sin(x+y)\\ x^{2} - y^{2} \\ 4xy^{3}}$ would be a mapping of $R^{2}$ to $R^{4}$?
Comment: Exactly :) Just a small mistake in your first sentence: it's _turn ONE value in $\mathbb{R}^2$_. (Sorry for the delay in my answer)
Comment: Many thanks, it all makes sense now! I can't believe my book never actually mentioned this, it assumed I already knew what they were.


Postfix maildir delivery failed - are my mails lost?

Question: I was facing the problem that postfix could not deliver emails to my home-directory. I have a running Ubuntu 14.04 server and due to some problem with encrypted home-drive postfix was not able to access my Maildir.
In mail.log I got the following error:
Apr  4 09:51:35 server postfix/smtpd[13658]: connect from localhost[127.0.0.1]
Apr  4 09:51:35 server postfix/smtpd[13658]: 6FE354360A18: client=localhost[127.0.0.1]
Apr  4 09:51:35 server postfix/cleanup[13661]: 6FE354360A18: message-id=<email@example.com>
Apr  4 09:51:36 server postfix/smtpd[13658]: disconnect from localhost[127.0.0.1]
Apr  4 09:51:36 server postfix/qmgr[2085]: 6FE354360A18: from=<email@example.com>, size=87170, nrcpt=1 (queue active)
Apr  4 09:51:36 server postfix/local[13664]: warning: maildir access problem for UID/GID=1000/1000: create maildir file /home/user/Maildir/tmp/1459756296.P13664.server: Permission denied
Apr  4 09:51:36 server postfix/local[13664]: warning: perhaps you need to create the maildirs in advance
Apr  4 09:51:36 server postfix/local[13664]: 6FE354360A18: to=<andreas@localhost>, relay=local, delay=0.95, delays=0.88/0.01/0/0.06, dsn=5.2.0, status=bounced (maildir delivery failed: create maildir file /home/user/Maildir/tmp/1459756296.P13664.server: Permission denied)
Apr  4 09:51:36 server postfix/cleanup[13661]: 668984360A1A: message-id=<20160404075136.668984360A1A@server>
Apr  4 09:51:36 server postfix/bounce[13665]: 6FE354360A18: sender non-delivery notification: 668984360A1A
Apr  4 09:51:36 server postfix/qmgr[2085]: 668984360A1A: from=<>, size=4544, nrcpt=1 (queue active)
Apr  4 09:51:36 server postfix/qmgr[2085]: 6FE354360A18: removed
Apr  4 09:51:36 server postfix/smtp[13666]: 668984360A1A: to=<firstname.lastname@example.com>, relay=smtp.otherserver.org:587, delay=0.54, delays=0.19/0.05/0.23/0.07, dsn=2.0.0, status=sent (250 2.0.0 Ok: queued as C979113D0138)
Apr  4 09:51:36 server postfix/qmgr[2085]: 668984360A1A: removed

I rebooted the server and hoped to find the emails which were sent in the meantime in /var/mail/xxx but there was only a zero byte file with my username.
Does this mean that the emails which I received in the meantime are lost? How can I configure that emails are saved?
EDIT: mailq shows empty mail queue.
EDIT2: added more log output
Comment: have you checked the mailqueue? Try 'mailq' in terminal.
Comment: Yes - mailq shows "Mail queue is empty"
Comment: Where are the rest of the log entries?
Comment: Added more log output
Answer: It should be in the mail queue
Send a simple email
# echo "Hello world" | swaks -4 --server smtp.example.net --from firstname.lastname@example.com --to email@example.com --h-Subject "Test message" --body -
=== Trying smtp.example.net:25...
=== Connected to smtp.example.net.
<-  220 smtp.example.net ESMTP Postfix
 -> EHLO tl-resin-node1.example.net
<-  250-smtp.example.net
<-  250-PIPELINING
<-  250-SIZE 10240000
<-  250-VRFY
<-  250-ETRN
<-  250-AUTH LOGIN PLAIN
<-  250-ENHANCEDSTATUSCODES
<-  250-8BITMIME
<-  250 DSN
 -> MAIL FROM:<email@example.com>
<-  250 2.1.0 Ok
 -> RCPT TO:<email@example.com>
<-  250 2.1.5 Ok
 -> DATA
<-  354 End data with <CR><LF>.<CR><LF>
 -> Date: Tue, 05 Apr 2016 03:45:43 -0400
 -> To: email@example.com
 -> From: email@example.com
 -> Subject: Test message
 -> X-Mailer: swaks v20130209.0 jetmore.org/john/code/swaks/
 ->
 -> Hello world
 ->
 ->
 -> .
<-  250 2.0.0 Ok: queued as 581271C1811
 -> QUIT
<-  221 2.0.0 Bye
=== Connection closed with remote host.

Check maillog on the smtp.example.net
# cat /var/log/maillog | grep 581271C1811
Apr  5 07:45:41 ci postfix/smtpd[31639]: 581271C1811: client=smtp.example.com[192.168.88.130]
Apr  5 07:45:41 ci postfix/cleanup[31642]: 581271C1811: message-id=<>
Apr  5 07:45:41 ci postfix/qmgr[31633]: 581271C1811: from=<email@example.com>, size=389, nrcpt=1 (queue active)
Apr  5 07:45:41 ci postfix/virtual[31643]: 581271C1811: to=<email@example.com>, relay=virtual, delay=0.07, delays=0.02/0.01/0/0.04, dsn=4.2.0, status=deferred (maildir delivery failed: create maildir file /email@example.com/tmp/1459842341.P31643.ci.example.net: Permission denied)

Check maillog
# postqueue -p
-Queue ID- --Size-- ----Arrival Time---- -Sender/Recipient-------
581271C1811      389 Tue Apr  5 07:45:41  email@example.com
(maildir delivery failed: create maildir file /firstname.lastname@example.com/tmp/1459842341.P31643.ci.example.net: Permission denied)
                                         firstname.lastname@example.com

-- 1 Kbytes in 1 Request.

Fix the permissions
# ls -la
total 16
drwxr-xr-x  4 alex alex 4096 Mar 18 14:32 .
drwxrwxr-x. 3 root mail 4096 Apr  2 03:35 ..
drwx------  3 virtual virtual 4096 Mar 15 09:18 example.com
drwx------  3 root    virtual 4096 Mar 18 14:32 example.net

# chown virtual:virtual example.net

Flush the mail queue and check maillog again
# postqueue -f

Apr  5 07:49:01 ci postfix/anvil[31640]: statistics: max cache size 1 at Apr  5 07:45:41
Apr  5 07:49:29 ci postfix/qmgr[31633]: 581271C1811: from=<email@example.com>, size=389, nrcpt=1 (queue active)
Apr  5 07:49:29 ci postfix/virtual[31894]: 581271C1811: to=<firstname.lastname@example.com>, relay=virtual, delay=228, delays=228/0.02/0/0.06, dsn=2.0.0, status=sent (delivered to maildir)
Apr  5 07:49:29 ci postfix/qmgr[31633]: 581271C1811: removed

Comment: I am using a different SMTP for relaying so this example cannot be applied here - sorry.
Comment: It doesn't matter. By default these emails should be in the mail queue. Because error code was 4xx - it means that error is temporary and mail server should keep such emails in mail queue.
Comment: But "postqueue -f" did not deliver mails :-(
Answer: TLDR: By default behaviour of postfix, your email was bounced (i.e. your sender will get non-delivery message) and postfix won't keep the email even in the queue.

Based on both logs from mercury and ALex_hha, I can concluded that there are different behavior when mail was delivered by virtual daemon (ALex_hha case) or local daemon (mercury case). When virtual daemon can't deliver email because of permission issue, it will use defer the email (soft bounce), so the email stays in queue.
Apr 5 07:45:41 ci postfix/virtual[31643]: 581271C1811: to=<email@example.com>, relay=virtual, delay=0.07, delays=0.02/0.01/0/0.04, dsn=4.2.0, status=deferred (maildir delivery failed: create maildir file /firstname.lastname@example.com/tmp/1459842341.P31643.ci.example.net: Permission denied)

In the other case, local daemon will bounced the email (hard bounce) so the email doesn't stay in queue.
Apr 4 09:51:36 server postfix/local[13664]: 6FE354360A18: to=<andreas@localhost>, relay=local, delay=0.95, delays=0.88/0.01/0/0.06, dsn=5.2.0, status=bounced (maildir delivery failed: create maildir file /home/user/Maildir/tmp/1459756296.P13664.server: Permission denied)

This behavior can also viewed when you peek in source of virtual/maildir.c and local/maildir.c in line with dsb_simple function.
local/maildir.c
    dsb_simple(why, mbox_dsn(errno, "5.2.0"),
           "create maildir file %s: %m", tmpfile);

virtual/maildir.c
    dsb_simple(why, mbox_dsn(errno, "4.2.0"),
           "create maildir file %s: %m", tmpfile);

How can I prevent hard bounce in this case?
AFAIK based on above source code, this behavior was unconfigurable via postfix main.cf. But try to set soft_bounce = yes, but beware of the global effect when you enable this feature.


How to integrate $\int \sqrt{x^2+a^2}dx$

Question: $a$ is a parameter. I have no idea where to start
Comment: relevant: http://en.wikipedia.org/wiki/Trigonometric_substitution
Comment: Do you know a trigonometric function that you might multiply by $a$ and substitute for $x$?  The idea is to get a square under the square root.
Answer: I will give you a proof of how they can get the formula above. As a heads up, it is quite difficult and long, so most people use the formula usually written in the back of the text, but I was able to prove it so here goes.
The idea is to, of course, do trig-substitution.
Since $$\sqrt{a^2+x^2} $$ suggests that $x=a\tan(\theta)$ would be a good one because the expression simplifies to $$a\sec(\theta)$$
We can also observe that $dx$ will become $\sec^2(\theta)d\theta$.
Therefore$$\int \sqrt{a^2+x^2}dx = a^2\int \sec^3(\theta)d\theta$$
Now there are two big things that we are going to do.
One is to do integration by parts to simplify this expression so that it looks a little better, and later we need to be able to integrate $\int \sec(\theta)d\theta$.
So the first step is this. It is well known and natural to let $u=\sec(\theta)$ and $dv=\sec^2(\theta)d\theta$ because the latter integrates to simply, $\tan(\theta)$.
Letting $A = \int \sec^3(\theta)d\theta$,you will get the following $$A = \sec(\theta)\tan(\theta) - \int{\sec(\theta)\tan^2(\theta)d\theta}$$
$$=\sec(\theta)\tan(\theta) - \int{\sec(\theta)d\theta - \int\sec^3(\theta)d\theta}$$
therefore,$$2A = \sec(\theta)\tan(\theta)-\int \sec(\theta)d\theta$$
Dividing both sides give you $$A = 1/2[\sec(\theta)\tan(\theta)-\int \sec(\theta)d\theta]$$
I hope you see now why all we need to be able to do is to integrate $\sec(\theta)$.
The chance that you know how is rather high because you are solving this particular problem, but let's just go through it for the hell of it.
This is a very common trick in integration using trig, but remember the fact that $\sec^2(\theta)$ and $\sec(\theta)\tan(\theta)$ are derivatives of $\tan(\theta)$ and $\sec(\theta)$, respectively. So this is what we do.
$$\int \sec(\theta)d\theta = \int {{\sec(\theta)(\sec(\theta)+\tan(\theta))} \over {\sec(\theta)+\tan(\theta)}} d\theta$$
Letting $w = \sec(\theta)+\tan(\theta)$,
$$= \int {dw \over w} = \ln|w|$$
So, long story short,
$$\int \sqrt{a^2+x^2}dx = a^2/2[\sec(\theta)\tan(\theta) - \ln|\sec(\theta)+\tan(\theta)|]$$
$$= \dfrac{1}{2} \left({x\sqrt{a^2+x^2}} + {{a^2\ln \left|{x+\sqrt{a^2+x^2} \over a}\right|}}\right) + C$$
Comment: We can also observe that $d\theta$ will become $\sec^2(\theta)d\theta$.  <--- This should be $\mathrm{d}x$ becoming $a \sec^2 \theta \mathrm{d}\theta$
Answer: Since $\sinh^2(x)+1
=\cosh^2(x)
$,
this suggests
letting $x = a \sinh(y)$.
$dx = a \cosh(y)$
and $x^2+a^2 = a^2(\sinh^2(y)+1)
= a^2 \cosh^2(y)$,
so $a \cosh(y) = \sqrt{x^2+a^2}$.
$\begin{align}
\int{\sqrt{x^2+a^2}}dx
&=\int a^2 \cosh^2(y) dy\\
&= a^2 \int (e^{2y}+2+e^{-2y})\,dy/4\\
&= (a^2/4) (e^{2y}/2 + 2y - e^{-2y}/2)\\
&=(a^2/4)(\sinh(2y)+2y)\\
&=(a^2/4)(2\sinh(y)\cosh(y)+2y)\\
&=(a^2/2)((x/a) (1/a)\sqrt{x^2+a^2}+\sinh^{-1}(x/a))\\
&=(x \sqrt{x^2+a^2})/2+(a^2/2)\sinh^{-1}(x/a)
\end{align}
$
I'll leave it at this - you can find $\sinh^{-1}$.
Answer: Integrating by parts
$$I=\int \sqrt{x^2+a^2}\cdot1dx$$
$$=\sqrt{x^2+a^2}\int dx-\int\left( \frac{d \sqrt{x^2+a^2}}{dx}\int dx\right)dx$$
$$=x\sqrt{x^2+a^2}-\int\frac{x^2 dx}{\sqrt{x^2+a^2}}$$
Now, $$\int\frac{x^2 dx}{\sqrt{x^2+a^2}}=\frac{x^2+a^2-a^2}{\sqrt{x^2+a^2}}dx=I-a^2\int\frac{dx}{\sqrt{x^2+a^2}}$$
Put $x=a\tan \theta $ in
$$\int\frac{dx}{\sqrt{x^2+a^2}}$$
Answer: Substitue $x=a \sinh t$, so $t=\text{arcsinh} \frac{x}{a} $ $dx=a\cosh t dt$ and $x^2+a^2=a^2(1+\sinh^2t)$. Your integral becomes $$\int|a|\cosh t a\cosh t dt=a|a|\int \cosh^2tdt.$$
Use the identity $\cosh^2t=\frac{1}{2}(1+\cosh2t)$ to get $$\frac{a|a|}{2} \int(1+\cosh2t)dt=\frac{a|a|}{2} \left(t+\frac{\sinh 2t}{2} \right)+C $$
If we go back to $x$, we get: $$\frac{a|a|}{2} \left(\text{arcsinh }\frac{x}{a}+\frac{\sinh2 \text{arcsinh } \frac{x}{a} }{2} \right) .$$
This can be further simplified using the identities $\sinh 2t=2\sinh t \cosh t$ and $\cosh \text{arcsinh t}=\sqrt{1+t^2}$
Answer: Another standard method: Applying the Euler substitution $$\sqrt{x^2 + a^2} = -x + t$$ transforms the integral to
$$\frac{1}{8} \int \frac{(t^2 + a^2)^2 \,dt}{t^3},$$
and the substitution $t^2 = u, 2 t \,dt = du$ transforms the integral to
$$\frac{1}{8} \int \frac{(u + a^2)^2 \,du}{u^2}
= \frac{1}{8} \int \left(1 + \frac{2 a}{u} + \frac{a^2}{u^2}\right) \,du
= \frac{u}{8} + \frac{a^2}{4} \log u - \frac{a^4}{8 u} + C.$$
Now, back-substitute $u = t^2 = (\sqrt{x^2 + a^2} - a)^2$.


Como verificar se um arquivo existe por numeragem

Question: Queria poder fazer um cadastro de usuarios em sequencia numeral crescente (1,2,3,4)
mas eu queria saber algum jeito de saber se o usuario ja existe e tentar com um numero maior
Exemplo:
Tente criar um arquivo 1 - Eduardo.txt
se ja existir um arquivo de codigo 1
tentar com 2 e assim em diante
Tentei fazer isso e não funcionou
import os.path

def verifica(x):
    certeza = os.path.exists("C:\Users\danie\Desktop\saida\{}.txt".format(x))
    if certeza == True:
        x += 1
enc = 'UTF-8'
decisao = str(input("Quer criar um novo usuario?"))
if decisao == 'sim':
    x = 0
    verifica(x)
    arquivo = open(r'C:\Users\danie\Desktop\saida\{}.txt'.format(x), 'w', encoding=enc)
    arquivo.write('Teste de texto')
    arquivo.close()

Answer: O problema no seu código é que você não repete a verificação para achar um arquivo X que não exista no diretório. Dentro da sua função verifica() por exemplo, você incrementa a variável x caso o arquivo já exista, porém você não chama novamente a função.
Para resolver o problema você pode criar um bloco de repetição ou então utilizar da recursividade para repetir a verificação quantas vezes forem necessárias. Veja abaixo alguns exemplos:
Utilizando recursividade:
import os

def verifica(arquivo, x = 0):

    if os.path.exists(arquivo.format(x)):
        return verifica( arquivo, x + 1 )
    else:
        # Ao invés de retornar só o número, ele já retorna
        # o nome de arquivo formatado.
        return arquivo.format(x)

enc = 'UTF-8'

# A função input já retorna por padrão uma string, então não é necessário
# converter o dado obtido para str().
decisao = input("Quer criar um novo usuario? ").lower()

# Verifica se a decisão começa com a letra "s".
if decisao.startswith('s'):

    nome_de_arquivo = verifica(r"C:\Users\danie\Desktop\saida\{}.txt")

    arquivo = open(nome_de_arquivo, 'w', encoding = enc)
    arquivo.write('Teste de texto')
    arquivo.close()

Utilizando bloco de repetição:
# Como estamos utilizando um bloco de repetição, não é necessário criar a função verifica().
if decisao.startswith('s'):

    x = 0
    nome_de_arquivo = r"C:\Users\danie\Desktop\saida\{}.txt"

    while True:
        if os.path.exists(nome_de_arquivo.format(x)):
            x += 1
        else:
            break

    arquivo = open(nome_de_arquivo.format(x), 'w', encoding=enc)
    arquivo.write('Teste de texto')
    arquivo.close()

Se você quiser também limitar a quantidade de X arquivos no seu diretório, basta substituir o bloco while por um for..range(limite) dessa forma:
if decisao.startswith('s'):

    limite = 1000  # Limite de 1000 arquivos
    nome_de_arquivo = r"C:\Users\danie\Desktop\saida\{}.txt"
    x_arquivo = None

    for x in range(limite)
        if not os.path.exists(nome_de_arquivo.format(x)):
            x_arquivo = x

    if x_arquivo:
        arquivo = open(nome_de_arquivo.format(x), 'w', encoding=enc)
        arquivo.write('Teste de texto')
        arquivo.close()
    else:
        print("ULTRAPASSOU O LIMITE!")


How do I theme a block created with the Views module?

Question: I'm Newbie user in drupal, i need to custom design theme block created for views module.
Example HTML:

title1

content1

title2

content2

Comment: is your Drupal site already using a custom theme to which you can just add additional css to theme your block or are you asking how to add a custom theme in the first place?
Comment: i custom my theme using region/blocks. i start design theme/block with default views. i.e: `Front page` this print any content type with `promoted in front page` in index. this worked perfectly, now i need to custom this theme block for `my example html`. NOTE: i set (`Database overriding code`) field in views. now how to custom this block theme?
Answer: I'm not perfectly sure what you are asking...
If you want to theme a view then you can add a css class name under the advanced drop-down, or add a  css class to any field.
Or are you looking to adjust how a block appears using views?
Comment: i.e: i need add custom theme for show last article in jquery news ticker.
Answer: There are two options to choose from.

Use the native template suggestion system that Drupal provides for you. Check template information when editing your view.
Use a contributed module like Semantic Views which lets you customize the output of your view thoroughly from the back-end configuration.


wondering use of computed property

Question: before.
class DrawingView: UIView {

    var arcCenter = CGPoint(x: frame.midX, y: frame.midY)  // error
}

after.
class DrawingView: UIView {

    var arcCenter: CGPoint {
        return CGPoint(x: frame.midX, y: frame.midY)
    }
}

I know why that error occur, but I can't understand why the second codes are not makes error.
Answer: The first form is not a computed property.
It is a stored property with a default value.
it uses self which causes the error because at the moment the default value is going to be assigned the instance is not guaranteed to be instantiated.
An alternative to a computed property – which is computed only at the moment it's called – is a lazy instantiated property.
lazy var arcCenter: CGPoint = CGPoint(x: self.frame.midX, y: self.frame.midY)

Unlike the stored property the default value is assigned when the property is accessed the first time.
Comment: no need to use a closure. `lazy var arcCenter: CGPoint = CGPoint(x: self.frame.midX, y: self.frame.midY)`

wondering use of computed property