Expo - Invalid hook call dentro de componentes de função

Question: Estava aprendendo Expo, e precisava criar uma lista dinâmica de contadores.
Na minha tela eu tenho um botão + que adiciona outros quadrados, e cada um desses quadrados tem um contador dentro deles, pelo o que entendi dos tutoriais, é que cada um desses componentes precisa de um Hook para que possam mudar o seu estado.
Cada componente separado funciona, mas quando eu utilizo os dois hooks na mesma página, eu tenho um problema Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons
Já li a documentação do expo e do react native sobre os Hooks e não consegui sair do lugar.
Eu utilizo o projeto padrão gerado pelo expo, com apenas alterações na HomeScreen.js. Segue o código:
HomeScreen.js
import React, { useState } from 'react';
import { StyleSheet, Text, TouchableOpacity, View, FlatList } from 'react-native';
import { ScrollView } from 'react-native-gesture-handler';

import { Square } from '../components/Square';

export default function HomeScreen(props){

  const [participantes, setParticipantes] = useState([]);

  const adicionarParticipante = () => {
     setParticipantes([...participantes, Square(props)]);
  }

  return (
    <View style={styles.container}>
    <ScrollView style={styles.container} contentContainerStyle={styles.contentContainer}>

    <View style={styles.getStartedContainer}>
    <TouchableOpacity onPress={adicionarParticipante} style={styles.button}>
    <Text style={styles.buttonPlacar}>+</Text>
    </TouchableOpacity>
    <FlatList data={participantes} showsVerticalScrollIndicator = {false}
    renderItem= { ({ item }) => item }/>
    </View>

    </ScrollView>
    </View>
    );
}

HomeScreen.navigationOptions = {
  header: null,
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
  },
  contentContainer: {
    paddingTop: 30,
  },
  getStartedContainer: {
    alignItems: 'center',
    marginHorizontal: 50,
  },
  button: {
    backgroundColor: "#ffc107",
    padding: 20,
    height: 100,
    width: 100,
    justifyContent: 'center',
    borderRadius: 5,
  },
  buttonPlacar: {
    textAlign: 'center',
    fontSize: 20,
    color: 'white',
  }
});

Square.js
import React, { useState } from 'react';
import PropTypes from 'prop-types';
import { Text, View, TouchableOpacity} from 'react-native';

export function Square(props) {

    const [count, setcount] = useState(0);

    const sqStyle = {
        backgroundColor: "#007bff",
        padding: 20,
        height: 100,
        width: 100,
        marginTop: 10,
        justifyContent: 'center',
        borderRadius: 5,
    };

    const tStyle = {
        textAlign: 'center',
        fontSize: 20,
        color: 'white',
    }

    return  <TouchableOpacity onPress={() => setcount(count+1)}>
                <View style={sqStyle}>
                    <Text style={tStyle}>{count}</Text>
                </View>
            </TouchableOpacity>;
}

Square.propTypes = {
  count: PropTypes.int
};

Desde já, agradeço o tempo de todos.
Answer: Eu não tinha entendido o real conceito dos hooks no react-native, o meu código faltando apenas alinhamento final, ficou assim:
homescreen.js
    import React, { useState } from 'react';
    import { StyleSheet, Text, TouchableOpacity, View, FlatList } from 'react-native';
    import { ScrollView } from 'react-native-gesture-handler';
import { Square } from '../components/Square';

export default function HomeScreen(){

  const [participantes, setParticipantes] = useState([])

  const gera_cor = () => {
    var hexadecimais = '0123456789ABCDEF';
    var cor = '#';

    let aux = 0;
    // Pega um número aleatório no array acima
    for (var i = 0; i < 6; i++ ) {
    //E concatena à variável cor
        cor += hexadecimais[Math.floor(Math.random() * 16)];
    }
    return cor;
  }

  const adicionarPessoa = () => {
    const novo = {
      count : 1,
      cor   : gera_cor()
    }
    setParticipantes([...participantes, novo]);
  };

  const adicionarPedaco = (i) => {
    var p = participantes;
    p[i].count = p[i].count+1;
    setParticipantes([...p]);
  }

  return (
    <View style={styles.container}>
      <View style={styles.container} contentContainerStyle={styles.contentContainer}>
        <View style={styles.getStartedContainer}>
          <TouchableOpacity onPress={adicionarPessoa} style={styles.button}>
            <Text style={styles.buttonPlacar}>+</Text>
          </TouchableOpacity>
          <FlatList
            style={styles.list}
            data={participantes}
            keyExtractor={(item, index) => index.toString()}
            numColumns = {3}
            renderItem= { ({ item, index }) => Square(item, adicionarPedaco, index)} />
        </View>
      </View>
    </View>
  );
}

HomeScreen.navigationOptions = {
  header: null,
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignContent: 'stretch',
    backgroundColor: '#fff',
  },
  contentContainer: {
    paddingTop: 30,
  },
  getStartedContainer: {
    alignItems: 'center',
    marginHorizontal: 1,
  },
  button: {
    backgroundColor: "#ffc107",
    padding: 20,
    height: 100,
    width: 100,
    justifyContent: 'center',
    borderRadius: 5,
  },
  buttonPlacar: {
    textAlign: 'center',
    fontSize: 20,
    color: 'white',
  },
  list :{
    width: '100%'
  }
});

Square.js
import React, { useState } from 'react';
import PropTypes from 'prop-types';
import { Text, View, TouchableOpacity} from 'react-native';

export function Square(pessoa, adiciona, i) {

    const sqStyle = {
        backgroundColor: pessoa.cor,
        padding: 20,
        height: 100,
        width: 100,
        marginTop: 5,
        marginBottom: 5,
        marginLeft: 5,
        marginRight: 5,
        justifyContent: 'center',
        borderRadius: 5,
    };

    const tStyle = {
        textAlign: 'center',
        fontSize: 20,
        backgroundColor: 'white',
        borderColor: 'grey',
        borderRadius : 10,
        borderWidth: 1,
        color: 'black',
    }

    return  <TouchableOpacity onPress={() => adiciona(i)}>
                <View style={sqStyle}>
                    <Text style={tStyle}>{pessoa.count}</Text>
                </View>
            </TouchableOpacity>;
}


Acessando dados armazenados no cookies?

Question: No login, armazeno informações do usuário logado em um cookie (nome, senha, etc...)
Como faço para acessar esse cookie e resgatar informações dele?
Por exemplo, quero que na barra superior fique aparecendo o nome do usuario logado, pela minha lógica teria que buscar o nome que ja está armazenado no arquivo e joga-lo em uma @Viewbag determinada no controller, está correta essa forma de pensar? E qual a maneira mais estética e correta de se fazer essa ação?
Segue o exemplo de quando faz a autenticação:
[HttpPost]
    public ActionResult Login(Login form, string retornarurl)
    {
        var usr = db.Usuario.FirstOrDefault(u => u.nome == form.nome);

        if (usr == null || !usr.CheckPassword(form.passwordHash))
            ModelState.AddModelError("nome", "Usuário ou senha estão incorretos ou não existe");

        if (!ModelState.IsValid)
            return View(form);

        FormsAuthentication.SetAuthCookie(usr.nome, true);

        return RedirectToAction("Index", "Admin" );

    }

Comment: Você está usando algum provedor de autenticação como o Membership ou ainda o Identity?
Comment: Creio que não. Eu mesmo criei um repositório para fazer a autenticação, que posteriormente será feito através de um formulário personalizado.
Comment: Pode colocar uma parte do código dele na sua pergunta?
Comment: Na vdd ele esta no controller mesmo...
Answer: Você usa a maneira antiga, que era usada no Web Forms. Pode ser feito desta forma:
HttpCookie authCookie = Request.Cookies[FormsAuthentication.FormsCookieName];
FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(authCookie.Value);

string cookiePath = ticket.CookiePath;
DateTime expiration = ticket.Expiration;
bool expired = ticket.Expired;
bool isPersistent = ticket.IsPersistent;
DateTime issueDate = ticket.IssueDate;
string name = ticket.Name;
string userData = ticket.UserData;
string version = ticket.Version;

