Fret spacing for setar

Question: What is the formula for calculating the frets spacing on the setar?
It's not straightforward as the guitar because the Setar is based on the 17 tone modes of Persian scale: 256/243 27/25 9/8 32/27 243/200 81/64 4/3 25/18 36/25 3/2 128/81 81/50 27/16 16/9 729/400 243/128 2/1
where the ratios are not evenly spaced.
Thanks
Comment: You have answered your own question.  The spacing of the frets is defined by the intervals of your scale, with the height of the action reckoned in.
Comment: @ScottWallace Has the right idea - but you want to invert each ratio. So theoretically the first fret will be 243/256 * the scale length of the instrument from the bridge.
Comment: Which one of those ratios is D koron?
Comment: No, the fret for the note with ratio 27/25 would be (25/27) * 66 cm from the bridge. Alternatively, you can measure from the nut by subtracting the inverted ratio from 1, so that would be (2/27) * 66 cm away from the nut. This can easily be seen by considering that the fret for the note with ratio 2/1 should be 1/2 along the scale length, or 1/2 * 66 = 33 cm from the bridge and 33 cm from the nut.
Comment: Thanks for your reply. Can you provide also an example ? for example, whats is the distance from the bridge for the note D koron ? thanks
Comment: Thanks for your reply. Can you provide also an example ? for example, whats is the formula that gives the distance from the bridge for the note D koron for a scale length of 66 cm ? thanks in advance.
Comment: D koron correspond to this ratio:   27/25  (large limma)
Answer: The spacing of the frets is defined by the intervals of your scale, with the height of the action reckoned in. But you want to invert each ratio. So theoretically the first fret will be 243/256 * the scale length of the instrument from the bridge.
Example:
If the scale length of the instrument is 66 cm, the fret for the note with ratio 27/25 would be (25/27) * 66 = 61.11 cm from the bridge. Alternatively, you can measure from the nut by subtracting the inverted ratio from 1, so that would be (2/27) * 66 = 4.88 cm away from the nut. This can easily be seen by considering that the fret for the note with ratio 2/1 should be 1/2 along the scale length, or 1/2 * 66 = 33 cm from the bridge and 33 cm from the nut.
Note that these are the theoretical/ideal placements. As mentioned in the comments, you have to also consider the width of each fret, the thicknesses of the strings, and the height of the action if you want the best intonation. I believe a popular technique for luthiers is to start with the ideal calculations and mock up the fretboard. Then do some testing and adjusting and arrive at the precise positions for best intonation through experimentation. Then they make careful and detailed notes and templates about those positions to be able to create identical instruments more quickly.
Comment: @RomainL.I'm confused. Do you already have answers to your question from another source? If so it would make a big difference to tell us that up front and then explain why you're still wondering what the formula is.
Comment: @RomainL. I'm not an expert, professional, or any kind of luthier at all. I'm just good at math, which as you point out, isn't good enough to get it to sound right. I hope the right math can at least get you close and then you can adjust from there.
Comment: Indeed because these websites show completely different results
 Than the one you mentioned https://en.m.wikipedia.org/wiki/Setar.    https://ebraminio.github.io/extra/setar.html
Comment: If we apply the classical formula used for the guitar with the frequencies ratio of the setar we get close results as the results mentioned in these websites. I wondered the reasons of the significant gap between formula and these results.
Comment: Surely come from the instrument itself luckily the frets can be adjusted.
Comment: Yes but contrary to you I'm not an expert and definitely not a professional. And from my side I found that using only math doesn't give all the answer. Many thanks for your answers!

Fret spacing for setar


JSP - java.lang.IllegalArgumentException: Parameter value [11] did not match expected type [java.lang.Integer (n/a)]

Question: ALGUÉM SABE DIZER O QUE EU ESTOU FAZENDO DE ERRADO?
public List<Usuario> obterusuario(String user){

    Consultar consulta = new Consultar ();
    EntityManager obconsulta = consulta.getEntityManager();

    System.out.println("passou"+user);

    String query = "SELECT U FROM CADASTRO_USUARIO U WHERE U.USR_CODIGO=:user";

    TypedQuery<Usuario> tq = obconsulta.createQuery(query,Usuario.class);
    tq.setParameter("user", user);

    return tq.getResultList( );
}

