Dynamically creating a json in react-native

Question: I know that this kind of question is asked before like this & this. from these SO Question I arrived at this code. Trust me am new into React Native and Javascript. I have two troubles 1. I need to get data like this
[
  {
"title": {
  "StudentName": "DIYA",
  "studentId": "00002",
  "name": "DIYA",
  "parentName": "BIJU V",
  "dob": "18 Dec 2009",
  "image": "234567890"
},
"member": [
  {
    "title": "DIYA",
    "date": "31 Aug 2108",
    "month": "Apr",
    "type": "TUTION FEE",
    "amount": "85.000"
  },
  {
    "title": "DIYA",
    "date": "31 Aug 2108",
    "month": "Apr",
    "type": "BUS FEE",
    "amount": "50.000"
  }
]
  },
  {
    "title": {
      "StudentName": "PONNU",
      "studentId": "00003",
  "name": "PONNU",
  "parentName": "BIJU V",
  "dob": "17 Oct 2009",
  "image": "234567890"
},
"member": [
  {
    "title": "PONNU",
    "date": "31 Aug 2108",
    "month": "Apr",
    "type": "TUTION FEE",
    "amount": "90.000"
  },
  {
    "title": "PONNU",
    "date": "31 Aug 2108",
    "month": "Apr",
    "type": "BUS FEE",
    "amount": "55.000"
  }
]
  }]

but what I get is
[
  {
"title": {
  "StudentName": "PONNU",
  "studentId": "00003",
  "name": "PONNU",
  "parentName": "BIJU V",
  "dob": "17 Oct 2009",
  "image": "234567890"
},
"member": [
  {
    "title": "DIYA",
    "date": "31 Aug 2108",
    "month": "Apr",
    "type": "TUTION FEE",
    "amount": "85.000"
  },
  {
    "title": "DIYA",
    "date": "31 Aug 2108",
    "month": "Apr",
    "type": "BUS FEE",
    "amount": "50.000"
  },
  {
    "title": "PONNU",
    "date": "31 Aug 2108",
    "month": "Apr",
    "type": "TUTION FEE",
    "amount": "90.000"
  },
  {
    "title": "PONNU",
    "date": "31 Aug 2108",
    "month": "Apr",
    "type": "BUS FEE",
    "amount": "55.000"
  }
]
  },
  {
"title": {
  "StudentName": "PONNU",
  "studentId": "00003",
  "name": "PONNU",
  "parentName": "BIJU V",
  "dob": "17 Oct 2009",
  "image": "234567890"
},
"member": [
  {
    "title": "DIYA",
    "date": "31 Aug 2108",
    "month": "Apr",
    "type": "TUTION FEE",
    "amount": "85.000"
  },
  {
    "title": "DIYA",
    "date": "31 Aug 2108",
    "month": "Apr",
    "type": "BUS FEE",
    "amount": "50.000"
  },
  {
    "title": "PONNU",
    "date": "31 Aug 2108",
    "month": "Apr",
    "type": "TUTION FEE",
    "amount": "90.000"
  },
  {
    "title": "PONNU",
    "date": "31 Aug 2108",
    "month": "Apr",
    "type": "BUS FEE",
    "amount": "55.000"
  }
]
  }
 ]

I have two apis response which need to be combined to form as the first json. But I doesn't seem to work out as expected the second json is the output got `
 var studentsDetailJson = [];

var eachItem = {
  title: {},
  member: []
};

this.state.data.map((stuItem) => {

  eachItem.title = {
    "StudentName": stuItem.StudentName,
    "studentId": stuItem.StudentID,
    "name": stuItem.StudentName,
    "parentName": stuItem.FatherName,
    "dob": stuItem.DOB,
    "image": "234567890"
  };
  console.log("stu" + JSON.stringify(stuItem));

  this.state.feesDetails.map((feesItem) => {

    if (stuItem.StudentName === feesItem.StudentName) {
      // console.log("fees" + JSON.stringify(feesItem))
      eachItem.member.push({
        "title": feesItem.StudentName,
        "date": feesItem.FeeDueDate,
        "month": "Apr",
        "type": feesItem.FeeDescription,
        "amount": feesItem.FeeAmount
      });
    }

  });
  console.log("eachitem.title" + JSON.stringify(eachItem.title))
  studentsDetailJson.push(eachItem);

});
  console.log("feeitem"+JSON.stringify(studentsDetailJson))
  this.setState({
     processedData : (studentsDetailJson),
     hasData : true
   });

`
Under the student name I need to get only that student details. but am getting both students data. Also its showing same student name in second json item in son array(see second json response) I don't know whats wrong. Pls help.
EDIT 1
I just noticed that after first iteration on this.state.data my son response looks like this `
    [
  {
    "title": {
      "StudentName": "DIYA",
      "studentId": "00002",
      "name": "DIYA",
      "parentName": "BIJU V",
      "dob": "18 Dec 2009",
      "image": "234567890"
    },
    "member": [
      {
        "title": "DIYA",
        "date": "31 Aug 2108",
        "month": "Apr",
        "type": "TUTION FEE",
        "amount": "85.000"
      },
      {
        "title": "DIYA",
        "date": "31 Aug 2108",
        "month": "Apr",
        "type": "BUS FEE",
        "amount": "50.000"
      }
    ]
  }
]