Recomendo você dar uma olhada no ASP.NET Identity, que realiza um gerenciamento mais interessante do usuário e os ciclos de registro, login e registro de logins externos.
Comment: Nunca precisei reimplementar porque uso o ASP.NET Identity atualmente (antes usava o ASP.NET Membership), mas de repente posso fazer isso como um exercício. [Recomendo este artigo para você](http://www.codeproject.com/Tips/574576/How-to-implement-a-custom-IPrincipal-in-ASP-NET-MV).
Comment: Entendi, eu andei dando uma estudada no Identity, porem por ele ser CodeFirst e criar tabelas diferentes, fica mais complicado pra mim por já ser um projeto existente e ter um banco de dados já criado. Vou dar uma olha no artigo recomendado.
Comment: Hm... interessante. Mas nesse modo ai, eu teria que criar um repositório ?
Comment: Por que você precisa criar um repositório? [Reimplemente `Principal`](https://msdn.microsoft.com/pt-br/library/system.directoryservices.accountmanagement.principal(v=vs.110).aspx). Fica muito mais elegante.
Comment: E você teria algum exemplo pratico de como seria a autenticação nesse modo?

Acessando dados armazenados no cookies?


How to find match number from comma separated numbers using sql query?

Question: I have a SQL Server table with comma separated number as datatype varchar(200) like this:

Now I am passing parameter like comma separated number to my query for get a output like below:
Id      MatchNumber

1       286
1       133
1       338
3       152
8       161
8       133
10      144
10      139
10      177

I have tried this SQL Query:
DECLARE @Ids varchar(50);
SET @Ids = '286,133,338,215,152,378,161,144,139,177';
select * from TblMMGameCard where Id IN (@Ids);

I want a output like above table. How can I do?
Answer: SQL Server does not support macro substitution.  One option is to parse the search string and then test for the hit via a JOIN
Example
DECLARE @Ids varchar(50) = '286,530,338,215';

Select A.ID
      ,MatchNumber = B.RetVal
 From  TblMMGameCard  A
 Join (
        Select RetVal = ltrim(rtrim(B.i.value('(./text())[1]', 'varchar(50)')))
        From  (values  (cast('<x>' + replace(@IDs,',','</x><x>')+'</x>' as xml)))A(x)
        Cross Apply x.nodes('x') AS B(i)
      ) B  on charindex(','+RetVal+',',','+[cardNumbers]+',')>0

Comment: @Abhilash.J.A Always happy to help
Comment: Thank @John Cappelletti


How can I combine a product attribute with a subset of another one in Drupal Commerce?

Question: Assume I have 2 product attributes (using the Drupal Commerce module):

Background color (white, black, green, blue, yellow).
Surface (glossy or matte).

And assume that surface "glossy" can be only selected in combination with background color "white" or "black".
How should I configure this conbination of attributes?
Answer: Required steps
Step 1
Create 2 taxonomies:

Background color, with terms white, black, green, blue, yellow
Surface, with terms glossy or matte.

Step 2
For each prod type, add field "Background color", which is a field "term referenace" (and refer to the Background color taxonomy).
Attentionn: make sure to check the option "attribute field settings" (enables this field to function as an attribute field on the add-to-cart-form).
Then add a similar term reference field "Surface".
Step 3
Use store / products / add product to add individual products, with a specific SKU, and for which you pick the right values for each of both taxonomies.
So for "Matte surface", you should create 5 individual products (one for each background color). But for "Glossy surface", you only create 2 individual products (1 with a white background color, and 1 with a black background color)
Video tutorials
For a more detailed video tutorial of the steps described above, refer to Drupal Commerce - Pruduct Attributes (16:13). Before doing so, you may want to first view these related videos:

Drupal Commerce - Pruduct Types (9:11).
Drupal Commerce - Pruduct Displays (11:36).

By only reviewing/studying these 3 videos (total time = about 37 mins), you'll have a very good foundation to get started with the fundamentals of Drupal Commerce.
Commerce Backoffice
Managing products (and orders) can be confusing. However, the Commerce Backoffice module helps with that. For more details about that module, refer to my answer to the question about
Correct way for Attributes in Commerce
Comment: Merci (again), aka "Thank you". Just so you know: nobody is perfect, and my name is not "nobody" ... Anyway, let e go find your "next question" to work on ... may I?
Comment: @Pierre.Vriens Always wanted to tell you. I admire your willingness to help :) Thank you for all your answers!
Comment: @AjitS ... euh ... not sure what to reply to your comment, something like "merci for the kudos"? Or am I still missing "something"?
Comment: Perfect as always...
Yeah, I already watched these views a couple of times, but you know, something some tiny bit of explanation is required to get it 100%.
Thank you!
Comment: @Pierre.Vriens hah! That should do it.


Prove the regular surface with 2 geodesics from p to q, and negative curvature cannot be simply connected.

Question: What ideas/formulas are required to solve this? Exercise: If a and b are two geodesics from point p to q, how do you prove that M is not simply connected? M is a regular surface in R3 and has negative Gaussian curvature K. Points p & q are two distinct points on surface M.
I know surface is simply connected if any simple closed curve can be shrunk to a point continuously in the set. So a sphere is simply connected, and a donut is not simply connected. And I know that since the curvature is negative, and since K=det(Sp)=w*z, so eigenvalues w and z have opposite signs. I also have the formula K=(eg-f^2)/(EG-F^2) based on the 1st fundamental forms and derivatives for solving for E,F,G,e,f,g. Not sure what if anything that is used to solve. And the only geodesic equations I can think of off hand are
d/dt(E u' + F v')=1/2[E_u u'^2 + 2F_u u'v' +G_u v'^2 ], d/dt(Fu'+Gv')=1/2[E_v u'^2 +2F_u u'v' +G_v v'^2 ], and geodesic curvature c=, and Gauss-Bonnet integrals but not sure how that can be applied. If they can be applied, please let me know. Maybe the fact that the normal of any point on the geodesic arc also is on the same normal vector to the surface M at that point helps? What ideas and equations are required to solve the exercise?
Comment: You are calling $a$ and $b$ geodesics, but you are also calling $a$ and $b$ principal curvatures. It would be good to use different notations for these things.
Comment: thanks @treble, i fixed it to say w and z for principal curvatures. maybe it is not even necessary for me to mention them at all since Will seems to have solved the exercise without them
Answer: EDIT, Thursday evening: a good illustration for the bit about negative curvature is the inner circle in the "hole" in a torus of revolution, which is a "closed geodesic" and cannot be contracted continuously to a point. The closed geodesic occurs in the (inner) part of the torus where the Gauss curvature is negative, while the outer portion has positive curvature. Meanwhile, no compact surface in $\mathbb R^3$ can have negative Gauss curvature everywhere, for which Neal gave a simple answer in comments. It is, of course, possible to have noncompact surfaces with negative curvature, such as the catenoid of revolution. However, for any such surface of revolution with negative curvature, the absolute value of the curvature goes to $0$ as we get far from the central axis. So Mariano asked whether there are any infinite surfaces in $\mathbb R^3$ with Gauss curvature that is bounded away from $0,$ and the answer is no, not for a $C^2$ surface. Link to the question MARIANO QUESTION.
ORIGINAL: This is Gauss-Bonnet for polygons on an oriented surface. The familiar case should be this: the area of a geodesic triangle on the unit sphere is $\alpha + \beta + \gamma - \pi,$ where $\alpha, \beta, \gamma$ are the angles at the vertices of the triangle. Next, we define the external angles $\theta_1 = \pi - \alpha, \; \theta_2 = \pi - \beta, \; \theta_3 = \pi - \gamma, $ according to Figure 4-25 of do Carmo:
==========

==========
The unit sphere has curvature $K=1,$ so the integral of $K$ over a polygon is just its area. Furthermore, the boundary arcs are geodesics, with geodesic curvature $k_g = 0.$ So the statement about this area is equivalent to
$$  \int \int_T \; K d \sigma \; + \theta_1 + \theta_2 + \theta_3 = 2 \pi.  $$
Compare this with Gauss-Bonnet, formula (1) here:
==========

===========
You may or may not be told this: in the simply connected hyperbolic plane of constant curvature $-1,$ the area of a triangle is $ \pi - (\alpha + \beta + \gamma),$ where $\alpha, \beta, \gamma$ are the angles at the vertices of the triangle. However, because $K = -1,$ this is once again the same as
$$  \int \int_T \; K d \sigma \; + \theta_1 + \theta_2 + \theta_3 = 2 \pi.  $$
For your exercise, you are asked about an (oriented) "diangle" $D,$ with angles $0 \leq \alpha, \beta \leq \pi.$ If an angle is equal to $0,$ that is what the author calls a "cusp," see Figure 4-26, the right half. We take the external angles as before, and get
$$  \int \int_D \; K d \sigma \; + \theta_1 + \theta_2  = 2 \pi,  $$
$$  \int \int_D \; K d \sigma \; + (\pi - \alpha) + (\pi - \beta)  = 2 \pi,  $$
$$  \int \int_D \; K d \sigma \; =  \alpha + \beta.  $$
What does this mean? We have $K < 0.$ The right hand side of the equation is nonnegative. If there is any interior to the "diangle," the integral is strictly negative. The only legal possibility is that the two geodesics are identical, both vertices are cusps, the two geodesic arcs are exactly the same, once out, once back.
Otherwise, and here is where the topology comes in, the two geodesic arcs do not bound a piece of surface as I was assuming, and the loop cannot be deformed homotopically to a single point, thus the surface is not simply connected.
Well, I hope that works for you. There is quite a bit of detail that could be added about orientation. Furthermore, I do not think a closed surface in $\mathbb R^3$ can have negative Gauss curvature. I know that a closed surface in $\mathbb R^3$ cannot have constant negative Gauss curvature.
Comment: I asked on MO for Ian to answer :-P
Comment: @MarianoSuárez-Alvarez, I do not see how, but my dissertation was in minimal surfaces, which is a special case and may be too restrictive. I'm thinking Ian Agol would know. If there is an example, it is awfully damn crinkly.
Comment: A closed surface in $\mathbb{R}^3$ can have negative Gauss curvature at some points (e.g. on the line $s = 0$ of the embedding $(\cos{s}\cos{t},\cos{s}\sin{t},\sin{s})$ of $T^2\hookrightarrow\mathbb{R}^3$).  A closed surface must have at least one point of positive Gauss curvature (enclose the surface in a sphere of minimal radius, which must be tangent to the surface at some point; the surface has positive curvature at that point).
Comment: @Neal, works for me. Right, the version I recall is the farthest point from the origin.
Comment: But I'd guess, for some reason, that a closed surface (closed in that it is a closed subset of $R^3$) can be of negative curcature. I dunno!
Comment: @MarianoSuárez-Alvarez, yes, a standard example i s the (non-compact) catenoid, $x^2 + y^2 = \cosh^2 z,$ which is a minimal surface. However, the absolute value of the curvature still goes to $0$ as one goes far away from the origin. http://en.wikipedia.org/wiki/Catenoid
Comment: Ah! I knew it was easy :-) Can we de it bounded away from zero too?
Comment: @MarianoSuárez-Alvarez My first thought was a pseudosphere, but I guess it isn't closed since you have to remove the singularity at the equator.
Comment: (For reference: http://mathoverflow.net/questions/111101/closed-surfaces-in-mathbb-r3-with-negative-curvature-bounded-away-from-zero)
Comment: @Neal , Will --- there is a possible contradiction - my professor said that in the hyperbolic plane, α+β+γ < π since

0=α+β+γ -π -∫K dA, with negative Gaussian curvature (K=-1), so then α+β+γ = π+s, for some positive value s. In that case, the ∫KdA+θ1+θ2+θ3 would equal π-(α+β+γ)+(π-α)+(π-β)+(π-γ)=4π-2(α+β+γ), which does not simplify to your 2π.
Comment: @user47735, your equation after the word "since" comes out to $ \int K dA = \alpha + \beta + \gamma - \pi,  $ so the quantity after "would equal" should be $$  \alpha + \beta + \gamma - \pi + (\pi - \alpha) + (\pi - \beta) + (\pi - \gamma)   $$
Comment: thank you @Will, i have to remember better to multiply by the -1!!.. thanks again for your clear comprehensive explanations..
Comment: @WillJagy A suggestion - perhaps edit into the end of your answer a link to Mariano's question at MO?
Comment: @Neal, I did that. My habit is to put edits in the beginning if I can. Few read past that without a good reason.


Foreign Key referencing Primary key in the same table

Question: I have a table with two columns as the primary key. These two columns are also a foreign key that references the same table:
(This table was created some time ago by someone who has since left the company)
CREATE TABLE [dbo].[tblItemLink](
    [ItemListID] [int] NOT NULL,
    [ItemID] [int] NOT NULL,
 CONSTRAINT [PK_tblItemList] PRIMARY KEY CLUSTERED
(
    [ItemListID] ASC,
    [ItemID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
ALTER TABLE [dbo].[tblItemLink]  WITH CHECK ADD  CONSTRAINT [FK_tblItemLink_tblItemLink] FOREIGN KEY([ItemListID], [ItemID])
REFERENCES [dbo].[tblItemLink] ([ItemListID], [ItemID])
GO

ALTER TABLE [dbo].[tblItemLink] CHECK CONSTRAINT [FK_tblItemLink_tblItemLink]
GO

In practice, ItemID refers to tblItem.ItemID, and ItemListID is found nowhere else in the DB but there is a corresponding enum in the application.
Is there any reason for the primary key to also be a foreign key referencing itself (ie. some undocumented performance improvement), or is it just a mistake?
Answer: I know of no reason why this, specifically, could provide a benefit - so I'm going to go with option 2 - a mistake.
Of course, if it was different columns in the same table, that would make sense, and as @Jignesh.Raj points out, that would form some kind of hierarchy.
You can even sometimes end up with multiple hierarchies within the same table with such multi-column references:
CREATE TABLE T (
   GroupID int not null,
   ItemID int not null,
   ParentItemID int null,
   constraint PK_T PRIMARY KEY (GroupID,ItemID),
   constraint FK_T_Parent FOREIGN KEY (GroupID,ParentItemID) references T (GroupID,ItemID)
)

In the above, the GroupID column always references itself.
But as I say, with your current table, where both columns only reference themselves, it makes no sense.
Comment: Just to add to the reasons that this is most likely a mistake: when a new constraint is added using SSMS the default configuration is for the "primary key" and the "foreign key" to both refer to the primary key of the current table.
Answer: Thats how you would create a hierarchy, and could also ensure you can't have a child with an invalid parent.
See also Should you make a self-referencing table column a foreign key?
Comment: Yes, it would be a hierarchy if there was a foreign key referencing a primary key in the same table, but in this case, the primary key IS the foreign key - so each row really refers to itself.


How do I download a file in python without using the urllib, urllib2 and urllib3 modules? I neither can use request module

Question: I have a problem because I need to download a file using python but I cannot use the libraries urllib, urllib2 and urllib3 neither request
If someone can help me I thanks him a lot
Comment: you can use the `wget` package. Why can't you use the other ones?
Comment: I'm doing a job but with this libraries I can do this
Comment: I use python 3.6 and wget doesn't work
Comment: you can use https://docs.python.org/3/library/socket.html
Answer: you can use subprocess module and curl command
import subprocess
result = subprocess.run(['curl', 'https://www.google.com'], stdout=subprocess.PIPE)
# do with result

Answer: You need to do wget in terminal to get the package. Why can't you use these!? (I can't ugh comment)
Try using requests to get the data of the file and write it a path if you can't use urllib's package.
To download files with requests use this example from here
def download_file(url):
    local_filename = url.split('/')[-1]
    # NOTE the stream=True parameter
    r = requests.get(url, stream=True)
    with open(local_filename, 'wb') as f:
        for chunk in r.iter_content(chunk_size=1024):
            if chunk: # filter out keep-alive new chunks
                f.write(chunk)
                #f.flush() commented by recommendation from J.F.Sebastian
    return local_filename

Here's the aiohttp example for async functions:
import aiohttp

async def download_file(url):
    async with aiohttp.ClientSession() as session:
        async with session.get(url) as resp:
            with open(filename, 'wb') as fd:
                while True:
                    chunk = await resp.content.read(chunk_size)
                    if not chunk:
                        break
                    fd.write(chunk)

url = "URL"
await download_file(url)

I recommend using aiohttp if you don't can't use requests.
Comment: if you can't comment, don't. provide a full answer when you can
Comment: Will do rn, I literally had to transfer devices,
Comment: OP states: "I cannot use the libraries urllib, urllib2 and urllib3 neither request"
Answer: Thanks to all, finally I could solve my problem
I give you the solution that I used
import * from socket
    s = socket(AF_INET, SOCK_STREAM)
    s.connect((url, port))
    file_mess="GET /" + step2[:5] + " HTTP/1.1\r\n\r\n"
    s.send((file_mess).encode('utf-8'))
    print(s.recv(1024).decode('utf-8'))
    print(s.recv(1024).decode('utf-8'))

I used the second print for obtaining all the data, because with the first I only get a 200 OK


Proving Convergence and Absolute Convergence of Power Series

Question: How do you prove the following claim?
If a power series $\sum_{n=0}^{\infty} a_n (x-a)^n$ converges at some point $b ≠ a$, then this power series converges absolutely at every point closer to $a$ than $b$ is.
Here's what I tried so far. Does this proof make sense? What would you change to hone it further?
Proof:
Suppose that $\sum_{n=0}^{\infty} a_n (x-a)^n$ converges at $b ≠ a$.
Then, the $ \lim\limits_{x\to \infty} |a_n (b-a)^n|=0$
For $ɛ=1>0$, $∃N$ such that, if $n>N$, then $-ɛ<|a_n (b-a)^n|<ɛ$
That is to say, $|a_n (b-a)^n|<1 (*)$
Take any $x$, such that $|x-a| < |b-a| $ Implicitly, $\frac{| (x-a)|}{|(b-a)|}<1 (**)$
For $n>N$, notice that $|a_n (x-a)^n| = |a_n (x-a)^n| × \frac{|a_n (b-a)^n|}{|a_n (b-a)^n|}$
Rearranging, we get:
$|a_n (b-a)^n| × \frac{| (x-a)^n|}{|(b-a)^n|} < 1× \frac{| (x-a)^n|}{|(b-a)^n|} $  because of $(*)$
$\sum_{n=0}^{\infty} |a_n (x-a)^n| =\sum_{n=0}^{N} |a_n (x-a)^n| +\sum_{n=N+1}^{\infty} |a_n (x-a)^n|
< \sum_{n=0}^{N} |a_n (x-a)^n| +\sum_{n=N+1}^{\infty} \frac{| (x-a)^n|}{|(b-a)^n|}$
But, $\sum_{n=N+1}^{\infty} \frac{| (x-a)^n|}{|(b-a)^n|}$ is a geometric series, with ratio $<1$ (from **)
Therefore, $\sum_{n=N+1}^{\infty} \frac{| (x-a)^n|}{|(b-a)^n|}$ converges.
Hence, $\sum_{n=0}^{\infty} |a_n (x-a)^n| $ also converges (by the comparison test).
Consequently, by definition, $\sum_{n=0}^{\infty} a_n (x-a)^n$ converges absolutely.
Answer: There's something a bit strange about your proof.  Look at the line after "Rearranging, we get:"..  That inequality you say is because of (*) but if you cancel $\frac{|(x-a)^n|}{|(b-a)^n|}$ it's simply equivalent to $|a_n(b-a)^n|<1$.  So you don't need to go to all that work to get to this inequality.
Also, how do you get $\sum_{n=N+1}^{\infty} |a_n (x-a)^n|
< \sum_{n=N+1}^{\infty} \frac{| (x-a)^n|}{|(b-a)^n|}$
I don't think that follows from what you showed pervious to that line.
Comment: Well, remember that the whole re-arrangement comes from re-writing the term $|a_n (x-a)^n|$ Hence, showing that $|a_n (b-a)^n| × \frac{| (x-a)^n|}{|(b-a)^n|}$ is less than $\frac{| (x-a)^n|}{|(b-a)^n|}$ is equivalent to showing that  $|a_n (x-a)^n|$ is less than $\frac{| (x-a)^n|}{|(b-a)^n|}$

Does this answer your concern regarding the line inequality?


Bypassing Linux cluster gateway - going directly to node from your desktop

Question: From my desktop I usually executing this command to go to linux cluster:
I have this in my .bash_profile
alias gothere="ssh -i ~/.ssh/id_rsa_macmini_mine firstname.lastname@example.com"

Then call it with this to go to the cluster:
dhcp190-206:~ pdubois-macmini$ gothere
Last login: Tue Mar 25 15:41:03 2014 from dhcp190-206.mycompany-u.ac.jp
[pdubois@thelinuxcluster ~]$

Then once I reach the gateway of that cluster I do this again to go to the node:
alias blogin="bsub -Is -q intj bash -l"

Call it this way to go to the node:
[pdubois@thelinuxcluster ~]$ blogin
Job <221825> is submitted to queue <intj>.
<<Waiting for dispatch ...>>
<<Starting on clusternode61>>
[pdubois@clusternode61 ~]$

My question is, is there a way I can simplify the above two steps into one step?
So that I can go directly to the cluster node from my desktop.
Comment: This question appears to be off-topic because it is not related to programming.
Comment: I'm not sure but `ssh -t -i ~/.ssh/id_rsa_macmini_mine email@example.com bsub -Is -q intj bash -l` may work.
Comment: Not it doesn't work. It gave me `bash: bsub: command not found`.
Comment: maybe your PATH or alias is not set, to read ~/.bashrc when ssh -t, read http://superuser.com/questions/207200/how-can-i-set-environment-variables-for-a-remote-rsync-process/207262 or http://apple.stackexchange.com/questions/23633/source-profile-and-bashrc-on-ssh-login-without-tty
Answer: The ssh is a login to a user node (gateway as you called it) on the cluster, the bsub with -I is an interactive job submission request which puts you on the cluster by running an interactive job on a compute node.
So no, you can't combine these two. The interactive job is started from the user node.
Perhaps more importantly, once you login to the "gateway", you are effectively "on" the cluster already for programming and debugging purposes. Access to the nodes should be reserved for job submission and interactive debugging jobs. Once you run the bsub command, your account is being charged for time on the machine.
Answer: alias gothere="ssh -i ~/.ssh/id_rsa_macmini_mine firstname.lastname@example.com \"bsub -Is -q intj bash -l\""

Gotta escape the double quotes!


how to do i fire this code on click of a button in javascript

Question: i'm new to JavaScript and i want this code to start with a click of a button and also in every click it should start a new different timer from zero. anyone here to help!

// add a count-down timer
 function startTimer(duration, display) {
  var timer = duration, minutes, seconds;
  setInterval(function () {
      minutes = parseInt(timer / 60, 10);
      seconds = parseInt(timer % 60, 10);

      minutes = minutes < 10 ? "0" + minutes : minutes;
      seconds = seconds < 10 ? "0" + seconds : seconds;

      display.textContent = minutes + ":" + seconds;

      if (--timer < 0) {
          timer = duration;
      }
  }, 1000);
}
var butt = window.document.getElementById('button');
window.onload = function () { //i tried using ' butt.onclick' but this did not work
  var fiftenMinutes = 60 * 15,
      display = document.querySelector('#time');
  startTimer(fiftenMinutes, display);
};

Answer: If you want a different timer each time you click, you need to add an element dynamically to the DOM to hold it.

// add a count-down timer
function startTimer(duration, display) {
  var timer = duration,
    minutes, seconds;
  setInterval(function() {
    minutes = parseInt(timer / 60, 10);
    seconds = parseInt(timer % 60, 10);

    minutes = minutes < 10 ? "0" + minutes : minutes;
    seconds = seconds < 10 ? "0" + seconds : seconds;

    display.textContent = minutes + ":" + seconds;

    if (--timer < 0) {
      timer = duration;
    }
  }, 1000);
}
window.onload = function() { //i tried using ' butt.onclick' but this did not work
  var fiftenMinutes = 60 * 15,
    display = document.querySelector('#time');
  startTimer(fiftenMinutes, display);
};
var butt = window.document.getElementById('button');
butt.addEventListener("click", function() {
  var new_h3 = document.createElement("h3");
  document.body.appendChild(new_h3);
  startTimer(60*15, new_h3);
})

<button id="button">Start timer</button>
Comment: Thank you so much, it really helped. this is what i was looking for, appreciate it.
Answer: Just add event listener to the button and clear already set timer, if it has been set. Run the following snippet.

function startTimer(duration, display) {
        var timer = duration, minutes, seconds;

        return setInterval(function () {
            minutes = parseInt(timer / 60, 10);
            seconds = parseInt(timer % 60, 10);

            minutes = minutes < 10 ? "0" + minutes : minutes;
            seconds = seconds < 10 ? "0" + seconds : seconds;

            display.textContent = minutes + ":" + seconds + ' Click to Restart';

            if (--timer < 0) {
                timer = duration;
            }
        }, 1000);
    }

    var timerID = null;

    // replace 'time' if the h3 element isn't the button.
    document.getElementById( 'time' ).addEventListener( 'click', function() {
        if ( timerID ) {
            clearInterval( timerID );
        }

        var fiftenMinutes = 60 * 15,
            display = document.querySelector('#time');

        timerID = startTimer(fiftenMinutes, display);
    })

Click To Start Timer

Answer: First you need to add a button with an id of "button" to make your code work:
<button id="button">Button Text</button>

Next, each time you click the button, you want the previous interval to be cancelled, otherwise you'll end up with more and more intervals changing the content of the h3:
var intervalId

...

if (intervalId) clearInterval(intervalId)

intervalId = setInterval(function() {})

This leaves us with the following:

var intervalId;

// add a count-down timer
 function startTimer(duration, display) {
 if (intervalId) clearInterval(intervalId);
  var timer = duration, minutes, seconds;
  intervalId = setInterval(function () {
      minutes = parseInt(timer / 60, 10);
      seconds = parseInt(timer % 60, 10);

      minutes = minutes < 10 ? "0" + minutes : minutes;
      seconds = seconds < 10 ? "0" + seconds : seconds;

      display.textContent = minutes + ":" + seconds;

      if (--timer < 0) {
          timer = duration;
      }
  }, 1000);
}
var butt = window.document.getElementById('button');
butt.onclick = function () { //i tried using ' butt.onclick' but this did not work
  var fiftenMinutes = 60 * 15,
      display = document.querySelector('#time');
  startTimer(fiftenMinutes, display);
};

<button id="button">Button Text</button>


I need to find $v$ so that $v\times v'$ equals $A(n \times n)$

Question: Be $A_{n\times n}$  symmetric.
I need to find $v_{m\times n}$ so that $v^T \times v = A$ for an algorithm in Julia.
Can anyone help me (either w/ Julia or linear algebra)?
Comment: Certainly not every $n\times n$ matrix that is symmetric is of rank $1$. Or are you assuming $A$ is of rank $1$?
Comment: Sorry, I wrote it wrong. Just fixed my question
Comment: To write $A = BB^t$, I think you want to assume $A$ is positive semidefinite, right?
Comment: For better undestanding, check this question: https://math.stackexchange.com/questions/2681367/building-matrix-so-that-the-inner-product-of-columns-results-in-an-element-of-an
Sorry about all the mess
Answer: If your matrix rank is more that 1 this is impossible and for rank 1 we have $$v=\begin{bmatrix}v_1\\v_2\\.\\.\\.\\v_n\end{bmatrix}\to v\times v^T=\begin{bmatrix}v_1.v&v_2.v&.&.&.&v_n.v\end{bmatrix}$$which is obviously of rank 1
Comment: Sorry, I wrote it wrong. Just fixed my question


Autoplay and Playlist not working on multiple youtube API iframe players

Question: Problem do not appear on chrome /!\
I'm using the iframe player providing by the youtube API. I've created two players and hide one of them if a button isn't pressed or held.
Furthermore I use a playlist for each of them and the option autoplay off playerVars is enable.
My problem is, when the second video in the playlist comes to the player2 it is not loading automatically and the video isn't the next one in the playlist wished.
An example is running at this address -> http://dev.alphas-projects.com
Wait ~1 min so that the second video appears and press or hold spacebar to switch to the second player. You will see the issue.
NB: I'm pretty sure that the problem resides to the youtube player API code because if we disable the 'display: none' of the second video player the issue appears.
Here is my code.

Javascript
var tag = document.createElement('script');

tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

var player1;
var player2;

function onYouTubeIframeAPIReady() {
    player1 = new YT.Player('player1', {
        videoId: 'Ja53GAN1lpA',
        playerVars: {
            'autoplay': 1,
            'loop': 1,
            'showinfo': 0,
            'controls': 0,
            'rel': 0,
            'playlist': 'WCBDPLga_tI,8RYpwS1vxKk'
        },
        events: {
            'onReady': onPlayerReady1
        }
    })
    player2 = new YT.Player('player2', {
        videoId: 'B7C1eiP8qVU',
        playerVars: {
            'autoplay': 1,
            'loop': 1,
            'showinfo': 0,
            'controls': 0,
            'rel': 0,
            'playlist': 'ou0E2tJrU_Q,yD1eVgZrD6U'
        },
        events: {
            'onReady': onPlayerReady2
        }
    })
}

function onPlayerReady1(event) {
    event.target.playVideo();
    player1.setVolume(30);
}

function onPlayerReady2(event) {
    event.target.playVideo();
    player2.setVolume(30);
    player2.mute();
}

Comment: I used your code above ( but removed the style="display: none"). It seems to work fine. So your js in your page might be to blame. Also, videoID "yD1eVgZrD6U" is blocked and not viewable.
Comment: https://www.youtube.com/watch?v=yD1eVgZrD6U Works for me... Did you wait the second video in the playlist bc the first one is showing properly. It only happens when the second comes. Anyway, I will try to test the code with a clean project to see if my js is the real problem.
Comment: yD1eVgZrD6U is blocked from playing outside of YouTube. Test it on a stand alone embedded player to see.
Comment: Yep it was just an option I unchecked yesterday on youtube
Answer: Ok, I think I found your problem.
First switch your id="media-2" div with your id="media-1". This is just for practicality.  Then remove the style="display: none;" from your id="media-2" div.
Then in the player code when "state" is equal to "playing", set
        $('#media-2').hide()

iFrame player needs to initialise fully before you can hide it.
EDIT:
OK, as it seemed to be a bit buggy, I looked at it again.
This is all I changed ( using main page, not demo script ) and it seems to work ok on IE11 and Chrome. Well it is for me.

Comment: Edit: Only worked for chrome :/   Question still alive.
Comment: @AlphA-Fr . I had another look. EDIT is above to test out.
Comment: All what you changed is the allowfullscreen value set to 0 ? Does not work atm :-)  Only for chrome. Tested on IE and firefox.
Comment: Sorry dude, but I never touched that at all. If you actually take a look at your original code and this, you will see that I have switched players and removed the disply:none completely. It is your code, I only made it work.
Comment: If you are happy, then ok.
Comment: I'm still working on it. I tried to remove and reset all my js code step by step to see what is wrong but it seems firefox kept my videos in his cache.. Could you send me a jsfiddle of what you tested so far ?
Comment: As I needed to see the site fully working, I downloaded it as best as was possible to me. here is a temporary link to what I have. This message and link will be deleted in a few days as will no longer be required ( I hope ), and then we can put the fix on the main answer.   http://www.myonlinelocation.com/AlphA_test/   I only modified what is in my answer above. The rest is as you had it originaly
Comment: Ok, I've the same code as you except for the css part. It should be a css conflict with some -moz -o etc.. values. I will go in the way for tomorrow. Thanks for your time! (tested on dev.alphas-projects/test.php)


Como personalizar a linha de uma ListVIew de acordo com o valor no ArrayAdapter

Question: Supondo que eu tenha um objeto chamado Item, e que nele possua as propriedade texto, id e validação, no caso, texto é uma string, id é um inteiro, e validação é um valor booleano.
class Item
{
    private int id;
    private String texto;
    private boolean validacao;
    //get and set
}

E que este objeto sirva como parâmetro para um ArrayAdapter
ArrayAdapter<Item> itemAdapter = new ArrayAdapter<Item(this,R.layout.layoutItem,view)
//no momento os parametros do construtor do ArrayAdapter não são levados em conta

Porém preciso ter a possibilidade de personalizar alguns elementos de cada linha do  ListView de acordo com o items.
Cada linha terá:
1- uma imagem, que será escolhida de acordo com o valor do atributo validação do Item da linha atual.
2- um EditText, que receberá e manipulará o valor da propriedade texto do Item da linha atual.
4- uma imagem com o desenho de uma lixeira que ao ser clicada exclui o item atual.
5- O id  do item deve ser alterado conforme a posição na array.
Como posso personalizar as linhas da view desta maneira?, devo criar uma classe que estende a classe ArrayAdapter ?, tem alguns exemplos ?, ou uma alternativa, ou padrão, melhor para esta necessidade ?
Comment: porém ainda resta uma duvida ainda , os eventos de um elemento dentro de uma lista iram responder normalmente como por exemplo , on click listener
Comment: Isso mesmo Leonardo, você terá que extender a classe `ArrayAdapter`. Segue um exemplo de uma pergunta que respondi, pode te ajudar a começar: http://pt.stackoverflow.com/questions/26229/como-mudar-a-cor-do-texto-de-um-listview/26231#26231. No caso você pode alterar elementos de uma linha, adicionar `Listeners`.
Comment: seria essa uma maneira certa ? http://www.ezzylearning.com/tutorial/customizing-android-listview-items-with-custom-arrayadapter
Comment: Exatamente, meu exemplo era só para pintar a cor do texto, mas é possível fazer muito mais coisa. Sim, eles vão responder normalmente, bastando adicionar o listener. Para isso sugiro (não é obrigatório) usar esse modo que fiz na resposta a essa pergunta: http://pt.stackoverflow.com/questions/32771/problemas-ao-enviar-dados-de-um-listview-para-outra-activity/32885#32885. Usando o `Adapter` como o `OnClickListener` você evita de criar tantos `Listeners` quantos forem os itens do seu `ListView`, melhor para o GC.
Answer: Vou mostrar um exemplo usando com Adapter customizado usando TextView e um Button, resultando na imagem abaixo e que deseja inserir 50 elementos por exemplo:

Classe MainActitvy que tem base um ListView:
public class MainActivity extends ListActivity {

    private NumeroAdapter adapter;
    private final int numero = 50;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        adapter = new NumeroAdapter(this, numero);

        setListAdapter(adapter);

    }
}

Classe NumeroAdapter que utliza o BaseAdapter customizado responsável por mostrar na tela:
public class NumeroAdapter extends BaseAdapter implements View.OnClickListener {

    private List<String> array = new ArrayList<String>();
    private LayoutInflater inflater;
    private Context context;

    public NumeroAdapter(Context context, int tamanho) {
        this.context = context;
        inflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        for (int i = 0; i < tamanho; i++) {
            array.add(String.valueOf(i + 1));
        }
    }

    @Override
    public int getCount() {

        return array.size();
    }

    @Override
    public Object getItem(int position) {

        return array.get(position);
    }

    @Override
    public long getItemId(int position) {

        return 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        View view = convertView;
        ViewHolder holder = null;
        if (view == null) {
            view = inflater.inflate(R.layout.activity_main, null);
            holder = new ViewHolder();
            holder.texto = (TextView) view.findViewById(R.id.texto);
            holder.info = (Button) view.findViewById(R.id.info);
            holder.info.setOnClickListener(this);
            view.setTag(holder);
        } else {
            holder = (ViewHolder) view.getTag();
        }

        holder.texto.setText(array.get(position));
        holder.info.setTag(array.get(position));
        return view;

    }

    @Override
    public void onClick(View v) {

        Toast.makeText(context, (String) v.getTag(), Toast.LENGTH_SHORT).show();

    }

}

Interface ViewHolder responsável por gerenciar as views que são mostradas na tela:
public class ViewHolder {
    public TextView texto;
    public Button info;
}

Layout utilizado pelo adapter:

<TextView
    android:id="@+id/texto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignBaseline="@+id/info"
    android:layout_marginLeft="10dp"
    android:layout_toLeftOf="@+id/info" />

<Button
    android:id="@+id/info"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentRight="true"
    android:text="@string/info" />

Esse exemplo serve de apoio para que você seja capaz de solucionar seu problema.


AOL is rejecting emails from my client's website, how can I troubleshoot?

Question: I am a bit of an email noob.  My website is trying to send email from a contact form using the PHP mail function.  This works fine when sending it to my Gmail account, but AOL rejects it.  I have set up an RDNS record for the client ( fallsroadsunoco.com )
Macintosh:~ TAmoyal$ nslookup 126.96.36.199
Server:     192.168.1.1
Address:    192.168.1.1#53

Non-authoritative answer:
220.127.116.11.in-addr.arpa    name = fallsroadsunoco.com.

Authoritative answers can be found from:

I have even set up an MX record (although I think this is irrelevant because that should only be needed for receiving email).  I did some poking around and randomly saw this on my server...but 2 things to note with this output:

i changed the receiving email address to email@example.com to keep it anonymous
bandop.com was my RDNS host name at the time this email was sent.  i changed it to the client's host name fallsroadsunoco.com to see if that would help...and it didn't

sudo more var/spool/postfix/deferred/0/0F902E4F7E
trace_flags=0SO^Lwww-data@comR^Lwww-data@comMN!Received: by bandop.com (Postfix)N5124671id 0F902E4F7E; Sat,ime=1246714223Alog_message_origin=localA
 4 Jul 2009 13:30:23 +0000 (UTC)N+Date: Sat,  4 Jul 2009 13:30:23 +0000 (UTC)N.From: MAILER-DAEMON@com (Mail Delivery System)N,Subject: Undelivered Mail Returned to SenderNTo: www-data@
comNAuto-Submitted: auto-repliedNMIME-Version: 1.0N<Content-Type: multipart/report; report-type=delivery-status;N,  boundary="B68D0E4F7D.1246714223/bandop.com"NContent-Transfer-Enco
ding: 8bitN2Message-Id: <firstname.lastname@example.com>NN$This is a MIME-encapsulated message.NN"--B68D0E4F7D.1246714223/bandop.comN!Content-Description: NotificationN*Content-Ty
pe: text/plain; charset=us-asciiNN+This is the mail system at host bandop.com.NN;I'm sorry to have to inform you that your message could notN<be delivered to one or more recipients. It'
s attached below.NN7For further assistance, please send mail to postmaster.NN9If you do so, please include this problem report. You canN8delete your own text from the attached returned
message.NN"                   The mail systemNNO<firstname.lastname@example.com>: host mailin-02.mx.aol.com[22.214.171.124] said: 501 SYNTAXND    ERROR IN PARAMETERS OR ARGUMENTS (in reply to MAIL F
ROM command)NN"--B68D0E4F7D.1246714223/bandop.comN$Content-Description: Delivery reportN%Content-Type: message/delivery-statusNNReporting-MTA: dns; bandop.comNX-Postfix-Queue-ID: B68D0E
Status: 5.0.0N%Remote-MTA: dns; mailin-02.mx.aol.comNBDiagnostic-Code: smtp; 501 SYNTAX ERRO(UTC)NN,Final-Recipient: rfc822; firstname.lastname@example.com: failedN
 IN PARAMETERS OR ARGUMENTSNN"--B68D0E4F7D.1246714223/bandop.comN(Content-Description: Undelivered MessageNContent-Type: message/rfc822NContent-Transfer-Encoding: 8bitNN1Received: by ba