Answer: No banco de dados, o campo ID está como outro formato que não é String, (varchar ou longtext).
Seu user está sendo passado como String.
A solução seria, ou você troca o argumento do método para Integer/int, ou você faz um parse com a classe Integer:
Integer realUser;
try {
  realUser = Integer.parseInt(user);
catch(NumberFormatException nfe) {
  //o valor passado não é um número
  realUser = null;
}

Por fim, na instrução tq.setParameter você vai passar a variável realUser ao invés da user.
tq.setParameter("user", realUser);

Espero ter ajudado.


$\partial_xF+F\partial_yF=0$ implies that $F$=const

Question: Let $F\in \mathit{C}^2(\mathbb{R^2},\mathbb{R})$ and $$\partial_xF+F\partial_yF=0.$$
How do I prove that $F$ is a constant on $\mathbb{R^2}$? I am trying to restrict $F$ to a line passing through the origin and prove that the values of $F$ on the line equal $F(0,0)$, but failed.
Comment: The solutions to Burger's equation are not all constant, your claim is not specific enough. Or perhaps it is specific in that the function is $C^2$ on all of $\Bbb R^2$, then you need to cleverly use that no characteristic curves can ever intersect, neither in positive nor in negative time.
Comment: @Lutz Lehmann Can you give a counterexample?
Comment: The first sentence was to your attempt to solve the problem by local considerations, as local twice differentiable solutions exist. You need to make global arguments from the start, essentially you have to show that the characteristic curves, which are lines, have to be all parallel. As slope is here connected to value, the claim follows.
Answer: Claim: If $F(x_0,y_0)=c$, then $F(x,y)=c$ for all $(x,y)$ satisfying $y=y_0+c(x-x_0)$. Indeed, $$\frac d{dx}F(x,y_0+c(x-x_0))=\partial_xF+c\partial_yF=(c-F)\partial_yF.$$ Since $\partial_yF$ is locally bounded, we therefore have (after restricting to a compact set $K$) $$|\frac d{dx}(c-F)|\leq C|c-F|$$ where we are saying $C$ is $\sup_K|\partial_yF|$. Then by Gronwall's inequality, we conclude that $F=c$ on the part of this line contained in $K$. Picking a sequence of compact sets that exhaust the plane, we conclude that $F=c$ on the whole line.
Now suppose there are two points $(x_0,y_0)$ and $(x_1,y_1)$ such that $F(x_0,y_0)=c_0$, $F(x_1,y_1)=c_1$. Then by the above claim, $F=c_0$ on a line of slope $c_0$ and $F=c_1$ on a line of slope $c_1$. If $c_0\neq c_1$ these lines would intersect and produce a contradiction, so we must have $c_0=c_1$.
It seems we have only assumed $F\in C^1(\mathbb R^2)$.


Negative binomial or Poisson

Question: Using MASS::glm.nb (R) I am having problems of convergence with certain dataset, and it seems theta goes very high, resulting in NaNs "In sqrt(1/i)" during the fit. I am trying to understand this and have run some tests to see if NB is a significant better fit than Poisson, and it isn't (p~0.3). My question: is it still appropriate to use a NB when it isn't significantly better than a Poisson, keeping in mind that in this case is better to be conservative? Many thanks!
Also, if anyone knows how to fix those sqrt(1/i) errors that would be great. I can avoid them if I remove the covariates from the model. (I guess the covariates are explaining all of the dispersion?)
Comment: What exactly are your data and the model? Why did you initially choose negative binomial distribution?
Answer: If the conditional (upon all the regressors) variance is less than or equal to the conditional mean, the NB will have a hard or impossible time being fit (which one depends on the algorithm), since there is no parameterization of the NB distribution for which this is the case.  The Poisson, however, relies only upon the conditional mean and consequently can be fit regardless of whether the conditional variance equals the conditional mean (the variance-mean relationship of the Poisson distribution.)  The error you are seeing is characteristic of this effect.  This conclusion is reinforced by the fact that it goes away when you remove the covariates; as you suspect, the covariates appear to be explaining enough of the dispersion to drive the conditional variance below the conditional mean.
Consequently, if you are having problems of this sort fitting the NB distribution, fitting the Poisson is perfectly acceptable.  After all, it is the limit of the negative binomial as the variance-mean ratio approaches one!
Comment: Many thanks for the very clear explanation!

Negative binomial or Poisson


Let $A$ be an invertible matrix. Find a singular value decomposition for $A^*$ and $A^{-1}$.

Question:
Let $A$ be an invertible matrix, and let $A = W\Sigma V^*$ be its singular value decomposition. Find a singular value decomposition for $A^*$ and $A^{-1}$.

If we take the conjugate transpose, we get $A^*=V\Sigma^* W^*=V\Sigma W^*$ since $\Sigma$ only has real diagonal entries. But how do we know the singular values of $A$ are the singular values of $A^*$?
Similarly, we have $A^{-1}=V\Sigma^{-1}W^*$. But how do we know the singular values of $A$ are the singular values of $A^{-1}$?
Comment: You need to characterise the SVD inductively in terms of norms and suitable subspaces. However, **any** time you have $A= U \Sigma V^*$ with $\Sigma$ diagonal with non negative entries then you have a SVD.
Comment: It is worth studying the subspace characterisation. To some degree, this is the whole point of the SVD.
Comment: What do you mean by subspace characterization?
Comment: The first singular value is given by $\|A\|$ and any vector for which $\|Av\| = \sigma_1 \|v\|$ is a corresponding singular vector. The next singular value is the norm of $A$ restricted to the orthogonal complement of $v$, etc, etc. See Golub & Van Loan's "Matrix Computations" for more details.
Comment: Here is a nice writeup by a frequent MSE contributor: https://qchu.wordpress.com/2017/03/13/singular-value-decomposition/
Comment: Actually, this is the characterisation I was really looking for: https://en.wikipedia.org/wiki/Min-max_theorem#Min-max_principle_for_singular_values
Answer: From the definition of singular-value decomposition, singular values are the diagonal entries $\sigma_i$ in $\Sigma$.

You already gave a decomposition $A^*=V\Sigma W^*$. Since $A$ and $A^*$ have the same $\Sigma$ in their decompositions, they have the same singular values.
You also gave a decomposition $A^{-1}=V\Sigma^{-1}W^*$. So if $\sigma_i$ is a singular value of $A$, then $1/\sigma_i$ is the singular value of $A^{-1}$. Don't worry about $\sigma_i=0$. It does not happen because $A$ is non-singular.
Comment: Because $V$ and $W$ are unitary, and $\Sigma$ is a diagonal matrix with nonnegative real entries.
Comment: We can write $A^*=V\Sigma W^*$, how do we know this is indeed a singular value decomposition?
Comment: Don't we need to check that $W$ is the matrix of eigenvectors of $AA^*$?
Comment: @AlJebr Any SVD satisfies that property, so you don't worry about that. For example, if $A=W\Sigma V^*$ is a SVD, then $A^*=V\Sigma W^*$ and so the diagonalization $AA^*=W\Sigma^2W^*$ gives the information of eigenvalues and eigenvectors of $AA^*$ what you wanted to check.


Insert automatically hyperlink in Slides with Google Apps Script

Question: I am currently working on the automatic creation of a Google Slides from a Sheets file. I have created a template which, thanks to a script, is duplicated and filled with data present in the Sheets.
Here is what the template looks like :

Everything works fine except for one column. Indeed, I would like to be able to add a hyperlink in the last part and I am blocked on this subject. I have searched for information on the internet but I can't adapt it to my code.
Indeed, my code replaces all my shapes with hyperlinks when I only want one per slide.
If anyone can help me with that, I would appreciate it very much.
This is my code :
function createSlides() {
    // Déclaration des constantes et des variables
    const classeur = SpreadsheetApp.getActiveSpreadsheet();
    const feuille = classeur.getSheetByName("Importrange");
    const feuilleReport = classeur.getSheetByName("Report des données à diffuser");
    var templateSlide, copy, nomSlide, slideFile, slides, gabaritSlide;
    var tEssais = [], tDonneesReportees = [], nbDonneesReportees = 0;
    var lastRow = 0;

    // Récupération du gabarit
    templateSlide = DriveApp.getFileById("1gYf8X40TePUIJJVR32cSPcLGTxRZ__t9ekeuuv27xgA");

    // Création d'une copie et ajout du nom au Slides
    copy = templateSlide.makeCopy();
    nomSlide = (Utilities.formatDate(new Date(),"GMT+1","dd/MM/yyyy")) + " BILAN ESSAIS";
    copy.setName(nomSlide);

    // Ouverture du Slides, récupération des diapositives qui sont à l'intérieur et attribution de la diapositive de référence
    slideFile = SlidesApp.openById(copy.getId());
    slides = slideFile.getSlides();
    gabaritSlide = slides[1];

    // Récupération de l'ensemble des données de l'onglet "Importrange"
    tEssais = feuille.getRange("A2:H").getValues();

    // Récupération du nombre de lignes reportées
    tDonneesReportees = feuilleReport.getRange("A2:H").getValues().filter(d =>d[0] !== '');
    nbDonneesReportees = tDonneesReportees.length;

    // Suppression des anciens essais
    feuilleReport.deleteRows(1,nbDonneesReportees + 1);

    // Pour chaque ligne du tableau tEssais
    for (let i = 0; i < tEssais.length; i ++){
      // Si l'essai est à diffuser
      if (tEssais[i][7]){
        // La reporter dans l'onglet "Report des données à diffuser"
        feuilleReport.appendRow(tEssais[i]);
      }
    }

    // Récupération de la dernière ligne de l'onglet "Report des données à diffuser"
    lastRow = feuilleReport.getDataRange().getValues().length;

    // Tri des données par site et secteur
    feuilleReport.getRange("B1:B"+ (lastRow)).sort({column: 2, ascending: false});
    feuilleReport.getRange("A1:A"+ (lastRow)).sort({column: 1, ascending: false});

    // Récupération des nouveaux essais à reporter dans le Slides
    tDonneesReportees = feuilleReport.getDataRange().getValues().filter(d =>d[0] !== '');

    // Récupération des nouveaux essais à reporter dans le Slides (après ajout si ligne pair ou impair)
    tDonneesReportees = feuilleReport.getDataRange().getValues().filter(d =>d[0] !== '');

    // Pour chaque essai, création d'un slide et report des données
    for (let i = 0; i < tDonneesReportees.length; i ++){
      let slide = gabaritSlide.duplicate();
      slide.replaceAllText("{{Site}}", tDonneesReportees[i][0]);
      slide.replaceAllText("{{Secteur}}", tDonneesReportees[i][1]);
      slide.replaceAllText("{{Nom}}", tDonneesReportees[i][2]);
      slide.replaceAllText("{{Contexte}}", tDonneesReportees[i][3]);
      slide.replaceAllText("{{Objectifs}}", tDonneesReportees[i][4]);
      slide.replaceAllText("{{Statut}}", tDonneesReportees[i][5]);
      slide.replaceAllText("{{Lien}}", "LienURL");

      var elements = slide.getPageElements();
      for (let j = 0; j < elements.length; j ++){
        var element = elements[j];
        if(element.getPageElementType() == "SHAPE" && element.asShape().getText().find("LienURL")){
          var text = element.asShape().getText();
          text.appendText("Lien");
          text.getTextStyle().setLinkUrl("www.google.com")
        }
      }
    };

    // Suppression de la diapositive qui servait de gabarit
    gabaritSlide.remove();
  }

For me, the problem comes from this part:
if(element.getPageElementType() == "SHAPE" && element.asShape().getText().find("LienURL")){

It can't find the LienURL element. But I don't see how else to do it. Here is what I get as a result :

I tried an other solution that i saw in this post. But I had an error with my objectID. This is the part of code i tried :
  for (let i = 0; i < tDonneesReportees.length; i ++){
     let slide = gabaritSlide.duplicate();
     slide.replaceAllText("{{Site}}", tDonneesReportees[i][0]);
     slide.replaceAllText("{{Secteur}}", tDonneesReportees[i][1]);
     slide.replaceAllText("{{Nom}}", tDonneesReportees[i][2]);
     slide.replaceAllText("{{Contexte}}", tDonneesReportees[i][3]);
     slide.replaceAllText("{{Objectifs}}", tDonneesReportees[i][4]);
     slide.replaceAllText("{{Statut}}", tDonneesReportees[i][5]);
     slide.replaceAllText("{{Lien}}", "Lien");
     var elements = slide.getPageElements();
     var requete = [];
     for (let j = 0; j < elements.length; j ++){
       var element = elements[j];
       if (element.getPageElementType() == "SHAPE"){
         var text = element.asShape().getText().find("Lien");
         if (text.length > 0){
           var idObject = element.getObjectId();
           for (let k = 0; k < text.length; k ++){
             var start = text[k].getStartIndex();
             var end = text[k].getEndIndex();
             requete.push({
               updateTextStyle : {
                 objectId : idObject,
                 textRange : {
                   startIndex : start,
                   endIndex : end,
                   type : "FIXED_RANGE"
                 },
                 fields : 'link',
                 style : {
                   link : {
                     url : "www.google.com"
                   }
                 }
               }
             });
             Slides.Presentations.batchUpdate({'requests':requete},copy.getId());
           }
         }
       }
     }
   };

And i obtain this error :

Thank you in advance for your help and sorry for my english...
------------ EDIT ------------
This is a minimal reproducible example for a better understanding :
function createSlides() {
   const ss = SpreadsheetApp.getActiveSpreadsheet();
   const sheet = ss.getSheetByName("Values");

   // Get Template
   var templateSlide = DriveApp.getFileById("13frZFGs3agqpLnEdXFEcsRadolzZsxeYwgzy2fqOLiw");

   // Create copy of template
   var copy = templateSlide.makeCopy();
   var nameSlide = (Utilities.formatDate(new Date(),"GMT+1","dd/MM/yyyy")) + " - SLIDE";
   copy.setName(nameSlide);

   // Open Slide, get all slide and choose what is the template
   var slideFile = SlidesApp.openById(copy.getId());
   var slides = slideFile.getSlides();
   var template = slides[1];

   // Get values of Sheet
   var tValues = sheet.getRange("A2:D").getValues().filter(d =>d[0] !== '');

   // For each row, create slide
   for (let i = 0; i < tValues.length; i ++){
     // Duplicate template
     let slide = template.duplicate();
     // Add Values
     slide.replaceAllText("{{Site}}", tValues[i][0]);
     slide.replaceAllText("{{Project}}", tValues[i][1]);
     slide.replaceAllText("{{Link}}", "Link");
     // Get all of elements in page
     var elements = slide.getPageElements();
     var request = [];
     for (let j = 0; j < elements.length; j ++){
       var element = elements[j];
       if (element.getPageElementType() == "SHAPE"){
         var text = element.asShape().getText().find("Link");
         if (text.length > 0){
           var idObject = element.getObjectId();
           for (let k = 0; k < text.length; k ++){
             var start = text[k].getStartIndex();
             var end = text[k].getEndIndex();
             request.push({
               updateTextStyle : {
                 objectId : idObject,
                 textRange : {
                   startIndex : start,
                   endIndex : end,
                   type : "FIXED_RANGE"
                 },
                 fields : 'link',
                 style : {
                   link : {
                     url : tValues[i][1]
                   }
                 }
               }
             });
             Slides.Presentations.batchUpdate({'requests':request},copy.getId());
           }
         }
       }
     }
   };
 }

This is my Sheets and this is my template's Slide.
Comment: You are describing a mail merge process. You may want to try the free [AutoCrat](https://cloudlab.newvisions.org/autocrat) add-on instead of writing your own code. AutoCrat lets you use a Google Slides file as template. Use the **Single document** option.
Comment: Thank you for your answer but my company doesn't accept add-ons by security...
Comment: Hi, can you provide a [minimal reproducible example](https://stackoverflow.com/help/minimal-reproducible-example), including a copy of the template you are working on?
Comment: Of course lamblichus, I edited my post. You can find in the bottom the minimal repoducible example and the links of my Sheets and template's Slide
Answer: I believe your goal is as follows.

You want to set the hyperlinks retrieved from the column "C" of the Spreadsheet to {{Link}}.

Modification points:

In your template and script, after Link : {{Link}} was converted, you are trying to set the hyperlink. In this case, how about replacing and setting both text and hyperlink by using {{Link}} as the search text? I thought that by this, your script might be able to be simply a little.
In your Spreadsheet, it seems that the hyperlinks are put in the column "C". But, you are using tValues[i][1]. In this case, I thought that it was tValues[i][2].

When these points are reflected in your script, how about the following modification?
In this modification, your bottom script is modified.
From:
for (let i = 0; i < tValues.length; i ++){
     // Duplicate template
     let slide = template.duplicate();
     // Add Values
     slide.replaceAllText("{{Site}}", tValues[i][0]);
     slide.replaceAllText("{{Project}}", tValues[i][1]);
     slide.replaceAllText("{{Link}}", "Link");
     // Get all of elements in page
     var elements = slide.getPageElements();
     var request = [];
     for (let j = 0; j < elements.length; j ++){
       var element = elements[j];
       if (element.getPageElementType() == "SHAPE"){
         var text = element.asShape().getText().find("Link");
         if (text.length > 0){
           var idObject = element.getObjectId();
           for (let k = 0; k < text.length; k ++){
             var start = text[k].getStartIndex();
             var end = text[k].getEndIndex();
             request.push({
               updateTextStyle : {
                 objectId : idObject,
                 textRange : {
                   startIndex : start,
                   endIndex : end,
                   type : "FIXED_RANGE"
                 },
                 fields : 'link',
                 style : {
                   link : {
                     url : tValues[i][1]
                   }
                 }
               }
             });
             Slides.Presentations.batchUpdate({'requests':request},copy.getId());
           }
         }
       }
     }
   };

To:
for (let i = 0; i < tValues.length; i++) {
  let slide = template.duplicate();
  slide.replaceAllText("{{Site}}", tValues[i][0]);
  slide.replaceAllText("{{Project}}", tValues[i][1]);
  slide.getShapes().some(s => {
    var t = s.getText().find("\\{\\{Link\\}\\}");
    if (t.length == 1) {
      t[0].setText("Link").getTextStyle().setLinkUrl(tValues[i][2]);
      return true;
    }
    return false;
  });
}

Note:

When I tested this modified script using your provided sample Spreadsheet and Slides, I confirmed that the script worked. When you change your Spreadsheet and Slides, the script might not be able to be used. Please be careful about this.

Reference:

getTextStyle()
Comment: Sorry for my late reply. It works perfectly. Thank you very much Tanaike !!!!
Comment: @devMethodes Thank you for replying and testing it. I'm glad your issue was resolved. Thank you, too.


What is the regex for a URL like this?

Question: I don't really know regex, but would like a quick solution to search and replace links. I want to use the search regex wordpress plugin to remove links in my post. How do I format the regex to a link like this:
http://website.com/index.php?id=934&title=item name

edit: the numbers in the id and the item name varies
Thank you in advance!
Comment: Well, the regex `/http://website\.com/index\.php\?id=934&title=item name/` would certainly work, but I suspect you want to match other URLs that are similar. If that's correct, you really need to specify what parts are allowed to vary.
Comment: Wow that is a quick reply. The numbers in the id and the item name varies. Thank you for your help!
Answer: Try this one out: http://regexr.com?2vjq6
Depending on whether or not you need whitespace in your "title" parameter, the regex I provided may need to be altered. Best practice would be to not have whitespace in your URLs (use URL encoding instead, where a space = %20).
http://website.com/index.php\?id=[0-9]*&title=[a-zA-Z0-9\-]*

Comment: I'm getting Invalid regular expression: Delimiter must not be alphanumeric or backslash
Comment: @user1122581 - in your own code or from the link I posted? The link I posted is working fine for me.
Comment: @user1122581 - here's a slightly updated version which escapes all the reserved characters in the regex: http://regexr.com?2vjq6.
Comment: Thanks. I have whitespace in the item name, so it only gets the first word and not the second word though
Comment: @user1122581 - If you always have two words in your item name, you can use http://regexr.com?2vjq9. Otherwise, it's going to be very difficult (how will you distinguish between words in your item name and words that appear after it?)
Answer: Try this pattern
(http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?

What is the regex for a URL like this?


Some errors when I save my content

Question: I have some errors when I try to validate my content, I add a lot a modules at the same time, and I don't know witch module causes this error. I uninstalled some of them without success, Is it some explanation in the following errors for the specialists you are?
<code>Notice : Undefined property: stdClass::$is_new dans node_save() (ligne 1108 dans /var/www/V1/modules/node/node.module).

Notice : Undefined property: stdClass::$is_new dans node_save() (ligne 1134 dans /var/www/V1/modules/node/node.module).

Notice : Undefined property: stdClass::$is_new dans node_save() (ligne 1140 dans /var/www/V1/modules/node/node.module).

PDOException : SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'nid' cannot be null: INSERT INTO {location_instance} (nid, vid, uid, genid, lid) VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2, :db_insert_placeholder_3, :db_insert_placeholder_4); Array ( [:db_insert_placeholder_0] => [:db_insert_placeholder_1] => [:db_insert_placeholder_2] => 0 [:db_insert_placeholder_3] => cck:field_endroit: [:db_insert_placeholder_4] => 9 ) dans location_save_locations() (ligne 1132 dans /var/www/V1/modules/location/location.module).
</code>
Answer: The error is related to the location module. Uninstalling that module will remove the errors.

Some errors when I save my content


Accessing a server with wrong IP out of segment range

Question: I have run into a similar problem as in this question about a wrong IP in LAN. However, the standard addr alias trick on the NIC did not help. I have no direct access to the server console, I might get physical access in a week or more if I'm lucky, but I hope I can find a faster way.
I can arping the (Linux) server on the address 10.0.0.1 from a server (Linux, with IP $MY_IP) on (supposedly) the same L2 segment and it replies with the $TARGET_MAC which is the correct and expected MAC for that server
root@host:~# arping -c 3 -I $IFACE 10.0.0.1
ARPING 10.0.0.1 from $MY_IP $IFACE
Unicast reply from 10.0.0.1 [$TARGET_MAC]  0.746ms
Unicast reply from 10.0.0.1 [$TARGET_MAC]  0.796ms
Unicast reply from 10.0.0.1 [$TARGET_MAC]  0.807ms
Sent 3 probes (1 broadcast(s))
Received 3 response(s)

I have hidden my IPs and MACs as these machines are publicly accessible.
If I add an address alias for that interface, I can still arping the target, but I cannot ping it. No other interface has the 10.0.0.0/24 range, it fails even with ping -I $IFACE.
root@host:~# ip addr add 10.0.0.2/24 dev $IFACE
root@host:~# arping -c 3 -I $IFACE 10.0.0.1
ARPING 10.0.0.1 from 10.0.0.2 $IFACE
Unicast reply from 10.0.0.1 [$TARGET_MAC]  0.788ms
Unicast reply from 10.0.0.1 [$TARGET_MAC]  0.766ms
Unicast reply from 10.0.0.1 [$TARGET_MAC]  0.794ms
Sent 3 probes (1 broadcast(s))
Received 3 response(s)
root@host:~# ping -c 3 10.0.0.1
PING 10.0.0.1 (10.0.0.1) 56(84) bytes of data.

--- 10.0.0.1 ping statistics ---
3 packets transmitted, 0 received, 100% packet loss, time 2015ms

The target server listens for SSH connections, but ssh won't get through
root@host:~# ssh -vvv 10.0.0.1
OpenSSH_6.7p1 Debian-5, OpenSSL 1.0.1k 8 Jan 2015
debug1: Reading configuration data /etc/ssh/ssh_config
debug1: /etc/ssh/ssh_config line 19: Applying options for *
debug2: ssh_connect: needpriv 0
debug1: Connecting to 10.0.0.1 [10.0.0.1] port 22.
debug1: connect to address 10.0.0.1 port 22: Connection timed out
ssh: connect to host 10.0.0.1 port 22: Connection timed out

I have tried forcing the target to update its ARP table by sending it ARP REPLY packets, but that didn't seem to help.
root@host:~# arping -A -c 3 -s 10.0.0.2 -I $IFACE 10.0.0.1
ARPING 10.0.0.1 from 10.0.0.2 $IFACE
Sent 3 probes (3 broadcast(s))
Received 0 response(s)
root@host:~# ping -c 3 10.0.0.1
PING 10.0.0.1 (10.0.0.1) 56(84) bytes of data.

--- 10.0.0.1 ping statistics ---
3 packets transmitted, 0 received, 100% packet loss, time 1999ms

There is a slight chance that there is some L3 component, because the server sent me email updates (apt-listchanges output), but the email headers contain an IP that is assigned to some switch, yet the hostname in the headers was correct (the target's hostname). Other admins have told me that it should be on the same L2 segment and arping seems to suggest that. Are there other ways to rule out L3 components?
The goal is to establish an SSH connection to the target server so that I can fix the problem.
Answer: Apparently your on the same L2 ethernet segment, using IPs 1 and 2 in the same range. I can think of two reasons why it wouldn't work:

Server with IP 10.0.0.1 has some kind of layer 3 filtering active (most probably IPTable) and drop the ICMP packets you're sending, despite everything is setup right to make it work on a network point of view. Try other probes (ssh, telnet, http, or whatever network service is known to be listening on the server).
For whatever reason your ping probes are not leaving through $IFACE (for example if the same IP range is also configured on another interface). Try using ping -i $IFACE
Comment: Thank you for your answer, but it didn't help so far, I've updated the question. ping fails even with $IFACE and so does ssh. There might be some L3 stuff going on, see mail stuff in the updated question.
Comment: Obviously you don't have access to the server console, neither locally with plain old keyboard and monitor,  nor with a virtual remote KVM ?   And you know for sure that there's no IPTable layer 3 filtering on the serveur ?
Comment: are you sure the arping answers you get are indeed sent by the server, and not by some other network device using that IP ?  Can you verify that `$TARGET_MAC` matches the expected MAC address of this server ?
Comment: Yes, I have no direct access to the server console. I'm waiting for physical access, but that might take a week or more. The $TARGET_MAC is indeed the expected MAC. I'll add this info to the question. I'm not entirely sure about the L3 layer though. In terms of arping it looks like there is none and other admins told me that it's the same L2 segment, but that mail thing suggests otherwise. Are there any other ways I could check for L3 components?


Waiting for some time on Z80 CP/M

Question: I want to write a game loop on CP/M 2.X (Z80) and would need to wait for some time e.g. a second. I've looked at BDOS but did not find a function, a loop depends on processor (emulation speed), interrupts like vertical blank do not exist.
Any ideas on how to write a game loop?
[Edit]
The z88dk CP/M lib says

Not (of course) CPM 1.x and 2.x, which have no real-time functions;
,nor QX/M, its clock is not BCD based.

There were action games like LADDER so there should be a way for a game loop.
[Edit2]
I could let the user check 5 secs with two keypresses and measure the speed (double loop) once to config the game - but only as a last resort.
Comment: You might have better luck on [Retrocomputing](https://retrocomputing.stackexchange.com/questions) with a question like this.
Comment: There's no standard clock or timer functionality in CP/M 2.2.  Your going to have to assume some clock speed or rely on machine dependent hardware.
Comment: I've implemented a CP/M; I can confirm there really is no timing information available. No clock, no timestamps. And between the 8080, the Z80A and B, and the V20, and including painfully crippled machines like the Commodore C128, there's a fairly broad range of performances out there.
Comment: Looking through the BDOS call list, I don't see anything that would help (DELAY isn't in Z80 CP/M). You may be able to get an estimate of how long to wait by getting the date and time again, waiting some large but arbitrary number of cycles (on the order of 10s) and getting the time again. This would however be slow, given the long time with nothing happening, and rely on few/no interrupts taking up cycles. If you're targeting something more specific (e.g. RomWBW) you should be able to get something semi-portable.
Comment: How would I get the time in a portable way? (e.g. NC 100, PC 1600, Emulator) - Also Turbo Pascal has delay(t) but I don't find the source.
Comment: My bad, I didn't even check that CP/M Z80 had it, I assumed that it was basic enough to be supported.
Comment: So you're using an OS that literally doesn't have a clock or any way to find out the current time?  Like there aren't even file timestamps?  If the OS really doesn't have a real-time clock, you might need to access a hardware timer if there is one.  But seriously, are you sure you want to try to do real-time stuff like a game on an (emulated) system that makes it that hard?  Perhaps just for the challenge, I guess.
Comment: Thanks @tum_ I will also ask on Retrocomputing, good idea.
Comment: @PeterCordes I don't know what is available.
Answer: There's no portable way of waiting for a certain amount of time under CP/M 2.2.  CP/M doesn't require or use a real time clock or any kind of timer, and so you can't even assume one is present in the system, let alone that it uses any kind of common interface.
Turbo Pascal's Delay function worked by assuming a certain CPU frequency, one that was configured when Turbo Pascal was installed.  The CP/M game Ladder was written in Turbo Pascal and used its Delay function, so it also assumed a certain CPU frequency.  If you played on a faster or slower CPU the game would play faster or slower than intended.
The simplest solution would be to implement your own delay function that assumed a certain CPU frequency.  I believe 4 MHz was the most common Z80 speed for CP/M.  You can make this a configurable option so users can change the assumed CPU speed.  You're probably also going to want to give users the option of changing the terminal type, just like Ladder did, as there are many possible terminals that can be used with CP/M.
Comment: Thanks, I'll do as you suggested configuring the CPU speed.
Answer: Yes, CP/M 2.x has no such mechanism.  CP/M 3 (a.k.a. CP/M Plus) however, DOES have a date/time mechanism that can be utilized for this purpose.
It is BDOS function 105 (69h):  Get date & time.  Unfortunately the granularity is only per second (returned in the accumulator when called).
You can do a call to this function, grab the value of the accumulator, then loop the call again until the accumulator changes.  Voila:  a 1 second wait.
Comment: That would wait until the "seconds" counter ticked.  The wait time depends on how close to the end of the current wall-clock second you are, and could be as short as the next call.
Comment: Longer delays would be fine, though: you can wait for `n` seconds plus an unknown time from 0.00001 to .99999 seconds or something like that.  Or if you want to display something on the screen every second, waiting until the start of the next second will lock your screen updates to 1 second intervals.  But you can't do a 1-second sleep from an arbitrary start point by polling a 1-second-granularity clock.
Answer: z88dk provides sleep(n), msleep(n), csleep(n).
In such cases the delay does not depend on a hardware clock, is calibrated on a hardcoded value defining the CPU speed.
For CP/M it is set to 4000000.  You can personalize it by editing:
{z88dk}/lib/target/cpm/classic/cpm_crt0.asm
You can also leave it untouched and tune the parameters of the functions:  supposing you have a 2mhz CPU (half speed than a 4mhz system), mleep(1000) would take 2 seconds.

Waiting for some time on Z80 CP/M


Formatar Número em Flutter

Question: Tenho a seguinte função que calcula e salva 2 dados no meu database, porém quero formatar kwhAparelho e totalAparelho de forma que não causem dízimas periódicas e de preferência desta forma ##,## ou ##.##, qual a melhor forma de fazê-lo?
void _calculoAparelho() {
double quantidade = double.parse(qtdControlled.text);
double horadia = double.parse(horadiaControlled.text);
double diames = double.parse(diamesControlled.text);
double potencia = double.parse(potenciaControlled.text);
double kwh = double.parse(controllerkwh.text);
// calculo kwh
double kwhAparelho = (potencia * horadia * diames * quantidade / 1000);
note.consumokwh = '$kwhAparelho';
// valor em reais
double totalAparelho = (kwhAparelho * kwh);
note.gasto = '$totalAparelho';  }

Answer: Essa pergunta está mais relacionada a Dart, do que Flutter em si.
Não sei se você quer arredondar o valor de acordo com as casas decimais, ou simplesmente formatar o número para obedecer a máscara ignorando as casas decimais.
Por exemplo o número 0.18941 e a máscara ##,##

Apenas formatando: 00.18
Arredondando e formatando: 00.19

A documentação é sua amiga, se você der uma olhada nesse método toStringAsPrecision() da classe num, você consegue passar um valor int de precisão e ele irá te dar um valor formatado com a precisão necessária.
Utilizando ele 0.18941.toStringAsPrecision(2)

O retorno é: 0.19

Rode um exemplo no DartPad
Agora para formatar esse valor de modo que em ambos lados do ponto flutuante (valor inteiro e valor decimal) obedeçam a máscara, pode ser usado a classe NumberFormat.
Esse precisa ser importado do pacote intl, e por conta disso não roda pelo DartPad, mas segue o código:
import 'package:intl/intl.dart';

main() {
  NumberFormat formatter = NumberFormat("00.00");
  double initialValue = num.parse(0.18941.toStringAsPrecision(2));
  double value = 0.19;

  print(formatter.format(initialValue));
  print(formatter.format(value));
}

O resultado do código vai ser:
0.19
00.19
Você precisa adicionar a dependência do pacote no pubspec.yaml
dependencies:
  intl: ^0.15.7

Formatar Número em Flutter


Express the statement using predicates and quantifiers.

Question: Ex: A passenger on an airline qualifies as a frequent flier if the passenger flies more than $25,000$ miles in one year or takes more than $25$ flights during that year.
I started and made up these three propositions knowing $x$ is a passenger:
$P(x)$ = passenger qualifies as a frequent flier
$R(x)$ = passenger flies more than $25,000$ miles in one year
$S(x)$ = passenger takes more than $25$ flights during that year
Not sure how to symbolize $P(x)\; IF\; (R(x)\; OR\; S(x))$
Comment: @Jared To be fair, here the predicate would be $(R(x)\wedge S(x))\to P(x)$, because the antecedent is the part that comes after the "if".
Comment: @Jared The fact is that, as far as I know, the correct way to interpret "$A$ if $B$" in English is "if $B$ then $A$" (meaning that if $B$ is true, then $A$ is true), or "$B\to A$". In mahematical Englis, "$A\to B$" is commonly worded, "$A$ only if $B$", meaning that "if $B$ fails $A$ fails".
Comment: @Jared By the way, the condition was $R(x)\vee S(x)$. And I don't agree with the fact that $R(x)\vee S(x)$ is a necessary, but not sufficient condition. If I read that, I had flied 30000 miles and I were exhonerated because I weight 70kg, I would be extremely upset.
Comment: That's another thing, I agree. What I say is that the correct way to interpret the text is "$R(x)\vee S(x)$ is a sufficient condition", but not a necessary one, a priori. Nowhere it states that being a Raptor is not a sufficient condition to qualify as a frequent flier, though many people would exclude it a priori.
Comment: You need to define sets, then you can define functions which map from that set to true or false.  Should look something like: $\forall x \in \mathbb{P}: P(x) \rightarrow (R(x)\wedge S(x))$.
Comment: @G.Sassatelli If the meaning is that if $R(x) \wedge S(x)$ then $x$ is definitely a frequent flier but if they _don't_ meet those requirements it's still possible they are frequent flyers, then yes that would be correct.  Also, the way I and the OP put it, it's possible that the passenger _does_ meet those requirements but is _not_ a frequent flyer.
Comment: @G.Sassatelli If it means that the passenger _will_ be a frequent flyer when they meet those requirement and, that if a passenger is a frequent flyer then they meet those requirements, then it's a double implication: $P(x) \leftrightarrow (R(x) \wedge S(x))$.
Answer: $P(x)$ IF $R(x) \lor $S(x) is equivalent to IF $R(x) \lor S(x)$ THEN $P(x)$, which translates to $R(x) \lor S(x) \to P(x)$ .
Edit: After the edit of the post it seems to now longer be clear how to translate $R(x)$ OR $S(x)$ - this is simply disjunction: $R(x) \lor S(x)$. I see no reason to try and go with a conjuuction or even an exclusive or; to me it seems clear that the or in the sentence equates a simple inclusive logical or, i.e. $\lor$.
Edit 2: After ther was some discussion in the comments about it, you could, as epxlained in my other post, also make the implication a biconditional:
$R(x) \lor S(x) \leftrightarrow P(x)$
This means that a passenger qualifies for a frequent flier if and only if $R(x) \lor S(x)$ holds true, and if this is false, no other condition can make $P(x)$ true. This would make $R(x) \lor S(x)$ a necessary condition.
I think, however, that in this not the intended meaning, I could imagine that one could posssibly also qualify for a frequent flier if, for example, one has made a certain amount of flights within the course of a longer time range, without having made it within a year but instead, say, 50.000 miles within the course of two and a half years. In that sense, I rather think that $R(x) \lor S(x)$ is a sufficient condition, but not a necessary one, as proposed b @G. Sassatelli in the comments, and would therefore be translated with a material implication if $\to$ rather than a biconditional iff $\to$.
In either case, if $R(x) \lor S(x)$ is true, $P(x)$ must be true. If that is not the case, the implication simply does not hold: If the antecedent is true but the consequent is false, the implication is false. In my opinion, it is pretty clear from the assignment that if the condition $R(x) \lor S(x)$ is satisfied, $P(x)$ will be true, so I don't understand why @Jared said that "it's possible that the passenger does meet those requirements but is not a frequent flyer", I think this definitely shouldn't happen.
However, the intutitive intepretation of such a sentence would be a more generic one (i.e. a rule-like one), meaning that it is not that well suitable to say $x = passenger$, because then, the formula becomes only true if the current variable assignment happens to assign to x an individual which is a passenger, and can therefore also only be true for one individual.
Instead, the sentence should rather say: For everyone who is a passenger it holds that if he passenger flies more than 25,000 miles in one year or takes more than 25 flights during that year, then he is a frequent flier.
Therefore, I would establish another predicate for passenger, over which you can then quantify.
Since you already chose $P(x)$ for the frequent predicate, let's call $F(x)$ the predicate for passenger ("flier").
The formula would then be:
$\forall x [F(x) \to (R(x) \lor S(x) \to P(x))]$
Meaning: For all x ($\forall x$) which are a passenger ($F(x)$) it holds that ($\to$) if he flies more than 25,000 miles in one year ($R(x)$) or ($\lor$) takes more than 25 flights during that year ($S(x)$), then ($\to$) it is a frequent flier ($P(x)$).
This would reflect the semantics of the sentence better IMO, but you can also stick with the more simple variant I gave above.


scala: How to sort Seq with an Ordering object?

Question: From the scala reference:
http://www.scala-lang.org/files/archive/nightly/docs/library/index.html#scala.math.Ordering
  case class Person(name:String, age:Int)
  val people = Array(Person("bob", 30), Person("ann", 32), Person("carl", 19))

  // sort by age
  object AgeOrdering extends Ordering[Person] {
      def compare(a:Person, b:Person) = a.age compare b.age
  }

But if I want to sort a Seq using an Ordering object:
  // Want to sort a Seq, or event and IndexedSeq
  val ps = people.asInstanceOf[collection.Seq[Person]]

  // Type not enough arguments
  // for method stableSort: (implicit evidence$6: scala.reflect.ClassTag[Person],
  // implicit evidence$7: scala.math.Ordering[Person])Array[Person]. Unspecified value
  // parameter evidence$7.
  Sorting.stableSort(ps)(AgeOrdering)

the compiler chokes. But the stableSort API says it will take an Seq. So why does the above fail?
Answer: In Sorting, the quickSort implementation is done in-place, with a bunch of index-based moves which are only suitable to be done on an Array (and a Seq does not define indexing at all).
quickSort[K](a: Array[K] ..): Unit

The quickSort method performs side-effects on the input and returns Unit.
The stableSort however, has two different forms. One that takes an Seq and one that takes an Array.
stableSort[K](a: Seq[K] ..): Array[K]
stableSort[K](a: Array[K] ..): Unit

The form that takes an Array also returns Unit and modifies the input (as quickSort but ensuring stability), while the form takes a Seq returns a new Array object (and the input sequence is not modified).

The error is because the quickSort method has the signature for the second parameter group: (implicit arg0: math.Ordering[K]) while the stableSort method has: (implicit arg0: ClassTag[K], arg1: math.Ordering[K]) - that is, it also requires a ClassTag[K/Person].
Even though the ordering was specified, no ClassTag[K] argument is specified (or implicitly resolved) and Scala needs this to create the Array[Person] that is used internally (and returned). Due to Scala being limited by Java's type erasure, the method doesn't get to know what type K really is without additional help.
I'm not sure why it's not being resolved implicitly (so much of Scala implicits is still "magic" to me!), but it's fairly easy to pass in explicitly:
val results = Sorting.stableSort(ps)(classTag[Person], AgeOrdering)

Some rational and usages of TypeTag/ClassTag is discussed in TypeTags and Manifests.
Also see Scala: What is a TypeTag and how do I use it?
Comment: Couldn't get classTag/ClassTag to work, but adding   mainfest[Person] did: http://stackoverflow.com/questions/2627919/scala-how-can-i-sort-an-array-of-tuples-by-their-second-element
Comment: Using 2.10. Missing an import for classTag - where does that come from? ClassTag  (with import reflect.ClassTag) complains about not enough parameters.
Comment: All good -- but then why does stableSort fail to compile with the provided Seq in the example above?
Comment: @user48956 Include the *full* compiler message in the post and then we'll see some answers address that ;-) Also remove the `quickSort` call in such case as it simply isn't defined over Seq.
Comment: @user48956 The Tags are newer (in Scala 2.10); which version are you targeting? In any case, glad you solved it!
Comment: let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/43643/discussion-between-user2864740-and-user48956)


What is signature in a packet payload?

Question: What is a signature in a packet payload?
Why are they even necessary ?
Also traffic classifiers use signature to detect the type of protocol of packet like there are regular expressions for http signature and ftp signature.
Answer: I think you may be reading too much into the use of the word "signature" for these definitions (often heuristics) used in various DPI-based solutions to recognize different protocols.
It's really just any aspect of the protocol that identifies what it is, whether the protocol outright states which protocol it is or whether it for example has specific commands or structures that can be recognized to disambiguate it from other protocols.
Eg, an HTTP 1 request would start with something like VERB path HTTP/version (eg GET /foo HTTP/1.1).
This pretty much gives away that it is HTTP in both senses above, it outright states an HTTP version, but even if HTTP hadn't been designed to include the protocol version as part of the request it would still be pretty clear from just something like GET /foo that it looks a lot like HTTP.
For some protocols the very first message is not necessarily what gives it away. For example both SMTP and FTP look potentially similar in terms of the greeting message from the server being 220 stuff about the server (the "stuff about the server" portion usually gives away what it is, but can be more noisy and potentially unclear), however the client immediately gives away that it's SMTP by saying EHLO host (or possibly HELO host), while an FTP client would say USER myuser and so on (might need to look at more of the conversation for the FTP case to properly disambiguate it from other things).
Now of course, if you are talking about some protocol that is tunneled over TLS (eg HTTPS), all the regular observer (not the TLS endpoint) would recognize in the sense discussed here is the TLS protocol itself (might simply be: the first thing transmitted is the client sending a TLS clienthello message). Unless you actually have access to the payload inside you would need to rely on other hints for what might be inside (maybe the port number, for instance).
Worth noting is that for many protocols the port number typically already correctly identifies which protocol it is. The method you are talking about is rather a way of identifying/confirming the protocol regardless which port number is used by peeking at the payload.

What is signature in a packet payload?


Enums Inheritance not Working in Python3.8?

Question: I've wrote below code, works fine in Python3.7
from enum import Enum

class UserRoles(Enum):
    ADMIN = 'ADMIN'
    MANAGER = 'MANAGER'
    MEMBER = "MEMBER"

class AuthorRoles(UserRoles, Enum):
    pass

Getting below error in Python3.8
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python3.8/enum.py", line 146, in __prepare__
    metacls._check_for_existing_members(cls, bases)
  File "/usr/lib/python3.8/enum.py", line 527, in _check_for_existing_members
    raise TypeError(
TypeError: AuthorRoles: cannot extend enumeration 'UserRoles'

Note: I'm aware that inheriting is not recommended according to python docs
just curious what caused the issue.
Answer: Enum inheritance is not allowed, but it worked in python3.7 due to this Bug
The issue was fixed in python3.8, so I got the above error.


Rspec testing to_param override

Question: I failed to google anything about this, so I bring it here.
I've overrode to_param on my model to concatenate it with the id for a prettier and safer URL.  I'm at a loss where this should have been in my test.  It seems like putting it to a routing test misses the point.  I would think that this would go in the model's spec, though:
#my model
class MyModel < ActiveRecord::Base
  def to_param
    [id,an_attr.parameterize].join("-")
  end
end
#my model spec
describe MyModel do
  mymodel = MyModel.create!(:an_attr => "test attr")
  mymodel.to_param should == [mymodel.id,"test_attr"].join("-")
end

What I get is:
 Failure/Error: mymodel.to_param should == [mymodel.id,"test_attr"].join("-")
   expected: "1-test_atttr"
        got: #<MyModel id: nil, an_attr: nil, created_at: nil, updated_at: nil> (using ==)

A model instance...I've got to be missing something obvious here --- maybe its just late for me---
insight greatly appreciated.
Answer: It looks like you're missing a period after to_param.
mymodel.to_param.should == [mymodel.id,"test_attr"].join("-")
Comment: doh!... yeah. that certainly was it... so would this be the appropriate place/way to test a URL slug? Doesn't seem like you'd want to do it in the router as you'd have to stub a model, right?

Rspec testing to_param override


Conditional Probability with Poker Hands

Question: I am trying to answer this question:
Draw $5$ cards at random from a standard deck of $52$ cards. Find:
$\text{a) } P(\text{full house} \mid \text{full-house or three-of-a-kind}) $
$\text{b) }P(\text{full house} \mid \text{at least two aces})$.
$\text{c) }P(\text{at least two aces} \mid \text{full-house}) \\$.
These are my relevant equations I'm working with:
$P(A\cup B)=P(A)+P(B)-P(A\cap B)$
$P(A|B)=\dfrac{P(A\cap B)}{P(B)}$
I'm having difficulty calculating all of it, but specifically the intersection and union probabilities are hardest for me. Any help would be appreciated!
Edit: I fixed the equation mentioned, thanks. Also, would we say that $P(\text{Full house} \cup \text{Three-of-a-kind})$ = P(Full house) + P(Three-of-a-kind) - P(Full house $\cap$ Three-of-a-kind)? And then P(Full house $\cap$ Three-of-a-kind) = 0 since you can't have both these hands?
Comment: The first equation is meant to be:  $P(A\cup B)=P(A)+P(B)-P(A\cap B)$.
Comment: Your first equation should actually read $P(A \cup B) = P(A) + P(B) + P(A \cap B)$.  The trickiest part of this problem is keeping straight exactly what the requirements are for each hand.  For instance, a full house is relatively straightforward—a set (of three) plus a pair—but a three of a kind is strictly a set plus two cards that are both distinct in rank from each other and the set (as otherwise it would be counted as either a four of a kind or a full house).
Comment: What you said in your edit is correct.
Answer:
Find $\Pr(\text{full house} \mid \text{full house or three of a kind})$.

Our sample space consists of hand in which a full house or three of a kind is obtained.
Full house:  We must choose a rank from which three cards are drawn, choose three cards of that rank, choose a rank from one of the remaining ranks from which two cards are drawn, and choose two cards of that rank.  This can be done in
$$\binom{13}{1}\binom{4}{3}\binom{12}{1}\binom{4}{2}$$
ways.
Three of a kind:  We must choose a rank from which three cards are drawn, choose three cards of that rank, choose two of the remaining ranks for the singletons, and choose one card from each of those ranks, which can be done in
$$\binom{13}{1}\binom{4}{3}\binom{12}{2}\binom{4}{1}^2$$
Another way of describing our sample space is that it contains hands in which there is one rank from which exactly three cards are drawn.  Thus, we must choose that rank, choose three cards from that rank, and choose two cards from the remaining ranks, which can be done in
$$\binom{13}{1}\binom{4}{3}\binom{48}{2}$$
ways.
As you can verify,
$$\binom{13}{1}\binom{4}{3}\binom{12}{1}\binom{4}{2} + \binom{13}{1}\binom{4}{3}\binom{12}{2}\binom{4}{1}^2 = \binom{13}{1}\binom{4}{3}\binom{48}{2}$$
Therefore,
\begin{align*}
\Pr(\text{full house} \mid \text{full house or three of a kind}) & = \frac{\Pr(\text{full house})}{\Pr(\text{full house or three of a kind})}\\
& = \frac{|\text{full house}|}{|\text{full house or three of a kind}|}\\
& = \frac{\dbinom{13}{1}\dbinom{4}{3}\dbinom{12}{1}\dbinom{4}{2}}{\dbinom{13}{1}\dbinom{4}{3}\dbinom{48}{2}}
\end{align*}
where
$$\frac{\Pr(\text{full house})}{\Pr(\text{full house or three of a kind})}
= \frac{|\text{full house}|}{|\text{full house or three of a kind}|}$$
because the denominator for both probabilities on the left-hand side of the expression is $\binom{52}{5}$, so it cancels out.
Since a full house and a three of a kind are mutually exclusive, we can simply add their probabilities, as you determined.

Find $\Pr(\text{full house} \mid \text{at least two aces})$.

The event at least two aces can occur in three mutually exclusive ways:

Exactly two aces and three other cards from the deck.
Exactly three aces and two other cards from the deck.
Exactly four aces and one other card from the deck.

Since our sample space consists of those hands with at least two aces, there are two favorable cases:

Two aces and three cards of another rank.
Three aces and two cards of another rank.

Find $\Pr(\text{at least two aces} \mid \text{full house})$.

Our sample space consists of those hands containing a full house.
Our favorable cases are those full houses containing:

Two aces and three cards of another rank.
Three aces and two cards of another rank.

I leave the calculations for the second and third questions to you.


How to read input of unknown length using fgets

Question: How am I supposed to read long input using fgets(), I don't quite get it.
I wrote this
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
    char buffer[10];
    char *input;
    while (fgets(buffer,10,stdin)){
        input = malloc(strlen(buffer)*sizeof(char));
        strcpy(input,buffer);
    }
    printf("%s [%d]",input, (int)strlen(input));
    free(input);
    return 0;
}

Comment: Look at `realloc`. And consider a strategy of doubling the allocation each time, as well as reading directly into the buffer. BTW: The printf-format for `size_t` is `%zu`.
Comment: Your code has a classic off-by-one error in the `malloc()`.  Using `strlen(str)` is almost always wrong; it should almost always be `strlen(str)+1`.  Your loop leaks memory horribly, too; you overwrite the previous pointer stored in `input` on each iteration.
Comment: If you have it, consider using [`getline`](http://linux.die.net/man/3/getline) instead of `fgets`.
Comment: i know about getline, but i have to use fgets
Comment: i saw them but i dont understand from it how fgets works, what happens when input is longer then buffer i specify, does it wait for me to allocate memory and store it there?
Comment: There are definitely other questions that cover exactly this topic:
[How to allocate memory for input string of unknown length](http://stackoverflow.com/questions/12878240/); [Safely reading in strings of unknown length](http://stackoverflow.com/questions/19507995/); and probably others.
Comment: If the buffer isn't big enough to fit the whole line, `fgets()` returns the buffer filled as much as it can, and null-terminated, and leaves you to decide what to do with the rest of the line which is waiting to be read by the next input operation.
Comment: is there any function that appends string? because i am also rewriting input by that one part that is left to be read
Comment: There's `strcat()`, but you don't want to use it for this task.  There's also `strncat()`; you even more definitely don't want to use it because its interface is just a booby-trap.  To use `strcat()` safely, you have to know how much space is available in the buffer to be copied into, how long the string already in the buffer is, and how much space is in the string to be appended to the end of it, and if you know those, you can use `memmove()` or `memcpy()`, or even `strcpy()`, to copy the correct amount of data into exactly the correct position.
Comment: Be careful of someone accidentally or maliciously on purpose giving you a binary file.  You may not want to print it in that case.
Answer: #include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(void)
{
    char buffer[10];
    char *input = 0;
    size_t cur_len = 0;
    while (fgets(buffer, sizeof(buffer), stdin) != 0)
    {
        size_t buf_len = strlen(buffer);
        char *extra = realloc(input, buf_len + cur_len + 1);
        if (extra == 0)
            break;
        input = extra;
        strcpy(input + cur_len, buffer);
        cur_len += buf_len;
    }
    printf("%s [%d]", input, (int)strlen(input));
    free(input);
    return 0;
}

This is about the minimal set of changes that will give you the complete line of input.  This grows the space by up to 9 bytes at a time; that isn't the best way to do it, but there's extra bookkeeping involved doing it the better ways (doubling the space allocated, and keeping a record of how much is allocated vs how much is in use).  Note that cur_len record the length of the string in the space pointed to by input excluding the terminal null.  Also note that the use of extra avoids a memory leak on failure to allocate.
The strcpy() operation could be legitimately replaced by memmove(input + cur_len, buffer, buf_len + 1) (and in this context, you could use memcpy() instead of memmove(), but it doesn't always work while memmove() does always work, so it is more reliable to use memmove()).

With length-doubling — the cur_max variable records how much space is allocated, and cur_len records how much space is in use.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(void)
{
    char buffer[10];
    char *input = 0;
    size_t cur_len = 0;
    size_t cur_max = 0;
    while (fgets(buffer, sizeof(buffer), stdin) != 0)
    {
        size_t buf_len = strlen(buffer);
        if (cur_len + buf_len + 1 > cur_max)
        {
            size_t new_len = cur_max * 2 + 1;
            if (buf_len + 1 > new_len)
                new_len = buf_len + 1;
            char *extra = realloc(input, new_len);
            if (extra == 0)
                break;
            input = extra;
            cur_max = new_len;
        }
        strcpy(input + cur_len, buffer);
        cur_len += buf_len;
    }
    printf("%s [%d]", input, (int)strlen(input));
    free(input);
    return 0;
}

Comment: thanks, so if i wanted to read lines that are generally very long, i have to use realloc resizing by 2 times more than its previous size?
Comment: No; the simplest thing is to use `char buffer[4096];` and get on with life.  Only JSON comes in lines longer than that, and then you get to read the whole file in one line.  (I exaggerate, but not by as much as all that.)  Failing that, the idea is that you allocate 10 bytes the first time, then reallocate 20, then reallocate 40 (but read 2 units of 10 into the extra space), then 80, then 160, then 320...  If you're not going to free the space before the function exits and there's more than, say, 64 bytes unused, you might use `realloc()` to shrink the allocation to its required size.
Comment: Unless you're on a tiny, tiny machine, a 4 KiB buffer isn't going to cause you grief.  If you're on such a tiny machine, you probably aren't using `malloc()` at all - or reading such long lines.
Comment: thanks for the answer, what does if (extra == 0)
            break; this do in your modification, is 0 representiing 'NULL'?
Comment: NULL is another name for 0 - more or less.  There are complications, but both are (or can be) null pointer constants.  You can use 0 in places that you should not use NULL; there's nowhere you can use NULL that you can't use 0.  In C, some systems define NULL as `((void *)0)` or thereabouts; that doesn't fly in C++ (but the correct value for NULL is a problem for the compiler, not the programmer using NULL).  You can use NULL where I wrote 0 in: `char *input = NULL;`, `while (fgets(buffer, sizeof(buffer), stdin) != NULL)`, `if (extra == NULL)`.
Comment: could you please show me how to implement this with resizing it each time 2 times?
Answer: A better approach is to use an input mechanism that will allocate for you such as getline (or even scanf). (Note: scanf does not allocate in all compilers. It does in gcc/Linux, but does not with Windows/Codeblocks/gcc)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
    char *input;
    scanf ("%m[^\n]%*c", &input);
    printf("\n %s [%d]\n\n",input, (int)strlen(input));
    free(input);
    return 0;
}

output:
$ ./bin/scanfinput
This is my longer string.

 This is my longer string. [25]

getline example
#include <stdio.h>
#include <stdlib.h>

int main()
{
    char *input = NULL;     /* input buffer, NULL forces getline to allocate */
    size_t n = 0;           /* maximum characters to read (0 - no limit      */
    ssize_t nchr = 0;       /* number of characters actually read            */

    if ((nchr = getline (&input, &n, stdin)) != -1)
        input[--nchr] = 0;  /* strip newline */

    printf ("\n %s [%zd]\n\n", input, nchr);
    free(input);

    return 0;
}

Comment: If you are working in Windows, `scanf` will not allocate if using `codeblocks`, etc.., Use `getline`. I'll update for Linux only. I was working with `gcc/C89` with gnu extensions.
Comment: Thanks for the feedback. So it is just a roll of the dice on implementations other than Gnu Linux. It would be readily apparent from the `man page` you would think. Either you have the `m` designation for causing `scanf` to allocate or you don't. I'm curious if there is actually an absence in the `man pages` on the implementations where it fails. (maybe I should say I would be 'surprised' to see an absence...)
Comment: thanks, this gives me warning, unknown format %m, im working with c90
Comment: Get rid of codeblocks `:)` I've had others report that `scanf` will not allocate if using `codeblocks`. It must be a limitation.
Comment: Code::Blocks has nothing to do with the compile.  Its just the IDE
Comment: What is the bottom line there? I had another report that using a `gcc` setup on windows with codeblocks, `scanf` could not allocate. I have neither and no way to test.
Comment: The ability to allocate or not is an implementation issue with whatever compiler OP is using.  I have used the MinGW implementation for several projects without a hitch, but do not have it now to test the issue.


Deny Creating Public Buckets / Objects in GCP Buckets

Question: Is it possible to create a policy in GCP that will disallow the creation of public buckets or items in buckets?
If yes, how that policy will look like?
Answer: Storage Object Admin or Storage Admin roles are needed for making data public. If you exclude these roles from an account and add Storage Object Creator or Storage Object Viewer roles, depending on your use-case, the account will not be able to make data public but create or copy objects.


Naming conventions for template types?

Question: Traditionally, the names of template types are just a single upper-case letter:
template<class A, class B, class C>
class Foo {};

But I hesitate to do this because it's non-descriptive and hard therefore to read. So, wouldn't something like this be better:
template<class AtomT, class BioT, class ChemT>
class Foo {};

I also tend to think the following would not be a bad idea:
template<class ATOM, class BIO, class CHEM>
class Foo {};

It makes them stand out (and also, it's upper-case letters again). What's your opinion?
Answer: For C++ templates I have a couple of patterns
If there is just a single template parameter, I name it T (or U,V for nested templates).
When there are multiple parameters and the use is not immediately obvious then I use descriptive names prefixed with T.  For example, TKey, TValue, TIdentifiier, etc ...  This makes the parameters fairly easy to spot throughout the template usage.
I would avoid the all upper case version though.  Most people use all upper case identifiers in C/C++ to represent a macro definition.  Repeating that pattern for a template parameter is likely to confuse people down the road.
Comment: ...and could also confuse the compiler. Try #include  template  class Foo {};
Comment: I don't use T as prefix because it is the same prefix used by some products from "Borland" and for me it is a bit confusing.
Comment: The T prefix also lets you use the *unprefixed* name as generic method name (or any other symbol in the namespace). For example, an accessor `const TValue& Value() const { return value_;}`
Answer: I use convention TName for the template parameter and NameT for stored template parameter.
template <typename TFirst, typename TSecond>
class Templated
{
    typedef TFirst FirstT;
    typedef TSecond SecondT;
}

typedef Templated<int, std::string> MyTemplated;
...
const MyTemplated::FirstT size;

Comment: What's the point of storing templated types? They are different. I just showed how I names those stored types. Kind of my own convention.
Answer: Generally, the traditional way is to use T if there is only one type param. If there is more, use T as prefix, e.g. TAtom. "T" prefix helps to instantly see it's type parameter. Using TAtom for a single type parameter is also valid.
Answer: You shouldn't use a special naming convention for templates, just use the same convention as for any other of that type (as for classes or variables). It shouldn't matter in the code whether you are working with template types/values or normal ones.
Comment: True for names of parameterised types, Foo, but the question was about type parameter names, the T in template Foo. So it's not a type, it's a parameter name.
Comment: Note that type parameters are only accessible by the template itself, to make them available for users of your template, you have to typedef them (e.g. `template  ... { typedef FooT Foo; };`, so if you just use standard convention, names may clash
Comment: Has your opinion changed any since '09? People use `mName` or `m_name` for members, `szName` in Hungarian style, etc. - if there are conventions for instances and arguments to support them, I don't see why those arguments wouldn't extend to templates. If a type or the type of an instance is fundamentally different, I say you should use conventions for both or neither. (Meta-conventions for metaprogramming!)
Comment: My main argument for `Foo_t` would be to provide `Foo(T) -> Foo_t` (when type is not explicitly required but rather deduced via ADL/SFINAE, the prefix or suffix is omitted; then by typing `Foo_t` you know you need template arguments instead of finding out when the compiler chokes) -- see how many SO questions you can find asking why we need `make_tuple`/`make_pair`!
Answer: If I have class with one type parameter I am using name T. Also it mean that all operartion in this class are working with T.
If I have few parameter I'm naming as in your explamle AtomT, BioT...
If template parameter is not type of object with which we working in clas e.g. strategy, comaparator or functor, I'm using name without T e.g. ThreadStrategy, Compare.
Sometimes for avoid mixing styles I'm making typedefs in class:
typedef T value_type;
--
Boost naming convention (http://www.boost.org/development/requirements.html#Naming_consistency) says about template parameters next:
Template parameter names begin with an uppercase letter.
Answer: I try to follow the notion my compiler vendor uses: it's not too short and not too verbose. And helps me read the error messages I get with standard templates. (Which is another reason why I switched from const T& to T const&). Something like:
template <class Ty, class Container>
class my_algo { ...

where my compiler will typically use:
template <class _Ty, class _Container>
class std_algo { ...

Comment: I think you already know this, but for anyone else reading this, note that he does not use a leading underscore. Those are RESERVED for the compiler. That is, standard library templates are allowed to use _Ty. Users are not. Ty is legal, since it does not start with an underscore.
Comment: Funny, Dinkumware (your standard library vendor) uses `_Ty` so as not to step on the users who use `T`.  Not criticizing your reasons at all, but it's a little funny that they spawned what they were trying to avoid. :)
Comment: Quod licet Iovi, non licet bovi.
Comment: @jalf: +1. Excellent catch :) I was being plain lazy to touch upon this little known but `can-come-back-and-bite-you-later` point.
Comment: Longum iter est per praecepta, breve et efficax per exempla.
Answer: At our shop, we use HungF##ngarian notation.  Template arguments are just arguments like all others, except they're not a const, nor a variable, but a type.
template< typename at_Container, typename at_Functor >
at_Functor& foreach( const at_Container& ac_Cont, at_Functor& av_Func ) {
    return std::foreach( ac_Cont.begin(), ac_Cont.end(), av_Func );
}

The prefix describes the type, while the name is meant to say something of the role the argument plays in the context of the defined function.
Answer: I follow the same general conventions naming template parameter typenames as I follow naming classes & structs, which is to capitalize the first letter or each word, like so:
class MyGizmo
{
};

struct Thingy
{
};

class TPSReport
{
};

template<class ValType> ...

template<typename Number> ...

Naming conventions for template types?


Expectation of inverse square under multivariate standard normal

Question: In one of the steps in my lecture notes, the following result was used without proof:
Given $X$ is a $p$-dimensional multivariate normal distribution, where $p\ge 3$, centred on zero, with covariance matrix equal to the $p\times p$ identity matrix, i.e.
$$X\sim N_p(0, I_p)$$ then we have $$\mathbb{E}\left(\frac{1}{\Vert X\Vert^2}\right) = \frac{1}{p-2}.$$
I have tried integrating it by brute force, but it's unwieldy. Also, I thought it might be somehow related to a $\chi^2$ distribution, but there is an inverse so I'm not sure.
Comment: Since $X^2$ has a $\chi^2(p)$ distribution by definition, https://stats.stackexchange.com/questions/198595/expected-value-of-gamma-distribution/198621#198621 is the same question and presents simple answers. My answer there explains why it's necessary that $p\gt 2.$
Comment: Thank you. Your answer illustrates the general strategy to finding expected values well.
Answer: The question is the same as asking what is the mean of an inverse-$\chi^2$ distribution with $p$ degrees of freedom.
I could look this up in Wikipedia, but the derivation of the mean is usually via manipulation of the PDF, so I would be remiss to just accept the magical-looking PDF of a Inv-$\chi^2_\nu$:
$$\frac{2^{-\nu/2}}{\Gamma(\nu/2)}\,x^{-\nu/2-1}  e^{-1/(2 x)}.$$
(Sidenote: the requirement that $p\ge 3$ is because the integrand has $x^{-\nu / 2}$, and we need the power to be less than 1 for the integral to converge, i.e. $\nu > 2$.)
However, this is easily derived from the PDF of a $\chi^2_k$:
$$\frac{1}{2^{k/2}\Gamma(k/2)}\; x^{k/2-1} e^{-x/2}.$$
How do we get this? We can derive the PDF of $\chi^2_1$ from scratch, getting $\Gamma(1/2, 2)$, and use the fact that if $X\sim \Gamma(a_1, b)$ and $Y\sim  \Gamma(a_2, b)$, then $X+Y\sim\Gamma(a_1+a_2, b)$.
Comment: Your last equation is ambiguous, because usually "$\Gamma(a_1,b)$" refers to a Gamma *function* and the sum is taken literally as a sum.  There's a problem with this informal notation!
Comment: Gamma function takes one variable while the Gamma distribution takes two parameters. It just saves me typing X~G(x,b), Y~G(y,b), then X+Y~G(x+y,b).
Comment: The Gamma function often takes two or even three parameters. Don't assume everybody uses the same convention you are familiar with: it's always best to explain your notation.


Mysql is taking .7 seconds to "copy into tmp table". What is the best way to cache this kind of query?

Question: I have a group-by query that is very fast when it comes to indexing, joining, sending the results etc. Unfortunately, mysql spends 99.6% of its time "copying to tmp table" when I profile it. I am at a loss as to how I can get mysql to perform better on its own.
This group by query essentially finds the number of entities for the top 20 tags in the system. I build on this query to filter out tags that the user selects, essentially narrowing down the field. As they select a new tag, the query performance improves drastically. If they select 2 or 3 tags, the query is extremely fast in finding the number of entities with those 2 or 3 tags, plus the next most popular tags after that.
Essentially, the performance problem is when no tags are selected, or when 1 tag is selected. What is the best way to solve this problem?
1) Memory cache, like ehcache? Get hibernate involved?
2) Mysql query cache?
3) Store the 0 and 1 tag selected results for every tag in the system in a cache table, and use those for a 24-hour period? Use a job to populate the results every day?
Any other ideas? I'm using Spring, Java, Hibernate, Mysql.
Answer: We definitely need the query and EXPLAIN query for answering this. Possibly also with schema.
Comment: Yes. We need the query, schema and explain plan, and some idea of how many data you have.
Answer: What are the column types involved?  If you look at the MySql reference  you can see some of the factors that might be triggering on-disk storage for your query during processing.  Is your disk system slow enough to cause this kind of issue?
Answer: Taking a stab in the dark here. MySQL may be writing the temp table to disk if with one tag the results are bigger than the setting for in memory temp tables.
If you have the resources, you may want to consider bumping up that setting. Or you can find a way to reduce the size of the results returned for zero or 1 tag.
Answer: Is it possible for you to just create a view rather than copying files?
Comment: A view is unlikely to perform better, in many cases views make the explain plan worse in MySQL.


Upgrade SQLite database in Android

Question: I am making one android app where I am using SQLite database. I have already released one version of it and now for second and third version suppose I require to change in the database table like adding/removing fields.
So How can I handle this upgrade in Android. Here I don't want to drop the complete table like stuff, Here it should use Alter to update the tables.
Suppose user has installed my first version of my application then after few days I released next version 1.1 with changes in database table - added one field and here user did not upgrade it and meanwhile I again released the 1.2 again added one more field
So here How I could handle this situation when this user upgrade my application from Version 1 to Version 1.2, where Version 1.1 is missed and attribute which I added is also missed that can create problems.
Any solution to handle this ??
Answer: Assuming you're using SQLiteOpenHelper, just increment the database version number for any to-be-released version with database schema changes. In case there's an older database file around, your onUpgrade() will be called so you can migrate the database from any old version.
For example, if your 1.0 database version is 1, 1.1 is 2 and 1.2 is 3 and the user is updating version 1.0 to 1.2. onUpgrade() is called with oldVersion set to 1 and newVersion set to 3. From these version numbers your code can figure out what needs to be done, like:
@Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    switch (oldVersion) {
        case 1:
        updateFrom1To2(db);

        case 2: // fall-through
        updateFrom2To3(db);

        break;

        default:
        Assert.fail("You forgot to write code for oldVersion " + oldVersion);
    }
}

Comment: Thanks I know this but So here How I could handle this situation when this user upgrade my application from Version 1 to Version 1.2, where Version 1.1 is missed and attribute which I added in that version is also missed that can create problems. What code should I write to handle this situation when user upgrade from version 1 to 1.3 and version 1.2 to 1.3
Comment: Just write the `onUpgrade()` code so that it can migrate any old version to current.
Comment: You'll have to design your db architecture the way that it will be convenient enough to upgrade from X to Y while there are Z versions between them.
Comment: Suppose in version 1.1 I add one `ALTER TABLE TABLE_SECRET ADD COLUMN    "attr1" INTEGER;` and next version 1.2 I add this  `ALTER TABLE TABLE_SECRET ADD COLUMN "attr2" INTEGER;`, so here If user upgrade from 1 to 1.3 then it will create issues because `attr1` has not added
Comment: so ALTER - ADD 2 columns :)
Answer: You can do anything you want in onUpgrade in sqldb
. You can use ALTER to add new columns to your table.
Worst case, if your schema is completely and entirely different, you'll have to create the new table, populate it using data from the old table, and then delete the old table.
In any case, onUpgrade was designed to allow for a smooth upgrade without any loss of data. It's just up to you to implement it properly.
You should put all changes in your onUpgrade method you can use this code:
@Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    String sql = "ALTER TABLE " + TABLE_SECRET + " ADD COLUMN " +
     "name_of_column_to_be_added" + " INTEGER";
    db.execSQL(sql);
}

for more look this
EDIT

This is a nice thought and i found one solution(not tested), you need
  to check the update ,example -  Check for the ALTER you have done  in 1.1 in the
  version  1.2  by reading the db rows or some thing , if it
  is not there, you want to Alter this too with the 1.2 alter .
Comment: Yes I know this but my question is different, read it again seriously - "So here How I could handle this situation when this user upgrade my application from Version 1 to Version 1.2, where Version 1.1 is missed and attribute which I added is also missed that can create problems." - What code should I write to handle this situation when user upgrade from version 1 to 1.3 and version 1.2 to 1.3
Comment: how you think Version 1 to Version 1.2 where Version 1.1 is missed make a problem?From my thoughts there is all the thing which you want in 1.2. then why you bother about 1.1
Comment: i am sorry to telling this but, this is not a good practice , changing the DB regularly, design one DB and ensure that will be perfect and a least chance for modification
Comment: Suppose in version 1.1 I add one ALTER TABLE TABLE_SECRET ADD COLUMN    "attr1" INTEGER; and next version 1.2 I add this  ALTER TABLE TABLE_SECRET ADD COLUMN "attr2" INTEGER;, so here If user upgrade from 1 to 1.3 then it will create issues because attr1 has not added
Answer: I usually follow a different kind of implementation to onUpgrade method to support backward compatibility in databases.
Note: Here I only show implementation to add more columns in the latest database versions.
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    //  1.  Copy the database file to temproary file.
    //  2.  Drop all the old tables from db
    //            db.execSQL("DROP TABLE IF EXISTS " +
 );
    //  3.  Create tables using new Schema
    //            this.onCreate(db);
    //  4. Copy the data from temproary file to new db
    //  5. Remove the temprorary file
}