`
after the next iteration it looks like the output json mentioned above
ISSUE RESOLVED
leaving solution as it might help someone sometime.
I modified my code below `
var studentsDetailJson = [];
this.state.data.map((stuItem) => {
  var eachItem = {
    title: {},
    member: []
  };
  eachItem.title = {
    "StudentName": stuItem.StudentName,
    "studentId": stuItem.StudentID,
    "name": stuItem.StudentName,
    "parentName": stuItem.FatherName,
    "dob": stuItem.DOB,
    "image": "234567890"
  };
  //console.log("stu" + JSON.stringify(stu));
  this.state.feesDetails.map((feesItem) => {

    if (stuItem.StudentName === feesItem.StudentName) {

       console.log("fees" + JSON.stringify(stuItem.StudentName))
      eachItem.member.push({
        "title": feesItem.StudentName,
        "date": feesItem.FeeDueDate,
        "month": "Apr",
        "type": feesItem.FeeDescription,
        "amount": feesItem.FeeAmount
      });
    }

  });
  studentsDetailJson.push(eachItem);

`
Thanks in Advance
Answer: You are pushing details to eachItem.member.
eachItem.member = this.state.feesDetails.map((feesItem) => {
    if (stuItem.StudentName === feesItem.StudentName) {
      // console.log("fees" + JSON.stringify(feesItem))
      return {
        "title": feesItem.StudentName,
        "date": feesItem.FeeDueDate,
        "month": "Apr",
        "type": feesItem.FeeDescription,
        "amount": feesItem.FeeAmount
      });
    }
  });

This could be one of solution. But I suggest rethinking using temp variable since I guess we are mutating the temp variable.
Comment: but doesn't it need to omit name other than current name. there is 2 students as of now. during the first iteration at this.state.data the response is correct (please see my edit 1) and when the second iteration comes the response totally changes


SSL error on XAMPP

Question: I installed ssl on XAMPP just fine. When I try to start Apache in the Xampp Control Panel, it says the following error:
(localhost:80) You configured HTTPS(443) on the standard HTTP(80) port!

Which is weird beacuse I created a domain that uses ssl, not localhost. My httpd-ssl.conf is as follows... (not the entire file, but VirtualHost directive)
<VirtualHost *:443>
    DocumentRoot "C:/xampp/htdocs/secure/movies/public_html"
    ServerName www.movies.local
    ServerAlias movies.local

    SSLEngineOn on

    SSLCertificateFile      "C:/xampp/htdocs/secure/resources/server.crt"
    SSLCertificateKeyFile   "C:/xampp/htdocs/secure/resources/server.key"
    SSLCACertificateFile    "C:/xampp/htdocs/secure/resources/ca_client.crt"

<Directory "C:/xampp/htdocs/secure/movies/public_html">
    Options Indexes
    Order allow,deny
    Allow from all

    SSLRequireSSL
    SSLVerifyClient require
    SSLVerifyDepth 1
</Directory>

</VirtualHost>

I tried investigating alot for the past 3 hours but nothing on this error. Also, so there would be no confusion, in httpd-ssl.conf it listens to port 443 and in httpd.conf it listens to port 80.
Comment: "...not the entire file, but VirtualHost directive..." - the error is probably in the other parts of the config which you did not show.
Comment: well i didn't change anything, i just added VirtualHost to httpd-ssl.conf
Answer: You've got a typo in that config:
SSLEngineOn on
should be
SSLEngine On

SSL error on XAMPP


This file does not belong to any project Code insight might not work properly when opening project in clion

Question: I am a total newbie in C programming and Clion interfaces, so please share the screenshot for me to understand it better. Recently I downloaded a training file .c when I open it in CLion, the compiler won't work. Instead, the compiler generated my other .c file. So far CLion works fine, but somehow CLion has the problem with this downloaded files. Although they work fine in CodeBlocks, How to fix this?
Clion file does not belong_img
Here is my training file c-learn
Comment: Welcome to [so]. Please review the [ask] section and provide a [mcve]. Moreover, please avoid the use of screenshots and actually post your relevant errors.
Answer: Add new executable to new file.
You need to open CMakeLists.txt and add something like
add_executable(foo 02-12_value2.c)
Comment: thanks, Maxim! you just need to add foo your_c_file_name


How can I analyse multiple choice questions in R?

Question: I have a CSV from an online survey including numerical, single choice and multiple choice questions. The multiple choice questions are represented like this:
<code>┌─────┬─────┬────┬─────┐
│  A  │  B  │ C  │  D  │
├─────┼─────┼────┼─────┤
│ "Y" │ NA  │ NA │ NA  │
│ NA  │ "Y" │ NA │ "Y" │
│ NA  │ NA  │ NA │ NA  │
│ "Y" │ "Y" │ NA │ NA  │
└─────┴─────┴────┴─────┘

</code>
So an answer is either the character "Y" or null.
Now my question is if there is a solution which lets me easily make a histogram or something similar to visualize the frequency of each answer and use it in statistical testing in R.
Sorry if this is trivial but I don't have the experience and couldn't dig something up yet.
Answer: If your csv is read in as a dataframe, df then:
<code>df2 <- !is.na(df)
nrows <- nrow(df2)
yes <- apply(df2, 2, sum)
percentyes <- 100 * yes / nrows
percentno = 100 - percentyes
barplot(percentyes)
</code>
Comment: I understand the logic in this. However it doesn't work, as `colSums()` expects numerical values and I only have the character "Y". I will see if I can find a solution.
Comment: Right.  Sorry.  Updated solution posted.  The "Y"s are converted to TRUE and summed.  There may be a simpler way but this one works.


LocalDate MySQL persistence comes back the date before

Question: I have seen this question posted a few times on StackOverflow, and it has been with mostly Spring Boot apps with Spring Boot Configuration.   I've followed all the steps, and I still have this issue.  If I can't get this resolved soon, I will have to go back to the old java.util.Date in order to persist my data to the database ... at least it worked without issues.  So, I have a Spring 5.1.2.Release app, with Hibernate 5.4.0.Final, the hibernate-java8 dependency, and the latest MySQL Connector 8.0.13.
I understand from previous posts and other articles on the Net that if the database is set for UTC, but the App is running in another timezone, in my case GMT-5 for EST, then this problem might pop up.
So, here are the technical details:
My MySQL connection looks like:
hibernate.connection.url=jdbc:mysql://localhost:3306/my_db?
serverTimezone=UTC&useLegacyDatetimeCode=false&useTimezone=true

The connection string, is used in the applicationContext.xml:
<bean id="dataSource"
    class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName">
        <value>${hibernate.connection.driver.class}</value>
    </property>
    <property name="url">
        <value>${hibernate.connection.url}</value>
    </property>
    <property name="username">
        <value>${hibernate.connection.username}</value>
    </property>
    <property name="password">
        <value>${hibernate.connection.password}</value>
    </property>
</bean>

My Hibernate properties in my applicationContext.xml look like:
<property name="hibernateProperties">
        <props>
            <prop key="hibernate.dialect">${hibernate.dialect}</prop>
            <prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
            <prop key="hibernate.cglib.use_reflection_optimizer">${hibernate.cglib.use_reflection_optimizer}</prop>
            <prop key="useUnicode">true</prop>
            <prop key="useLegacyDatetimeCode">false</prop>
            <prop key="serverTimezone">UTC</prop>
            <prop key="useTimezone">true</prop>
            <prop key="hibernate.jdbc.time_zone">UTC</prop>
        </props>
    </property>

My Maven dependencies are:
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>8.0.13</version>
    </dependency>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>5.4.0.Final</version>
    </dependency>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-java8</artifactId>
        <version>5.4.0.Final</version>
    </dependency>

My Entity Code is simple:
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "transaction_id")
private long txId;

@Column(name = "transaction_date")
private LocalDate txDate;

I save my code to the database like this:
@Override
public TxEntity create(TxEntity txEntity)
{
    this.sessionFactory.getCurrentSession().save(txEntity);
    this.sessionFactory.getCurrentSession().flush();
    this.sessionFactory.getCurrentSession().refresh(txEntity);
    return txEntity;
}

The database has "transaction_date" as a DATE field in MySQL.
My Unit Test shows that I can create a new record, and I have set the date as follows:
      LocalDate today = LocalDate.now();

I persist the record, and when I test:
assertEquals(today, myRecord.getTransactionDate());

this fails, because I get the previous date.
I thought that if I used the latest versions of Hibernate and the Hibernate-java8 I would be fine, but that's not the case.   I thought if I pulled in the latest JPA2.2 that would work, but it's not.  So, I think I am doing everything right, and I still have an issue.
So, if there is anything you need to see, let me know and I can add it.  I think I am doing everything right, but if there is anything off I need to fix, please let me know.    And of course, I'll keep looking at this myself.
Comment: Spring 4 doesn't officially support Hibernate 5.4 (afaik) so you might want to reconsider. Also the `java8` types are part of `hibernate-core` since hibernate 5.2 so ou don't need the additional dependency. You set the `hibernate.connection.url` but I don't see anywhere where you use this URL. If you use that to configure hibernate to use the connection but also injecting a manually configured datasource the setting is pretty much doing nothing. In short there is too little config information to see if you are configuring the right things.
Comment: I also mis the `hibernate.jdbc.time_zone` property being set to `UTC` in your hibernate configuration. Also see https://vladmihalcea.com/how-to-store-date-time-and-timestamps-in-utc-time-zone-with-jdbc-and-hibernate/
Comment: @M.Deinum   I just added where I use the connection string, it's right there in the applicationContext.xml file ... what else don't you see that might help.   I can always move this application to Spring 5 ... I am not a fan of Spring Boot.
Comment: Property name was misleading. None the less you should have the `hibernate.jdbc.time_zone` property in your hibernate properties and that is missing. See the linked article in my previous comment which explains all that.
Comment: @M.Deinum  my mistake, this is not Spring Boot, but it is using Spting 5.1.2.Release
Comment: Again you are missing the `hibernate.jdbc.time_zone` property in your configuration. See the earlier linked article.
Comment: @M.Deinum  added the missing property ... no change!   And yes, I read the article.   I actually tried that property last night  and there was no change, and I did read the article.
Comment: See https://dev.mysql.com/doc/connector-j/8.0/en/connector-j-properties-changed.html which clarifies that `useLegacyDatetimeCode` has been removed. Not sure what the replacement is.
Comment: According to one of the hibernate developers it might be a bug. Could create a small sample to reproduce the issue and create an issue in the [hibernate issue tracker](https://hibernate.atlassian.net/secure/Dashboard.jspa)?
Answer: If you don't want to touch your Java project or connection strings to solve this issue you can configure the MySQL timezone directly. On my computer the JVM timezone was correct (America/Sao_Paulo), so changing it to UTC in order to solve this conflict with MySQL was a no go.
The problem I had was just at the MySQL timezone configuration. Since I run MySQL on a container it got a wrong default timezone. The fix was to pass the --default-time-zone=America/Sao_Paulo to the MySQL container configuration, which fixed this issue. Now both MySQL and JVM got the same timezone.
Answer: For me, after some debugging for some time, I noticed Mysql timezone was UTC, but my default jvm timezone which can be seen by:
public class DefaultTimeZone {
    public static void main(String[] args) {
        System.out.println(java.util.TimeZone.getDefault().getID());
    }
}

was America/Montreal so in updated my ide (IntellJ) settings to pass -Duser.timezone=UTC as a parameter when starting the application. (Of course there are so many other ways to do this, but in my case this was enough)


What would be a good general practice routine for piano and guitar that anyone can build from?

Question: I'm a beginner on guitar and piano. I have studied (and kinda still am studying) theory for about 6 months now. I'm not interested in just learning songs, I would like to learn how to improvise and develop my own voicing.
I don't think there is a universal practice routine for everyone. That being said, I still feel like there's at least some techniques, exercises, and whatnot that every beginner might use to play toward an intermediate level and develop a personal routine. I've been told that just drilling scales won't help so I'm asking here for that added human element.
I'm hoping this will be helpful to more than just myself.
Answer: While learning songs shouldn't be your sole priority, I think that learning repertoire should still be a fairly substantial part of your musical development. Done right, it should also guide you towards what you need to practice. If you try to play a song on guitar (for example), and find that you can't make the chord changes fast enough, then you can turn those difficult changes into an exercise for yourself.
This is also good because it gives you a tangible sense of progress. It is often difficult to find motivation if all you're doing is playing abstract drills or exercises, but when you're instantly able to apply what you're learning towards a new song, then you'll have a much stronger sense of becoming better at your instrument. So instead of trying to figure out which techniques to practice, perhaps start out by figuring out what you want to play, and then think about which techniques will take you there.
Since you mention wanting to improvise, I think one important thing (which is often neglected by beginners) is to work on developing your ears. To be good at improvisation you need a strong connection between your ears and your fingers (so to speak). The ideal (which will likely take some practice) should be that you can imagine a phrase or melody in your head, and be able to play it on the instrument almost instantly.
One exercise you could start with to develop your ears is recognizing intervals. There are a lot of websites/apps/programs which will play you two notes and ask you to identify the interval between them (for example: here). Since you have been studying theory I assume you know about intervals already, but you should be able to identify them by sound as well. If you're new to this I would start out with only two or three intervals, and add more as you get comfortable (maybe start with perfect fourths and fifths, then add major and minor thirds etc.).
Another thing you should try working on is to transcribe music that you like. This is tricky if you haven't done it before but it's very worth it once you get going. Start out by finding some simple song that you like and try to work out how it's played just by listening (if you have a way of writing it down that would be good too). Figuring out chords is more difficult when starting out, but you should be able to make some progress with simple melodies.
Once you've worked out how something is played, you can use your study of theory to analyze it and figure out how it works. You may ask yourself things such as: Does the melody fit into a particular scale? Which notes are emphasized and which are avoided? How does the melody relate to the underlying chords? Does it mostly play chord-tones, or are there some "outside" notes as well? Are there any recurring melodic phrases or rhythmic patterns? There are endless things you can consider, but try to focus in on the things which make the music sound good to you. This doesn't only apply to the "theory" part the music, but will also be a good way to pick up on things like phrasing and dynamics, which are equally important in making something sound good.
When you can put a name to the things you like, you'll be able to incorporate it into your own playing. For example: say you analyze a guitar solo (or whatever) that you really like and you notice that the guitarist has a tendency to target a certain note in the underlying chord (the 3rd or 6th or 9th or whatever it is), then you can easily turn that into a practice exercise for yourself. Simply figure out where those notes are found on the instrument, and practice improvising while targeting those notes. That way you'll both expand your own vocabulary on the instrument, and develop a stronger sense of hearing.


Problema com dicionário - AttributeError: 'int' object has no attribute 'get'

Question: Estou começando a aprender o básico no Python, e um dos exemplos sobre listas de dicionário pede algo assim:
inventory = {'a' : 1 , 'b' : 6 , 'c' : 42 , 'd' : 1 , 'e' : 12}

def DisplayInventory(stuff):
    for k,v in stuff.items():
        stuff = k + v.get(stuff,0)
        print(k+v)

DisplayInventory(inventory)

Só que eu continuo tendo esse erro:
Traceback (most recent call last):
   line 8, in <module>
    DisplayInventory(a)
   line 5, in DisplayInventory
    stuff = k + v.get(stuff,0)
AttributeError: 'int' object has no attribute 'get'

Comment: em cada iteração, k vai ser uma chave (primeiro vai ser a, depois b, depois c etc.) e v vai ser o número correspondente a essa chave no dicionário (1, 6, 42 etc.). Não faz sentido fazer "get" num número. Nem eu e nem o Python estamos entendendo o que você quis fazer aí, por isso o erro. Explique qual saída você quer porque você provavelmente está no caminho errado. Faça o [tour] e dê uma lida em [ask] pra saber como fazer perguntas mais fáceis de serem respondidas.
Comment: A intenção do exercício que eu tentei fazer é exibir com o print algo como o nome da chave mais o nome do valor dessa chave
Comment: O que você quer fazer nesta linha "stuff = k + v.get(stuff,0)" ?
Answer: O erro aconteceu pois você tentou chamar um método que não existe em int.

v.get(stuff,0)

Como você explicou depois nos comentários que queria apenas mostrar a chave e valor de cada elemento em inventory, consegui chegar no seguinte código a partir do seu:
inventory = {'a' : 1 , 'b' : 6 , 'c' : 42 , 'd' : 1 , 'e' : 12}

def DisplayInventory(stuff):
    for k,v in stuff.items():
        print(str(k) + ' ' + str(v))

DisplayInventory(inventory)


SSL certificates - can they be used on more than one server

Question: I have many websites all scattered on different IIS servers but they all accessible via sitename.example.co.uk. i.e. site1.example.co.uk
Btw this is only an example so I can get to grips with SSL certificates hence they're all self-signed via the following process

Create my own CA
Generate key and csr
then generate signed certificate

http://datacenteroverlords.com/2012/03/01/creating-your-own-ssl-certificate-authority/
The resultant certificate of step 3 is assigned to *.example.co.uk.  Can that be used on multiple servers, or do I have create a new certificate + key for each server despite them matching the domain on the certificate?
Answer: The certificate is a third-party-signed public key, and can be used by anyone with the corresponding private key.  So as long as you give each server the matching private key, it can use the certificate.
But if you're making your own CA, why bother?  You can mint certificates for each server and they will be no less (nor any more) trusted than the one private-CA-signed certificate you're proposing to use everywhere, and you'll have less of a problem with keeping a single private key secure through distribution to, and use on, many endpoints.
Comment: We have a similar situition and have different web sites on different servers belonging to the same domain as site1.abc.com, site2.abc.com, site3.abc.com. So, which steps should we apply in order to use the certificate of abc.com on different IIS servers for these web sites? Could you please clarify us a little bit more?
Comment: @binary That's a different question, so you should ask it as a new question and not as a comment here.
Comment: @MikeScott I think it is exactly the same situation and creating a new question for this issue means that it will be marked as a duplicate of this question.
Comment: @binary You're asking about the details of configuring IIS, so to me it's a new question - though you should probably link to this one to show you're aware of it.  At any rate, I won't use non-free software, so I can't help with IIS config.  Sorry.
Comment: @MadHatter Ok, have a look at [Using the same SSL Certificate of a Domain on different IIS Servers?](http://serverfault.com/questions/764950/using-the-same-ssl-certificate-of-a-domain-on-different-iis-servers) please? Thanks...
Answer: There's no technical reason why you can't use a wildcard SSL certificate for *.example.co.uk on as many servers as you want whose domain names match the wildcard. But some certificate issuers have commercial terms & conditions that limit the number of servers on which the certificate can be used. It's not a technical limit, and the certificate will still work on as many servers as you want; you'll just be in breach of your contract with them if you use it on more servers than you have agreed. Of course that won't apply to your self-signed certificates that you're using to test it out, but it may when you get round to actually obtaining a certificate that's signed by a trusted CA.
Answer: There is nothing technically prohibiting you from installing a given cert on multiple machines. However, if you were purchasing the cert from a commercial CA then the license agreement probably requires you to pay for each server even if the same cert is installed.
I believe some security / corporate standards discourage high-level wildcard certs (so no *.example.co.uk, but perhaps *.somespecificapp.example.co.uk), to minimize damage if the cert is leaked.
A possible incentive to install the same cert+key on all machines is to use cert pinning (https://www.owasp.org/index.php/Certificate_and_Public_Key_Pinning/Certificate_and_Public_Key_Pinning)


I need help understanding the replacement of TWO in the below code

Question: I ran it through Code::Blocks and it shows me the final answer 1. How is TWO then replaced in the " i = i-2*TWO" statement and why is like that?
The code is part of a homework exercise I'm trying to solve/understand:
#include <stdio.h>
    #define  ONE    1
    #define  TWO    ONE + ONE
    int main(void) {
        int i = 2;
        i = i - 2 * TWO;
        printf("%d\n", i);
        return 0;
    }

Comment: Think like a preprocessor!
Comment: This is a simple one, but for more complex macros, some (or maybe all) compilers have an option to save the pre-processed code file. For example: [How do I see a C/C++ source file after preprocessing in Visual Studio?](//stackoverflow.com/q/277258)
Comment: It will be replaced as `i = i - 2*1 + 1`, which yields result 1.
Answer: Just make the substitution yourself.
i = i - 2 * TWO;

is
i = i - 2 * ONE + ONE;

So you have
i = 2 - 2 * 1 + 1;

So i will have the value 1.
If you want to get the result equal to -2 then rewrite the macro like
#define  TWO    ( ONE + ONE )

Comment: @painkiller It is like in mathematics because you are not using parentheses.
Comment: So it's not like in mathematics when you do the same replacement: i = i-2*TWO =  i = i-2*(ONE+ONE)  = 2 -2*(1+1)= 2-4 = -2 ?
Comment: Ok I get it, thank you all for the answers.
Answer: You can see what the compiler sees as final expression by running gcc -E <filename.c>.  That should help in understanding why the result is 1.


Keys.ESCAPE in selenium webdriver(python)

Question: I am using selenium webdriver (with python). I have a use case where I want to test that submit button get disabled once the form get submited. To test it, I send ESCAPE key to stop the page to load next page so that I can access the elements of same page.
password.send_keys("abcdef", Keys.ENTER, Keys.ESCAPE)

The problem is that it works fine in Firefox browser but it is not working in Chrome. In Chrome sending ESCAPE seems to be not working and it submits the form and loads the next page.
Is there any other solution or workaround to overcome this?
Answer: After trying many options, finally the following option seems to be working -
password.send_keys("abcdef", Keys.ENTER, Keys.ESCAPE)  # this works for Firefox driver
drive.execute_script("window.stop();")                 # this works for Chrome driver

Answer: You can try one of these 3 suggestions from https://sqa.stackexchange.com/a/6208 :

Installing an extension in Chrome called Stop load
using the built in pageLoadTimeout() method in Selenium
using Sikuli or Autoit to access the browser's native controls


Tensoring with vector bundle is a dense endofunctor of $D^b(\text{coh }X) $?

Question: A functor $F:T\to R$ between triangulated categories is dense if every object of $R$ is isomorphic to a direct summand in the image of $F$.
Let $R=T=D^b(\text{coh }X)$ for a variety $X$ and consider the functor $-\otimes \mathcal{V}$, $\mathcal{V}$ a vector bundle.
I do not understand the following
claim: "$-\otimes\mathcal{V}$ is a is a dense functor, as any object $P\in D^b(\text{coh }X)$ is a summand of $(P\otimes V^\vee)\otimes V$."
Can anyone help?
Answer: What part of the claim you don't understand?
For any vector bundle $V$ the bundle $V\otimes V^\vee$ contains trivial 1-dimensional vector bundle (spanned by the section "Id"$\in V\otimes V^\vee$; the map in the opposite direction is the evaluation map). So any object $P\in D^b$ is a summand of the image of the object $P\otimes V^\vee$.
Comment: Thanks Grigory. Are you saying $V\otimes V^\vee\to \mathcal{O}_X$ splits? I was not aware of that.
Comment: Yes, exactly (it splits because this map has section coming from $V\otimes V^\vee\cong hom(V,V)\ni Id$).


PSQL does not detect .pgpass file

Question: I have tried

Setting the permission of .pgpass to 0600
Confirmed .pgpass is in my user's home directory (/home/brandon/.pgpass)
use -w in pg_dumpall command
Confirmed the data in .pgpass is correct

The script (https://wiki.postgresql.org/wiki/Automated_Backup_on_Linux)  for automated backup works if I type the password again and again which is why i added -w to all the commands. It for some reason does not read the .pgpass file .
There are multiple error messages but they are generally this.
 pg_dumpall: could not connect to database "template1": FATAL:  password    authentication failed for user "postgres"

FATAL:  password authentication failed for user "postgres"
pg_pass file :
localhost:5432:my_db:postgres:password

command line :
username@droplet:~/ProjectDir$ bash cronjob/db_backup/pg_backup.sh
Making backup directory in /home/backups/database/postgresql/2017-12-06/

Performing globals backup
--------------------------------------------

Globals backup
cronjob/db_backup/pg_backup.sh: line 80: /home/backups/database/postgresql/2017-12-06/globals.sql.gz.in_progress: Permission denied
pg_dumpall: could not connect to database "template1": fe_sendauth: no      password supplied

[!!ERROR!!] Failed to produce globals backup

Performing schema-only backups
--------------------------------------------

psql: fe_sendauth: no password supplied
The following databases were matched for schema-only backup:

Performing full backups
--------------------------------------------

psql: fe_sendauth: no password supplied

All database backups complete!

Comment: Look at the PostgreSQL server log. Show your .pgpass file (excluding passwords) and your command line.
Comment: I added the pgpass and commandline output, going to figure out how to find the server log
Answer: You should supply the actual calls to pg_dump and pg_dumpall for a more detailed answer.
However, from your output I see that pg_dumpall (?) tries to connect to database template1, but in your .pgpass file the only database is my_db.
You'll have to add entries to .pgpass for all databases to which you are trying to connect.
localhost:5432:mydb1:postgres:password
localhost:5432:mydb2:postgres:password
localhost:5432:mydb3:postgres:password

Alternatively, you are also able to put an * as a placeholder for different database names.
localhost:5432:*:postgres:password

Make sure that all the fields in .pgpass are the right/matching ones. If any of them (host, port, etc.) don't match, the unclear, uninformative and arguably wrong fe_sendauth: no password supplied error message will be the same.
Comment: I did supplied the calls to pg_dump and pg_dumpall. the script I linked is that with the exception of adding -w to all calls.
Comment: You have to add a line to `.pgpass` for every database to which you want to connect.
Comment: Understood. I will try it tommorow. 12 AM here

PSQL does not detect .pgpass file


Why are arrays not implemented as hashes with numerical keys?

Question: Having returned to development after an absence of over a decade I am getting myself up to speed with the latest technologies for web development. Reading this post I see that I already understood the difference between hashes and arrays.
However, doesn't this mean that arrays are just a type of hash that uses a numerical key? As there is no reason to believe that an implementation of an array will automatically maintain the sequential nature of the array indices (when you delete or insert items for example), is there any greater difference than the inherent ordering of an array?
I mean, to step through an array, you need to set up a loop through the indices, the same as looping through the keys of a hash, and then you could order the numerical hash key set to behave the same (i.e. access the items from 1 to the last number that is a key in the hash in numerical sequence). To access an array element, you use the indices of the value you want, the same as giving the numerical key from the hash.
I came to this question while learning about arrays and hashes in Ruby on Rails, but it is a general question.
Answer: A Hash is essentially an array.  Hash keys have some type of conversion function to translate an object of another type (or an integer set of other values) into the integer index of an array.  Conversely, an array is a Hash that does not translate the keys into a separate type or value of index.  However, calling an array a Hash implies an extra layer of functionality that does not exist, since there is no key conversion.
By definition, the objects of an array are stored in consecutive locations in memory, accessible by index.
Even when either type of data structure can be used, one benefit of using hashes with Integer keys is that a larger spread of integers can be stored in a smaller number of buckets. E.g., if your number keys are 5 integers near 1, 10, 100, 1000 and 10000 you don't need 10K buckets to have a hash of these 5 elements, but you do need that many if you use a straight-up array. Hash functions tend to be recalculated and more memory reallocated as the hash grows and the benefit of using an array is that its size can be more easily controlled and can remain fixed.
Comment: Okay, so the benefit of having separate implementations of arrays and hashes is one of complexity? That is to say, sometimes an array does everything needed, so using a hash with a numerical key is going from array, to hash, back to array (due to the point you made about conversion of keys to integers), back to a hash, which you then force to behave as an array! Should I think of hashes as adding some functionality to the array data structure rather that an array being a special case of a hash data structure?
Comment: Ok, thanks. Although they seem to be the same or very similar, I think they are, in fact, different beasts. It seems to me that whenever it is appropriate an array should be preferred. Hashes are for different situations, when the goal is not simply to store a range of data, but when it is important what the array key is. Thanks for the explanation @La-comadreja.
Comment: Just changed my answer.  Yes, it is less efficient to use a Hash with a numerical key if the keys are more or less consecutive integers.  The hash function and rehashing can be extra overhead.  I like to think of hashes as a translation between other types, including objects, and array indices.  You don't always need the translation and when you don't, it's counterproductive.
Answer: Here is how declarative programming defines it.
Difference between Declarative and Procedural Programming?
http://en.wikipedia.org/wiki/Procedural_programming
http://en.wikipedia.org/wiki/Declarative_programming
There are primitive, composite, and abstract data structures.
 - An Array is composite.
 - A Hash is abstract.
We have both because they are fundamentally different.
For example you can't pop/push primitives into a Hash like you can with an Array, because a Hash uses unordered key-values while an Array has an index.
http://en.m.wikipedia.org/wiki/List_of_data_structures
Comment: Thanks for the link, but I am not sure that is correct. An abstract data type is a description of a data type given solely on the functionality. As you can describe an array mathematically as a datatype of two actions (get(A,i) and set(A,i,V)) such that get returns the element at position 'i' and set sets the element at position 'i' to 'V' such that get(set(A,i,V),i) = V, an array can also be an abstract data type. I take the point that they are different data types, as mentioned in the comments above, but I dispute that it is because they belong to different categories.
Comment: You would be correct if we were talking procedural languages, in the context of data structures and declarative programming an abstract is not based on functionality but definition.
Comment: A great explanation of this on SO: http://stackoverflow.com/questions/1619834/difference-between-declarative-and-procedural-programming
Comment: @NectarSoft Let me apologize, you and I are both correct.
Comment: Sorry, wurde, I am not sure what point your making. Data structures in the context you used them in your answer are independent of programming languages.
Comment: Ok. Describing a datatype as 'two actions' signals you think procedurally. The world around you is a sea of expressions, and what isn't immediately obvious to you are the transient states.


How Do I Plot Static Markers with Uber's "react-map-gl" Library?

Question: The documentation of the react-map-gl library is clear for DraggableMarkers, but it does not indicate if/how I can plot static markers.  I just want a simple map with a few map markers (fixed to a lat/lng position). Does anyone have an idea if this is possible?
Here is the link: https://github.com/uber/react-map-gl
Comment: What do you mean by static markers? If you have a dataset in mapbox studio that contains the markers, you could create a map style that contains the dataset and use the style in `react-map-gl`. Or are you looking to create a layer (e.g. with points) in your client?
Comment: @forrert I have a geoJson that contains multiple points (lat/lng). I want to plot them on the map (as a layer), but I don't want those points to be draggable. It doesn't seem like the documentation covers that though. Thanks!
Answer: In order to display a GeoJSON layer with react-map-gl I would recommend the following steps:

Use the mapbox API to download the style
Add your GeoJSON as a source to the style
Add your custom layer styling to the style
Wrap your resulting style with Immutable.fromJS and provide it to your MapGL component via the style prop.

If you built your app with redux and the GeoJSON points are part of your state, I would recommend to keep the points and the downloaded (original) style in the store separately. The final style can then be constructed as described in Computing Derived Data.


Deleting a certain line on linux

Question: For example I have a caf.txt file and I want to delete a "donut" word in the document without entering the document on linux .How can I do it?
Comment: Then check Mike's answer and accept it so the question could be closed. Thanks
Comment: You want to delete just the word or the line containing that word?
Comment: line containing that word
Comment: It took less than a minute to find a duplicate.
Answer: To delete just the word "donut"
sed -i 's/donut//g' caf.txt

To delete lines that contain the word "donut"
sed -i '/donut/d' caf.txt

Answer: What I do is:
sed '/text_to_delete/d' filename | sponge filename
This will make the change to the source file.

Deleting a certain line on linux


How to deal with both stationary and non-stationary time series

Question: I'm a bit frustrated since the time series I am trying to analyse right now has definitely non-stationary curve but it's last values differ greatly from the mean making the time series stationary.

According to Dickey-Fuller tests, if I exclude the last 5% of the dataset, the time series is non stationary but with the whole dataset included it's totally stationary according to the test's results.
The orange box in the right part of the plot is the part of the dataset i'm excluding/including.
Should I work with 95% of the dataset?
How should one deals with such kind of problems?
I've attached an image of the time series plot and the results of the Dickey-Fuller tests.
Dickey-Fuller with the whole dataset

Test Statistic                  -4.113412
p-value                          0.000920
no_of_Lags Used                       9.000000
Number of Observations Used    112.000000
Critical Value (5%)             -2.887712
Critical Value (1%)             -3.490131
Critical Value (10%)            -2.580730

Dickey-Fuller with the first 95% of the dataset

Test Statistic                   3.435185
p-value                          1.000000
no_of_Lags Used                       7.000000
Number of Observations Used    108.000000
Critical Value (5%)             -2.888697
Critical Value (1%)             -3.492401
Critical Value (10%)            -2.581255

Thanks in advance!
Comment: It seems that the structural break is messing with my time series
Answer: You need to specify what you mean by 'analyze'.
You seem to be dealing with a structural break in your time series. If your objective is to detect anomalies or to prove that a structural break occurred, there are tools for doing that.
If your objective is forecasting, then the structural break has made your time series very difficult to forecast and your going to need a lot more data about the periods after the break to be able to generate any reliable forecasts.
You will also want to look into some causal analysis of why the break happened.


Convert Jenkins Script to Declarative Pipeline

Question: I have a scripted pipeline which I need to checkout from a repo rather than have locally. However, when I add it to git the job fails instantly. Here is the working script;
node {
    INSTANCE_ID = ""

    stage('Get Instance Id') {
        INSTANCE_ID = sh (
            script: 'aws ec2 describe-instances --region=$awsRegion --filters Name=tag:Name,Values=\"$instanceName\" --query \'Reservations[0].Instances[0].InstanceId\'',
            returnStdout: true
        ).trim()

        if (INSTANCE_ID == "") {
            error 'No instance with the name ' + $instanceName + ' was found in the ' + $awsRegion + ' region.'
        }
    }

    stage('Start EC2 Instance') {
        sh ('aws ec2 start-instances --region=$awsRegion --instance-ids ' + INSTANCE_ID)
    }

    stage('Wait for instance to be running') {
        INSTANCE_STATE = sh (
            script: 'aws ec2 describe-instances --region=$awsRegion --instance-id ' + INSTANCE_ID + ' --query \'Reservations[0].Instances[0].State.Name\'',
            returnStdout: true
        ).trim()

        numberOfStatusChecksPerformed = 0
        while (INSTANCE_STATE != '"running"') {
            echo INSTANCE_STATE
            sleep 20
            numberOfStatusChecksPerformed = numberOfStatusChecksPerformed + 1

            // Wait 5 minutes
            if (numberOfStatusChecksPerformed > 15) {
                error 'Instance state was not running, it status is: ' + INSTANCE_STATE
            }

            INSTANCE_STATE = sh (
                script: 'aws ec2 describe-instances --region=$awsRegion --instance-id ' + INSTANCE_ID + ' --query \'Reservations[0].Instances[0].State.Name\'',
                returnStdout: true
            ).trim()
        }
    }
}

I try to convert it by changing; node { to;
#!/usr/bin/env groovy

def INSTANCE_ID = ""

pipeline {
    agent any
    stages {

The rest stays the same. I get the following error;
java.io.FileNotFoundException
    at jenkins.plugins.git.GitSCMFile$3.invoke(GitSCMFile.java:167)
    at jenkins.plugins.git.GitSCMFile$3.invoke(GitSCMFile.java:159)
    at jenkins.plugins.git.GitSCMFileSystem$3.invoke(GitSCMFileSystem.java:193)
    at org.jenkinsci.plugins.gitclient.AbstractGitAPIImpl.withRepository(AbstractGitAPIImpl.java:29)
    at org.jenkinsci.plugins.gitclient.CliGitAPIImpl.withRepository(CliGitAPIImpl.java:72)
    at jenkins.plugins.git.GitSCMFileSystem.invoke(GitSCMFileSystem.java:189)
    at jenkins.plugins.git.GitSCMFile.content(GitSCMFile.java:159)
    at jenkins.scm.api.SCMFile.contentAsString(SCMFile.java:338)
    at org.jenkinsci.plugins.workflow.cps.CpsScmFlowDefinition.create(CpsScmFlowDefinition.java:110)
    at org.jenkinsci.plugins.workflow.cps.CpsScmFlowDefinition.create(CpsScmFlowDefinition.java:67)
    at org.jenkinsci.plugins.workflow.job.WorkflowRun.run(WorkflowRun.java:303)
    at hudson.model.ResourceController.execute(ResourceController.java:97)
    at hudson.model.Executor.run(Executor.java:429)
Finished: FAILURE

Answer: You don't need to convert to a Declarative Pipeline; just stick with Scripted if it works for you.  Generally speaking, it's much more difficult to convert Scripted Pipelines to Declarative Pipelines than the other way around.  If you have a working Scripted Pipeline, don't change it at all, just put the working Pipeline script into your Jenkinsfile in your Git repository and it should work just fine.
Comment: According to https://stackoverflow.com/questions/53646808/jenkins-restart-from-stage-not-available-in-my-pipeline-ui there are some advantages to using declarative pipeline, such as the ability to restart from stage
Answer: Did you ever get this working? It's hard to tell without seeing the rest of the Jenkinsfile after you attempted to convert it. But the error output you pasted seems like something else is going on other than just declarative syntax issues. A simplified version I can offer based off the scripted one might look something like this:
#!/usr/bin/env groovy

def INSTANCE_ID = ""

pipeline {
  agent any
  options {
    // your options here
  }
  parameters {
    // your parameters here
  }
  environment {
    // KEY = "Value"
  }
  stages {
    stage('Get Instance Id') {
      steps {
        script {
          sh "./some_command.sh"
          INSTANCE_ID = sh(returnStdout: true, script: 'aws ec2 describe-instances ... ').trim()
        }
      }
    }
  }
}

Hopefully that helps.
It could have been the script {} wrapper for the sh(returnStdout: true, script: ... part. I think that might matter.


Proof of $-\frac{1}{4}$ upper bound to the spectrum of $\Delta$

Question: Picture below is from this paper. I don't know how to get the inequation 1. Because in the inequation 2, $f'$ is the derivative of $f(y)$, there is not $\partial_{xx}f$. Even though integrate inequation 2 , I can't get inequation 1. How to get it ?
Answer: In equation $(1)$ the function $f$ is assumed to be smooth and compactly supported.  Thus
$$
\int_H \partial_x^2 f(x,y) dx dy = \int_0^\infty \int_{-\infty}^\infty \partial_x^2 f(x,y) dx dy  =0
$$
since for a fixed $y >0$
$$
\int_{-\infty}^\infty \partial_x^2 f(x,y) dx = \lim_{T \to \infty} \partial_x f(x,y) \Big\vert^{x=T}_{x=-T} =0
$$
due to the fact that the support of $f$ is compact.  Hence for such $f$
$$
\int_H \Delta f(x,y) dx dy = \int_H \partial_y^2 f(x,y) dx dy,
$$
and so you can use equation $(2)$.
Comment: Sorry, there was a typo in my second equation.  It was supposed to be $\partial_x^2$ instead of $\partial_x$.  Then the vanishing of this integral follows from the fundamental theorem of calculus since $\partial_x f(\pm T,y) =0$ for $T>0$ sufficiently large.


How do I uninstall python from web platform installer?

Question: I've installed python and some other packages using web platform installer, but I was having some issues getting a Django project to work so I uninstalled everything and am trying to get it going from scratch.  Web Platform Installer still shows that I have 'Windows Azure SDK for Python" and "Python 2.7 (32-bit)" installed however and I can't mark them as uninstalled.
I don't see where to uninstall from WPI at all, I uninstalled them using control panel.  I think I had originally installed python from the python site and had version 3.3 and 2.7 (64-bit), but now there are no entries containing 'python' when I try to uninstall a program from the control panel.
Does anyone know what is going on or can I download the setups from somewhere and try them manually?  Is there a way to reset what shows as installed in WPI?  I tried uninstalling and reinstalling WPI but that didn't help.
Answer: Ok with a lot of fooling around I found this directory:
%LOCALAPPDATA%\Microsoft\Web Platform Installer\installers\PythonDetectInstalls

In a mangled sub-folder there is a powershell script DetectPythonInistalls.ps1 that has these two lines for checking if python is installed already:
$regKey = "hklm:SOFTWARE\Python\PythonCore\$pythonVersion\InstallPath";
$correctRegKey = "hklm:SOFTWARE\Wow6432Node\Python\PythonCore\$pythonVersion\InstallPath";

Uninstalling all my pythons did not remove these keys.  After removing these registry keys with regedit, WPI allowed me to install its own version of python 2.7 and all the other goodies to go with the Windows Azure Python SDK and it worked.


How to avoid overlapping of title of marker in unfolding maps?

Question: I am using unfolding maps to create markers.When a user hovers over a marker the title is displayed.But the other markers overlap the title so it hides the information presented in title. To prevent from this, i used PGraphics to draw the title as:
    public void showTitle(PGraphics pg, float x, float y)
{
    String name = getCity() + " " + getCountry() + " ";
    String pop = "Pop: " + getPopulation() + " Million";
    /
    /buffer is defined already.
    buffer.beginDraw();
    buffer.fill(255, 255, 255);
    buffer.textSize(12);
    buffer.rectMode(PConstants.CORNER);
    buffer.rect(x, y-TRI_SIZE-39, Math.max(pg.textWidth(name), pg.textWidth(pop)) + 6, 39);
    buffer.fill(0, 0, 0);
    buffer.textAlign(PConstants.LEFT, PConstants.TOP);
    buffer.text(name, x+3, y-TRI_SIZE-33);
    buffer.text(pop, x+3, y - TRI_SIZE -18);
    buffer.endDraw();

}

And then drawing buffer on screen through method
public void draw() {
      map.draw();
      image(buffer, 0,0);
      }

It resolves the problem, now the title is not overlapped with markers but its not drawn right below the marker instead its drawn some where random on screen as shown in image
 How can i avoid it? Any help please.
Comment: Please provide a [mcve]. You can use simplified hard-coded examples instead of your entire sketch.
Answer: You need to store the position of the buffer before you draw it. Basically, you need to change this line:
image(buffer, 0,0);

To something like this:
image(buffer, bufferX, bufferY);

You'll have to calculate bufferX and bufferY depending on where you want the buffer to show up. A very dumb implementation might be something like this:
public void showTitle(PGraphics pg, float x, float y)
{
   bufferX = x;
   bufferY = y;
   //rest of your code

I'm not familiar enough with Unfolding Maps to tell you exactly what to do, but those are the basics. Note that Unfolding Maps might be doing its own translations, so you might have to use the pushMatrix() and popMatrix() functions. Also note that you might need to project from map space to screen space. The Unfolding Maps library probably has documentation on how to do that.
Comment: I did almost the same as you have mentioned. I stored the screen positions of selected marker and used those in image() function but it did not work that way. Isnt there any other solution that provides "focus" on current component?
Comment: @BatulMajid I don't really know what you mean by providing focus. If you have follow-up questions please post an updated [mcve] in a new question, and we'll go from there.
Answer: In setup you created a map with some size and offset. Buffer should be created with same size.
But most important is to draw buffer with same offset.
Your title is just drawn with negative offset, not random.
private PGraphics buffer;

public void setup() {
    size(900, 700);
    //Create map with offset
    map = new UnfoldingMap(this, 200, 50, 650 ,600, new Google.GoogleMapProvider());
    //Create buffer, same size as map
    buffer = createGraphics(650, 600);
    //rest of the code..
}

public void draw() {
    background(0);
    map.draw();
    //put buffer over the map, with same offset
    image(buffer, 200, 50);
}

Answer: I took the same Coursera course (Object Oriented Programming in Java) and worked on fixing this feature as well. Here is how I fixed this problem.
I realized that the titles are covered because the markers are drawn over and over inside the map.draw() method in draw() section of the EarthquakeCityMap class. So the fix would be moving the showTitle implementation from marker classes to the EarthquakeCityMap class, and let the title be drawn at the screen position of the markers instead of latitude and longitude.
The SimplePointMarker class in UnfoldingMaps Library has a method getScreenPosition() inherited from AbstractMarker class. See the JavaDoc for more details. Because the CommonMarker class is a subclass of SimplePointMarker class, and EarthquakeMarker class is a subclass of the CommonMarker, EarthquakeMarker class has the getScreenPosition() method available as default as well.
Below is how the method of showing earthquake titles look like in the EarthquakeCityMap.java file. Please note that you can use Processing's graphics methods here automatically because the EarthquakeCityMap class extends PApplet.
    /** Show the title of the earthquake if this marker is selected */
    private void showEqTitle(EarthquakeMarker m, UnfoldingMap map)
    {
        float x = m.getScreenPosition(map).x;
        float y = m.getScreenPosition(map).y;

        String title = m.getTitle();

        pushStyle();

        rectMode(PConstants.CORNER);
        stroke(110);
        fill(255,255,255);
        rect(x, y + 15, textWidth(title) + 6, 18, 5);
        textAlign(PConstants.LEFT, PConstants.TOP);
        fill(0);
        text(title, x + 3 , y +18);

        popStyle();
    }

And here is how I implement the method above in the draw() function.
    public void draw() {
        background(0);
        map.draw();
        addKey();

        for (Marker m: quakeMarkers) {
            EarthquakeMarker eq = (EarthquakeMarker) m;
            if (m.isSelected()) {
                showEqTitle(eq, map);
            }
        }
    }

Finally, here's the resulting image showing the titles are no longer covered by the markers. Horray~
The earthquake map display when the mouse hovers one of the earthquake marker


How to display a message on login until a user fills out a specific Webform?

Question: Relevant modules installed:

Rules.
Webform.
Webform rules.
Conditional rules.
Permissions per Webform.

What I have tried:

Rule 1: activates on user login that displays a system message.
Rule 2: activates on Webform submission with the condition that the Webform's name is the required name. The rule executes PHP code to disable Rule 1 if true.

<code>/**
* Implements hook_update_N().
* Disables name_of_rule rule.
*/
function hook_update_N() {
  $rules_config = rules_config_load('name_of_rule');
  $rules_config->active = FALSE;
  $rules_config->save();
}
</code>

However, this set of rules is NOT working at the moment.
Concerns:

If Rule 1 was working, how do I ensure that it permanently disables Rule 1 per user, and not globally?
Is there a better way to do this?
For example, all I should need is one rule: On user login + if a Webform has not been filled out, display a message. However, I have not been able to find a module that adds the "If Webform has not been filled out" rule.
Answer: I think the module you are looking for is 'Rules Webform Submitted'.
This module is similar to Webform Rules in that it supports integration between Webform and Rules, but different in that Webform Rules supports the Event "Webform Submitted", while Rules Webform Submitted provides a Condition which is typically triggered by a Node Event.
So, you can use the event 'On user login' and the condition that 'Rules Webform Submitted' offers to create your rule.
Comment: Forgot to mention I looked into this module, but it doesn't have a version for Drupal 7
Answer: Referring to your "is there a better way to do this": not sure if you'll consider it "better", but this is how I would adapt your 2 rules to actually "display a message on login until a user fills out a Webform" (as in the title of your question):

in your Rule 2, I'd use an Action to "flag" the user, using the Flag module, with a (none-global) flag named something like "Webform OK" (and "Webform not OK" as the alternative). By the way, the nature of such flag is that it is for each user individually.
in your Rule 1, add a Condition like "Is this user NOT flagged (with the Webform OK flag)".

With these 2 corrections of your 2 rules, and by adding the Flag module to your mix, you can:

probably simplify both rules, such as removing the (potentially dangerous?) PHP code in your Rule 2.
possibly eliminate the "Conditional rules" module.
Comment: Thanks for the reply, that sounds more elegant than writing a quick custom module to do this which is what I was about to resort to... I'll give this a try later in the week!
Comment: Thanks for the feedback. Are you familiar with the Flag module? Or should I add a few pointers to recommended video tutorials to my answer?


laravel belongsTo gives null

Question: belongsTo relation in laravel is returning null
public function games(){
    return $this->belongsTo('App\Models\Game');
  }

but when i provide key as argument it seems to work fine
  public function games(){
        return $this->belongsTo('App\Models\Game','game_id');
      }

but as per the docs game_id is itself is a default argument. What is the small thing i am missing here.
Thanks
Comment: This is more of a side note, but shouldn't that be `game()` since it belongs to a single game?
Comment: @ThunderBird can you provide the other side of the relation as well? Also any relevant parts to your database schema?
Answer: The belongsTo side of the relationship builds the foreign key name based on the name of the relationship method. This behavior is different than the hasOne/hasMany side of the relationship, which uses the name of the class.
In this case, your relationship method is named games, so it will look for the foreign key field games_id. You can either provide the foreign key field as the second parameter, as you have shown, or you can rename your relationship method to game().
Answer: It looks like the name of your method "games" may be the issue. The assumption with a 1-to-many relationship is that the parent class is singular while the child is plural. Try changing the name "games" to "game" and the key argument shouldn't be required.
At this point, I'm guessing Laravel is thinking your id key would be "games_id".
Answer: In my case, i was using public for defining variables. When I change to protected it worked.
public $fillable = [..class properties..];

changed to
protected $fillable = [..class properties..];

laravel belongsTo gives null


Convergence of a sum in distribution space

Question: I have a exercise that I'm supposed to show a convergence of a sum of distributions.
Let $c_k\in\mathbb{C}$ such that $|c_k|\leq C(1+|k|)^m$, for all $k\in\mathbb{Z}$ and some $C\geq 0$ and $m\in\mathbb{R}$. I have to show that
$$I=\sum_{k\in\mathbb{Z}}c_ke^{2\pi ikx}$$
Converge in $D'(\mathbb{R})$.

PS:
I tried to define $$I_n=\sum_{k=-n}^{n}c_ke^{2\pi ikx}$$
and show that $I_n$ is a cauchy sequence. As $D'(\mathbb{R})$ is banach space (dual of $D(\mathbb{R})$), then it would imply that $I$ is convergent in $D'(\mathbb{R})$, but I didn't get too far.
Comment: It is not. For $f_n(\phi)$ to converge you need to check the decay of $\hat{\phi}$ (Fourier transform)
Comment: D' as the weak* topology. What do you mean by $\phi$?
Comment: Concretely what does it mean, what is the definition of $\sum_k c_k e^{2i\pi kx}$ converges in $D'$ ? And what is the decay of $\hat{\phi}$ ? $$ $$ Also $D(\Bbb{R})$ is not a Banach space, it is only a topological vector space but it doesn't have a norm. It is $\bigcup_r C_c^\infty([-r,r])$ where $C_c^\infty([-r,r])=\bigcap_{m\ge 0} C_c^k([-r,r])$ is the intersection of infinitely many Banach spaces from which we have a metric on $ C_c^\infty([-r,r])$ but it is not a norm and it doesn't extend to $D(\Bbb{R})$
Comment: it's says that $f_n$ converge to $f$ if  $f_n(\phi)$ converge to $f(\phi)$, for all $\phi\in D$
Comment: I said that $D'$ was Banach, not $D$
Answer: For a test function in Schwartz space $\mathscr{S}(\mathbb{R})$, let me define the Fourier transform as
$$
\widehat{f}(\xi):=\int_{\mathbb{R}}e^{-i\xi x}f(x)\ dx\ .
$$
For a distribution $T$ in the space of temperate distributions $\mathscr{S}'(\mathbb{R})$, the Fourier transform $\widehat{T}$ will then be given by
$$
\langle \widehat{T},f\rangle:=\langle T,\widehat{f}\rangle\ .
$$
It is easy to see that, as temperate distributions (or generalized functions of $x$)
$$
\sum^{n}_{k=-n} c_k\ e^{2i\pi kx}=\widehat{A_n}(x)
$$
where $A_n$ is the temperate generalized function of $\xi$ given by
$$
A_n(\xi):=\sum^{n}_{k=-n} c_k \ \delta(\xi +2\pi\ k)\ .
$$
Namely, for every $f\in\mathscr{S}(\mathbb{R})$,
$$
\langle A_n,f\rangle:=\sum^{n}_{k=-n} c_k \ f(-2\pi k)\ .
$$
Now let me go ahead and define
$$
\langle A_{\infty},f\rangle:=\sum_{k\in\mathbb{Z}} c_k \ f(-2\pi k)\ .
$$
I will first show that $A_{\infty}$ is well defined and belongs to $\mathscr{S}'(\mathbb{R})$.
I will use the notation $\langle x\rangle=\sqrt{1+x^2}$ for the so-called Japanese bracket.
By Cauchy-Schwarz we have $1+|x|\le \sqrt{2}\ \langle x\rangle$. We also have the trivial inequality $1+|\xi|\le 1+|-2\pi\xi|$.
For nonnegative integers $p,q$ let me define the seminorms
$$
||f||_{p,q}=\sup_{x\in\mathbb{R}}\ \langle x\rangle^q\ |f^{(p)}(x)| \ .
$$
These define the topology of $\mathscr{S}(\mathbb{R})$.
Now we have
$$
|\langle A_{\infty},f\rangle|\le \sum_{k\in\mathbb{Z}} |c_k| \ |f(-2\pi k)|
$$
$$
\le \sum_{k\in\mathbb{Z}} C (1+|k|)^{-2} (1+|k|)^{m+2}\ |f(-2\pi k)|
$$
$$
\le \sum_{k\in\mathbb{Z}} C (1+|k|)^{-2} 2^{\frac{m+2}{2}} \langle -2\pi k\rangle^{m+2}\ |f(-2\pi k)|
$$
$$
\le C\times\left(\sum_{k\in\mathbb{Z}} (1+|k|)^{-2} \right)\times 2^{\frac{m+2}{2}}\times ||f||_{0,m+2}\ .
$$
These bounds show the absolute convergence of the series defining $\langle A_{\infty},f\rangle$.
The latter is clearly linear in $f$. Most importantly, we bounded $|\langle A_{\infty},f\rangle|$ by a constant times the seminorm $||f||_{0,m+2}$ which proves continuity in $f\in\mathscr{S}(\mathbb{R})$. So $A_{\infty}\in\mathscr{S}'(\mathbb{R})$.
The correct topology to use systematically on $\mathscr{S}'(\mathbb{R})$ is the strong topology and not the weak-$\ast$ topology. A subset $B\in\mathscr{S}(\mathbb{R})$ is called bounded if and only if for all $p,q$,
$$
\sup_{f\in B}||f||_{p,q}\ <\infty\ .
$$
The strong topology on $\mathscr{S}'(\mathbb{R})$ is the one defined by the seminorms
$$
||T||_{B}=\sup_{f\in B} |\langle T,f\rangle|
$$
where $B$ ranges over bounded subsets of $\mathscr{S}(\mathbb{R})$.
Let $B$ be such a bounded set and let $f\in B$. Then by the repeating the previous estimates, now with the extra condition $|k|>n$ on the summation index,
$$
|\langle A_n,f\rangle-\langle A_{\infty},f\rangle|\le
C\times\left(\sum_{k\in\mathbb{Z},|k|>n} (1+|k|)^{-2} \right)\times 2^{\frac{m+2}{2}}\times ||f||_{0,m+2}\ .
$$
Therefore
$$
||A_n-A_{\infty}||_B\le
C\times\left(\sum_{k\in\mathbb{Z},|k|>n} (1+|k|)^{-2} \right)\times 2^{\frac{m+2}{2}}\times
\sup_{f\in B} ||f||_{0,m+2}
$$
and consequently $||A_n-A_{\infty}||_B\rightarrow 0$ when $n\rightarrow\infty$ because the series
$$
\sum_{k\in\mathbb{Z}} (1+|k|)^{-2}
$$
converges. The above argument proves that $A_n$ converges to $A_{\infty}$ in $\mathscr{S}'(\mathbb{R})$.
To finish, invoke the continuity of the Fourier transform $\mathscr{S}'(\mathbb{R})\rightarrow \mathscr{S}'(\mathbb{R})$
and the continuity of the canonical injection $\mathscr{S}'(\mathbb{R})\rightarrow \mathscr{D}'(\mathbb{R})$. Again, the spaces  $\mathscr{S}'(\mathbb{R})$ and $\mathscr{D}'(\mathbb{R})$ carry the strong topology. In the case of $\mathscr{D}'(\mathbb{R})$, one first needs to understand the topology of $\mathscr{D}(\mathbb{R})$ which is explained in
Doubt in understanding Space $D(\Omega)$
Then one needs to understand what are the bounded subsets in $\mathscr{D}(\mathbb{R})$. These are sets of test functions whose supports are contained in a common compact set and whose derivatives are bounded uniformly (in the function chosen in the set, not in the order of derivation).
Comment: Thanks Abdelmalek Abdesselam!! that's a very good explained answer!!


How can I develop a custom theme from scratch?

Question: I wonder how to develop a custom theme from scratch. I understand the overall structure of Drupal theme. I've created an .info file and enabled the theme through the admin interface, but I get a blank screen.
I haven't yet coded any of the theme files. I'm unable to define html.tpl.php, page.tpl.php, node.tpl.php, region.tpl.php.
I do have empty css, js and images folders. In my templates folder I've an empty html.tpl.php, page.tpl.php, node.tpl.php, region.tpl.php, field.tpl.php.
Any suggestions?
Comment: Sorry but our aim isn't to reproduce documentation or provide broad tutorials, rather to answer more specific questions. The [theming guide](https://www.drupal.org/documentation/theme) has all the information you need in it, if you get stuck at a particular part please ask a specific question about that
Comment: a good starting point would be to copy the templates of an existing theme that most closely resembles your custom theme into your custom templates folder, then customize these. The templates print the various page elements so if you have blank templates nothing would be printed, hence you see a blank page.
Comment: As an "educated person" yourself, you'll no doubt recall agreeing to ask questions that follow our, admittedly strict, guidelines, when you signed up. So far you haven't been doing that consistently, and some are getting closed. There isn't really any more to be said about it, taking it out on me won't solve anything.
Answer: Hello World
It seems that the current version of your theme works as designed: empty templates that result in a blank screen, that's exactly what "I" would expect. Try adding "Hello Umair" in any of those empty files, and see what you get next.
Start from an example
A much more effective approach however might be as suggested by longboardnode : copy from whatever theme you like, and apply the "same-as-except"-strategy.
Start from a base theme
Or maybe create a subtheme from your favorite base-theme (Omega, Zen, Bootstrap, ... there are plenty to pick from).
Follow the instructions in the documentation
An extremely basic example you may want to look at: Create a new custom theme with CSS alone. And if you're ready for it, study the Theming guide, especially the Theming Drupal 6 and 7 child pages of it.


Best practice to trunk two GB switches?

Question: I already read some similar questions but I still have no clue on how to do it the right way. I have a D-Link DGS-1248T 48 port GB-switch with 4 mini GBIC ports and I want to connect it to another switch.
My questions are:

Do I need another D-Link switch or even the same model or can I connect a switch of a different vendor?
How should I connect the two switches? Using regular Cat6 cables or using the GBIC ports?
Can I use all 4 GBIC (or the matching ethernet ports) to connect the switches?

My first thought was to buy the D-Link DGS-1210-24 (or the 48 port version) and connect them using normal Cat6 cables.
I am really not a network administrator but unfortunately the only IT-Guy in my office. So any suggestion on how the connect the new switch would help.
Answer: Best thing to start with is setting up a Trunk Port on one of the four last Ethernet ports, as you will need to Tag all our VLANs out to the next switch. could be best to buy the same vendor (DLINK) as i've had to do a few firmware upgrades on DLINK's myself to get them to properly tag packets for and trunk
It also sounds like you want to setup an Aggregated link, this is possible with this switch but only in "Static Link Aggregation" mode, if you've got a Cisco 3700 handy you should be able to set it up using LACP
best to have a quick read of this;
http://en.wikipedia.org/wiki/Link_Aggregation_Control_Protocol
btw.. the DGS-1248T has 4 SFP ports, not sure it's mini-GBIC ports on that device
Comment: OK, thanks so far. But what's the difference of trunking and static link aggregation. For me it looks like it's just a synonym. And should I use fiber optic or is cable just fine for a 20cm cable?
Answer: Its a big difference. LACP joins ports and allows you to have more bandwith. Trunking like you intendt do NOT give you more bandwith and makes a loop in your trunks.
So LACP or Static Link Aggregation is what you need.
You can use switches from any vendor as long as they support VLANs. The tagging is a standard, so its same for all. For simplicty in maintenance and functionality i however recommend same brand.
SFP ports is commonly referred to as mini-GBICs even though the GBIC is a SFP device, one of many varieties.

Best practice to trunk two GB switches?


Reporting an absolute increase in a given metric

Question: In a research article, what is the best formulation to report an absolute increase for a given metric (e.g. F1-score)?
Examples:

System X achieved an F1-score 9% (absolute value) higher than system Y.
System X achieved an F1-score 9% higher in absolute value than system Y.
System X achieved an F1-score 9 points higher than system Y.
Answer: It depends what you mean:
A score of 87.2 percent is 9% higher than a score of 80 percent, but 7.2 points higher.
I would opt for an unambiguous formulation such as the following:
"System X achieved an F1 Score 87.2, 9% higher than system Y at 80."
This is good general advice, but in terms of an actual F1 score it doesn't apply well, as a percentage rise in F1 score is not a metric with a real meaning. For this exact purpose, I would simply report the actual values of the F1 scores.
Comment: In that case, yes, "points" or "percentage points" will effectively communicate a change in the magnitude of a rate. I.e. 80% -> 85% is 5 points. This will be well understood by the large majority of readers in a statistical area.
Comment: Sorry- it will be understood by the majority of English speakers- anyone who works more closely with rates (statisticians, scientists, mathematicians, engineers of any kind) are even less likely than an average English speaker to misunderstand the distinction. Your audience will have no problem with this terminology.
Comment: Thanks. I meant in terms of absolute increase (vs. relative increase). "Points" is definitely what I would use in French, but I've seen a bunch of articles written in English talking about percentage increases in terms of absolute values (to mean points), so I was curious to know whether it's best to use "points" or "% increase in absolute", as I was starting to have doubt whether "points" what understood by most readers in the English-speaking community.
Comment: Thanks, [percentage point](https://en.wikipedia.org/wiki/Percentage_point) sounds like a great option.
Comment: (I forgot to mention that the readers are from the machine learning and natural language processing communities)


How to write this measure on Finale Notepad?

Question: I'm trying to transpose a PDF Piano Sheet to Finale Notepad so I can hear and practice together.
I'm having trouble writing this:

So, this looks really weird. Because the upper one (sorry, I don't know the names in english) have two half notes (finger 5) and 8 eight notes at the same time.
Is this notation correct? I don't think so.
I think whoever wrote it wanted the finger 5 from right hand to keep the key pressed while doing the other notes with the other fingers, i don't know.
Comment: The notation is correct, except the stem of the E should be up, not down.
Comment: I am a bit confused as to what you're trying to say. If you meant how to play this, the common practice is to hold the half notes while playing the eighth notes if possible. If you are referring to writing finger numbers, this is fine, but you don't need to write finger numbers for this simple passage. If you meant how to write this in Finale, use two different layers. Hope this helped!
Comment: Yes.  Make sure the half notes (E and D) are in layer one, and the eighth notes in layer two.  Then I think you will find the rests in the right place.  The half notes' stems will automatically go up.
Comment: @AnselChang Thanks! Layers is what I was looking for. And yes, I could imagine the way to play it by looking but could not write on finale without using layers.
Comment: @alephzero I've never seen it before, but then again, I'm very new to this. I was able to write it on Finale using layers but it displays the rest notes above the half notes. And both stems are now down. I'm not sure how to configure that to be up but I guess it is enough for what I want for now. Thanks.
Comment: You could try inputting the voices in a different order (try high voice first or low voice first), and I know Sibelius will flip the stems, so Finale probably does too
Answer: The notation is correct (although it might be more usual to have the first half-note with its stem up).
There are two 'voices' to be played in the RH.  In this case - a simple sustained melody with broken chords underneath - it's very easily achieved using the fingering indicated.
Keyboard players are often presented with much more complex problems. Work this one out!
Answer: That technique of combining melodies/harmonies on the same line is called counterpoint. Here's a good reference: https://www.britannica.com/art/counterpoint-music.
I used to occasionally see it in piano music, but once I started playing organ I encountered it all over the place, mainly because of two reasons:

notes don't decay naturally like they do on piano, they are at 100% volume until you release it
organs don't have a sustain pedal, so whereas using all 8th notes in the right hand of your example on piano might result in a very similar sound to using counterpoint, on organ it would make a big difference.

That all being said, I have notated counterpoint frequently in Finale, and it's done using Layers as previous commenters have identified. In the course of notating counterpoint I've often put notes on the wrong layer as it can be confusing and annoying to correct, so I suggest using Layer 2 for the simplest of the two counterpoint pieces so you don't have to switch back and forth as much.
Comment: Hardly counterpoint.  Just a polyphonic texture.  Counterpoint implies independent melodies in multiple voices.  This is just filler.
Answer: You've got already the correct answers above and in the comments!
In Finale  you can change the layer of single notes by selecting them and use alt - shift and 1, 2 or another number. (Maybe this function is the same in notepad.) This will evoke a half note rest leaving in this measure which must hide. And then you have just to change the stem up (L). The better option is to change also the second half note to layer 2, then you don't have to hide the rest. But you will surely finish the entire piece in the same way with less trouble.
So the most simple solution will be to play the two right hand voices  ( of the Pachelbel Canon - isn't it) separately in two different staffs, the upper voice with layer 1 and the second voice with layer 2) and merge  them (implode) when you have finished the whole song.
The problem will be that all stems are in the same direction. Using the "repitch" tool and key L it will be easy to change this.
If this is the Pachelbel Canon you can import the midi file and save a lot of time.
Comment: The most simple solution will be to enter the notes directly into appropriate voices (I think Finale calls them 'layers').    Attempting to capture a performance is rarely the most effecient method of getting notes onto the page.
Comment: exactly, enter the notes directly  as you describe it is the fastest way, espacially when they have always the same length as in the example above.  I didn't talk about capture a performance, ( this would be is a possibility too, but you have to slow down the tempo quite a lot.


How do I add a validation handler to a specific exposed filter form?

Question: I want to add a custom validation handler to the exposed filter form that is part of a view.
I am not able to target that specific exposed filter form: The validation handler is added to other forms too.
Is there a way to add a validation handler only to a specific exposed filter form and avoid the validation handler is added to other forms too, including other forms for exposed filters?
Answer: To form alter a specific view exposed filter form, you need 2 conditions to check: the form id & the form's '#id' element.
function MYMODULE_form_alter(&$form, $form_state, $form_id) {

  // @NOTE: $form['#id'] will vary based on your your view & display machine names.
  // Here the view machine name is 'view' & display machine name is 'display'.
  // Use Devel's dpm() to inspect or the Views administration UI
  // to find your own form's values.

  if ($form_id == 'views_exposed_form') {
    if ($form['#id'] == 'views-exposed-form-view-display') {
      // @TODO: Add form alter code.

    }
  }
}


Show either a node or a blocks page at frontpage

Question: At the path "/" - the frontpage of my site, I want to show either

For anonymous users, the content of a particular node, which is normally available at "/somepath".
For authenticated users, a series of blocks.

How do I do this?
I think the most elegant answer involves using page manager to take control of the "/" route. With this it is easy to show a series of blocks as one variant, but I don't see how to show a particular node.
I have tried setting the "Default front page" at admin/config/system/site-information to "/somepath". But when I do this my panel page defined in page manager does not show up, either when it targets "/" or "/somepath".
As a fallback, I can probably achieve the same result without page manager at all, by choosing to hide the "content" block on the home page and show only the blocks I want. But I worry this gets messy fast, even using the block visibility groups module to avoid repeating the conditions.
Comment: I think you've answered your own question. At the moment, for simple things, you can use block visibility to display one block for anonymous and another for authenticated. Dynamic page cache and Block cache should handle things in a scalable way for that.
Answer: I agree, the block layout gets quite messy when you try to do this. Another option would be a separate twig template for the front page.
Create two new regions frontpage_auth and frontpage_anon and fill them with the blocks you want to show. Don't configure the visibility here. Just place the blocks.
Modify page.html.twig, so that {{ page.content }} is enclosed in a twig block maincontent:
{% block maincontent %}
  {{ page.content }}
{% endblock %}

Then create a new twig file for the front page
page--front.html.twig
{% extends "page.html.twig" %}

{% block maincontent %}

  {% if logged_in %}
    {{ page.frontpage_auth }}
  {% else %}
    {{ page.frontpage_anon }}
  {% endif %}

{% endblock %}

where you display one of the two regions dependent on the variable logged_in.
For the node you can use the Main page content block or you can put the node in a view and use this view as a block.


Are microphones meant for Karaoke and PA bad for recording vocals and instrument music?

Question: Recently I picked up a karaoke microphone (cost me about $15, so clearly - most entry level). It has an unbalanced output and I've used it with my PC (connecting it to the "mic" input) to record audio in Audacity, and also directly plugged to my small practise guitar amp (15W, 6.5" speaker).
For my untrained ears, the recording quality is not too different compared to what I have with some of the el-cheapo headphone+mic sets one uses with PCs. Probably, that is expected. Another observation is that the karaoke microphone seems to be able to pickup sound only when held very close to my mouth.
Wondering as to, in what all ways are microphones used for recording vocals different ? I am not talking of the high-end studio microphones, but microphones used by people who do gig in clubs, or sidewalks etc.?
Comment: You're on the wrong track, "meant for PA" does not mean bad quality. $15 dollars means it's amazing it functions at all. Please realise this - Sound gear costs money.
Answer:
You note that your ears are untrained. This is probably the biggest factor in how you will experience recording and sound engineering in general. Just like learning to play an instrument better helps one appreciate the differences between quality levels of instruments, so it is with professional sound gear. As you learn and practice engineering, your ears will start hearing things you never noticed before. It's both amazing and sometimes frustrating to start hearing small details in your favorite recordings - amazing when it adds to your appreciation of the craft of recording and frustrating when you notice poor engineering on recordings you otherwise like.
Just because a microphone is cheap doesn't mean it's outright bad (it's much more likely to be "bad" in many ways). Even something that almost everyone would describe as "bad sounding" can sometimes have a sound that works very well for some situations. Guitar distortion was originally not intentional and was a "bad" sound that musicians and engineers realized was actually good for certain kinds of playing and music.
Some microphones are used primarily in studio recording environments, some are used primarily in live situations, and most microphones are used in both places. Highly directional microphones with small pickup patterns are favored for live use because the unwanted sounds from other instruments and the potential for feedback can be reduced when using a highly directional mic. Mics that are primarily used in the studio are often very sensitive and even fragile and therefore the loud noises, feedback, and rough treatment that can happen in a live situation would potentially damage these kinds of microphones. Also, some specialized microphones require external power and control boxes, careful placement, or are otherwise very inconvenient for live shows where speed, convience, and reliability are sometimes more important than sound quality.
Even for those with budgets greater than $15, cost is a factor. A live show requires many microphones, power amps, speaker systems, special processing, etc. A studio that does not need many of those things can afford to invest more money where it counts most for a studio: in microphones, mic preamps, outboard signal processors, and/or a studio console (which can be very different from a live console).

Are microphones meant for Karaoke and PA bad for recording vocals and instrument music?

"Bad" is situational and in the ear of the beholder. You will not get the same sound quality that is present on most (but not all) professional, famous recordings, since most (but not all) of those recordings were made with high-end studio microphones like the Neumann U87 or the AKG C2. However, some famous recordings (like Michael Jackson's Thriller album) have been made with much more affordable microphones that some might consider "less good" (maybe not "bad") for studio recording in general.
Your specific mic could be just the ticket for a punk, rap, metal, or industrial recording, either for vocals or instruments. Or there could be a silky jazz singer out there who loves the sound of their voice through that specific microphone. Production is an art, and like all artist's tools, no one can tell you what you should be using, and choice of tools is part of the process of artistic expression.
Comment: Yes, the small pickup area is good for live (karaoke or PA) use since it helps prevent unwanted sounds getting into the mic.
Comment: Thanks for the answer. Does the ability of a mic to pickup sound when held a little distance away from mouth (even 2 inches or so) have anything to do with it being of Karaoke vs PA vs Vocals type ?
Answer: Store brand karaoke mics which cost $15 and have the 1/8" plug on the end to plug into a karaoke machine are likely not going to sound very good, but this has more to do with build quality and parts than anything. They build them cheap to sell them cheap and the audience they are trying to reach isn't really concerned with sound quality. However, if this is what you have to record with then by all means go for it. This is exactly what I started out recording with and a radio shack condenser mic for drums. We all have to start somewhere. Working with "bad" equipment and squeezing every ounce of life you can out of it will help you hone your skills and you will be more able to appreciate the "better" equipment when you get it.
When it comes to live and recording, there is actually a lot of crossover between mics that are used live on stage and in the recording studio. For example, the Shure SM57 is a standard for guitar amps and drums both live and in the studio. Mics used for kick drum/bass cab will work the same both live and in the studio. Drum overheads will also work the same.
A main difference between recording/studio and live/PA is that condenser microphones are very common for vocals in the studio, but for live they are less common because condenser mics in general are more sensitive and thus are more prone to feedback. Microphones that work well live will also work well in the studio. Todd Wilcox mentioned Michael Jackson's Thriller being recorded on an affordable mic...this mic was the Shure SM7 / SM7b which brand new is $350 (extremely inexpensive compared to many studio vocal mics). This mic was actually created as a broadcast mic, but people loved it for studio and live so it kept getting used. The list of pro recordings that have used this mic is off the charts from Metallica, Incubus, Red Hot Chili Peppers, Smashing Pumpkins, John Mayer, etc., it's also used frequently live, and in broadcast the SM7b along with the EV RE20 completely dominate the field.
So really the main issue is whether the mic itself sounds good, not its price or what it's intended purpose was. The SM7b is not an expensive studio mic and it was not created for recording or live use, but it sounded amazing in these applications so now it's used all the time even by studios with essentially an unlimited budget...when a mic sounds good then it IS good! :)
Comment: Great answer, and indeed as you say -- we need to start somewhere. It so happens that I could've bough another mic from Shure (SV100 or SV200), which was just 10$s more, but that too had the "Karaoke / PA" use tagged.
Comment: Feedback is about a mic's directional properties, not about its sensitivity.


Sending password through shell script

Question: I am using redhat linux. I was trying to write a script to enter passwords automatically thru invoking the script.
When ever i wanted to enter the build env, it asks for password twice and we have to enter that. So with the .sh file i wud be needing to enter the passwrd twice.
So is it really required to have the expect package installed in the system or can we do without this.?
the script is something like:
invokegd #cmd to enter build env
expect "*password:"
send abcde@123

I am not sure how to send it twice.. and also it says expect: not found
Comment: twice means it both times prompt `password:`  if yes then use your shell code twice.
Comment: what is the command that requires a password? Is it ssh or passwd or ...?
Answer: First need to install expect package please follow below steps:
1)    Download the expect package from the below link
http://sourceforge.net/projects/expect/
2)    Install the required dependecy packages "Tcl/Tk" language toolkit
     # yum install tcl

3)    Install the "expect" package using the below commands
        # tar -zxvf expectx.xx.tar.gz
        # ./configure
        # make
        # make install

Then make script by adding code like
login()
{
   expect<<EOF
   expect "password"
   send "abcde@123\r"
   EOF
}
login

Sending password through shell script


Permitir somente números inteiros em uma coluna da JTable

Question: Abaixo tenho um modelo de Jtable. Existe somente uma coluna editável para número (segundos). Como validar para que aceite somente números inteiros, e no caso do usuário digitar qualquer outra coisa, exceto número inteiro, retorne ZERO?
public class Tabela_Fluxograma extends AbstractTableModel {
private ArrayList linhas = null;
private String[] colunas = null;

public Tabela_Fluxograma (ArrayList lin, String[] col){
    setLinhas(lin);
    setColunas(col);
}

public ArrayList getLinhas() {
    return linhas;
}

public void setLinhas(ArrayList dados) {
    this.linhas = dados;
}

public String[] getColunas() {
    return colunas;
}

public void setColunas(String[] nome) {
    this.colunas = nome;
}

public int getColumnCount(){
    return colunas.length;
}

public int getRowCount (){
    return linhas.size();
}

public String getColumnName (int numCol){
    return colunas[numCol];
}

public Object getValueAt (int numLin, int numCol){
    Object[] linha = (Object[])getLinhas().get(numLin);
    return linha[numCol];
}

@Override
public boolean isCellEditable(int row, int column) {
return column == 3;
}

@Override
public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
    Object[] linha = (Object[]) getLinhas().get(rowIndex);
    linha[columnIndex] = aValue;
    //este método é quem notifica a mudança do model na tabela
    fireTableDataChanged();
}

Answer: A forma correta de restringir isso é através do método getColumnClass que seu TableModel herda da AbstractTableModel:
public Class<?> getColumnClass(int columnIndex) {
    return columnIdex == 3 ? Integer.class : super.getColumnClass(columnIndex);
}

Dessa forma ai não vai permitir que se salve nenhum valor que não seja do tipo Integer nesta coluna, sendo necessário ou deixar em branco ou preencher corretamente para que se permita a conclusão da edição da célula nesta coluna.
Apenas para exemplificar o que vai ocorrer, veja o gif abaixo:
Answer: Bom dia. Conforme comentou Articuno, precisei mudar pra não permitir texto ou retornar zero, embora seja bem útil sua sugestão. Obrigado pelas sugestões. Só pra concluir vou colocar o trecho final do tablemodel. Passo o valor para outro método, valida e retorna.
@Override
public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
    Object[] linha = (Object[]) getLinhas().get(rowIndex);
    int valor = validateInt(aValue);
    linha[columnIndex] = valor;
    fireTableDataChanged();
}

private int validateInt(Object numberObj){
    try {
        int number = Integer.parseInt((String) numberObj);
        return number;
    } catch (Exception e) {
        return 0;
}
}

Comment: Como assim produtivo? Minha sugestão não deixa o setvalueat ser chamado até que a conversão implicita do tipo da coluna esteja correto. Então seu código da pergunta não está completo. Minha sugestão foi com base nele, mas se você não apresenta tudo que é necessario na pergunta, pode acontecer isso.
Comment: **Sempre apresente um [mcve]**, dessa forma, evita que receba respostas que estejam incompletas ou que nem a atendam seu problema.
Comment: Acho que da pra simplificar: `linha[columnIndex] = validateInt(aValue);`
Comment: Isso mesmo.. rsrs.. Obrigado
Comment: Não entendi, se fez dessa forma, o getcolumnclass não se faz necessário.
Comment: Alias, o método `getColumnClass` não vai deixar passar nada que não possa ser convertido pra integer para o `setValueAt`. Você não usou este método?
Comment: Não usei o método. Não estava "produtivo" aqui a exibição de texto. Foi necessário zerar imediatamente. O valor digitado vai direto para o banco de dados.
Comment: Então, foi um equívoco meu. Como sou iniciante em java achei que não seria necessário apresentar. Mas foi útil também para outro table model que eu tenho. As duas sugestões me ajudou.
Answer: Usando cast de Int você consegue fazer esta validação:
private int validateInt(float number){
if(number == (int)number)
   return number;
else
   return 0
}

Comment: Entrada de inteiros **numa jtable**, portanto esse metodo não vai funcionar, nao desta forma. A forma correta é como respondi, utilizando a propria classe model que irá monitorar entrada de dados de acordo com o tipo. Outra coisa, a linha da tabela permite digitar qualquer coisa, se eu digito uma string, esse metodo seu ai vai travar a aplicaçao toda estourando uma exceção.
Comment: Obrigado pela colaboração de ambos.
O que queria mesmo foi o que o Articuno me sugeriu. Validar inteiro, na coluna 3 e numa jTable. Acabei de complementar o código aqui e ficou como esperado. Obrigado
Comment: E como ele vai aplicar isso na tabela? Além disso não se aplicar a jtable, ainda vai estourar exceção.
Comment: Ele pediu uma função para validar entrada de numeros inteiros amigo
Comment: @rafB o problema é que esse método com certeza vai estourar exceção se você aplicar no seu Model, e vai travar a tabela, por isso questionei o autor. Em modo texto, talvez seja funcional, pra JTable esse método não funcionaria.


There is the warning when I run database backup bash script

Question: My database is 8GB
When I run the database backup bash script, there is the warning/failure. They have appeared since 1 month ago
Here are my warning/failure
mysqldump: Error 2013: Lost connection to MySQL server during query when dumping table `xxx` at row: 427348

mysqldump: Couldn't execute 'SELECT engine, table_type FROM INFORMATION_SCHEMA.TABLES WHERE table_schema = DATABASE() AND table_name = 'xxx'': MySQL server has gone away (2006)
mysqldump: Couldn't execute 'SET SQL_QUOTE_SHOW_CREATE=1': MySQL server has gone away (2006)
.....

mysqldump: Couldn't execute 'UNLOCK TABLES': MySQL server has gone away (2006)
mysqldump: Got error: 2002: "Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (111)" when trying to connect

Comment: What in the **server** log corresponds to this client message? What it is doing that time?
Answer: The Error 2013: Lost connection to MySQL server and MySQL server has gone away (2006) errors always mean that the connection between the program and the database was broken unexpectedly. Usually this happens due to the connection being killed by something, server running out of memory or due to a bug that ends up crashing the server process.
To find out what actually caused this, inspect the server error logs which by default is /var/lib/mysql/hostname.err.
Comment: there isn't any file .err in my server. I searched it
Answer: If the server is not restarting for some reason, adding --quick --single-transaction to mysqldump may help.
Comment: Can you guide me more detail? I am newbie :(