ndop.com (Postfix, from userid 33)N5    id B68D0E4F7D; Sat,  4 Jul 2009 13:30:22 +0000 (UTC)NTo: firstname.lastname@example.com!Subject: Your contact form works!N$Date: Sat, 4 Jul 2009 09:30:22 -
X-Priority: 3N?X-Mailer: PHPMailer (phpmailer.sourceforge.net) [version 2.0.4]NMIME-Version: 1.0NContent-Transfer-Enallsroadsunoco.com>N
oding: 8bitN)Content-Type: text/plain; charset="UTF-8"NNName: Tony AmoyalN
firstname.lastname@example.com:NCan you see this?NNN$--B68D0E4F7D.1246714223/bandop.com--XA

Any idea why only AOL would be rejecting my messages? Also note that they are not making it to the SPAM folder.
Answer: A packet capture showing the SMTP conversation would be useful here, probably more so than the contents of your mail log.  Also be advised that AOL's mail servers are pretty psycho about who they receive mail from.   Check out their FAQ at http://postmaster.aol.com/guidelines/standards.html:

AOL's servers will not accept
connections from unsecured systems.
These include open relays, open
proxies, open routers, or any other
system that has been determined to be
available for unauthorized use.
Ensure all forms on your web server
are secure. If you use formmail
scripts, ensure they cannot be used
to send spam.
AOL's mail servers will not accept connections from systems that use
dynamically assigned or residential
IP addresses.
Organizations may not hard code AOL's
MX records into their configuration
files.
All e-mail must be compliant with RFCs 2821 and 2822.
AOL's mail servers will reject connections from any IP address that
does not have reverse DNS (a PTR
record). All e-mail servers
connecting to AOL's mail servers must
have valid and meaningful (not
dynamic-looking) reverse DNS records.
For example:  Meaningful RDNS:
mail.domain.com Generic RDNS:
184.108.40.206.domain.isp.com
AOL may reject connections from
servers whose recipient lists
consistently generate a higher than
10% bounce failure rate. (i.e. over
10% of a sender's mailing list is
destined for users that do not exist
on our system)
AOL may reject connections from senders who are unable to accept at
least 90% of the bounce-return
messages (mailer-daemon failure/error
messages) destined for their
systems.
Complaints submitted by AOL members
may be used as a basis for refusing
connections from any mail server.
Persons sending bulk mail from the
whitelisted IP Address must
immediately remove any e-mail address
which causes a permanent failure
"bounce" message to be generated with
one of the following error codes:
550 "AOL username" Is Not Accepting
Mail From This Sender  550 Mailbox
not found 550 We would love to have
gotten this email to
email@example.com. But, your
recipient never logged onto their
free AIM Mail account. Please contact
them and let them know that they're
missing out on all the super features
offered by AIM Mail. And by the way,
they're also missing out on your
email.
AOL, LLC does not authorize the use
of its proprietary computers and
computer network to accept, transmit
or distribute unsolicited bulk
e-mail. AOL's unsolicited bulk e-mail
policy can be found at our website.