It is more convenient for me to use this kind of implementation than using ALTER commands.

Upgrade SQLite database in Android


Query de Pesquisa vinda de um formulário Dinamico (Codeigniter)

Question: Estou com um problema para construir uma QUERY que vem de um formulário dinâmico.
Tenho um formulário de pesquisa em que os campos para pesquisa são dinâmicos (podem ser de texto ou checkbox), ou seja sempre que é adicionado um novo campo tem de ser possível pesquisar por esse campo, alguém me pode dar uma luz de como o fazer?
Obrigado
Comment: me explica uma coisa, como que eh adicionado esses campos na parte da pesquisa?
Comment: através de um outro formulário, numa outra secção do site
Answer: Laranja, poderia explicar melhor sua situação?
Pelo que entendi, você possui uma aplicação de tela única e nessa existe campos TextBox e ComboBox, e precisa criar uma query de consulta ao banco com esses campos, quando esses são preenchidos, é isso?
Se sim, uma idéia simples.
Use um if para identificar qual Text ou Combo foi preenchido ou selecionado e preencha a TAG dos campos com o nome das colunas da tabela.
Ex:
<code>private void DefineNomeCampos()
    {
        comboBox1.Tag = "COL_TIPOPESSOA";
        textBox1.Tag = "COL_NOMEPESSOA";

    }
    private void PreencheQuery()
    {
        StringBuilder sbSelect = new StringBuilder();
        StringBuilder sbWhere = new StringBuilder();

        sbSelect.Append("Select ");
        if (!string.IsNullOrEmpty(textBox1.Text))
        {
            sbSelect.Append(textBox1.Tag + ",");
            sbWhere.Append(textBox1.Tag + "=" + textBox1.Text + ",");

        }
        if (Convert.ToInt32(comboBox1.SelectedValue) != -1)
        {
            sbSelect.Append(comboBox1.Tag + ",");
            sbSelect.Append(comboBox1.Tag + "," + comboBox1.SelectedText + "," );

        }
    }
