Gerar array em JSON pelo PHP

Question: Eu estou estudando uma forma de enviar um resposta JSON do PHP para o JS. Eu olhei diversos posts aqui e em outros fórums, mas não consigo encontrar o meu erro.
Eu faço um SELECT de tudo em uma tabela do MySQL através do PHP, mas quando envio ao JS e vejo a resposta no console, apenas um resultado é mostrado, o primeiro, não os demais.
Provavelmente há algo errado no meu PHP, pois o JS apenas mostra o resultado no console.
No código tem um trecho assim:
<code>($result->num_rows > 5)
</code>
Esse trecho é proposital, pois queria testar se receberia um resultado igualmente, sei que o correto é testar se é > 0.
Código PHP:
<code>    public function selectTable(){
     $return_arr = array();

     $sql = "SELECT * FROM coletas";
     $result = mysqli_query($this->mysqli, $sql);
     if ($result->num_rows > 5) {
       while($r = mysqli_fetch_assoc($result)) {
          $codigo_intervencao = $r['codigo_intervencao'];
          $sql2 = "SELECT intervencao FROM intervencoes WHERE id = $codigo_intervencao";
          $intervencao = mysqli_query($this->mysqli, $sql2);
          $intervencao2 = mysqli_fetch_assoc($intervencao);
          $return_arr['codigo_intervencao'] = $intervencao2['intervencao'];
          $return_arr['tempo'] = $r['tempo'];
       }
     }
     return json_encode($return_arr, JSON_FORCE_OBJECT);
   }