I've bolded the points you may want to look into.  I've had trouble with sending mail to them in the past, which turned out to be a misconfigured PTR record for the server that was sending the mail.  I think you're OK there, but you should check the others out.
Comment: This is an excellent response, RainyRat.  I will add that even after you have done all these things and even if you setup a "feedback" address so AOl can report spam to you, they sometimes seem to reject email for no good reason.  After checking all the above points, you may find you have to wait a few days before AOL starts accepting your email again.
Comment: +1 as I was just about to point this user to AOL's technical standards for email delivery:

http://postmaster.aol.com/guidelines/standards.html
Comment: Thanks for the great response, Rainy Rat.  I will look into these items today. My RDNS seems cool because it is a domain name, and I am using a static IP address.  Does the last bold item mean that I need to have an incoming mail server set up to receive bounced emails?
Comment: I think so, yes.  I guess it's to stop spam sent with fake "from" addresses.
Answer: I imagine that you are not correctly setting the FROM header on the PHP side.  It would help to post the PHP code that was used to send the email.
Comment: I am pretty sure the code just uses the php mail function which should work.  I also imagine that if the problem is in the code, google would not accept the emails.  Do you still think I should investigate this?
Comment: The parameters that you pass the to the PHP mail function can be tricky, and different service providers can be picky about what kinds of mail and what format of headers they accept.
Answer: If you're doing email, you want to sign up for a feedback loop with AOL, and then to be on the AOL whitelist (which requires your server to be well behaved).  It's worth it in the long run.
Post a capture of the SMTP conversation (anonymized as you like) so we can help more.
Comment: `tcpdump -s 0 -i eth0 -w foo.pcap tcp port 25` would be a good place to start.  That will make a file `foo.pcap` that you can read with wireshark or tcpdump later.
Comment: Looks like the feedback loop and AOL whitelist are for people sending bulk mail.  This question is for emails sent via a contact form.  I don't think the whitelist should be necessary.
Comment: can you tell me how to capture an smtp conversation? i am using an ubuntu vps from slicehost
Answer: According to the error message the FROM syntax isn't correct.
Answer: I've had the same problem but mostly it was with receiving e-mail notifications from forums in which I had placed a post. It wasn't until about two weeks ago when I opened up a new website that I found this problem to be much more serious.
My new website e-mail address was being rejected by AOL and would not show up in the spam folders. Of course my Yahoo and Gmail accounts would accept the e-mails. So I contacted AOL and received help from an upper-level technician.
After running some quick tests, he said that he knew the problem was that AOL was identifying my website and the forums as some kind of spam prone websites. He seriously suggested that I contact each and every one of these website's hosts and asked them to logon to postmaster.aol.com and then send AOL their IP connection address.
I told him that I doubted any of these large companies would do anything that he has suggested but I tried anyway. I contacted my websites host and relayed the information to him with instructions on how to go about sending AOL their IP connection address.
To no surprise, my website host replied with suggestions of what I can do because they had no intention of sending AOL anything. I had told the technician that his solution, (actually, AOL's solution), was unrealistic and that AOL should allow the paid user to adjust his or her own spam filters.
That is pretty much where it ends so now I have my new websites e-mail set up so that anyone who sends e-mail to that website will have it redirected to my Gmail account which will then redirected to AOL.
This is just making my life a little more complicated and I can see my future with AOL coming to a quick end shortly.


Is there a term for metric equivalence analogous to "enharmonic" for pitch equivalence?

Question: Key signatures, chords, scales, and phrases are said to be enharmonically equivalent if they contain the same pitches, but are notated differently.
Is there an analogous term to express that time signatures, meters, or rhythmic phrases are metrically equivalent when notated differently?
Comment: I like the suggestions in the answers, but I think there's actually a reason why, historically, there isn't a term for this but there *is* a term for the harmonic equivalent. Essentially, I think Western music theory focuses far more on harmony than on rhythm or melody. Additionally, there *is* a term for one common instance of this: *hemiolas* are temporary "rhythmic modulations" in which the rhythm of the piece temporarily matches that of a different key signature than the one it's actually written in.
Comment: I didn't mean to suggest that "hemiola" works in the general case, and you're right that "isorhythm" has an established musical meaning that isn't quite what you're looking for, but as far as I can tell, "isometer" does not.
Comment: Interesting; I hadn't found that.
Answer: For some pieces of music from medieval days (or English descriptions of some Indian ragas), the term is isorhythmic. This may be commonly used in a more narrow sense than is being asked about. It applies to a rhythm pattern that is applied to a given tone sequence and repeated throughout a piece. If the lengths of tone sequence (called the color) and the rhythmic pattern (called the tala) differ, the entire pattern repeats after the LCM of their lengths. (I think the tala or rhythmic pattern is also called the hand.
https://en.wikipedia.org/wiki/Isorhythm
I think that isorhythmic would be a good term and not introduce confusion.
Answer: If you have durations with different rhythmic meaning in parallel (either due to polyrhythmic notation or because of using duplets or quadruplets), I'd lean towards calling them commensurate.
Answer: I don't know of a term as universally used as "enharmonic" (I've never heard "enmetric," for instance), but with the use of algebraic group structures in music theory over the past few decades, the term "isomorphism" is becoming much more common.
Thus you may choose to say that the two key signatures, or two rhythmic profiles, etc. are "isomorphic."
Comment: "Isomorphism" can apply to essentially any "class" of thing, though--for instance "enharmonic" could be defined as *harmonically* isomorphic. So specifying "rhythmic isomorphism" would be good, I think. Perhaps "isorhythmic" or (to use an existing word) "isometric" would be even better.
Comment: Isomorphism in mathematics just means something which can be "stretched" or "squeezed" to become the other thing.  I'm not sure that's really the concept the OP wants to imply :-) .