</code>
Comment: Luiz obrigado pela dica, mas queria uma solução para php (framework codeigniter), no entanto eu tenho uma tela com várias checkbox  e varias caixas de texto, mas esses campos hoje podem ser 10 amanha podem ser 100 e com nomes diferentes, ou seja eu preciso que a query seja montada de forma dinâmica para que sempre que haja um campo novo a query seja feita com esse campo, a parte das validações se um campo esta preenchido ou não eu já resolvi e consigo pegar as caixas de texto pelo o id de cada, mas na hora de montar a query não estou a conseguir em codeigniter


Consulta SQL unificando 3 tabelas

Question: Tenho 4 tabelas que preciso uni-las em uma unica consulta onde o resultado seja:
nome |COUNT(terrenosDeCadaID)|COUNT(conversasDeCadaID)
joao |         2             |       3
maria|         1             |       2

As tabelas estão assim:
users
id|nome
1 |joao
2 |maria

terrenos
id|idterreno |iduser(mesmo que id da tabela users)
1 |    20    |  1
2 |    21    |  1
3 |    22    |  2

conversas
id|idterreno|msg|iduser(mesmo que id da tabela users)
1 |   20    | a |  1
2 |   20    | b |  1
3 |   21    | c |  1
4 |   22    | d |  2
5 |   22    | d |  2