</code>
Comment: mysqli_fetch_assoc obsoleto...
Comment: @VictorGomes [Hein?](http://php.net/manual/en/mysqli-result.fetch-assoc.php)
Answer: Você só está recebendo um resultado pois você está sobrescrevendo os demais, com o código abaixo:
<code>$return_arr['codigo_intervencao'] = $intervencao2['intervencao'];
$return_arr['tempo'] = $r['tempo'];
</code>
Para retornar todos, é necessário criar um array multidimensional. Exemplo:
<code>$return_arr[]['codigo_intervencao'] = $intervencao2['intervencao'];
$return_arr[]['tempo'] = $r['tempo'];
</code>
Dessa forma você conseguirá armazenar todos os valores para exibi-los posteriormente.
Comment: Great, it works.

Gerar array em JSON pelo PHP


Do the Betti numbers determine the topology?

Question: Do the Betti numbers determine the topology? I.e., if we are given a list of the Betti numbers of a topological space, then are we able to find the topology? What about in the smooth manifold case? Or in the compact case?
Comment: This is what Poincare discovered over 100 years ago: He first expected that for compact connected manifolds homology groups (he did not have the notion but he knew about Betti numbers and torsion numbers) determine the manifold. But then he discovered the [Poincare homology sphere](https://en.wikipedia.org/wiki/Homology_sphere). This led him to state the [Poincare Conjecture](https://en.wikipedia.org/wiki/Poincar%C3%A9_conjecture) and geometric topology was not the same ever since.
Comment: If only..........
Comment: @C.F.G: If you are asking if homotopy-equivalent topological spaces are homeomorphic then the answer is obviously negative: $R^n$ is homotopy-equivalent to a point. But if you are asking this question for homotopy-equivaent closed manifolds, then it is a good question (still, negative answer), deserving a separate post.
Comment: @MoisheKohan: Thanks for your nice historical comment. similar to Poincare argument, Homotopy groups can do this?
Comment: https://math.stackexchange.com/questions/281339/what-is-the-difference-between-homotopy-and-homeomorphism
Comment: @MoisheKohan: I have posted a new question as you suggested. https://math.stackexchange.com/q/3437720/272127
Answer: In general topological spaces this does not work, consider
$$X_n = \mathbb R^n \setminus \mathbb R^{n-2}.$$
Then the homotopy type of all the $X_n$ is identical, so they have the same Betti numbers (but are not homeomorphic). So a better question might be whether they determin the homotopy type. The answer is still no: consider the space
$$\mathbb R \mathbb P^3 = S^3/\pm1.$$
This space falls in all of your categories, has the same Betti numbers as $S^3$, but is not homeomorphic to $S^3$ (it has nontrivial but finite fundamental group).
Comment: No, this fails for even $n$ since then $\mathbb R \mathbb P^n$ is non-orientable. If I understand it correctly, what you suggest in your second question fails for the same reason.
Comment: Why $RP^3$ and $S^3$ have same Betti numbers? Is it true in general for $RP^n$ and $S^n$? and for $b_i^M=b_i^{M/\Gamma}$? where $\Gamma$ is a discreet subgroup of isometry group that acts properly discontinuous.


How do you calculate simple statistics for left censored data in R?

Question: I have left censored data where the distribution is known (it's near enough lognormal, at least in theory).
I'd like to calculate some simple summary stats: geometric mean and standard deviation in this case.
I've previously used R's NADA package for this but it is no longer on CRAN.  Is there an alternative available?
EDIT:
I contacted Lopaka Lee, the package maintainer, and he says that he's

working on updating the package for
  the upcoming release of R

so hopefully the package's absence is only temporary.
Answer: I will let other suggest better alternatives to NADA, but it seems the package is still available on CRAN, in the Archive section. The last version is from May, 2009.
Installation went fine for me, using
R CMD install NADA_1.5-2.tar.gz

Under Windows, I guess you can just download the tgz and use built-in install facilities.
Comment: (+1) I located and installed this package less than two months ago.  For more sophisticated work, consider using censored regression models.
Comment: @whuber: I've done MCMC modelling on the data but the target audience is chemists so some simpler stats are useful to warm them up.  My worry is that NADA was withdrawn because it gave the wrong answers.  (I know it's calculations of medians was dodgy.)
Comment: @Richie That is extremely interesting to hear.  I didn't test NADA that far: I tried it out, quickly found it lacking in capabilities, and went immediately to survival analysis and censored regression models.


How to remove square brackets from name attribute in webform elements?

Question: Name attribute in rendered webform elements contain square brackets like submitted[field_machine_name].

.

Is there a way to replace square brackets in the name, so the name attribute looks something like "field_machine_name", without breaking the webform submission handler?
Answer: you can use hook_form_alter
Example D8
function hook_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {

  if ($form_id=='comment_comment_form') {

    $form['subject']['widget']['0']['value']['#name'] = 'field_machine_name';

  }

}

Example D7
function comment_form_alter(&$form, $form_state, $form_id) {

 if ($form_id=='comment_node_article_form')        {
    $form['subject']['#name'] = 'field_machine_name';
 }

}


Is the for loop in my code the speed bottleneck?

Question: The following code looks through 2500 markdown files with a total of 76475 lines, to check each one for the presence of two strings.
#!/usr/bin/env python3
# encoding: utf-8

import re
import os

zettelkasten = '/Users/will/Dropbox/zettelkasten'

def zsearch(s, *args):
    for x in args:
        r = (r"(?=.* " + x + ")")
        p = re.search(r, s, re.IGNORECASE)
        if p is None:
            return None
    return s

for filename in os.listdir(zettelkasten):
    if filename.endswith('.md'):
        with open(os.path.join(zettelkasten, filename),"r") as fp:
            for line in fp:
                result_line = zsearch(line, "COVID", "vaccine")
                if result_line != None:
                    UUID = filename[-15:-3]
                    print(f'›[[{UUID}]] OR', end=" ")

This correctly gives output like:
›[[202202121717]] OR ›[[202003311814]] OR

, but it takes almost two seconds to run on my machine, which I think is much too slow. What, if anything, can be done to make it faster?
Comment: from glancing over the code: why not read the file as a whole (instead of line by line) and use `re.matchiter`? you construct a new regex pattern for each line in each file. that pattern is static (you might even use `re.compile`).
Comment: The reason for reading line by line is that I want to return where the search terms appear in a single line and not anywhere in the file. Ideally, I'd like to search to file and find occurrences of the two search terms, maybe within ten words, even if in separate lines. But I'll start here and see.
Answer: The main bottleneck is the regular expressions you're building.
If we print(f"{r=}") inside the zsearch function:
>>> zsearch("line line covid line", "COVID", "vaccine")
r='(?=.* COVID)'
r='(?=.* vaccine)'

The (?=.*) lookahead is what is causing the slowdown - and it's also not needed.
You can achieve the same result by searching for:
r=' COVID'
r=' vaccine'

Comment: Making the change you suggested took the time to execute from almost 2 sec. to .3 sec. Yahoo!! No speed difference when I look for 3 terms instead of two. Thank you @KarlT


How can I create a dynamic join between 2 SQL Server tables on 2 different servers?

Question: I have data in 2 SQL Server 2012 database servers. I need to create a view containing data from both servers.
My first step was to import the join-table from Server2 into Server1 and create the view. The problem is though, that I need to keep the exported table up-to-date and thus a static "export" of the table is not ideal.
What methods could I use in order to create a dynamic join between 2 tables on 2 different servers?
Answer: You could establish linked server and use 4 part names:
CREATE VIEW dbo.my_view
AS
SELECT * -- cols list
FROM dbo.table_name t
JOIN server_name.database_name.schema_name.table_name c
  ON t.id = c.id;

Note:

If view will be part of transaction, MS DTC (distributed transaction coordinator) should be enabled.
Depending how you build your query, performance may be degraded.
Not every type can be used (like XML)


Return value from Oracle function using Mybatis

Question: I have looked at a number of StackOverflow questions on this issue but can't find one that makes any sense.   This one comes closest but doesn't show how to get the return value from the function.
Here's my mapper call:
public Long callMyFunction(@Param("recordId") Long recordId, @Param("otherId") Long otherId, @Param("date") Date date, @Param("comments") String comments);

Here's the mapper XML:
<select id="callMyFunction" parameterType="map" statementType="CALLABLE"  resultType="java.lang.Long">
    {  #{resultId,javaType=java.lang.Long,jdbcType=NUMERIC,mode=OUT} = call MYSCHEMA.MYPACKAGE.my_function(
    #{recordId,jdbcType=NUMERIC,mode=IN},
    #{otherId,jdbcType=NUMERIC,mode=IN},
    #{date,jdbcType=DATE,mode=IN},
    #{comments,jdbcType=VARCHAR,mode=IN})}
</select>

The call works, but the return value (resultId) is always null.
Can anybody spot the problem?
Comment: Have you tried it with recordId, javaType=long (native type) rather than Long (object wrapper)?
Answer: If you want to return directly the result, then the SQL call must be:
SELECT MYSCHEMA.MYPACKAGE.my_function(...) FROM DUAL
If you want to keep with calling the function in the procedure call style, that means the result is an OUT parameter (you env declared it OUT).
The minimum change would consist in adding a parameter to the mapper method signature:
public Long callMyFunction(@Param("recordId") Long recordId, @Param("otherId") Long otherId, @Param("date") Date date, @Param("comments") String comments, @Param("resultIdContainer") Map<String, Long> resultIdContainer);
In the XML: forget the resultType, this is for selects. And the call:
{  #{resultIdContainer.resultId, javaType=java.lang.Long,jdbcType=NUMERIC,mode=OUT} = call ...
Not that I use here a map to contain the resutlId: an indirection is required: the function will write the parameter 'result' value somewhere you can read later (after your mapper call), you can also use a class with a resultId property.
Comment: That was precisely what I needed, thank you very much!
Comment: in the first variant `ORA-00923: FROM keyword not found where expected`
Comment: Fixed. It worked as it was in other DBMS, while in Oracle we must indeed select anything `FROM DUAL`
Comment: What if my jdbcType is Cursor?
Comment: Should be `call #{params.resultList, jdbcType=CURSOR, javaType=java.sql.ResultSet, resultMap=myResultMap, mode=OUT} = my_function()` which is same principle as with procedure: `call  my_procedure(#{params.resultList, jdbcType=CURSOR, javaType=java.sql.ResultSet, resultMap=myResultMap, mode=OUT})`. Note that `params` is used for input AND output. The mapper result type is `void`.


Show naturality of $\infty$-natural transformation

Question: Working with the model category of complete Segal spaces $\text{CSS}$, which has as its underlying category the category of simplicial presheaves on $\Delta$, one has a suitable internal hom in $\text{CSS}$. Indeed, for complete Segal spaces $\mathcal{C}, \mathcal{D}$ one defines $\mathcal{D}^\mathcal{C} = \text{hom}(\mathcal{C} \times y_{\Delta^{\times 2}}, \mathcal{D})$ where $y_{\Delta^{\times 2}}$ is the Yoneda embedding $\Delta^{\times 2} \hookrightarrow \text{Psh}_\Delta(\Delta)$ into the category of simplicial presheaves on $\Delta$.
Now the set $\mathcal{D}^\mathcal{C}_{0,0} = \text{hom}(\mathcal{C}, \mathcal{D})$ precisely corresponds to all $(\infty,1)$-functors and in the same spirit $\mathcal{D}^\mathcal{C}_{1,0} = \text{hom}(\mathcal{C}\times \Delta^1_{\bullet\star}, \mathcal{D})$ (where $\Delta^1_{\bullet\star}$ denotes the bisimplicial set which is constant in the second component, i.e., $(\Delta^1_{\bullet\star})_{k,l} = \Delta^1_k$) should correspond to the set of $(\infty,1)$-natural transformations.

Is there an elegant way to see that any $\zeta \in \text{hom}(\mathcal{C} \times \Delta^1_{\bullet\star}, \mathcal{D}) \cong \text{hom}(\mathcal{C}, \mathcal{D}^{\Delta^1_{\bullet\star}})$ really satisfies some naturality condition? More explicitly, we realize that $\zeta$ induces a map
$$\zeta_{0,0} \colon \mathcal{C}_{0,0} \to \mathcal{D}^{\Delta^1_{\bullet\star}}_{0,0} \cong \mathcal{D}_{1,0}$$
i.e. $\zeta$ induces a family of 1-morphisms $(\zeta_c)_{c \in \mathcal{C}_{0,0}}$ in $\mathcal{D}$. I am expecting that this family of maps satisfies a naturality condition with respect to $\infty$-functors $F,G$ defined so that the
diagram
commutes. The mentioned naturality property should be so that the naturality square commutes, that is, $\zeta_{c'}\circ Ff \simeq Gf\circ\zeta_c$ for any $c, c' \in \mathcal{C}_{0,0}$ and any $(f \colon c \to c') \in \mathcal{C}_{1,0}$. Any ideas on this?
Answer: For every 1-morphism in $C$, i.e., a map $f\colon Δ^1→C$, the map $ζ$ induces a map $$ζ_f\colon Δ^1⨯Δ^1→D.$$
By the Yoneda lemma, the map $ζ_f$ is given by a pair of 2-simplices in $D$ that coincide along their 1st faces.  Geometrically, it looks like a commutative square with a diagonal arrow in it.
This is precisely how naturality is implemented in complete Segal spaces: the naturality "square" is given by gluing two triangles along a common face.  The data of triangles is additional data supplied to us by $ζ$, not just a property.
Additional higher coherence data for naturality is given by evaluating $ζ$ on higher simplices in $C$.  These function in much the same way as 1-simplices.


Raphael ID Different on iPad than on browser

Question: so I am making a browser based game using raphael v2 to serve up some nice vector maps which zoom. I am using a lot of "getById(xx)" calls which works fine cross browser. But when testing on my iPad the call does not work. I used a firebug applet on the iPad so I could see what the internal id's for each shape was. On desktop I am getting 52 and on the iPad I am getting 69.
Has anyone else run into this issue?
Any resolutions?
Thanks.
Answer: Are you able to save the ID of an element when you create it into a separate data structure? Then you can just use this data structure when you need to reference an element, and that way your program won't be as tightly coupled to the internals of Raphael JS, and shouldn't be as liable to breaking with future updates of the library.
Comment: Yes, you can use element.id(); to set the id of the element. Was hoping there was a less hardcode way of doing this. Oh well I suppose.
Comment: Admittedly, I've only done a little Raphael dev, so there might be a better way out there. What are you trying to get the elements for? If it's for events, such as clicks and the like, I found [this SO question pretty handy](http://stackoverflow.com/questions/3908812/combining-raphael-and-jquery-to-achieve-browser-compatibility)


Is the Trefoil knot isotopic to the unknot (torus) in ambient $\mathbb{R}^4$?

Question: I am watching this video on topology:
https://youtu.be/CJBfpvWBmSs
One of the claims is in an earlier video:
https://youtu.be/CZqeAC07_UE?t=1037
Suppose we have manifolds with dimensions $L$ and $K$ in ambient with a dimension $M$. If $K + L - M = -1$, then the manifolds must cross to "change sides". If $K + L - M < -1$, then the crossing can be avoided. The meaning of "changing sides" is left somewhat undefined in the video.
Consequently, in one of his later examples, the lecturer says that to untie the Trefoil knot, you need the ambient space $\mathbb{R}^6$ (one of the students also gives the answer 6).
However, it seems to me that it is possible to untie a Trefoil knot in $\mathbb{R}^4$. If you pull out one part of the knot into the direction of the 4-th dimension, then you can obviously circumvent the adjacent part without crossing it. In fact, this is observed in one of the comments below the video too.
Is this intuition correct? Can you untie the Trefoil knot in 4 dimensions?
If it is, then according to this definition, the Trefoil knot is isotopic to the unknot in $\mathbb{R}^4$.
EDIT:
When I said "Trefoil knot", I actually meant the following 2-dimensional surface:
Answer: Yes, all (1-dimensional) knots can be unknotted in $\mathbb{R}^4$, exactly as you argue. A nice visualization is to let the fourth dimension be color-then you can accomplish the necessary crossings by turning, say, the lower strand red and the upper blue. This actually agrees with the inequality given in your lectures.
Comment: @CameronWilliams Embedded surfaces, in particular embedded 2-spheres. There's a [great book](https://www.springer.com/us/book/9783540210405) on this.
Comment: @axel22 If your surface is the boundary of a small neighborhood of a 1-D knot in $\Bbb R^3$, those are unknotted in $\Bbb R^4$ by more or less the same argument.
Comment: @axel22 The trefoil knot picture in Wikipedia is misleading. You can shrink the diameter of the "thread" making up that knot to zero to see that this should really be seen as a 1-dimensional knot: there's only one degree of freedom in moving along the knot itself. More formally, the trefoil knot is naturally seen as the image of a continuous map from $S^1$ to $\mathbb{R}^3$. My best guess is that your lecturer was confused confused. A legitimate knotted surface will involve a (hollow) torus or sphere that, viewed in 3D, appears to pass in and out of itself.
Comment: @MikeMiller Yes, that's what I thought - thanks for confirming that!

But then, by Thm 2 from the lecture, e.g. two entangled tori (i.e. manifolds of dimension 2) have an overflow $-1$ in an ambient $\mathbb{R}^5$ (i.e. $2 + 2 - 5 = -1$), and consequently must cross. This seems to be a contradiction, because, if they can be unknotted  in $\mathbb{R}^4$, then obviously they can be unknotted in $\mathbb{R}^5$ too. It seems that the Thm 2 is either stated incorrectly, or I'm misinterpreting it.
Comment: @axel22 I think I get the confusion. Mike gave you an example of a "2-dimensional knot" that can be unknotted in $\mathbb{R}^4$, but more or less by definition this means that it's not *entangled*-it's a 2-dimensional unknot. I think the theorem is fine. In general, moving a 2D surface across another 2D surface will use up 5 degrees of freedom, so there will generally be some collision points in $\mathbb{R}^5$.
Comment: There are actually not any 'really' knotted tori in $S^3$, in the sense that one of the sides of the torus is always a (knotted) solid torus; in particular any $T^2$ in $S^3$ is truly unknotted in $S^4$. Higher genus surfaces can have very knotty embeddings in $S^3$ (neither side extends to a handlebody), and sometimes they also don't unknot in $S^4$.
Comment: Here's a possibly silly question. What then plays the proper role of a knot in dimension 4?
Comment: Ok, I don't know much about topology, so sorry if maybe my question is not precise enough. When I said "Trefoil knot" I meant a 2-dimensional manifold, like this one: https://en.wikipedia.org/wiki/Trefoil_knot#/media/File:Blue_Trefoil_Knot.png

Isn't that a 2-dimensional knot?
Comment: In other words, to say that 1-dimensional knots can be unknotted in $\mathbb{R}^4$ seems consistent with his Theorem 2. What about 2-dimensional knots - can at least some of them be unknotted in $\mathbb{R}^4$?
Comment: I didn't watch the video. This doesn't make any sense to me.
Comment: Ok, thanks for explaining this. I understand now - the knot is 1-dimensional entity (in fact, it's defined like that here https://en.wikipedia.org/wiki/Knot_theory#Knot_equivalence). About the theorem, I think that it applies to planes, and not arbitrary surfaces, and that it should not have been used in that example to conclude that $\mathbb{R}^6$ is the smallest ambient for isotopy.
Comment: Thanks for the reference @MikeMiller ! I suspected it was a 2D surface, but wasn't sure.
Comment: There is the application of that theorem in Lecture 7 again. The lecturer claims that you need $\mathbb{R}^5$ to "remove" the circle from the surface of a torus without intersecting the torus with the circle. The argument is summarized in the 1.5 min of the video, starting here: https://youtu.be/AgUGxqeVFZE?t=1075 . But by all the arguments in this thread, $\mathbb{R}^4$ should be sufficient. Who is wrong here?


How to fetch all music apps name contains in device

Question: I have to fetch all music apps name contains in device (like google play,gaana,saavan) and has to show all name in my app. I search a lot but not able to find a solution.Please help me if anyone has an idea.
                        Is there any way to fetch downloaded music files or list from iTunes store?
Comment: iOS doesn't allow this. This is not what you have asked for but you can use share extension to see what all apps are supported by apps on the device. If you want to open a music file then using Share Extension iOS will show all the apps which can open this file.
Answer: iOS applications are installed in Sandboxed environment, meaning that they cannot do anything outside their own application. It may work on Jailbroken devices!
More details given in this link,


Convexity of Binomial Term

Question: I am reading a book on the probabilistic method, and the following claim was made:
$\dbinom{y}{n}$ is convex.
Why is this the case?
Comment: I think it's even convex if you take the log of it
Comment: can you prove it for me?
Comment: @Henry Concavity with respect to n is out of the question, by inspection for y=6 or by comparison with a normal density when y is large.
Comment: @Did: Fair enough - I will delete that comment
Answer: Hint:
Compare $\dfrac{\dbinom{y+1}{n} }{\dbinom{y}{n}}$ with $\dfrac{\dbinom{y}{n} }{\dbinom{y-1}{n}}$ for $y \gt n$
Comment: I admit that I don't see how this leads to a proof that the sequence is convex in y. But I think that considering the differences instead of the ratios, will work.

Convexity of Binomial Term


How to remove first line text from text-box?

Question: What wrong with my code as below:
Select Case chkSTC.Checked
        Case True
            txtCargoDescription.Text = Resources._Global.ContrSTC & vbNewLine & txtCargoDescription.Text

        Case False
            Dim b As String() = Split(txtCargoDescription.Text, vbNewLine)
            txtCargoDescription.Text = String.Join(vbNewLine, b, 1, b.Length - 1)
    End Select

As I refer to other reference,
Dim b As String() = Split(txtCargoDescription.Text, vbNewLine)
txtCargoDescription.Text = String.Join(vbNewLine, b, 1, b.Length - 1)

show that can remove the first line of multi-line from text-box, BUT it remove all text inside the text-box. Please help me to fix this.
Thank you in advanced :)
Answer: Try setting your text box to multiline=true
Answer: Its working for me
In C#.net
 string[] sep = new string[] {"\r\n"};
 string[] lines = TextBox1.Text.Split(sep, StringSplitOptions.RemoveEmptyEntries);
 TextBox1.Text = string.Join("\r\n", lines.Skip(1).ToList());

In vb.net
Dim sep() As String = New String() {""& vbCrLf}
Dim lines() As String = TextBox1.Text.Split(sep, StringSplitOptions.RemoveEmptyEntries)
TextBox1.Text = String.Join(""& vbCrLf, lines.Skip(1).ToList)

Comment: I have checked it by write code (Asp.net C#.net) and it works 100%
Comment: actually the condition was if user checked the box, then "Container STC:-" will appear, but if user unchecked, "Cotanainer STC:-" should be remove.
Comment: inside `{""}` do I need to put something?
Answer: It is works if I use
txtCargoDescription.Text = txtCargoDescription.Text.Replace(Resources._Global.ContrSTC, "").Trim()


CKFinder - Clicking 'send it to the server' when uploading an image does nothing

Question: I am trying to get CKFinder to work correctly. The file manager and related functionality is recognized.  When I click the little image in the toolbar to upload a photo the window comes up properly. I then select 'upload, browse (to select the file)' and then I click 'Send it to the server.'
At that point, nothing happens - the upload / file field disappears and greys out.
Nothing is actually uploaded, so, upload is not working.
Any thoughts as to why this might be happening?
Comment: EDIT - I am getting this error as well when I click the 'browse server' button "System Error: It was not possible to load the XML response from the web server. The server returned an empty response." maybe the issues are related?
Comment: Use IMCE instead of CKFinder, it's closer to the Drupal...
Comment: after tearing half my hair out for the past few hours, I am wondering if there is a better solution.  Currently, I am using CKEditor and CKFinder. SHould I keep CKEditor and use IMCE for images? or Should I abandon the CK series alltogether for another / better solution? What do you recommend
Comment: Did you check for Javascript errors in the console ?
Comment: yea, no JS errors at all to be had, nor does the Apache error log have any php or possibly other related errors. weird
Comment: IMCE is the same as CKFinder, but it hasn't troubles that came from CKFinder...
Answer: The answer to this, as inspired by Nikit's comment, was to not use CKFinder at all.
CKFinder / CKEditor combination has to be one of the most frustrating experiences in all of Drupal, and it is the one thing I dread on each project. I have no idea why it has to be so complicated.
I kept CKFinder and used IMCE as suggested. The recipe works great; no complicated configuration; and is a much better module, in my opinion, for managing user images and file content.  I would suggest trying it as well if you find CKE and CKF as frustrating as I do.
Answer: I was getting JS errors and PHP errors after following the README.txt "Installing CKFinder" instructions. The JS error was the following:

Failed to load resource: the server responded with a status of 500
  (Internal Server Error)
http://example.com/sites/all/modules/contrib/ckeditor/ckfinder/core/connector/php/connector.php?command=Init&type=Images&id=Full

The PHP errors was:

PHP Fatal error:  require_once() [function.require]:   Failed opening
  required '../../../../../includes/filemanager.config.php'
  (include_path='.:/opt/php/pear') in
  /var/www/example.com/htdocs/sites/all/modules/contrib/ckeditor/ckfinder/config.php
  on line 86, referer:
  http://example.com/sites/all/modules/contrib/ckeditor/ckfinder/ckfinder.html?Type=Images&id=Full&CKEditor=edit-body-und-0-value&CKEditorFuncNum=563&langCode=en

It was pretty obvious that I had incorrectly included the filemanager.config.php file. In my case, CKFinder is located under /sites/all/modules/contrib/ckeditor/ckfinder so I updated the require statement in /sites/all/modules/contrib/ckeditor/ckfinder/config.php (as indicated in the ckeditor module README.txt) to  read:
<code>require_once '../../../../includes/filemanager.config.php';
</code>
The filemanager.config.php is now properly included which fixed the issue.


Silent install of AVG 2013 Business updates

Question: Our company uses AVG 2013 Business Edition in a Windows environment, all Windows 7 Pro. At one of the off-site locations, there is only a Linux server available, and it's on its own network (the site, not the server).
At most of my other sites, I have a Windows workstation setup that is always on, and I have the AVG Admin Console installed for being the updates and program Proxy server for AVG. At the site I need help with, I am having issues with updates.
If I try updating through the AVG program on the users' computers, it always fails (cannot access the AVG site). I can browse the Internet just fine, and download the 105MB .bin updates manually. I can then manually install the .BIN update on each computer, but it requires my intervention on each system for an update.
I cannot select an update on a network drive, AVG seems to require it on a local hard drive. I am thinking of saving one copy to the server, then using the login script to copy the file to the client's local hard drive, then I'd like to run a command to install the update. My question is, how can I run the update via a command or batch file, without user intervention?
NOTE: The servers at each site is Debian, not Windows. My organization does not want to spend money on another tech machine, as this site has only 3 clients. It is far out of my way though, so I'd prefer to SSH to the server, download the file to a shared folder, and know that Windows is automatically installing updates.
Answer: As a user on Spiceworks pointed out, this is actually possible! This answer allows me to run a command to have AVG update itself:

<code>"C:\Program Files (x86)\AVG\AVG2013\avgmfapx.exe" /Appmode=UPDATE /source=folder /pri=2 /path="\\servername\binfile.bin"</code>

I'm just learning about the other switches that command takes in.


Forbidden 403 http request using deployment module

Question: When I use the deployment module on my local websites it works perfectly, I make a devlopment plan, add one or more endpoints, I select some nodes and then I deploy the plan and run Cron.
This way nodes that I selected are copied to my other sites in the multisite set-up.
When I use the exact some set-up for my live websites I get this error when executing the Cron:
Link to image: http://imageshack.com/a/img401/5973/bwju.png
This has to be something with the permissions when I look it up on the net but I cannot find a solution.
Link to module: https://drupal.org/project/deploy
Is there anyone that has tested this module and had the same issue and fixed it?
Or is there someone that can tell me what to fix to make it work?
Thanks in advance
Comment: Nobody? Deployment module is really handy why does nobody use it...
Answer: The answer to my own question:
Add this to your .htaccess file (I have put it at the top):
<code>#
# Apache/PHP/Drupal settings:
# Paste the code under this sentence
<Limit PUT>
    allow from all
</Limit>
</code>


Capistrano and Readline user input

Question: I have a script that prompts for user input via Readline.readline. I'd like to execute it remotely via Capistrano, but it seems like cap doesn't play nice with Readline. Is there any other way to prompt for user input in an executed script? I need to be able to execute the script outside of cap, so I can't make it a cap task and use ask.
Here's the script:
unless User.find_by(is_administrator: true)
  user_name = Readline.readline("Enter your name: ", true)
  user_email = Readline.readline("Enter your email: ", true)

  user = User.create!({ name: user_name, email: user_email, is_administrator: true })
end

Answer: Capistrano is not intended to run scripts that require interactive input. My recommendation would be to change your approach. For example, you could prompt for the information you need locally (i.e. with ask), and then use that information to generate a script that you upload and execute remotely.
That said, there is a low-level extension point in Capistrano that allows some possibility of interactivity. It will require you to run a lot of custom code, but there is some documentation on the subject:
https://github.com/capistrano/sshkit#interactive-commands

in some cases, you may want to programmatically drive interaction with a command and this can be achieved by specifying an :interaction_handler option when you execute, capture or test a command.

Capistrano and Readline user input


Integral when absolute inequality holds

Question:
Suppose that $f_1,f_2:[0,\infty) \rightarrow ℝ, f_1,f_2 \in \mathcal{R}$, $\lvert f_1(x) \rvert \leq f_2(x) $ for all $x \geq 0 $. Prove that $\int_0^\infty {f_1(x)\mathrm dx}$ converges if $\int_0^\infty {f_2(x)\mathrm dx}$ converges.

Here is my attempt:
Since $-f_2(x) \leq f_1(x) \leq f_2(x) $, $-\int_0^x {f_2(t)dt} \leq \int_0^x {f_1(t)dt} \leq \int_0^x {f_2(t)dt} $ for all $x \geq 0 $. Meanwhile, let $\int_0^\infty {f_2(x)dx}=L$ so that there exists some $N$ such that $x \geq N$ implies $\lvert \int_0^x {f_2(t)dt} - L \rvert < \epsilon$, which is equivalent to $ L - \epsilon < \int_0^x {f_2(t)\mathrm dt} < L + \epsilon $, for an arbitraily small $\epsilon > 0$. Then, $-L - \epsilon < \int_0^x {f_1(t)\mathrm dt} < L + \epsilon $.
Now this tells that $\int_0^x {f_1(t)\mathrm dt}$ is bounded, but not that its limit converges. How should I proceed?
Answer: $|\int_{x_1}^{x_2} f_1(x)dx| \leq \int_{x_1}^{x_2} f_2(x)dx \to 0$ as $x_2>x_1 \to \infty$. For any sequence $x_n \to \infty$ $(\int_{0}^{x_n} f_1(x)dx)$ is  Cauchy sequence , hence it has  a finite limit. I will let you check (using above inequality) that the limit does not depend on what sequence $(x_n)$ tending to $\infty$ you take.

Integral when absolute inequality holds


Convert string representation of list to list in Python

Question: I have a string that looks identical to a list, let's say:
'[万福广场西,凰花苑]'

I would like to convert it into something like this:
['万福广场西','凰花苑']

I used eval()  and  ast.literal_eval() but got error as following:
y=eval('[万福广场西,凰花苑]')

---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-117-0aadbead218c> in <module>()
----> 1 y=eval('[万福广场西,凰花苑]')

<string> in <module>()

NameError: name '万福广场西' is not defined

when using ast.literal_eval(),  I got this error ValueError: malformed node or string: <_ast.Name object at 0x000002A67FFA5CC0>
Comment: `print( '[万福广场西,凰花苑]'.strip("[]").split(",") )` ?
Comment: You got `malformed node or string` because it does NOT look *identical* to a list, it only look similar.
Comment: @Stephen Rauch ok, how can I convert this to actual list?
Comment: @ Rakesh  thanks for your answer
Answer: Try Something like
my_list = '[万福广场西,凰花苑]'[1:-1].split(",")

It will return you an list -- ['万福广场西', '凰花苑']
You can check it as -- type(my_list) #<class 'list'>
Answer: Use strip and split
>>> '[万福广场西,凰花苑]'.strip('[]').split(",")
['万福广场西', '凰花苑']

Answer: The content of your string isn't actually a valid list of literals because the literals are lacking the necessary quotes, so you can't parse it with eval() or ast.literal_eval().
Instead, you can use regular expression to parse the string into a list:
import re
print(re.findall(r'[^\[\],]+', '[万福广场西,凰花苑]'))

This outputs:
['万福广场西', '凰花苑']

Answer: eval() will consider the given string as python code and return the result. So as per your string, the python code will something like this [万福广场西,凰花苑] which means two variable 万福广场西 and 凰花苑 are in a list.
If you want it to be evaluated as a list of strings you need to bound both strings with double quotes (") such as
'["万福广场西","凰花苑"]'.
When you subject this string to eval(), the output would be,
['万福广场西', '凰花苑']

If you want this to happen dynamically, you need to use split and join functions like,
''.join(list('[万福广场西,凰花苑]')[1:-1]).split(',')

which first makes the list of strings given by
list('[万福广场西,凰花苑]')[1:-1] # O/P ['万', '福', '广', '场', '西', ',', '凰', '花', '苑']

then joins all the strings as
''.join(['万', '福', '广', '场', '西', ',', '凰', '花', '苑']) # O/P 万福广场西,凰花苑

and splits the string by comma (,) to create your desired output.
'万福广场西,凰花苑'.split(',') # O/P ['万福广场西', '凰花苑']

Hope you have got what you were searching for. Feel free to comment in case of any clarifications required.
Comment: @Sidhom Welcome!


running a mysql query inside a loop of another without a sync error

Question: If I have code like this (irrelevant things like initialising the connection and handle omitted):
MYSQL_RES *res;
MYSQL_ROW row;
mysql_query(mysql, "some select query");
res = mysql_use_result(mysql);
while (row = mysql_fetch_row(res)) {
    MYSQL_RES *res2;
    MYSQL_ROW row2;
    mysql_query(mysql, "some other select query using an id from the first");
    res2 = mysql_use_result(mysql);
    /* ... */
    mysql_free_result(res2);
}
mysql_free_result(res);

Whenever I run the second mysql_query (in the loop), I get the error
mysql: 2014: Commands out of sync; you can't run this command now

How can I run another select query while fetching rows from one select query?
Answer: I sent an email to the MySQL mailing list. Basically, to be able to do this, I need to have two independent MySQL connections. Thanks, Shawn Green (from Oracle).

The mysql object you are using for your connection can only have one active query or result on it at a time. To have two sets of results working, you need a second independent connection to the MySQL server


One IP, One Port, Multiple Servers

Question: I am looking for a solution to forward one public IP address and one specific port to different machines based on hostname (as of now, I need it only for HTTP).
The current setup is NAT on a commodity router (it only provide simple public port to private IP address / port forwarding). I can add a Windows Server 2008 R2 machine before the router if required, but prefer not to do so.
So ideally, I would like to have the current setup and the forwarding is done on one of the Windows Servers. Is it possible to do this?
Answer: Sounds like what you want is really name based virtual hosts.
http://httpd.apache.org/docs/2.2/mod/core.html#namevirtualhost
Comment: Yes! Except that I need to forward to different servers not just one.
Answer: Try using Apache's name based virtual hosts and mod_proxy to redirect it to another host.
<code><VirtualHost *:80>
        ServerName      www.example.com
        ProxyRequests Off
        <Proxy *>
                Order deny,allow
                Allow from all
        </Proxy>
        ProxyPreserveHost On
        ProxyPass / http://192.168.254.197/
        ProxyPassReverse / http://192.168.254.197/

</VirtualHost>
<VirtualHost *:80>
        ServerName      www.other_example.com
        ProxyRequests Off
        <Proxy *>
                Order deny,allow
                Allow from all
        </Proxy>
        ProxyPreserveHost On
        ProxyPass / http://192.168.254.198/
        ProxyPassReverse / http://192.168.254.198/

</VirtualHost>
</code>
The above will catch the example.com and other_example.com on your front facing IP address and then pass each of them off to a different IP address.
Answer: You can buy very expensive devices from Cisco, f5 and others which do this, or more simply you could setup an instance of squid cache to listen for incoming requests and then either rewrite the URL on squid or maintain local name/address mappings in your hosts file.
If you need to handle HTTPS, then run an instance of stunnel in front of the HTTP proxy to terminate the SSL.
Comment: BTW: you can run a custom Linux installation on a lot of commodity routers (and hence run stunnel and squid on the router). See also http://openwrt.org/

One IP, One Port, Multiple Servers


can we show change in frequency of a SIMULINK model using FFT

Question: i have a SIMULINK model. it is a PLL. now i want to see the changes in the Frequency which is the output of the PLL. So is there any way by which i can see the changes in Frequency. of the PLL. can FFT help me to show the changes in the Frequency?
Comment: I'm working in Simulink too but can't understand your question :( I Assume FFT - is a fast Fourier transformation? but what is PLL? And can you show some code or picture maybe? Or it's not necessary and  I just didn't get it?
Comment: Maybe https://en.wikipedia.org/wiki/Phase-locked_loop?
Answer: If you just want to see the frequency changes, then the output of the PLL can be used as an input to a, say, sine box or controlled voltage source.
Then I would use the scope box to plot the initial and final signals. Finaly,by just zooming in the waveforms you should be able to verify that your frequency has changed.
Please let me know If I got something wrong.
--Kostas


expand zoo timeline in R

Question: Hi I have a time series dataset contains a few data points in Aug and Sep.
How can I fill in the missing days with a default value easily, say 0 in this case:
What I am thinking right now to merge the dataset with a sequential time series for the timeline I like, then do na.fill to replace NAs with the default value I want.
This is what I have done:
# This is my data z1
z1 <- zoo(c(1,2,3,4,5), as.Date(c('2013-08-09', '2013-08-12', '2013-09-02', '2013-09-09', '2013-09-15')))

# This is the timeline I want
z2 <- zoo(0, seq(from=as.Date('2013-08-01'), to=as.Date('2013-09-30'), by="day"))

# This is my result
na.fill(merge(z1, z2)[,1], 0)

But I am wondering is there a function already existing to do what I want. Something like:
result <- foo_fill(z1, 0, start, end)

Answer: If you want to replace NAs with fixed specified values, I think merge is the way to go. You can make some simplifications though: you don't need the 'zero-column' in z2, and you can fill with zeros in the merge step:
# input as per question
z1 <- zoo(c(1,2,3,4,5),
        as.Date(c('2013-08-09', '2013-08-12', '2013-09-02', '2013-09-09', '2013-09-15')))
start <- as.Date('2013-08-01')
end <- as.Date('2013-09-30')

tt <- seq(start, end, by = "day")
merge(z1, zoo(, tt), fill = 0)

On the other hand, if you want to replace NAs by the last previous non-NA (na.locf), then the xout argument may be a way to specify which date range to use for extra- and interpolation, and you don't need merge. For example:
na.locf(z1, xout = tt)

expand zoo timeline in R


Reducing splitting field

Question: If we have splitting field:
$$L=\mathbb{Q}(\sqrt{2+i\sqrt{6}},\sqrt{2-i\sqrt{6}}) $$
we can multiply these two zeroes and get $\sqrt{10}$ so we have
$$L=\mathbb{Q}(\sqrt{2+i\sqrt{6}},\sqrt{10})$$
Can we reduce it a little more and write $\sqrt{10}=\sqrt{5}\sqrt{2}$ so $L = \mathbb{Q}(\sqrt{2+i\sqrt{6}},\sqrt{5})$?
I have one additional question here. Can we take $(\sqrt{2+i\sqrt{6}})^2$ and then reduce it like $L = \mathbb{Q}(\sqrt{2+i\sqrt{6}},i \sqrt{6})$?
Comment: Is it obvious that $\sqrt{2}\in L$?
Comment: No, I think it is not.
Answer: It is not obvious. In fact, I'd say that is false.
If it is true, you must show that $\sqrt 2\in \mathbb{Q}(\sqrt{2+i\sqrt{6}},\sqrt{5})$.
Comment: I agree, I tried and I can not show that. Maybe I'm making a mistake somewhere but I'm pretty sure it's not true. Thank You.
Comment: Can we take $\sqrt{2+i \sqrt{6}}^2$ and then get $L=\mathbb{Q}(\sqrt{2+i \sqrt{6}}, i \sqrt{6})$? It seems right but when I try to find extension degree of L over Q, I get 4 where it should be 8.

Reducing splitting field


Salt: Raise Error if file.replace did not find anything to replace

Question: Maybe I am blind, but I could not find a way to let the salt-ssh call fail, if file.replace did not replace a single line.
If the pattern I provide did not match, then I want to get noticed.
Example:
enable_foo:
  file.replace:
    - name: /etc/foo/foo.config
    - pattern: DisallowBar
    - repl: AllowBarUntilMidnight

Case1: DisallowBar found and replaced, gets replaced: OK
Case2: AllowBarUntilMidnight is already in the file: OK
Case3: DisallowBar and AllowBarUntilMidnight are not in the file: I want salt to fail.
Comment: out of sheer curiosity I asked how ansible would solve this: https://serverfault.com/a/950406/90324
Answer: Saltstack is a configuration management tool so when using states you define what you want, you normally don't bother to be warn when something is done or not.
So in your example I would say "you want replace pattern X by string Y" and that's it. Saltstack does the job to replace the pattern if it exists and do nothing if not.
Moreover, in configuration management, you generally want states to be 'idempotent'. It means successive executions must produce the same result. Wether you execute your state one time or 1000 times should be the same.
I'm not sure that what you want to do is really provided by saltstack.
update: of course you can do what you want with saltstack, but you may have to separate in two states: one to check current state and eventually fail (check failhard https://docs.saltstack.com/en/latest/ref/states/failhard.html), and another to replace
Comment: I like the Zen of Python #10: Errors should never pass silently. If there is a broken state, I want to get a error. About 'idempotent', that is case2 of the question.
Comment: This is not a broken state. This is a non-applied state which is quite different. Check https://docs.saltstack.com/en/latest/ref/states/failhard.html for what you want to do.
Comment: case3 is a broken state for me, and I want to get an error if the system is in this state. Yes, I could use a second state with failhard after the file.replace state. This would be a work-around.
Comment: I looked but didn't find anything so you may have to use a cmd.run or cmd.script with `grep`
Comment: out of sheer curiosity I asked how ansible would solve this: https://serverfault.com/a/950406/90324


Rspec error: undefined local variable or method `cookies' for #<RSpec in the model for Sign_in method

Question: I don't use any gem for authentication in my app...so my sign_in method looks like this
def sign_in(user)
 remember_token = User.new_remember_token
 cookies[:remember_token] = remember_token
 user.update_attribute(:remember_token, User.encrypt(remember_token))
 self.current_user = user
end

I have this under both app/helpers/session_helper.rb and spec/support/helpers/session_module.rb
I need to call sign_in(user) in my model specs... I get the error undefined local variable or method `cookies' for
Answer: The cookies hash is only available in RSpec's controller tests.  You can tell your specs to pretend that they're controller specs by adding type: :request to your context, like so:
describe 'something that requires cookies', type: :request do
   it { expect(cookies[:remember_token]).to be_nil } // now the variable is defined as nil.
end

That said, needing your models to know about signing in surprises me.  That kind of cross-scope testing usually belongs in a feature.
Answer: model spec don't setup a test request context. so you ain't got no cookies dude!
use stubs or mocks here.


Alterar objeto em outro método

Question: Oque há de errado com alterar um objeto, que foi passado para outro método ?, ex:
public void doSomething(User user){
    edit(user);
    //...
    EntityManager.persist(user);
}

public void edit(User user){
    //...
    user.setName("new name");
}

Em geral todos dizem que a forma abaixo seria a "mais correta"
public void doSomething(User user){
    User updatedUser = edit(user);
    //...
    EntityManager.persist(updatedUser);
}

public User edit(User user){
    //...
    user.setName("new name");
    return user;
}

Mas oque não entendo é porque retornar a mesma instância do objeto alterado ? Alguns dizem que isso é menos propenso a erros, porque na primeira forma você acaba perdendo o "rastro" de onde o objeto está sendo alterado. Sinceramente não esse argumento não me convenceu.
Existe alguma "boa prática" para esses casos, ou seria mesmo uma questão ideológica de desenvolvedor ?
Comment: Quem diz? Cite uma fonte disto.
Comment: @bigown Na verdade isso é algo que venho ouvindo de algumas pessoas durante minha carreira, e só hoje resolvi questionar com mais detalhes essa questao.
Comment: Sempre que alguém diz algo pergunte porque. Peça para a pessoa mostrar para você o motivo daquilo. Em muitos casos ela está apenas repetindo o que ela ouviu de outra pessoa que está fazendo a mesma coisa até que chega em alguém que inventou uma maluquice qualquer. Questione na hora quando alguém vomita uma regra para você.
Answer: Não é regra, você pode realizar alterações de um objeto passado pois ele é apenas um "ponteiro". Apenas tome cuidado nas bibliotecas e APIs, que você estiver usando.
Por exemplo suponha um projeto JPA/Hibernate, com o seguinte código:
 public void updateEmployee(Employee emp) {
    entityManager.merge(emp);
    emp.setLastAccessTime(new Date());
 }

A nova instância de new Date() será persistida no banco de dados quando o contexto dessa transação terminar?
Não será persistida! Porque o método object merge(object) retorna uma instância que está no contexto persistent e não no detached. Dessa forma, o objeto passado como parâmetro continua não conversando com o context persistence do JPA, mas somente o seu retorno. Assim para que o código persistisse a nova data seria necessário fazer uma pequena alteração no código.
 public void updateEmployee(Employee emp) {
    Employee empDB = entityManager.merge(emp);
    empDB.setLastAccessTime(new Date());
 }

Dessa forma quando a transação terminar a nova instância de Date será persistida.
Espero que tenha ajudado!

Alterar objeto em outro método


Custom layout just to override onMeasure()

Question: I want to use my custom layout that extends the LinearLayout class and overrides the onMeasure() method like this :
<com.myPackage.CustomLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        .....
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        .....
    </LinearLayout>

</com.myPackage.CustomLayout>

My custom layout :
public class CustomLayout extends LinearLayout {
    private static final double VIEW_ASPECT_RATIO = 2;
    private ViewAspectRatioMeasurer varm = new ViewAspectRatioMeasurer(
            VIEW_ASPECT_RATIO);

    public HomeLayout(Context context) {
        super(context);
    }

    public HomeLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        varm.measure(widthMeasureSpec, heightMeasureSpec);
        setMeasuredDimension(varm.getMeasuredWidth(), varm.getMeasuredHeight());
    }
}

The issue is that it doesn't display at all the child Layouts, so how do I get this work?
Thanks!
(Sorry for my bad english)
EDIT: I've used this class https://github.com/jesperborgstrup/buzzingandroid/blob/master/src/com/buzzingandroid/ui/ViewAspectRatioMeasurer.java
Answer: Error is you're using android:orientation="horizontal" for CustomLayout(which extends LinearLayout) and android:layout_width="match_parent" for your child LinearLayouts.
Try to change your layout to this:
<com.myPackage.CustomLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <LinearLayout
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        layout_weight="1" >
        .....
    </LinearLayout>

    <LinearLayout
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        layout_weight="1">
        .....
    </LinearLayout>

</com.myPackage.CustomLayout>

Edit: Also I don't see any reason using a subclass of LinearLayout if your CustomLayout's code is you've shared.
Comment: Thanks for your answer but it doesn't work. I just want to keep the same aspect ratio in any screen size.
Comment: Remove your onMeasure method and try. Problem should be on your ViewAspectRatioMeasurer class.
Comment: Ok thanks a lot ! Thanks to your notice about the onMeasure method, I found the problem : I've forgotten to call the method :

super.onMeasure(widthMeasureSpec, heightMeasureSpec);

So now, it's working very well. Thanks


Proving this function is an isomorphism

Question: Let $1\longrightarrow H\longrightarrow G\longrightarrow F\longrightarrow 1$ be a short exact sequence with $H$ abelian. Let $T=\{t_{\sigma}\}$ be a transversal of $H$ in $G$. Let also be $Z^{1}(F,H)$ the 1-cocycles defined as normalized cochains. Given $d\in Z^{1}(F,H)$ I want to show that the map:
$$\varphi(t_{\sigma}a):=t_{\sigma}d(\sigma)a$$
with $a\in H$ defines an isomorphism of $G$. If $F$ acts by conjugation then I know already how to prove it, but that'a an assumption which is nowehere else required.
Answer: 1-Cocycles are always defined with respect to some action, in this way the notation can be somewhat misleading. $Z^1(F,H)$ is really $Z^1(F,H,\tau)$ where $\tau : F \to \text{Aut}(H)$ is an action.
This is because the cocycle condition, which says
$$d(g_1 g_2) = d(g_1) + g_1 \cdot d(g_2) = d(g_1) + \tau(g_1)(d(g_2))$$
makes explicit use of the action $\tau$. There is no way to define a cocycle without mention of a chosen group action of $F$ on $H$.
What you are missing, I think, is that this action becomes conjugation in the group extension. When we write $1 \to H \to G \to F \to 1$, it is implicit that the group action of $F$ on $H$ we are considering is conjugation inside $G$.
If $t_\sigma H$ is identified with an element $\sigma \in F$, then we would expect
$$\sigma \cdot h = t_\sigma h t_\sigma^{-1}$$
Conversely, when we have two groups $F$ and $H$, and we want to find a $G$ such that
$1 \to H \to G \to F \to 1$ is exact, part of the data required in finding such a $G$ is a fixed action of $F$ on $H$, which will become the conjugation action in $G$.
This is all to say that you are perfectly able to assume that the action of $F$ on $H$ is conjugation. There is no other relevant action. If I have misunderstood your question, feel free to comment and clarify. I'll be happy to update my answer.

I hope this helps ^_^
Comment: It's part of the definition. If we are trying to "glue" $F$ and $H$ together into a group $G$, it is not enough to specify $F$ and $H$. We also need to specify the action that will correspond to conjugation in $G$. Sure you _could_ make $\tau$ be some arbitrary action, which is separate from the conjugation action in $G$, but there isn't a reason to. Just like when we talk about continuous functions on $\mathbb{R}$ we should _technically_ specify the topology we're working with, but nobody does because it's standard. We should _technically_ say that $\tau$ becomes conjugation, but nobody does.
Comment: May I ask you why the general action $\tau$ of $F$ on $H$ has to become the conjugation on $G$?

Proving this function is an isomorphism


SQL Efficiency on Date Range or Separate Tables

Question: I'm calculating historical amount from a table in years(ex. 2015-2016, 2014-2015, etc.) I would like to seek expertise if its more efficient to do it in one batch or  repeat the query multiple times filtered by the date required.
Thanks in advance!
OPTION 1:
select
    id,
    sum(case when year(getdate()) - year(txndate) between 5 and 6 then amt else 0 end) as amt_6_5,
    ...
    sum(case when year(getdate()) - year(txndate) between 0 and 1 then amt else 0 end) as amt_1_0,
from
    mytable
group by
    id

OPTION 2:
select
    id, sum(amt) as amt_6_5
from
    mytable
group by
    id
where
    year(getdate()) - year(txndate) between 5 and 6

...

select
    id, sum(amt) as amt_1_0
from
    mytable
group by
    id
where
    year(getdate()) - year(txndate) between 0 and 1

Comment: Well, you could just try both versions and see for your self... I'm betting on version 1.
Answer: 1.
Unless you have resources issues I would go with the CASE version.
Although it has no impact on the results, filtering on the requested period in the WHERE clause might have a significant performance advantage.
2. Your period definition creates overlapping.
select    id
         ,sum(case when year(getdate()) - year(txndate) = 6 then amt else 0 end) as amt_6
         -- ...
         ,sum(case when year(getdate()) - year(txndate) = 0 then amt else 0 end) as amt_0
where     txndate >= dateadd(year, datediff(year,0, getDate())-6, 0)
from      mytable
group by  id

Answer: This may be help you,
WITH CTE
AS
(
    SELECT  id,
            (CASE   WHEN year(getdate()) - year(txndate) BETWEEN 5 AND 6 THEN 'year_5-6'
                    WHEN year(getdate()) - year(txndate) BETWEEN 4 AND 5 THEN 'year_4-5'
                    ...
                    END)    AS my_year,
            amt
    FROM    mytable
)
SELECT  id,my_year,sum(amt)
FROM    CTE
GROUP BY id,my_year

Here, inside the CTE, just assigned a proper year_tag for each records (based on your conditions), after that select a summary for the CTE grouped by that year_tag.


Fluid dynamics - Form of fluid surface

Question: An ideal fluid is rotating under gravity g with a constant angular velocity about the z-axis, which is vertical, so that in the fixed Cartesian axes u(x,y,z,t)=(-wy,wx,0). Find the form of the fluid surface.
Comment: Can you add the specific system of equations being applied, or more details on the context? This is a mathematics site, the physics of the question are a better fit for physics.stackexchange.com, I think.
Comment: [I assume the fluid is in some kind of container?](http://en.wikipedia.org/wiki/Free_surface)
Comment: See too this [Physics thread](http://physics.stackexchange.com/questions/19880/rotating-fluid-under-gravity-fluid-dynamics-question) or directly Wikipedia's ['Bucket argument'](http://en.wikipedia.org/wiki/Bucket_argument).
Answer: Essentially, the surface of your fluid is orthogonal to the resultant force acting on the fluid. Since this is the sum of gravitation and the centrifugal force (when looked at from the rotating frame) it should not be too hard to compute the shape of the surface.
The centrifugal force is easily computed by taking the derivative of the speed $u$, namely
$$-a=-\frac{du}{dt}=-(-w\frac{dy}{dt},w\frac{dx}{dt},0)=-(-w^2x,-w^2y,0)=(w^2x,w^2y,0)$$
Add to that the effect of gravity $(0,0,-g)$ and you get that the gradient of the implicit equation of the surface ($f(x,y,z)=0$) should be propotional to
$$\nabla f(x,y,z) \sim (w^2x,w^2y,-g)$$
This leads to a set of partial differential equations that can be solved to give
$$f(x,y,z)=k\left(\frac{1}{2}w^2x^2 + \frac{1}{2}w^2y^2 - gz + c\right)$$
in which $k$ is some proportionality factor that does not really matter.
Thus, the equation of the surface is that of a paraboloid:
$$z= \frac{w^2}{2g}x^2 + \frac{w^2}{2g}y^2 + \kappa$$

Fluid dynamics - Form of fluid surface


What purpose does adjusting the violin bow tension serve?

Question: A violin bow has a screw that allows you to adjust the hairs' tension. Like a tuning peg so to speak.
When I just got mine, I didn't pay attention to it. I worked with the tuning pegs because I knew I would need to, but I didn't touch the violin screw because, well, I have no idea why should I.
Tutorials and such don't seem to talk much about it. All I understood from a quick read around is that it is kind of an early improvement to the bow. This suggests me that it really isn't very necessary in the first place.
I think I also heard that a "proper" tension level is when you can pass a finger through the gap, no more and no less.
Exactly what role does adjusting the violin bow tension play?
Answer: The screw plays several roles:

The hair can (and should) be loosened when not playing so that the bow is not constantly subjected to hair tension. It's the same reason some people recommend loosening guitar strings when storing a guitar for a longer period of time, except a guitar neck has the advantage of a stiff metal rod inside it, which the violin bow does not.
It allows hair tension to be adjusted to suit one's playing style, as well as certain techniques like spiccato (bouncing the bow off the strings). While guidelines like "the gap should be the width of a finger" (some also say a pencil) are well-known, they're not hard rules, as different players might prefer a different amount of tension.
It also allows hair tension to be adjusted in response to changes in air temperature and humidity, which affect both the hair and the wood of the bow, and thus the playability of the instrument.
Comment: Does low bow tension allow for playing chords easier?
Answer: It can certainly be adjusted for different playing styles and conditions as mentioned already, and this is definitely something to bear in mind.
However, the primary reason is really to preserve the condition of the bow when not in use, and is why you should always loosen your bow off when you're not using it. Constantly subjecting the wooden rod of the bow to tension will likely cause it to prematurely warp and twist, which is initially just a bit annoying but can eventually lead to uneven tension along the length of the bow and an uneven balance, making it incredibly hard to play and essentially rendering the bow a write-off. Not a great thing when you consider some bows easily stretch into the thousands of pounds range.
Yes, you could make the argument for loosening strings on instruments as well, but generally I'd argue against that, the instruments are designed to take the tension this way for extended periods. The wood on the bow is not, and generally being much thinner and deliberately more flexible than say a violin neck, is much more subject to abuse.


Infinitely nested radicals

Question: In a recent paper it was stated (and maybe proved) that we can solve any polynomial equation with nested radicals.
Here "nested radicals" means expression such as:
$$
\sqrt[n]{a+b\sqrt[n/p]{a+b\sqrt[n/p]{a+b \cdots}}}
$$
i.e. with infinite radicals nested each other.
This means that every algebraic number can be expressed by a sort of ''generalized radicals'' and, since every such number can also be expressed by a series, I've searched if there is some way to transform infinitely nested radicals into series.
Searching on the web I've find nothing interesting, so my question is:

there is some canonical way to transform an infinitely nested radical
  in a series?
Comment: A one minute glance at the paper didn't find any claim to solve "any polynomial equation". Where did you see that?
Comment: Abstract anf final statement pag 7
Comment: But also I'm re-reading the paper to see if the proof is correct. Anway the question has some sense
Comment: @EmilioNovati: The paper is interesting, but needs some refining. The general 5th deg is known to be solved in infinitely nested radicals. Bagis's similar result for the general 6th deg apparently is new. However, his results for 7th deg and higher _seem to be hand-waving_. His eqs 22-30 are problematic and he even mentions in a note about "conjectures". Some claims need to be clarified.
Comment: @Tito: I see. My word ''proved'' in OP may be too strong, so I've edited. But the reference was only a context for my question. Anyway i'm interesting about the possibility to transform an infinitely nested radicals in some kind of series.
Answer:
...canonical way to transform an infinitely nested radical in a series?

There is no such way in general. In fact, general non-periodic nested radicals allow no alternative ways to express them (except for trivial identity transformations, which still lead to a nested radical expression).
If we are talking about periodic nested radicals, connected to polynomial equations, such as in the OP, it might indeed be possible to express their limit as a series (if they converge). But as far as I know, there is no better way to do that, than to consider the original algebraic equation.
The theory of nested radicals still has a long way to grow. There is not much known about them, except for the convergence theorem. I suggest reading this article which gives a very good review on the topic of nested radicals and other such expressions.
Also, there are two papers by Dixon Jones, investigating a more general case of continued powers (which also incorporates infinite series and products, continued fractions, etc):
His papers can be found here: first and second.
Mathworld entry here provides other references and examples.

Infinitely nested radicals


I am getting an accuracy of 1.0 every time in neural network

Question: I am doing binary classification using multilayer perceptron with numpy and tensorflow.
input matrix is of shape = (9578,18)
labels has the shape = (9578,1)
Here's the code:
#preprocessing
input = np.loadtxt("input.csv", delimiter=",", ndmin=2).astype(np.float32)
labels = np.loadtxt("label.csv", delimiter=",", ndmin=2).astype(np.float32)

train_size = 0.9

train_cnt = floor(inp.shape[0] * train_size)
x_train = input[0:train_cnt]
y_train = labels[0:train_cnt]
x_test = input[train_cnt:]
y_test = labels[train_cnt:]

#defining parameters

learning_rate = 0.01
training_epochs = 100
batch_size = 50
n_classes = labels.shape[1]
n_samples = 9578
n_inputs = input.shape[1]
n_hidden_1 = 20
n_hidden_2 = 20

def multilayer_network(X,weights,biases,keep_prob):
'''
X: Placeholder for data inputs
weights: dictionary of weights
biases: dictionary of bias values

'''
#first hidden layer with sigmoid activation
# sigmoid(X*W+b)
layer_1 = tf.add(tf.matmul(X,weights['h1']),biases['h1'])
layer_1 = tf.nn.sigmoid(layer_1)
layer_1 = tf.nn.dropout(layer_1,keep_prob)

#second hidden layer
layer_2 = tf.add(tf.matmul(layer_1,weights['h2']),biases['h2'])
layer_2 = tf.nn.sigmoid(layer_2)
layer_2 = tf.nn.dropout(layer_2,keep_prob)

#output layer
out_layer = tf.matmul(layer_2,weights['out']) + biases['out']

return out_layer

#defining the weights and biases dictionary

 weights = {
'h1': tf.Variable(tf.random_normal([n_inputs,n_hidden_1])),
'h2': tf.Variable(tf.random_normal([n_hidden_1,n_hidden_2])),
'out': tf.Variable(tf.random_normal([n_hidden_2,n_classes]))
 }

 biases = {
'h1': tf.Variable(tf.random_normal([n_hidden_1])),
'h2': tf.Variable(tf.random_normal([n_hidden_2])),
'out': tf.Variable(tf.random_normal([n_classes]))
 }
keep_prob = tf.placeholder("float")

X = tf.placeholder(tf.float32,[None,n_inputs])
Y = tf.placeholder(tf.float32,[None,n_classes])

predictions = multilayer_network(X,weights,biases,keep_prob)

#cost function(loss) and optimizer function
cost = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=predictions,labels=Y))

optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost)

#running the session
init = tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init)

#for loop

for epoch in range(training_epochs):
    avg_cost = 0.0
    total_batch = int(len(x_train) / batch_size)
    x_batches = np.array_split(x_train, total_batch)
    y_batches = np.array_split(y_train, total_batch)
    for i in range(total_batch):
        batch_x, batch_y = x_batches[i], y_batches[i]
        _, c = sess.run([optimizer, cost],
                        feed_dict={
                            X: batch_x,
                            Y: batch_y,
                            keep_prob: 0.8
                        })
        avg_cost += c / total_batch

        print("Epoch:", '%04d' % (epoch+1), "cost=", \
            "{:.9f}".format(avg_cost))

print("Model has completed {} epochs of training".format(training_epochs))
correct_prediction = tf.equal(tf.argmax(predictions, 1), tf.argmax(Y, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))
print("Accuracy:", accuracy.eval({X: x_test, Y: y_test,keep_probs=1.0}))

After running my model for 100 epochs, the cost decreases after each epoch which means that the network is working okay, but the accuracy is coming out to be 1.0 everytime and I have no clue why as I am sort of a beginner when it comes to neural networks and how they function. So any help will be much appreciated. Thanks!
Edit:
I tried checking the predictions matrix after each epoch and I am getting all zeros in that, everytime. I used the following code in my for loop with epochs to check the predictions matrix:
    for epoch in range(training_epochs):
    avg_cost = 0.0
    total_batch = int(len(x_train) / batch_size)
    x_batches = np.array_split(x_train, total_batch)
    y_batches = np.array_split(y_train, total_batch)
    for i in range(total_batch):
        batch_x, batch_y = x_batches[i], y_batches[i]
        _, c,p = sess.run([optimizer, cost,predictions],
                        feed_dict={
                            X: batch_x,
                            Y: batch_y,
                            keep_prob: 0.8
                        })
        avg_cost += c / total_batch

    print("Epoch:", '%04d' % (epoch+1), "cost=", \
            "{:.9f}".format(avg_cost))
    y_pred = sess.run(tf.argmax(predictions, 1), feed_dict={X: x_test,keep_prob:1.0})
    y_true = sess.run(tf.argmax(y_test, 1))
    acc = sess.run(accuracy, feed_dict={X: x_test, Y: y_test,keep_prob:1.0})
    print('Accuracy:', acc)
    print ('---------------')
    print(y_pred, y_true)

print("Model has completed {} epochs of training".format(training_epochs))

Here's output of 1 epoch:
Epoch: 0001 cost= 0.543714217
Accuracy: 1.0
---------------
[0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] [0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]

Comment: I don't see where you split your data into a train and test set.  Without a withhold set of data for evaluation, your model might be memorizing the data
Comment: I just didn't post that part earlier, edited. Can you have a look now? @James
Comment: There doesn't seem much wrong with your code, maybe part of your dataframe got copied? Or you have only one label to predict? Or you just have an easy dataset to analyze? :)
Answer: You aren't calling sess.run on the predictions. That means that it is currently a variable representing the tensorflow graph, rather than the values predicted.
Replace your _, c = sess.run([optimizer, cost], ...) with _, c, p = sess.run([optimizer, cost, predictions], ...). Then do the correct_prediction calculations on the p values that you get. Similarly, the truth values are batch_y, since your Y variable is also a tensorflow graph object. As such, you're now going to be working in numpy variables, so the argmax call should be done with np instead of tf. I believe that should do the trick.
If you want to do it in tensorflow, move the correct prediction and accuracy computations up to where you compute cost, and change your sess.run line to: _, c, a = sess.run([optimizer, cost, accuracy], ...)
For some explanation as to why you were getting 100%, you had the line correct_prediction = tf.equal(tf.argmax(predictions, 1), tf.argmax(Y, 1)), where both predictions and Y are tensorflow graph variables. You can think of those as wrappers for where the values will be flowing through when you call sess.run(). So when you print the accuracy, you're comparing tensorflow graph operations to tensorflow graph operations, and I guess the backend treats them as always being equal.
EDIT: Sample code for the two different mentioned methods below. Not 100% sure it works since I can't test it easily (I don't have your data), but it should be something like this.
First method:
    _, c, p = sess.run([optimizer, cost, predictions], ...)
    .
    .
    .
correct_prediction = np.equal(np.argmax(p, axis=1), np.argmax(batch_y, axis=1))
accuracy = np.mean(correct_prediction)

Second method:
cost = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=predictions,labels=Y))
correct_prediction = tf.equal(tf.argmax(predictions, 1), tf.argmax(Y, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
.
.
.
    for i in range(total_batch):
        batch_x, batch_y = x_batches[i], y_batches[i]
        _, c, a = sess.run([optimizer, cost, accuracy],
                        feed_dict={
                            X: batch_x,
                            Y: batch_y,
                            keep_prob: 0.8
                        })
        print(a)

EDIT 2:
While the above information is still true, there's another problem as well. It doesn't make sense to use cross entropy and accuracy when there's only one class that you're predicting. If you call argmax on something of length 1, then you'll always get 0, since that's the only position that exists! Accuracy and cross entropy only make sense in the context of class-based predictions, where your truth values are a one-hot vector across the list of classes.
Comment: Thank you for the great answer. You are making a lot of sense but the shifting of accuracy to the part where cost is being calculated doesn't seem to be working, it still gives 100% accuracy. The first part is a bit unclear, I tried doing the _,c,p thing using np.equal and np.argmax but I am getting an AxisError. It's would be really helpful if you could clarify the first method a little. Thank you.
Comment: I am still getting the same accuracy, i.e., 1.0. I tried checking my predictions and truth matrix and i get all zeros in both of them so it makes sense why it's coming out to be 1. I checked my y_test matrix and it's not all zeros. Thanks anyway, I'll keep digging.
Comment: Oh yeah, that pointed out another problem. You're doing cross entropy on only one class! Basically, you're doing argmax on the 1st axis, which has length 1. So the position of the maximum is always going to be 0. Accuracy and cross entropy don't make sense in the context you're using it for, since you aren't trying to predict classes. I'd recommend, instead, using Mean Squared Error or something similar. Does this make sense? The answer above still holds true, though, regarding running the variables with sess.run() before being able to manipulate them.
Answer: In your code I see x_train and x_test, so it looks like you've split your dataset a training/testing set correct? It's important that these two sets are independent of each other... i.e. the instances in each set are unique from each other. It's possible that you have a dataset with many repeating instances, if so... then your random split of the test set probably is just a subset of the training set and you are overtraining.
One useful tool to debug is a plot of the learning curve. To do this, simply plot the accuracy of the training and test set after every training epoch. It can tell you a lot about the model: under-fitting, over-fitting, stagnant learning, etc.


The product of 2 independent markov chains

Question: Let $(X_n)_{n≥0}$ and $(Y_n)_{n≥0}$ be two independent Discrete-time Markov chains $\in Z$.
a) Define the process $Z_n = (X_n, Y_n)$ $\in Z^2$. Is $(Z_n)_{n≥0}$ a Markov chain?
b) Define the process $W_n = X_nY_n$ $\in Z$. Is $(W_n)_{n≥0}$ a Markov chain?
For a) I've got $$ P[Z_n=k | Z_{n-1}=z_{n-1}, Z_{n-2}=z_{n-2},...,Z_0=z_0] = P[Xn=k_x, Yn=k_y | X_{n-1}=z_{n-1_{x}}, Y_{n-1}=z_{n-1_{y}},..., X_{0}=z_{0_{x}}, Y_{0}=z_{0_{y}}] = \text{(due to the independence of {Xi} and {Yj} and Markov property for Xn and Yn}) = P[X_n=k_x | X_{n-1}=z_{n-1_{x}},Y_{n-1}=z_{n-1_{y}}]P[Y_n=k_y | Y_{n-1}=z_{n-1_{y}}, X_{n-1}=z_{n-1_{x}}] = P[Z_n=k|Z_{n-1}=z_{n-1}] $$ - so $(Z_n)$ is a Markov chain. Is my reasoning correct?
For b) I have no idea.
Comment: @whuber Just a simple product, probably I shouldn't have typed it
Comment: What operation on random variables does "$*$" signify in part (b)?
Comment: Thanks.  (Sometimes the star is used for a convolution and represents the *sum* of random variables.)
Comment: cross-posted https://math.stackexchange.com/questions/4317544/the-product-of-2-independent-markov-chains
Answer: For a, your answer looks fine.
For b, you need to think about possible factorization from the primes of XY.
Let's say XY = 12, for all pairs of X and Y whose product is 12, namely, 1 and 12, 2 and 6, 3 and 4, the process is still memoryless. This is the result in part a, stating all possible pairing retains memorylessness.
Comment: You mean the answer is yes? And to prove it i should use the following idea: let  {$a_i$, $b_i$} ($i \in 1,...,m$) be all ($m$) possible pairs of integers such that $a_ib_i=k$. Thus
$$ P[W_n=k | W_{n-1}=w_{n-1}, W_{n-2}=w_{n-2},...,W_0=w_0] = P[X_nY_n=k | X_{n-1}Y_{n-1} = w_{n-1},...,X_0Y_0=w_0] = P[(X_n=a_1, Y_n=b_1) U ... U (X_n=a_m, Y_n=b_m) | X_{n-1}Y_{n-1} = w_{n-1},...,X_0Y_0=w_0] = P[X_n=a_1, Y_n=b_1 | X_{n-1}Y_{n-1} = w_{n-1},...,X_0Y_0=w_0] + ... + P[X_n=a_m, Y_n=b_m | X_{n-1}Y_{n-1} = w_{n-1},...,X_0Y_0=w_0] $$
But what should I do next? How can i use that ${Z_n}$ is Markov?
Comment: I can do the same decomposition for $w_{n-1},...,w_0$ : $w_i = c_{i_j} d_{i_j}$ for $j \in 1,...,m_i$ and get something like
$$P[X_n=a_1, Y_n=b_1 | ((X_{n-1}=c_{{n-1}_1}, Y_{n-1} = d_{{n-1}_1}) U...U (X_{n-1}=c_{{n-1}_{m_{n-1}}}, Y_{n-1} = d_{{n-1}_{m_{n-1}}})), ((X_{n-2} = ...) U ... U (..)),..., ((X_0 = c_{0_1}, Y_0=d_{0_1}) U... U (X_0 = c_{0_{m_0}}, Y_0 = d_{0_{m_0}}))]$$ If I didn't have union in the conditional part it would be easy (I would just use the Markov property for $(X_n, Y_n)$, so how should I deal with these unions?


Why is my byte array displaying the wrong length?

Question: BigInteger number = new BigInteger("7316717653133062491922511967442657474235534919493496983520312774506326239578318016984801869478851843858615607891129494954595017379583319528532088055111254069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828064444866452387493035890729629049156044077239071381051585930796086670172427121883998797908792274921901699720888093776657273330010533678812202354218097512545405947522435258490771167055601360483958644670632441572215539753697817977846174064955149290862569321978468622482839722413756570560574902614079729686524145351004748216637048440319989000889524345065854122758866688116427171479924442928230863465674813919123162824586178664583591245665294765456828489128831426076900422421902267105562632111110937054421750694165896040807198403850962455444362981230987879927244284909188845801561660979191338754992005240636899125607176060588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450");
byte[] array = number.toByteArray();

System.out.println((int)array.length);

I was working on number 8 for project euler, where the length of number is supposed to be 1000, but whenever I run this program, I receive 416. Could someone please explain to me why this isn't working?
Comment: Because the textual representation of a number has absolutely nothing to do with the binary value.
Answer: one char doesn't mean one byte here, for example number 11 is 00001011 which can be represented by just 1 byte
Similarly in your case
7316717653133062491922511967442657474235534919493496983520312774506326239578318016984801869478851843858615607891129494954595017379583319528532088055111254069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828064444866452387493035890729629049156044077239071381051585930796086670172427121883998797908792274921901699720888093776657273330010533678812202354218097512545405947522435258490771167055601360483958644670632441572215539753697817977846174064955149290862569321978468622482839722413756570560574902614079729686524145351004748216637048440319989000889524345065854122758866688116427171479924442928230863465674813919123162824586178664583591245665294765456828489128831426076900422421902267105562632111110937054421750694165896040807198403850962455444362981230987879927244284909188845801561660979191338754992005240636899125607176060588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450

is in binary
1011001000110011100000101111011000010111001000110011110000001000000000010100100101011100100110100100001010111010001101011100100100011110110101101111001100110111101110101000011011011101011001010111001000000101110101100000100100010011010111010111100010100110000101010101101100000110100111000111001001011111001001010110110110111011010111100010111101001011010110111000110111111011011000110110110110110001110100001011010001101110110010011100010010000000011011100101110101100011110010010010110110001111101111101100010011000110001000111111001010111110001000111010000010000011110000111101011010011010100001011110001010000001001000101111110000110000011111110000010110100010110101100111011000000001100011100111000000000100100101110101000100010001010100101111001100110011000110001110101010100001010101011000111011010110010000101010100110010110111100011100011000001001011100111000001001101111111001101111011000111011110101101010001001000110100110010011110101001101110110000000010011100101011111110110101001101000011011111110001011001110111010010001110000010100111010001011101011111000111001000011010111111001000101010001101100001000111111011001010010101100000001001100111100011001010111111010011111100100101011011010000010100100101110000010101000110010011010001001100011101101111110001000001000011101011111111011010100010010101011111011101000010111011001000000001100011111101100111011001111111100100001100110111110110110000101101000101110101111000101101111010010101000000001110100111011001000011001100010001110001000010110110011000111001000110010100110111000010110110100110010100101111111000100101011001100111100111001011100000000100110110000110001001001111011110101100101010010010000111110101011111101010101101011001001010000011000110010010111101001000110001011111001111011101010111010110111111110101011010011011101000011010010110010110101001100100010110000000110101001100101010110110011000101011000111100011000100110010011101111011111111100101110000011111110000110010001100011111101011100110001001001010100101001100011110110110000101001111010101001011101000101011011011000010010000001000110001000100101000000110010000100101000101001101111010010011101010001110011001110000001011011001111100100110010101101011000101001111110011101101010001111000111101101110111001001111101001010000011001101000111110100000000100011101000101111101001111100101111101010000100011101100000110010010001001110010100101010101101000100111000001110100010011110110000100001111001001001010111101001111001100010101000110000101111100101110001110001000011001010001000001101111100010110001000111111010101110110100100111011100100010000011111100001100011001011110010111111100011111010010100100000111100110101011000010100011100100001000101011101110000011101010110100111101101110000110010011110101110110100011001101110111101010110100000010001011111110011000010111111111101101110011110010100101011100100111101000110100001011011011010101111100001101111010110011110111000000010101101000111000100101101010110010110110010100001000000110000110011100011000111101011010110011010000100000111000101101100111111101111110100110010010011001011001010110001110111011100110101010101011000110100100001000011101111011100111010001101101011111011111001010110111011101110000001110010011001101010000010110001100101101111011111011111000100010100001000011001100010101100010100100101011101111010

Now if you check how many byte it requires to represent this number

More generally you can check this by
N length of binary string can represent up to 2^N - 1 number
For length: 2 = (max binary string) 11 = 2^2 - 1 = 3 (in 10)
Comment: `toString().toCharacterArray()` and convert each character to `int`
Comment: @JigarJoshi +1 for the example and evidence. The reason behind it printing `415` instead of `416` is due to integer division FYI.
Comment: Is there any way I could change it into a integer array?
Answer: This is because the toByteArray saves the binary representation of the number, not a decimal one. You can think of each byte representing a single digit in base-256. That's why the space required for the representation is more than twice less than the number of decimal digits.
If you need to save each digit to a byte, convert your BigInteger to String: its length is going to equal the number of digits (plus one character for the minus character '-' if the number is negative).
Answer: I don't know precisely how BigInteger stores values, but my guess would be that rather than storing them as a string, with one byte per digit, it stores them as one long number, with log_2(n) bits being used to store the number n, and therefore ceiling(log_2(n) / 8) bytes being used.
Answer: Because a byte array is a number in base 256 (since every digit can have range 0-255 or 0x00-0xFF) while the input number is in base 10. When you convert your number into a byte array you obtain a number which is in a different base, hence has a different amount of digits.
To prove it you can apply the change of base of logarithms:
logA(C) = logB(C) / logB(A)
log10(C) = log256(C) / log256(10)
1000 ~= 416 / log256(10)
1000 ~= 416 / (log2(10)/log2(256))
1000 ~= 416 / (3.3219/8)
1000 ~= 416 / 0.4152
1000 * 0.4152 ~= 416
415.2 ~= 416


InsertBefore sort row in table

Question: I have table, and I need  order (sort) th columns by available indexes (only VanilaJS not jQuery). How I can do it ?
Please see examples http://jsfiddle.net/mcqueen/AXF2Y/3/.
Comment: Questions usually have a `?` in them, and don't simply list a requirement. Until you show what you've attempted, you're just another "gimme the codez" freeloader.
Comment: Sorry. I don't freeloader... I want understand how work native js...
Answer: I would do it like this:
<code>var positions = [1, 4, 2, 0, 5, 3],
    tr = document.getElementById('table-id').tHead.rows[0],
    cells = [].slice.call(tr.cells);

positions.forEach(function(pos, i) {
    tr.insertBefore(cells[pos], tr.cells[i]);
});
</code>
http://jsfiddle.net/ybr6E/
Helps to make an Array out of the NodeList since a NodeList updates as you change the DOM.

InsertBefore sort row in table


how to replace the content of NSMutablestring in objective c

Question: I am new in objective c. I want to replace the content of mutable string I am using code as
NSMutableString *myMutableStringObj = [myMutableStringObj stringByReplacingOccurrencesOfString:@" & " withString:@"And"];

But It Shows me warning
Incomparable pointer types assigning to NSMutableString * from NSString *
Any Suggestion about this. I am using MutableString.
Comment: buz stringByReplacingOccurrencesOfString returns NSString not  NSMutableString.
Answer: It tells you this function returns NSString *. If you want to clean that warning. Just do like this:
NSMutableString *myMutableStringObj = [[myMutableStringObj stringByReplacingOccurrencesOfString:@" & " withString:@"And"] mutableCopy];

Comment: It Shows me same Warning.
Comment: You completely misunderstand how mutable strings work. Use "replaceOccurencesOfString". You are creating two objects without any need to do so.
Answer: Read the documentation for NSString and NSMutableString. That doesn't only apply to you, but to anyone answering here so far. The answers on this thread have been absolutely depressing.
There are methods that can be used for NSString but also work with NSMutableString which create a new, immutable string based on a previous string. Typically methods starting with "stringBy..." will be creating a new string.
And there are methods, in the NSMutableString interface, which modify the contents of an existing NSMutableString. Like "replaceOccurencesOfString".
Read the documentation and pick what is right for you. A method starting with "stringBy" is not going to modify your mutable string, it's creating a new immutable one. To modify a string, use the methods from the NSMutableString interface. Fortunately the compiler tells you when you use the wrong method.
Answer: See the method signeture from NSString Class.
- (NSString *)stringByReplacingOccurrencesOfString:(NSString *)target
                                        withString:(NSString *)replacement

this method return NSString object.
So you need to convert result into mutalbe string or catch the result in NSString.
Comment: Or - maybe - what about using a method for _mutable_ strings?
Comment: @gnasher you can follow the documentation of the apple. It is very clear and can be understable with no efforts
Answer: plz use this code
 NSMutableString * str1 = [NSMutableString stringWithString:@"Hello Testing"];
    str1 = [[str1  stringByReplacingOccurrencesOfString:@"T" withString:@"B"] mutableCopy];
    NSLog(@"%@",str1);

Comment: You completely misunderstand how mutable strings work. Use "replaceOccurencesOfString". You are creating three objects when you only need to create one.
Comment: @gnasher729 can you explain where i am using three objects ?