Demand Function

Question: A consumer has the utility function over goods X and Y, $U(X; Y) = X^{1/3}\cdot Y^{1/2}$
Let the price of good x be given by $P_x$, let the price of good $y$ be given by $P_y$, and let income be given by $I$.
(a) Derive the consumer's generalized demand function for good $X$.  This is simply the demand equation.  $X$ is a function of Price and Income ($P_x$ and $I$).
Can someone help me get in the right direction for this?
Comment: You may want to include what you have tried in order to improve your chances of getting an answer
Comment: What is the demand equation?
Comment: I am looking for the demand function. I do not have the demand equation. Set up the Lagrangean expression, L = X1/3Y1/2 + λ[I - PxX - PyY]:
Comment: I don't know what is meant by the demand equation.  This is a mathematics site.  The question would be better asked on https://economics.stackexchange.com/
Answer: You can solve the problem by using the method of lagrange multiplier as you have already written in the comment.
$$\mathcal L=X^{1/3}\cdot Y^{1/2}+\lambda (I-P_x\cdot X-P_y\cdot Y)$$
Then you have to calculate the partial derivatives w.r.t $X,Y$ and $\lambda$.
$\frac{\partial \mathcal L}{\partial X}=\frac13\cdot X^{-2/3}\cdot Y^{1/2}-P_X\lambda=0 \Rightarrow\frac13\cdot X^{-2/3}\cdot Y^{1/2}=P_x\lambda \quad (1)$
$\frac{\partial \mathcal L}{\partial Y}=\frac12\cdot X^{1/3}\cdot Y^{-1/2}-P_y\lambda=0 \Rightarrow\frac12\cdot X^{1/3}\cdot Y^{-1/2}=P_y\lambda \quad (2)$
$\frac{\partial \mathcal L}{\partial \lambda}=I-P_x\cdot X-P_y\cdot Y=0 \quad (3)$
Dividing (1) by (2)
$\frac23\frac{Y}{X}=\frac{P_x}{P_y}$
Solving for $P_y\cdot Y$
$P_y\cdot Y=\frac32P_x\cdot X$. The expression can be insert in (3).
$I-P_x\cdot X-\frac32P_x\cdot X=0$
What is left is to solve the equation for $X$. Can you finish?
Comment: I will try! So solving for X will create the demand function?
Comment: Yes, that´s right. I hope you can comprehend the steps before.
Answer: You need to solve the following:
$$\max_{X,Y}X^{1/3}Y^{1/2}$$
subject to $I \geq  P_x X + P_y Y.$
Set up Lagrangian
$$L = X^{1/3}Y^{1/2} + \lambda (I -(P_x X + P_y Y)).$$
FOC's yield:
\begin{eqnarray*}
\frac{1}{3}\left(\frac{Y^{1/2}}{X^{2/3}}\right) - \lambda P_x &=&0,\\
\frac{1}{2}\left(\frac{X^{1/3}}{Y^{1/2}}\right) - \lambda P_y &=&0,\\
I - (P_x X + P_y Y) &=&0.
\end{eqnarray*}
I will leave the algebra for you.  You should get the following answer:
$$X= \frac{2I}{5 P_x}.$$
Comment: Your production function is wrong. Also pay attention on the signs $L = X^{1/3}Y^{2/3} + \lambda (I -(P_x X \color{red}+ P_y Y)).$
Comment: @callculus Thanks, edited
Comment: Now there is no contradiction between our answers anymore.