Tentei fazer com INNER JOIN, mas ainda sou iniciante, e não consegui, quando adicionei o conversas deu errado, abaixo o que tentei:
SELECT nome, COUNT(t.iduser), COUNT(c.user) FROM users u
INNER JOIN terrenos t on u.id = t.iduser
INNER JOIN conversas c on u.id =t.iduser
GROUP BY t.iduser

Comment: A sua ideia está correta, mas o segundo join com a tabela conversas que está com a referência errada: `INNER JOIN conversas c on u.id =t.iduser` deveria ser assim: `INNER JOIN conversas c on u.id =c.iduser`
Answer: Pode chegar a esses valores da seguinte forma:
SELECT      u.nome
        ,   IFNULL(t.totalterrenos, 0)  AS totalterrenos
        ,   IFNULL(c.totalconversas, 0) AS totalconversas
FROM        users   u
LEFT JOIN   (
                SELECT      iduser
                        ,   COUNT(1) AS totalterrenos
                FROM        terrenos
                GROUP BY    iduser
            )       t ON t.iduser = u.id
LEFT JOIN   (
                SELECT      iduser
                        ,   COUNT(1) AS totalconversas
                FROM        conversas
                GROUP BY    iduser
            )       c ON c.iduser = u.id

Estava a dar erro porque o campo nome não estava no GROUP BY.
A consulta nunca iria dar o resultado que esperava porque tinha dois INNER JOIN a duas tabelas com associações diferentes à tabela user, e mesmo corrigindo o GROUP BY não se iria conseguir contabilizar corretamente as ocorrências em cada uma das tabelas.
Comment: ah blz, Obrigado!
Comment: Respondendo à sua questão @LeandroMarzullo, sim, o _LEFT JOIN_ permite obter informação das tabelas associadas tendo ou não registos associados (ao contrário do _INNER JOIN_, que "obriga" a que o _iduser_ exista em todas as tabelas ligadas), e ligamos a uma consulta direta, associando o _iduser_ dessa consulta com o iduser da tabela _users_.
Comment: entendi, funciooun, só teve um porém, tem um usuario que não tem conversa, aí não apareceu na consulta, tem como fazer ele aparecer na consulta com conversas "0"?
Comment: Resposta editada para responder à sua questão. Basicamente, trocámos os _INNER JOIN_ pelos _LEFT JOIN_ e aplicámos um _ISNULL_ aos campos que podem ter valores _NULL_ (devido à falta de informação nas tabelas).
Comment: ele deu esse erro: #1582 - Incorrect parameter count in the call to native function 'ISNULL'
Comment: Alterados os _ISNULL_ para _IFNULL_ (não sabia inicialmente que era MySQL).
Comment: show, deu certinho, só pra eu enteder, vc usou o left join e fez como se fosse uma consulta dentro da outra, isso?
Comment: @LeandroMarzullo Como sugestão, eu colocaria na pergunta (nessa e nas próximas) a tag [tag:mysql], assim todos que forem responder (ou consultar, no caso desta, que já foi respondida) já saberão de qual banco se trata.
Comment: show, agora entendi bem a diferença do join e do left, estou até aplicando em outras consultas aqui...rs
Answer: Se estiver usando o MS SQL Server pode fazer assim:
select

A.nome,
B.terrenos,
C.conversas

from users as A

cross apply (select count(1) as terrenos from terrenos where iduser = A.id) B

cross apply (select count(1) as conversas from conversas where iduser = A.id) C

Teste: http://sqlfiddle.com/#!18/c56b1/11
Comment: não, é mysql, não deu certo

Consulta SQL unificando 3 tabelas


How to get the value from each index?

Question: I'm extremely new to Java and we're tasked to take random values of an array and pass them through a method where it adds all of them for a running total.
For the sumMethod I'd like to take each value from all the index (given by sizeOfArray) and add them together.
Thank you!
public static void sumMethod(double[] arrayOfDoubles){
   //How to get the value from each indexes (given by sizeOfArray) and add them for the sum
   int arrayLength = arrayOfDoubles.length;

        System.out.println(arrayOfDoubles);
   }

  public static void main(String[] args) {
   //1-3: Set up Scanner object to collect user's input on the size of array.
      Scanner keyboard = new Scanner(System.in);
      System.out.println("How many double numerical entries do you have?");
   //4: Declare an array of size sizeOfArray
      int sizeOfArray = keyboard.nextInt();

      //Initialize array
      double[] arrayOfDoubles;
      arrayOfDoubles = new double[sizeOfArray];

      for(int i = 0; i < sizeOfArray; i++){
      //5: Use the Random number Class and walk over the array
         Random randomNum = new Random();
         arrayOfDoubles[i] = randomNum.nextDouble(0.0 , 100.0);
      //6: Invoke SumMethod
         sumMethod(arrayOfDoubles);
      }

   }
}