Demand Function


How to play repeating notes quickly in the left hand on the piano

Question: I've been working on Fur Elise, and I came to one section repeating a single note staccato in the bass.

How do I play this? I've tried playing it normally, but I can't sustain it for more than a measure or so. Is there some other way to play this, or must I just keep practicing?
Comment: Reading just this passage, I keep slipping into Brahms' Violin Concerto!
Answer: Well, it's like a slow tremolo so you definitely want to alternate fingers. Thumb - Middle - Thumb - Middle is a good general-purpose tremolo fingering. To do this easily, you should pull your thumb a little under the palm, almost touching the middle finger. The wrist should be straight but not rigid. You descend upon the keyboard, leading with the thumb. Then a very slight rise of the forearm should allow you to pivot forward to reach with the middle finger. The wrist may move, but only slightly.
If there are shifting accents, you almost always want to play the strong beat with your "power fingers": thumb or index, and then just roll through the other fingers until you need to start over. Use the index for the accent if you want to use the thumb for backbeat.
Comment: My teacher suggested alternating three fingers (3, 2, 1, 3, 2, 1…).  The hand will then move slightly «deeper» into the keyboard and then back.  No tilting is required, the palm is always parallel to the keyboard.
Comment: @Mischa, a three-finger pattern is probably easier on your wrists for the reasons you describe. But here, I think a two-finger pattern is a better fit for the 3/8 time signature.
Comment: So should I be moving my hand around or angling it?


How come i keep getting a memory leak when i run this function in my C program?

Question: So basically im writing code for a linkedList, but I keep getting a memoryLeak as a result of this code here. Could anyone help me find why, and also explain to me what im doing wrong?
struct Node* deleteNode(int data, struct Node* head){

    struct Node* current = head;
    struct Node* previous = NULL;

    if(head == NULL){
        return NULL;
    }
    while(current->data != data){
            if(current->next == NULL){
                return NULL;
            }else{
                previous = current;
                current = current->next;
            }
    }
    if(current == head){
        struct Node* temp = head;
        head = head->next;
        free(temp);
    }else
    {
        previous->next = current->next;
    }
    current = NULL;
    return head;
}

Answer: You never call free() on the deleted list node when its not the first element of your linked list.
Comment: @JorgeUrena You need to call `free()` on the node even in the case when `current != head`. Similar to what you did under the `if (current == head)` block.
Comment: Im sorry, im fairly new to all this. What do you mean? If im deleting a node shouldnt i free that nodes address?
Answer: You are getting a memory leak because you are not calling free in the case where current != temp. All you are doing in the else portion is simply assigning previous->next = current->next without deleting the current node.
You have already found the node you wish to delete using your while loop, so add free(current) after previous->next = current->next.


Migrating content from older custom CMS

Question: Initial Question
Given an older CMS that kept data in a mysql database, how could we move this into a new D7 install?
It has a mysql database with a content table containing Title and Body (with HTML content) columns, could I do an import of this into Drupal and fill in the gaps as needed? I'm okay to rebuild menus and tie up other loose ends, but I'm fearing hours of cutting and pasting putting.
Follow Up and Outcome
:** After considering all the great advice below, I opened the older database in mysql Query Browser, executed a query on the profiles table to give me a CSV file with the following headers...

FirstName
MiddleName
LastName
Address1
Address2
phone
Email
title
cvFilePublic
pageContent
lastUpdateDate
pageName
pageURI
pageID

Then I created a Feed Importer with the following mapping:
Answer: If you know any php I recommend the Migrate module to easily write a SELECT title, body FROM old_content and map them to Title and Body fields of a Drupal Page type. You would do this with a Migration class. See documentation on the project page.
You could also try the Feeds project.
There are modules for Migrate to migrate from Wordpress or older Drupal sites. You could use that as example migrations to move content, menus, etc into a new drupal site.
I've migrated pages, and custom Joomla content for courses and instructor content into Drupal content types .... but every migration use-case is always unique; I'm just recommending tools I've used.
Comment: +1 for Migrate. Cleanest and most powerful way to do data migrations into Drupal.
Answer: The most quick and painless way would be to dump the old content from SQL to a CSV and import using Feeds - this can be done using a SQL program and point-and-click through Drupal. If this is a one-time thing, you should be fine with this.  Feeds has mapping for most field types.
If you need to fully integrate, or do a more complex migration (import to field collections, for example, or do something other than create nodes) you can use migrate and directly query the other db then map the fields.  This seems like overkill if you're just migrating title and body fields though.  Again, I would use Feeds for something simple like this.
Answer: One option, though a decent amount of work, is to write a custom import script.
Typically, when I do this I will take the default index.php, copy it to something like import.php, and edit it to remove everything below the bootstrap code.
Then, I add in a loop to query the remote database, build up a node object from the results, and then do a node_save().  There are a few ways to build up node objects from scratch.  A search will turn them up.  Then I will browse to my import script and watch it run.  Once the import is done, I will delete the script from the server.
This glosses over a fair number of details.  The main advantage of this over Migrate or Feeds, is that it allows you to have more complex logic for how you handle the import, and more control over any data massaging.  This is only an advantage, though, if you need these.
Comment: 90% of the time I fall back to a manual import script too, it usually takes less time than what I estimate doing the same thing with migrate would
Comment: but then you dont get pretty drush/gui progress indicators :) or the whole "reset the migration" ... i dunno maybe i just see the implementation time as useful in that migrations offer a form of "standard" documentation as to how i moved stuff to this site (and the last 10 sites) ....
Comment: @tenken  I think it just depends on the situation.  The last few imports I have done have been simple enough for Feeds.  A lot in the past, though, have required a lot of complex logic to massage the data.  I just find it easier to bypass Migrate and do a one-off script.  I also have done enough of these that I have a decent library to build from.
Comment: A custom script will always require more time and offer much less than a Migrate solution, once you learn the rather basic Migrate concepts.
Comment: @BojanZivanovic  After doing this a lot, I would respectfully disagree.  You need to pick the best solution for your particular problem.  Using Feeds or Migrate does work in a lot of instances.  However, I have had been instances with content imports that are very complex (eg, take six loosely structured XML exports from custom systems, and weave together into four different content types, three taxonomies, and build up node references between everything).  I have tried Migrate with these, and custom imports have always been quicker.

Migrating content from older custom CMS


Get file size before uploading