Comment: you get the value with `arrayOfDoubles[index]`. declare an `int sum = 0` variable outside the `foor loop`, then `sum += arrayOfDoubles[i]` inside your `for loop`. in the end do what you wanna do with the sum.
Comment: @EmadAli This should be posted as an answer, not a comment.
Comment: @Code-Apprentice sorry about that, i'm still unclear about which should be answers and what is comments, I had the idea an answer should be a full long detailed explanation, I see a lot of people giving short description in comment section.
Comment: @EmadAli No need to apologize. Comments are intended to ask the OP for clarification. If you are giving direct advice to how to solve the problem, that should go in a question. The best guidelines I can find are [here](https://meta.stackexchange.com/questions/19756/how-do-comments-work) on [meta].
Comment: @EmadAli `giving direct advice to how to solve the problem [should] go in a question` *direct advice to how to solve a problem should go in an answer*…
Answer: For sumMethod, I'd say the first thing you could do is give it a return value rather than void, (public static double sumMethod). That way when you run that method in main you can hold onto the result it prints out.
I may be wrong but my understanding is that your goal is to take an array and sum up the values within. For that purpose, the following would be a way to do it.
public static double sumMethod(double[] arrayOfDoubles) {
    double total = 0;
    for (double num : arrayOfDoubles) {
        total += num;
    }
    return total;
}

Comment: Our instructor restricted us to have the method return void as well as having the method print out all of the values in the array.
Answer: public static void sumMethod(double[] arrayOfDoubles) {
        double sum = 0;
        for (int j = 0; j < arrayOfDoubles.length; j++) {
            sum += arrayOfDoubles[j];
        }
    }

This will work too, if you are not familiar with the for-each loop yet.
Additionally, it is better to use arrayOfDoubles.length in the loop, in case you edit the code later, and change the size, or add or remove an element.

How to get the value from each index?


Guardar vários valores em um array

Question: Boas, Tenho uma duvida em como poder guardar vários valores em um único array. Tenho o seguinte código que retorna o id da secção .
`$seccaoid = $prod['id_seccao'] = findIDByDescricao($arraySeccaoProduto[$i]);
save('amostras_custos', $prod);`

Isto faz com que me mostre o id do $arraySeccaoProduto[$i].
Por exemplo:
SECCAO----------------------------ID

findIDByDescricao(SECCAOa)----------1

findIDByDescricao(SECCAOc)----------3

findIDByDescricao(SECCAOd)----------4

findIDByDescricao(SECCAOb)----------2

Eu pretendia que no final de percorrer todos os $arraySeccaoProduto[$i] pegasse em todos os ids e guardasse assim:
$ids=[1;3;4;2]

Comment: Como essa publicação ganhou um upvote? Não dá para entender o que o AP quer fazer, não há um [mcve], o AP citou vagamente elementos duma estrutura de dados indeterminada, nenhum do exemplo métodos tem o funcionamento claramente conhecido. Favor ler o [Guia de sobrevivência do Stack Overflow em Português](https://pt.meta.stackoverflow.com/q/8045/101).
Comment: Vê [aqui](https://www.portugal-a-programar.pt/forums/topic/43653-preencher-array/) se te ajuda, na parte: "Agora um exemplo de preenchimento de um array".
Answer: Para guardar diversos valores em um mesmo array tem 2 opções.
Utilizar a função array_push().
Ou utilizar $arr[] = $var.
Doc: https://www.php.net/manual/pt_BR/function.array-push.php
Acredito que você precise utilizar algo mais ou menos assim:
<?php

$arrId = [1,2,3,4,5];

function findIDByDescricao($id)
{
    return $id;
}

for($i=1; $i <= count($arrId); $i++)
{
    $prod['id_seccao'][] = findIDByDescricao($i);
}

print_r($prod);

?>

A Saída ficou assim:
Array
(
    [id_seccao] => Array
        (
            [0] => 1
            [1] => 2
            [2] => 3
            [3] => 4
            [4] => 5
        )

)

Guardar vários valores em um array


difference between IEEE International Conference on Big Data and IEEE ICDM (international conference on data mining)

Question: I'm not sure if this is the right place to ask this question, but I didn't know where to ask.
Recently, I went to the IEEE 2016 International Conference on Big Data in Washington DC, but was surprised to find that there is also a different, IEEE International Conference on Data Mining (ICDM) in Barcelona. Is one more highly ranked than the other, and why does IEEE have two (or more) similar conferences?
Answer: They are two different but related topics. You can do Data Mining on Big Data for instance.
If you look at the call for papers to see the tracks of both conference, you will notice they are pretty different.
ICDM 2016:

Foundations, algorithms, models and theory of data mining
Machine learning and statistical methods for data mining
Mining text, semi-structured, spatio-temporal, streaming, graph, web, multimedia data
Data mining systems and platforms, their efficiency, scalability and privacy
Data mining in modeling, visualization, personalization and recommendation
Applications of data mining in all domains including social, web, bioinformatics and finance

BigData2016:

Big Data Science and Foundations
Big Data Infrastructure
Big Data Management
Big Data Search and Mining
Big Data Security, Privacy and Trust
Big Data Applications

Only one track covers both. Big Data Management or infrastructure has nothing to do with Data Mining, and many Data Mining algorithms are not scalable to Big Data.
Maybe your understanding of these concepts led you to think at first that these conferences are similar but they are definitely not. However, I agree that some papers could go in both, but this is the case for many other conferences.
Conference ranking doesn't mean too much when topics are different. If you work with Big Data, your paper will have more impact if published in a conference focused on Big Data because researchers in this field will more easily be reached, and opposite if you work in Data Mining.


JAXB API to generate Java source files directly to OutputStream

Question: I have a schema file and I want to generate the class files directly into MEMORY instead of file system. I have searched a lot, but everywhere I am finding API to generate java files into filesystem only.
Can any please provide links of API to generate the java source files directly into memory.
Thanks,
Harish
Answer: I haven't leveraged this code in the way you described, but this fragment might point you in the right direction:
<code>import com.sun.codemodel.*;
import com.sun.tools.xjc.*;
import com.sun.tools.xjc.api.*;

SchemaCompiler sc = XJC.createSchemaCompiler();
sc.setEntityResolver(new YourEntityResolver());
sc.setErrorListener(new YourErrorListener());
sc.parseSchema(SYSTEM_ID, element);
S2JJAXBModel model = sc.bind();
</code>
Comment: are we allowed to use com.sun.* code in our production code? Aren't the above package classes subject to change? Please clarify.
Comment: @Harish - There isn't a standard API for generating JAXB source from an XML schema.  You will need to leverage APIs from one of the available schema-to-java tools from a JAXB implementation.  The API above comes from the Metro JAXB implementation.
Comment: @Harish - How are you planning to leverage the source generated directly into memory?
Comment: I will use JavaCompiler in memory compilation feature to generate the classes.
Comment: Could You post more details of the solution? It's very interesting