Question: Is there any way to find out the file size before uploading the file using AJAX / PHP in change event of input file?
Comment: and obviously duplicate of http://stackoverflow.com/search?q=file+size+before+upload
Comment: possible duplicate of [How to check file input size with jQuery?](http://stackoverflow.com/questions/1601455/how-to-check-file-input-size-with-jquery)
Comment: Possible duplicate of [JavaScript file upload size validation](http://stackoverflow.com/questions/3717793/javascript-file-upload-size-validation)
Answer: For the HTML bellow
<input type="file" id="myFile" />

try the following:
//binds to onchange event of your input field
$('#myFile').bind('change', function() {

  //this.files[0].size gets the size of your file.
  alert(this.files[0].size);

});

See following thread:
How to check file input size with jQuery?
Comment: @ErdalG. Good question! MDN is [missing](https://developer.mozilla.org/en-US/docs/Web/API/File/size) the documentation, but `FileList.files` is an array-like of `File` objects, which is an extension of `Glob`. And [according to the spec](https://w3c.github.io/FileAPI/#attributes-blob), `Glob` indeed defines the `size` property as the number of _bytes_ (0 for an empty file). So yes, **the result is in bytes**.
Comment: Yes, this does not work pre IE 10 and only has partial support in android and ios. http://caniuse.com/fileapi. If it were only this easy...
Comment: I suppose the result is in bytes?
Comment: Isn't the files array non-existent on internet explorer (older versions)?
Answer:

<input id="fileInput" type="file" onchange="AlertFilesize();" />

Work on IE and FF
Comment: downvoted because the answer uses ActiveX.  in 2015, even Microsoft is abandoning ActiveX.  While it was a reasonable suggestion when given, I would recommend developers avoid this now and in the future.
Comment: I like this solution, because only older versions of IE will return true for window.ActiveXObject.
Comment: @scottstone I don't understand why you down voted all answers supporting legacy browsers? This answer is much cleaner than the ones using browser fingerprints and by no means recommand anyone to use ActiveX.
Comment: @NicolasBouvrette - I agree that this answer is much cleaner than the others, but I can't remove the downvote at this point.  The original question did not ask for compatibility with old versions of IE, and this answer doesn't advise readers that most of the code is there to support 5+ year old versions of IE.
Comment: @scottstone Actually one more tangible point from my view on why not to use ActiveX is because it displays a warning message in IE which is an horrible (scary?) user experience.
Comment: Thanks for your answer. May I ask a question about your solution please? I notice if I use ``, the function works. However, if I change to ``, the function will not work. Would you mind let me know my mistake please? Thank you very much.
Comment: I tried to change `function AlertFilesize(){` to `function AlertFilesize(value){` and then change`` to ``, but still not working.
Comment: I think, it shoud be:
parseFloat(Math.floor(fSize*100)/100) +''+fSExt[i];
Answer: Here's a simple example of getting the size of a file before uploading. It's using jQuery to detect whenever the contents are added or changed, but you can still get files[0].size without using jQuery.

$(document).ready(function() {
  $('#openFile').on('change', function(evt) {
    console.log(this.files[0].size);
  });
});

<form action="upload.php" enctype="multipart/form-data" method="POST" id="uploadform">
  <input id="openFile" name="img" type="file" />
</form>

Here's a more complete example, some proof of concept code to Drag and Drop files into FormData and upload via POST to a server. It includes a simple check for file size.
Answer: Best solution working on all browsers ;)
function GetFileSize(fileid) {
    try {
        var fileSize = 0;
        // for IE
        if(checkIE()) { //we could use this $.browser.msie but since it's deprecated, we'll use this function
            // before making an object of ActiveXObject,
            // please make sure ActiveX is enabled in your IE browser
            var objFSO = new ActiveXObject("Scripting.FileSystemObject");
            var filePath = $("#" + fileid)[0].value;
            var objFile = objFSO.getFile(filePath);
            var fileSize = objFile.size; //size in b
            fileSize = fileSize / 1048576; //size in mb
        }
        // for FF, Safari, Opeara and Others
        else {
            fileSize = $("#" + fileid)[0].files[0].size //size in b
            fileSize = fileSize / 1048576; //size in mb
        }
        alert("Uploaded File Size is" + fileSize + "MB");
    }
    catch (e) {
        alert("Error is :" + e);
    }
}

from http://www.dotnet-tricks.com/Tutorial/jquery/HHLN180712-Get-file-size-before-upload-using-jquery.html
UPDATE :
We'll use this function to check if it's IE browser or not
function checkIE() {
    var ua = window.navigator.userAgent;
    var msie = ua.indexOf("MSIE ");

    if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./)){
        // If Internet Explorer, return version number
        alert(parseInt(ua.substring(msie + 5, ua.indexOf(".", msie))));
    } else {
        // If another browser, return 0
        alert('otherbrowser');
    }

    return false;
}

Comment: downvoted because the answer uses ActiveX. in 2015, even Microsoft is abandoning ActiveX. While it was a reasonable suggestion when given, I would recommend developers avoid this now and in the future. –
Comment: @scottstone this is for backward compability and that's not true Microsoft won't abdon ActiveX it is to much used in many things and here is the proof http://www.computerworld.com/article/2481188/internet/why-microsoft-won-t-abandon-internet-explorer.html
Comment: $.browser was removed from jQuery in version 1.9 (deprecated since v 1.3).
Comment: @SilvioDelgado Changed and updated they removed $.browser into a plugin so we'll need just a small test for IE browser (works with all versions)
Answer: I had the same problem and seems like we haven't had an accurate solution. Hope this can help other people.
After take time exploring around, I finally found the answer. This is my code to get file attach with jQuery:
var attach_id = "id_of_attachment_file";
var size = $('#'+attach_id)[0].files[0].size;
alert(size);

This is just the example code for getting the file size. If you want do other stuffs, feel free to change the code to satisfy your needs.
Comment: I like this one because it doesn't need to be put on the change event like the most popular solution.  And I also like the fact you have given me permission to change the code to satisfy my needs :)
Answer:

$(document).ready(function() {
  $('#openFile').on('change', function(evt) {
    console.log(this.files[0].size);
  });
});

<form action="upload.php" enctype="multipart/form-data" method="POST" id="uploadform">
  <input id="openFile" name="img" type="file" />
</form>
Answer: Browsers with HTML5 support has files property for input type.
This will of course not work in older IE versions.
var inpFiles = document.getElementById('#fileID');
for (var i = 0; i < inpFiles.files.length; ++i) {
    var size = inpFiles.files.item(i).size;
    alert("File Size : " + size);
}

Answer: Please do not use ActiveX as chances are that it will display a scary warning message in Internet Explorer and scare your users away.

If anyone wants to implement this check, they should only rely on the FileList object available in modern browsers and rely on server side checks only for older browsers (progressive enhancement).
function getFileSize(fileInputElement){
    if (!fileInputElement.value ||
        typeof fileInputElement.files === 'undefined' ||
        typeof fileInputElement.files[0] === 'undefined' ||
        typeof fileInputElement.files[0].size !== 'number'
    ) {
        // File size is undefined.
        return undefined;
    }

    return fileInputElement.files[0].size;
}

Answer: ucefkh's solution worked best, but because $.browser was deprecated in jQuery 1.91, had to change to use navigator.userAgent:
function IsFileSizeOk(fileid) {
    try {
        var fileSize = 0;
        //for IE
        if (navigator.userAgent.match(/msie/i)) {
            //before making an object of ActiveXObject,
            //please make sure ActiveX is enabled in your IE browser
            var objFSO = new ActiveXObject("Scripting.FileSystemObject");
            var filePath = $("#" + fileid)[0].value;
            var objFile = objFSO.getFile(filePath);
            var fileSize = objFile.size; //size in b
            fileSize = fileSize / 1048576; //size in mb
        }
        //for FF, Safari, Opeara and Others
        else {
            fileSize = $("#" + fileid)[0].files[0].size //size in b
            fileSize = fileSize / 1048576; //size in mb
        }
        return (fileSize < 2.0);
    }
    catch (e) {
        alert("Error is :" + e);
    }
}

Answer: you need to do an ajax HEAD request to get the filesize. with jquery it's something like this
  var req = $.ajax({
    type: "HEAD",
    url: yoururl,
    success: function () {
      alert("Size is " + request.getResponseHeader("Content-Length"));
    }
  });

Comment: But if do that file input will clear(empty) ?? Can u make a example thank
Answer: Get the size of the file by files.item(i).size.
You should try this.
https://www.geeksforgeeks.org/validation-of-file-size-while-uploading-using-javascript-jquery/
Answer: You can use PHP filesize function. During upload using ajax, please check the filesize first by making a request an ajax request to php script that checks the filesize and return the value.
Answer: You can by using HTML5 File API: http://www.html5rocks.com/en/tutorials/file/dndfiles/
However you should always have a fallback for PHP (or any other backend language you use) for older browsers.
Answer: Personally, I would say Web World's answer is the best today, given HTML standards.  If you need to support IE < 10, you will need to use some form of ActiveX.  I would avoid the recommendations that involve coding against Scripting.FileSystemObject, or instantiating ActiveX directly.
In this case, I have had success using 3rd party JS libraries such as plupload which can be configured to use HTML5 apis or Flash/Silverlight controls to backfill browsers that don't support those.  Plupload has a client side API for checking file size that works in IE < 10.

Get file size before uploading


Does default destructor free the memory pointed by the member pointers?

Question: When I delete a node in a linked list, do I need to set the next to NULL?
The ListNode is defined as this
struct ListNode {
    int val;
    ListNode* next;
    ListNode(int x): val(x) {}
}

Now I wanna delete the node after m
ListNode *tmp = m->next;
m->next = m->next->next;
delete tmp;

If tmp->next would be deleted in the destructor, the linked list should be in trouble. However, if tmp->next is not deleted, there could be another case that causes memory leak:
ListNode *tmp = new ListNode(0);
tmp->next = new ListNode(1);
delete tmp;

If tmp->next is not deleted, there's no way to find this piece of memory again.
So it's a dilemma here, what does the default destructor actually do?
Comment: It will not call delete on member pointer
Comment: How can default destructor possibly know whether to free that memory or not? There's no guarantee that that memory was even dynamically allocated.
Answer: The default destructor destroys all member variables (that have destructors) and does nothing else.
None of ListNode's member variables have destructors, so the default destructor for ListNode does nothing.
Note that while next is a member variable, the thing next points to isn't.
Comment: So does it mean I should either delete `tmp->next` or give it another pointer before I delete `tmp`?
Comment: @KingstonChan You already have the information you need to answer that question. Do you think it does?
Comment: Thanks! you're very helpful!
Comment: @KingstonChan Do you think it does?
Comment: Yes I think so.
Comment: @KingstonChan Why?
Comment: Because if I don't do so, I'll lose the piece of memory pointed by `tmp->next` forever, and not able to access / deallocate it.
Comment: @KingstonChan In the first case (remember the question contains two different code snippets), `m->next` still points to the same piece of memory as `tmp->next`. So if you delete the piece of memory, `m->next` is now pointing to unallocated memory - is that what you want? In the second case, yes, if you don't delete `tmp->next` now then you won't be able to delete it later, so you'll leak memory.
Comment: Thanks for elaboration! This confirms by guess.
Answer:
So it's a dilemma here, what does the default destructor actually do?

The default destructor destroys the member variables. If the member variables have user defined destructors, they are called. If they are fundamental types, nothing happens.
There is more to it than what I described above. It will be worth your while to read up the section on destructors in the standard. In C++11, that section is 12.4. You can also find more information at cppreference.com.


2 actionbar tabs don't fill a screen width on FULLHD (xxhdpi) Android device

Question: I have required styles (from designer) applied on my TABs used in Actionbar for navigation and I use Actionbar Sherlock. They look perfectly from ldpi to xhdpi devices, but situation changes on xxhdpi devices.
I have only 2tabs and except mentioned styling, I have the same code as Sherlock DEMO app in "Tab Navigation". I found 2 older simmilar questions not answered yet.
Stacked ActionBar tab bar not filling parent
(I've got a simmilar problem, centered tabs. Sorry for inconvenience, I can't attach images because of rep points.)
and
action bar tabs not fill screen in android
Since the time of their posts, this is not only the issue of tablets, but now, there are many FULLHD (flagship) smartphones and this is becomming the big "design" issue.
I want my 2tabs to fill/match the full width of ANY device size, so in my case to fill 50% width each. Default Holo styled tabs doesn't look that bad (as shown in previous link), but my styled tabs on this big screen look much worse.
PS: Situation doesn't change if I make a text in tabs bigger or longer. Tabs don't adujst their width, instead they change their height and text takes 2 lines.
Answer: Unfortunatelly, this is a another JB changes:
https://android.googlesource.com/platform/frameworks/base/+/b8139af3dcae80c0030afd0354dc424a7c72c3d9
One of solution: set target SDK 15 or lower.
Comment: Thx for the info & valuable link, I think that this might be the cause. I tried setting targetSDK to 15 & lower, but unforutnatelly, it haven't solved it :-/


Receiving a null pointer exception

Question: I'm receiving a null pointer exception from some code I've wrote, I cannot see the reason for the exception. This is my code:
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.Scanner;

public class SearchingFilesMain {

public static void main(String[] arg) {

    int checker4 = 0;
    String checker3 = "";
    String checker2 = "";
    String checker1 = "";
    String checker = "";

    try {
        Scanner scan = new Scanner(new BufferedReader(new FileReader(
                "C:\\Users\\User\\Desktop\\asciiTracks.txt")));

        while (checker != null) {

            String pattern = "Array Start";
            checker = scan.findWithinHorizon(pattern, 0);

            if(checker.equals("Array Start")){

                String pattern2 = "Array Size";
                checker3 = scan.findWithinHorizon(pattern2, 300);
                System.out.println(checker3);

                if(checker3.equals("Array Size")){
                    checker4 = Integer.parseInt(scan.findInLine("(10000|\\d{1,4})"));
                    System.out.println(checker4);

                }else{System.out.println("no array size");}
        System.out.println(checker4);
    }else{System.out.println("no array size");}}}catch (FileNotFoundException e) {}}}

This is the error i get on the console:
Exception in thread "main" java.lang.NullPointerException
at SearchingFilesMain.main(SearchingFilesMain.java:31)

This error occurs at this line of the code:
if(checker3.equals("Array Size")){

This makes no sense to me, as surely if checker3 is not equal to the text it will simply move onto the else statement and go from there, rather than just throw null pointer exception and stop the program? Am i wrong in thinking this?
Anyone got any ideas on why this is happening?
Comment: Please check with "checker3" its get null value from
checker3 = scan.findWithinHorizon(pattern2, 300);
Answer: Though you have initialized checker3 with empty string, it is overrited by checker = scan.findWithinHorizon(pattern, 0); which seems to be returning null.
To avoid NullPointerException you should add null check in your if statement -
if(checker!=null && checker.equals("Array Start")){
   ...
}else{
   ...
}

Comment: okay thank you, yeah i realised it was returning null because that's precisely what it should return, but i couldn't see how it was managing to throw the null pointer exception. Thank you for clarifying :D
Comment: `"Array Start".equals(checker)` is more concise as there's no need to explicitly check for null.
Answer: scan.findWithinHorizon(pattern, 0) may returning null into checker3 and
calling equals() on it gives you NullPointerException.
If you want you ignore this exception,change your condition to
 if("Array Size".equals(checker3)){
 }

here the condition is false when checker3 is not equals to "Array Size" and also when checker3 is null, otherwise it is true
Answer: In your case, checker3 = scan.findWithinHorizon(pattern2, 300); causes it to be null
If checker3 is not initalized, it will be null, and calling a method on reference variable that refer to null will result into NullPointerException.
Comment: okay but why isn't checker3 initialized then? It should be initialized before the entire while statement.
Comment: it is initialized to a blank string before while loop, but in while loop the call to findWithinHorizon is returning null
Answer: checker3 = scan.findWithinHorizon(pattern2, 300);

I can only assume that the above line of code is assigning a null value to checker3.

Receiving a null pointer exception


Multiple count values on one column

Question: I want to query my database and get counts of the occurences of each id in a single column.
The two tables related to this query are:
categories: this table has a list of all categories with titles
id | title
----------
1  | project
2  | tech
3  | other

category_news: this table is used to assign news items to categories, each news item can be in multiple categories
id | category_id | news_id
--------------------------
1  | 1           | 2
2  | 1           | 5
3  | 1           | 3
4  | 2           | 4
5  | 3           | 2
6  | 3           | 1

I would like to get a result of (doesnt have to be an array, I can sort out the results of a query, just using an array below for an example of the returned results):
array(
'project' => 3
'tech'    => 1
'other'   => 2
);

Where the key is the category title and the value is the total number of news items in each category.  I know that I could do it with a query for each category:
select count(cn.category_id), c.title from category_news cn join categories c on c.id = cn.category_id where category_id = 1

But my question is, can I do it with one query to get all the counts? As if I have 100 categories thats 100 queries my way and I would love to do it in one.
Any help would be much appreciated
Regards
Luke
Answer: Try this:
SELECT     c.title, count(cn.category_id)
FROM       categories c
LEFT JOIN  categories_news cn
ON         c.id = cn.category_id
GROUP BY   c.title

Comment: Lol so simple, I feel a little silly for writing such a long question now :)  Thanks.
Answer: This will work(tested):
SELECT COUNT(cn.category_id), c.title
    FROM category_news cn
    JOIN categories c ON c.id = cn.category_id
    GROUP BY cn.category_id

Answer: Yes, you can. You have to use a query like the following (tested)
SELECT count( * ) , c.title
FROM category_news cn
JOIN categories c ON c.id = cn.category_id
WHERE 1
GROUP BY cn.category_id

Multiple count values on one column


Document classification question

Question: I've got a tricky document classification question.  Each document in my collection can be assigned a label.  In my training set the average is about 3 different labels assigned to each document.  What I have learned in the training set is $P(\text{label}|\text{doc_word})$ for many label/doc_word pairs.  I want to calculate
$P(\text{label}|\text{word}_1,\ldots,\text{word}_n)$ but I cannot simply calculate it by
$$P(\text{label}|\text{word}_1,\ldots,\text{word}_n)=P(\text{label}|\text{word}_1)\cdot \ldots \cdot P(\text{label}|\text{word}_n)$$
because there are many words where $P(\text{label}|\text{word}_i)=0$.  Furthermore, if there are two words in the document where $P(\text{label}|\text{word})>0$, their product would be less than the individual probabilities thus making the label less likely.  This is counter-intuitive to me because I would think that having two words where $P(\text{label}|\text{word})>0$ should make the label more likely.  So maybe the independence assumption does not hold.
Perhaps I should just use these probabilities as association rules in order to assign labels?
Answer: This is a really interesting question; I'm assuming that you are using a maximum likelihood framework, where the likelihood of of a particular word $w_i$ appearing in a document having label $L$ is simply given by $p(L|w_i) = \frac{count(L,w_i)}{count(w_i)}$.
Now, part of the reason that this problem arises is because of the use of this maximum likelihood framework, where the likelihood that a document has label $L$ can only be non-zero when all of the words in the constituent document have appeared at least once in documents with label $L$ in our observations before. In that sense, your derivation is correct; when working with a maximum likelihood framework, it is entirely reasonable to assign a document zero probability of having label $L$ even if only one of its words has never had label L before.
That said, this is obviously quite unsatisfactory for our purposes. One, on a practical level, it is rather evidently not true. And two, it rather seriously affects our ability to score and classify documents based on the evidence. I'll talk about each one briefly.
The first objection - that is, that on a practical level it doesn't really work as we've formulated - is entirely the result of the fact that the maximum likelihood approach is a frequentist one. In a Bayesian treatment, these probabilities might be very small, but would presumably be non-zero as the result of the inclusion of some reasonable prior.
Despite that caveat, can still use this framework for prediction, bringing us to number two. One approach is to do what you mentioned; that is, to entirely discard the probabilistic framework and simply use the observed counts as scoring features, allowing ranking of particular labels for a given document. In this formulation, simply label a given document $D$ via the procedure:
$label(D)= arg max_{l \in L}[\sum_{w_i \in D} P(l|w_i)]$
This is nicely computationally tractable, of course, and uses the counts we've already gathered. Note, by the way, that despite the use of the observed MLE probabilities for scoring, the quantity yielded by this is NOT normalized, and thus not a probability distribution.
However, this approach does have shortcomings - for example, it does not deal with the fact that the probability distribution over the labels in $L$ is likely not uniform. There are a number of ways to treat this; a commonly used approach which would be useful here is the Naive Bayes Classifier, which nicely adds estimates over the label observations.
Lastly, given the pairs that you have, and the number of irrelevant features that are appearing in each document (ie, words that have no real use in classification, like "the"), you might look into linear models such as Winnow, which is extendable to multiple classes and is designed for dealing with large numbers of irrelevant features.
I hope that helps!
Answer: Let me clarify a couple of things.
Fist of all, when you use Naive-Bayes to calculate the probability  $P(\text{label}|\text{doc_word})$, you have to change that relation into something you know. In this case, the natural route is to use Bayes' theorem that states the following:
$$P(\text{label}|\text{doc_word}) = \displaystyle \frac{P(\text{doc_word}|\text{label})P(\text{label})}{P(\text{doc_word})}$$
Usually, you can disregard the denominator because it only provides a normalization factor, which is usually not needed.
As you said, there are issues regarding the calculation of $P(\text{doc_word}|\text{label})$ when you don't have a word assigned to a given label, so the whole expression would be zero. However, there is an easy fix. You can pretend that words not assigned to a given label are actually seen once. Therefore, the maximum likelihood estimate, that is, the good old frequentist view of probability, is calculate as:
$$P_{Lap}(\text{word}|\text{label}) =\frac{ C(\text{word}) + 1}{N + d}$$
where $C(\text{word})$ is the number of times a given word appears assigned in a label, $N$ is the total number of words in your corpus and $d$ is a correction factor that accounts for the number of extra words you are considering in the corpus.
This trick has a serious drawback. As you should expect, there are a fairly large number of words you may encounter in a document that are not assigned to any label, so you are allocating a tiny bit of probability to those words and subtracting the same tiny bit to the words in your corpus. Therefore, a large chunk of the probability space will be been given to unseen words, and that is quite unsatisfactory. That is why there have been proposal to remedy this issue. One of them is the  Lidstone smoothing, in which we add a fraction $\lambda$ instead of $1$:
$$P_{Lid}(\text{word}|\text{label}) =\frac{ C(\text{word}) + \lambda}{N + d\lambda}$$
An even better estimate of the frequency of a word is the Good-Turing estimator, so I encourage you to give it a read.
Depending on your particular application, you may want to try more sophisticated smoothing procedures, but this is really the low-hanging fruit.

Document classification question


How do I sum this summation?

Question: How do I find the sum:
$$\sum_{n=0}^{1947}{\frac{1}{2^n+\sqrt{2^{1947}}}}$$
The method of telescoping surely won't work for this, and I tried rationalizing each terms to try and cancel consecutive terms but it didnt work for me. How do I go about approaching this?
Comment: Hint: if $a_n=1/(2^n+\sqrt{2^{1947}})$, then $a_n+a_{1947-n}=\ldots$
Comment: I can't seem to be able to simplify $a_0+a_{1947}...$ could you help? Also, how do I notice these kinds of patterns while solving questions?
Comment: I've edited the title and the question modifying the term series by summation.
Answer: We have
$$\sum_{n=0}^{1947} \frac{1}{ 2^n+\sqrt{2^{1947}} }=\frac1{\sqrt{2^{1947}} }\sum_{n=0}^{1947} \frac{1}{2^{n-\frac{1947}2}+1}=\frac1{\sqrt{2^{1947}}}\sum_{n=0}^{1947}a_n$$
then
$$a_0+a_{1947}=\frac{1}{2^{-\frac{1947}2}+1}+\frac{1}{2^{\frac{1947}2}+1}=\\=\frac{2^{\frac{1947}2}}{2^{\frac{1947}2}+1}+\frac{1}{2^{\frac{1947}2}+1}=1$$
and so on for the remaining terms.

How do I sum this summation?


How to translate database field values?

Question: I cannot find information on how translate database field values. On my site I use Support Ticketing System module. If I'm trying translate interface to German (for example) everithing is ok except Status field (Status field is reffering to support ticket status - new, in progress, closed). I can see in the database all these values (new, in progress, closed) in certain table. But how to translate them?
The built-in Drupal interface translation does not recognize these values.
Can you advise the correct way for translation of these field values?
Answer: Have a look at the Field Translation module, a submodule (i18n_field) of the i18n module. Some more details about it (from the Community documentation):

... allows for translation of text associated with a field's settings including the label, help text, default value, and list options. Translation of these field settings can be added through the 'Translate interface' pages (Administration > Configuration > Regional and language > Translate interface).

Especially the "list options" mentioned above seem to be what you're looking for.

How to translate database field values?