NoMethodError: undefined method `production' for "development":ActiveSupport::StringInquirer

Question: Não entendi por que não está migrando.
    deploy@vps8029:/var/www/maisonconvite$ rails db:drop db:create db:migrate db:seed
    rails aborted!
    NoMethodError: undefined method `production' for "development":ActiveSupport::StringInquirer
    /home/deploy/.rvm/gems/ruby-2.4.2/gems/activesupport-5.1.6/lib/active_support/string_inquirer.rb:28:in `method_missing'
    /var/www/maisonconvite/config/initializers/devise.rb:281:in `block in <top (required)>'
    /home/deploy/.rvm/gems/ruby-2.4.2/gems/devise-4.4.3/lib/devise.rb:307:in `setup'
    /var/www/maisonconvite/config/initializers/devise.rb:5:in `<top (required)>'
    /home/deploy/.rvm/gems/ruby-2.4.2/gems/activesupport-5.1.6/lib/active_support/dependencies.rb:286:in `load'
    /home/deploy/.rvm/gems/ruby-2.4.2/gems/activesupport-5.1.6/lib/active_support/dependencies.rb:286:in `block in load'
    /home/deploy/.rvm/gems/ruby-2.4.2/gems/activesupport-5.1.6/lib/active_support/dependencies.rb:258:in `load_dependency'
    /home/deploy/.rvm/gems/ruby-2.4.2/gems/activesupport-5.1.6/lib/active_support/dependencies.rb:286:in `load'
    /home/deploy/.rvm/gems/ruby-2.4.2/gems/railties-5.1.6/lib/rails/engine.rb:655:in `block in load_config_initializer'
    /home/deploy/.rvm/gems/ruby-2.4.2/gems/activesupport-5.1.6/lib/active_support/notifications.rb:168:in `instrument'
    /home/deploy/.rvm/gems/ruby-2.4.2/gems/railties-5.1.6/lib/rails/engine.rb:654:in `load_config_initializer'
    /home/deploy/.rvm/gems/ruby-2.4.2/gems/railties-5.1.6/lib/rails/engine.rb:612:in `block (2 levels) in <class:Engine>'
    /home/deploy/.rvm/gems/ruby-2.4.2/gems/railties-5.1.6/lib/rails/engine.rb:611:in `each'
    /home/deploy/.rvm/gems/ruby-2.4.2/gems/railties-5.1.6/lib/rails/engine.rb:611:in `block in <class:Engine>'
    /home/deploy/.rvm/gems/ruby-2.4.2/gems/railties-5.1.6/lib/rails/initializable.rb:30:in `instance_exec'
    /home/deploy/.rvm/gems/ruby-2.4.2/gems/railties-5.1.6/lib/rails/initializable.rb:30:in `run'
    /home/deploy/.rvm/gems/ruby-2.4.2/gems/railties-5.1.6/lib/rails/initializable.rb:59:in `block in run_initializers'
    /home/deploy/.rvm/gems/ruby-2.4.2/gems/railties-5.1.6/lib/rails/initializable.rb:48:in `each'
    /home/deploy/.rvm/gems/ruby-2.4.2/gems/railties-5.1.6/lib/rails/initializable.rb:48:in `tsort_each_child'
    /home/deploy/.rvm/gems/ruby-2.4.2/gems/railties-5.1.6/lib/rails/initializable.rb:58:in `run_initializers'
    /home/deploy/.rvm/gems/ruby-2.4.2/gems/railties-5.1.6/lib/rails/application.rb:353:in `initialize!'
    /var/www/maisonconvite/config/environment.rb:5:in `<top (required)>'
    /home/deploy/.rvm/gems/ruby-2.4.2/gems/activesupport-5.1.6/lib/active_support/dependencies.rb:292:in `require'
    /home/deploy/.rvm/gems/ruby-2.4.2/gems/activesupport-5.1.6/lib/active_support/dependencies.rb:292:in `block in require'
    /home/deploy/.rvm/gems/ruby-2.4.2/gems/activesupport-5.1.6/lib/active_support/dependencies.rb:258:in `load_dependency'
    /home/deploy/.rvm/gems/ruby-2.4.2/gems/activesupport-5.1.6/lib/active_support/dependencies.rb:292:in `require'
    /home/deploy/.rvm/gems/ruby-2.4.2/gems/railties-5.1.6/lib/rails/application.rb:329:in `require_environment!'
    /home/deploy/.rvm/gems/ruby-2.4.2/gems/railties-5.1.6/lib/rails/application.rb:445:in `block in run_tasks_blocks'
    /home/deploy/.rvm/gems/ruby-2.4.2/gems/railties-5.1.6/lib/rails/commands/rake/rake_command.rb:21:in `block in perform'
    /home/deploy/.rvm/gems/ruby-2.4.2/gems/railties-5.1.6/lib/rails/commands/rake/rake_command.rb:18:in `perform'
    /home/deploy/.rvm/gems/ruby-2.4.2/gems/railties-5.1.6/lib/rails/command.rb:46:in `invoke'
    /home/deploy/.rvm/gems/ruby-2.4.2/gems/railties-5.1.6/lib/rails/commands.rb:16:in `<top (required)>'
    /var/www/maisonconvite/bin/rails:9:in `require'
    /var/www/maisonconvite/bin/rails:9:in `<top (required)>'
    /home/deploy/.rvm/gems/ruby-2.4.2/gems/spring-2.0.2/lib/spring/client/rails.rb:28:in `load'
    /home/deploy/.rvm/gems/ruby-2.4.2/gems/spring-2.0.2/lib/spring/client/rails.rb:28:in `call'
    /home/deploy/.rvm/gems/ruby-2.4.2/gems/spring-2.0.2/lib/spring/client/command.rb:7:in `call'
    /home/deploy/.rvm/gems/ruby-2.4.2/gems/spring-2.0.2/lib/spring/client.rb:30:in `run'
    /home/deploy/.rvm/gems/ruby-2.4.2/gems/spring-2.0.2/bin/spring:49:in `<top (required)>'
    /home/deploy/.rvm/gems/ruby-2.4.2/gems/spring-2.0.2/lib/spring/binstub.rb:31:in `load'
    /home/deploy/.rvm/gems/ruby-2.4.2/gems/spring-2.0.2/lib/spring/binstub.rb:31:in `<top (required)>'
    /var/www/maisonconvite/bin/spring:15:in `require'
    /var/www/maisonconvite/bin/spring:15:in `<top (required)>'
    bin/rails:3:in `load'
    bin/rails:3:in `'
    Tasks: TOP => db:drop => db:check_protected_environments => environment
    (See full trace by running task with --trace

Answer: Você está rodando com ambiente de produção, enquanto era pra ser de desenvolvimento.
Sete o RAILS_ENV para development e rode as migrações dessa forma:
RAILS_ENV=development rails db:drop db:create db:migrate && db:seed

Uma pequena nota: atualmente no Rails 5 ou inferior, não faça rails db:drop db:create db:migrate db:seed, o db:seed junto com o db:migrate faz um tipo de cache nas informações das colunas. (veja a issue no GitHub)


Finding an example of exterior measure

Question: I am finding a sequence of set $E_1\supset  E_2 \supset ...$,and $m^*(E_k)<\infty $,satisfy$$m^*(\cap_{k=1}^{k=\infty}E_k)<\lim_{k\rightarrow \infty}m^*E_k$$
Attempt I think maybe I should use the unmeasurable set .because if a sequence of set named $A_n$ is measurable then $$m^*(\cap_{k=1}^{k=\infty}E_k)=\lim_{k\rightarrow \infty}m^*E_k$$
But I can't construct the sequence of $E_n$, can someone help me thanks a lot
Definition $$m^*(E)=inf\{mG|E\subset  G,\text{G is an open set}\}$$
Comment: I have deleted my careless answer.
Comment: @Jochen never mind ~
Comment: Which outer measure do you consider? $m^*(E)=0$ for $E\subseteq \mathbb R$ *finite* and $m^*(E)=1$ for $E$ infinite defines an outer measure where you can easily find examples, e.g., $E_n=[n,\infty)$.
Comment: @Jochen I am a new learner of real analysis ,I edited my question
Comment: For the Lebesgue outer measure on $\mathbb R$ this is more difficult. As far as I remember in the book *Measure and Category* of Oxtoby you can find (or use some result there to show existence) of a family of disjoint subsetes $A_x$ (with $x\in\mathbb R$) of $[0,1]$ each having outer Lebesgue measure $1$ . Then you can take $E_n=\bigcup\limits_{k\in \{n,n+1,\ldots\}} A_k$.
Comment: @Jochen thanks for your advise I am looking good book about real analysis
Answer: EDIT.
I think that the standard example of a non-measurable subset of $\mathbb R$ can be used: Let $A\subseteq [0,1]$ contain exactly one element of each equivalence class of the relation $x\sim y$ if $x-y\in\mathbb Q$. Then $m^*(A)$ is finite and strictly positive because of $\mathbb R=\bigcup_{q\in\mathbb Q} (A+q)$ and the sub-$\sigma$-additivity of the outer Lebesgue measure. Moreover, the sets $q+A$ are pairwise disjoint. Now take $E_n=\bigcup\limits_{k\in \{n,n+1,\ldots\}} (A+1/k)$. The intersection is empty but the outer measure of each $E_n$ satisfies $m^*(A)\le m^*(E_n)\le 2$.
Comment: In my question $m^*(E_k)<\infty$
Comment: Thanks a lot !and I think in your answer q+E means $q+E_n.$
Comment: but what about lim$m^*E_n$ ,is the limit exist?

Finding an example of exterior measure


VBA check value from column A exists in another workbook

Question: I am trying to build a macro that loops through a range of values within colA and check if they exist with another workbook. In one of them I would like to mark it "Worked"/"Not Worked"

Any guidance on where to start?
Comment: you can do this by, open one workbook(named book1) and store its value in Dictionary. Then access one by one value from another workbook(name book2) and check for existence of that word in Dictionary. If match found then mark that word in book2. Hope it will help you. For anymore query kindly make me know.
Answer: Example
Here is an example of what you're looking for. Remember that both the workbooks have to be opened in the same instance of Excel.
<code>Sub check()

Dim i As Integer, k As Integer, j As Integer 'Define your counting variables
Dim Report1 As Worksheet, bReport As Workbook, Report2 As Worksheet, bReport2 As Workbook 'Define your workbook/worksheet variables

Set Report1 = Excel.ActiveSheet 'Assign active worksheet to report1
Set bReport = Report1.Parent 'Assign the workbook of report 1 to breport

On Error GoTo wbNotOpen 'If an error occurs while accessing the named workbook, send to the "wbNotOpen" line.
Set bReport2 = Excel.Workbooks("otherworkbookname.xlsm") 'Assign the other workbook which you are cross-referencing to the bReport2 variable.
Set Report2 = bReport2.Worksheets("otherworksheetname") 'Do the same with the worksheet.
On Error GoTo 0 'Reset the error handler (to undo the wbNotOpen line.)

k = Report1.UsedRange.Rows.Count 'Get the last used row of the first worksheet.
j = Report2.UsedRange.Rows.Count 'Get the last used row of the second worksheet.

For i = 2 To k 'Loop through the used rows of the first worksheet. I started at "2" to omit the header.
    'Next, I used the worksheet function "countIf" to quickly check if the value exists in the given range. This way we don't have to loop through the second worksheet each time.
    If Application.WorksheetFunction.CountIf(Report2.Range(Report2.Cells(2, 1), Report2.Cells(j, 1)), Report1.Cells(i, 1).Value) > 0 Then
        Report1.Cells(i, 5).Value = "Worked" 'If the value was found, enter "Worked" into column 5.
    Else
        Report1.Cells(i, 5).Value = "Not worked" 'If the value wasn't found, enter "Not worked" into column 5.
    End If
Next i

Exit Sub
'This is triggered in the event of an error while access the "other workbook".
wbNotOpen:
MsgBox ("Workbook not open. Please open all workbooks then try again.")
Exit Sub

End Sub
</code>

This link also includes steps that tell how to check if a cell exists in another workbook. The comments are useful.

Excel macro - paste only non empty cells from one sheet to another (Stack Overflow)
Comment: The following code I am trying to make sense of {            If Application.WorksheetFunction.CountIf(Report2.Range(Report2.Cells(2, 1), Report2.Cells(j, 1)), Report1.Cells(i, 1).Value) > 0 Then
}  If you can explain how the referencing is working, I semi-understand it.
Comment: I ask the above because I have made the necessary changes and tried running the macro using some test data that exists in both documents however all it displays is "Not Worked"
Comment: @user1810449 That line is basically the VBA version of the CountIf function in excel. It works the same way; it uses two parameters: one for the range and one for the search value. The only difference is you have to specify the range using VBA `mySheet.Range(cellone,celltwo)`. In the code above, cell one is `Report2.Cells(2,1)` and cell two is `Report2.Cells(j,1)`. The search value is `Report1.Cells(i,1).Value`. You want the `.Value` there because we are referencing the contents of the cell and not the cell itself.
Answer: Thanks to #Lopsided's solution, I have tweeked his code to bring forth this solution. And this seems to work.
<code>{
Sub CheckValue()

Dim S1 As Worksheet
Dim S2 As Worksheet

Dim i As Integer
Dim k As Integer
Dim j As Integer

Set S1 = Worksheets("Sheet1")
Set S2 = Worksheets("Sheet2")

k = S1.UsedRange.Rows.Count
j = S2.UsedRange.Rows.Count

For i = 1 To k
If Application.WorksheetFunction.CountIf(S2.Range(S2.Cells(2, 1), S2.Cells(j, 1)), S1.Cells(i, 1).Value) > 0 Then
    S1.Cells(i, 5).Value = "Worked" 'If the value was found, enter "Worked" into column 5.
Else
    S1.Cells(i, 5).Value = "Not worked" 'If the value wasn't found, enter "Not worked" into column 5.
End If
Next i
End Sub
</code>
}
Comment: I would like to know if there is a quick resolve for this blanks cells get marked. Whenever I run the macro it marks it as desired, however it also marks the blanks cells also.
Comment: If you have blank cells within the used range of the first sheet, the countif function will use the empty string value as the search value. If you want to quickly omit these cells, just wrap the if function in another if. Like `If S1.Cells(i,1).Value <> "" Then`. Which basically says do the following only if the search value isn't blank.
Comment: Does that mean I have to write a nested if statement? Or just add another if then line below.
Comment: Nested. Put the line I wrote above it, and the `End If` line below.
Comment: I have added the if statement to the code and no matter what it displays "Not Worked" for all cells {For i = 2 To k
    If S1.Cells(i, 1).Value <> "" Then

    If Application.WorksheetFunction.CountIf(S2.Range(S2.Cells(2, 1), S2.Cells(j, 1)), S1.Cells(i, 2).Value) > 0 Then
        S1.Cells(i, 5).Value = "Worked"
        S1.Cells(i, 5).Interior.ColorIndex = 43
    Else
        S1.Cells(i, 5).Value = "Not worked"
        S1.Cells(i, 5).Interior.ColorIndex = 36        'If the value wasn't found, enter "Not worked" into column 5.
        End If
    End If
Next i}
Comment: Well my solution would only fix it if that was indeed the problem. It could be another issue. It might be best to just make another question.


Mybatis ResultMap is HashMap

Question: I can't seem to find a way to get the result map as a map
My sql is
<select id="retrievePackageHeader" parameterType="java.lang.String" resultType="PackageHeaderMap">
    SELECT CONCAT(SCE_WRK_CTRL_NB, AC_CRR_CDE) as row_id,
    MTC_CHK_TYP_CDE,
    PLNR_REVW_IND,
    PLNR_OWD_IND,
    PKG_SLOT_TYP_CDE
    FROM WSM_PKG_HDR WHERE AC_NB = '${value}';
    WITH UR
</select>

Now i need row_id as the map (key) and the other columns as attributes of a bean.
I want to do something like my code below, but I can't find the correct syntax.
 <resultMap id="PackageBeanResult"              type="PackageBean">
    <result property="checkType"                column="MTC_CHK_TYP_CDE"/>
    <result property="plannerReview"            column="PLNR_REVW_IND"/>
    <result property="plannerOwned"             column="PLNR_OWD_IND" />
    <result property="slotType"                 column="PKG_SLOT_TYP_CDE" />
 </resultMap>

 <resultMap id="PackageHeaderMap"               type="java.util.HashMap">
    <result property="java.lang.String"         column="row_id"/>
    <result property="object"                   resultMap="PackageBeanResult"/>
 </resultMap>

Any ideas?
Thanks.
Answer: In my case, add helper class:
/**
 * Helper converting list to map.
 * @param <K> key
 * @param <V> value
 */
@Getter
public class MappingHelper<K, V> {
    private K key;
    private V value;

    /**
     * Return map from {@link MappingHelper} list.
     * @param list DTO list
     * @param <K> key
     * @param <V> value
     * @return map
     */
    public static <K, V> Map<K, V> toMap(List<MappingHelper<K, V>> list) {
        if (list == null) {
            return Collections.emptyMap();
        }
        return list.parallelStream().collect(Collectors.toMap(MappingHelper::getKey, MappingHelper::getValue));
    }
}

And, init mapper.java:
List<MappingHelper<Integer, String>> getNames(@Param("ids") List<Integer> Ids);

mapper.xml:
<resultMap id="nameMap" type="package.model.MappingHelper">
    <id     property="key"   column="id"/>
    <result property="value" column="nm"/>
</resultMap>

<select id="getNames" resultMap="nameMap">
    SELECT id, nm
    FROM name_table
    WHERE id IN <foreach item="id" collection="ids" open="(" separator="," close=")">#{id}</foreach>
</select>

Finally, use as follows:
Map<Integer, String> names = MappingHelper.toMap(mapper.getNames(ids));

Answer: Mybatis does not support the feature you wanted. Why do you just use java.util.Map as your result set directly.
<select id="retrievePackageHeader" parameterType="java.lang.String" resultType="java.util.Map">
SELECT CONCAT(SCE_WRK_CTRL_NB, AC_CRR_CDE) as row_id,
MTC_CHK_TYP_CDE as checkType,
PLNR_REVW_IND as plannerReview,
PLNR_OWD_IND as plannerOwned,
PKG_SLOT_TYP_CDE as slotType
FROM WSM_PKG_HDR WHERE AC_NB = '${value}';
WITH UR

Comment: What's the key and value in this case?
Comment: The key is table field's alias, like *row_id*,*checkType*, and the value is your query result value.
Comment: double quotes for alias name worked for me, like: MTC_CHK_TYP_CDE as "checkType"
Answer: Its very simple.
If you use Interface as Dao, you have to add this annotation:
@MapKey("key")
public Map<String,Object> searchSomethings(... parameters ...);

You will have, in your query, a column with an alias as "key":
SELECT
  column_key as key,
  foo_column as fooColumn,
  ...
FROM table

In select statment, you have to leave resultType with Object class.
<select id="searchSomethings" resyltType="ObjectClass">
  ...
</select>

Comment: Alas, MySQL has `key` as a reserved word. https://stackoverflow.com/questions/924265/what-does-the-key-keyword-mean
Comment: After quoting the keyword (`@Select("select sources.host as 'key', count(*) total ..."`), it now gives `nested exception is org.apache.ibatis.reflection.ReflectionException: There is no getter for property named 'key' in 'class java.lang.String'`.
Comment: Mybatis doesnt care about reserved words when you are usin them in a select statement

Mybatis ResultMap is HashMap


Basics on setting up a hyper-v cluser on a Windows 8 host

Question: I'm a complete newbie to setting up servers and clustering, so baby gloves please :)
I am trying to simulate a cluster of 4 nodes on my windows 8 laptop using hyper-v (its a beefy laptop, so don't worry about the performance). So far, I have done the following steps:
1) Installed a VM (Windows Server 2012) to act as my domain controller
2) Installed 4 VM's (each with Windows Server 2012) to act as my cluster. Each VM is connected to the domain
3) Installed the Failover cluster feature on each of the 4 nodes and created a cluster using the Failover cluster Manager
Now, I need to setup a storage for this cluster. My initial thoughts were to use a shared folder from my laptop which can act as a common storage, but I can't figure out how to do this or even if this is possible. I keep hearing about setting up iSCSI but I have failed to find a basic tutorial on this.
I did also find iSCSI software target (http://www.microsoft.com/en-gb/download/details.aspx?id=19867), but I'm not sure how to use this. Should I install WS2012 on a new VM, join it to the domain and install this software on that VM in order to provide storage for my cluster? IF so, will I need to recreate my cluster?
Seeking help from one of the gurus on this forum on how to take this forward and configure a common storage for the cluster in the simplest manner possible. Just as a tiny bit of background, I need to do this in order to test out some cluster related runbooks from system center orchestrator, so this cluster won't really be used for anything real.
Thanks in advance :)
Comment: link bomb this is for guest clustering, you can't do host clustering with windows 8. http://blogs.technet.com/b/mghazai/archive/2009/12/12/hyper-v-guest-clustering-step-by-step-guide.aspx
Comment: Thanks for that link. I found another great step-by-step guide to setting up shared storage, but that doesn't work with in my setup http://clusteringformeremortals.com/2012/12/31/windows-server-2012-clustering-step-by-step/
Answer: I have now managed to do the above using information from a variety of links.
Adding these links here for completeness:
http://blogs.technet.com/b/sainfrateam/archive/2011/05/09/hyper-v-guest-clustering.aspx
http://blogs.technet.com/b/meamcs/archive/2012/03/30/installing-and-configuring-target-iscsi-server-on-windows-server-8-beta.aspx
Hope someone else can find the post useful
Comment: Found the definitive guide to doing what I want to do, again if it helps someone, look here http://blogs.technet.com/b/babulalghule/archive/2013/02/16/how-to-configure-two-node-windows-server-2012-cluster-on-virtual-machines-for-testing.aspx


Issue with Facebook SDK and iOS application (authButtonAction)

Question: I am not exactly sure what is going wrong. I implemented everything specified by developers.Facebook.com to authenticate Facebook login in my iOS application. Here is what I believe is relevant to the problem:
The application I am making is a tabbed application with a navigation controller.
I get a warning for the following code (provided by Facebook developers page):
<code>- (IBAction)authButtonAction:(id)sender {
    AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
    // The user has initiated a login, so call the openSession method
    // and show the login UX if necessary.
    [appDelegate openSessionWithAllowLoginUI:YES];
}
</code>
The warning is:
Initializing 'AppDelegate *' with an expression of incompatible type 'id< UIApplicationDelegate>'
When I click the authButton, the Facebook app on my iPhone opens and the appropriate message is presented to the user about granting my application access to post status updates. BUT...the control flow is never given back to my application and the Facebook application is left open. I believe this has to do with the above warning.
Answer: Try this:
<code>AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
</code>
Comment: Got rid of the warning, but flow still stays with Facebook app.
Comment: Looks like the warning didn't have anything to do with the issue. Can you paste other relevant codes to better understand the reason?
Comment: Thanks for the help and fixing the warning, but I just figured out the issue. In my .plist file, I had "URL schemes" and it needed to be "URL Schemes" haha :)
Comment: Glad you fixed it, it happens. ;)
Comment: Hi @OhhMee, This solved my error, but I'm not sure I understand why the solution works. Would you or anyone mind explaining to me? Thank you!


Adding a row to JList

Question: I'm trying to add a row to a JList, but it doesn't happen. I'm using Java + MySQL. But when using System.out.println(), it works.
Here is the code for receiving the data:
public void writeResultSet(ResultSet resultSet) throws SQLException {

    while (resultSet.next()) {

        String student_firstname = resultSet.getString("student_firstname");
        String student_middlename = resultSet.getString("student_middlename");
        String student_lastname = resultSet.getString("student_lastname");

        DefaultListModel listModel = new DefaultListModel();
        listModel.addElement("" + student_firstname + " " + student_middlename + " " + student_lastname);
        jList1.setModel(listModel);

    }
}

Also, if I try to add the listmodel in private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) but using defined string, it works, but I need to insert it in this method so that I can get the data from MySQL.
Comment: You are creating a new model and give it to the list once for each row of your result, are you sure this is what you want? With this you can only add the last student in the JList
Answer: As pointed out, you're re-instantiating the ListModel and setting it to the JList for every record in the result set, which means that the only thing you're going to see is the last record in the resultSet. Instead, you should be doing something like this:
public void writeResultSet(ResultSet resultSet) throws SQLException {

    DefaultListModel listModel = new DefaultListModel();

    while (resultSet.next()) {

        String student_firstname = resultSet.getString("student_firstname");
        String student_middlename = resultSet.getString("student_middlename");
        String student_lastname = resultSet.getString("student_lastname");

        listModel.addElement("" + student_firstname + " " + student_middlename + " " + student_lastname);

    }

jList1.setModel(listModel);

}

Adding a row to JList


In the 2005-2006 NBA season why was Denver seeded above Dallas despite having 16 fewer wins?

Question: In the 2005-2006 nba why was denver seeded above dallas even though they had 16 fewer wins? this never made sense to me?
Answer: In the Western conference, the Denver Nuggets won the Northwest division. Division winners (Spurs in Southwest, Suns in Pacific, and Nuggets in Northwest) get the highest seeds based on record (1 - Spurs, 2 - Suns, then 3 - Nuggets).
Then, non-division winners are seeded based on record. The Dallas Mavericks finished second in the Southwest division and had the best record of a non-division winner, thus awarding them the fourth seed (followed by 5 - Grizzlies, 6 - Clippers, 7 - Lakers, and 8 - Kings). You will also notice that the 8th seeded Sacramento Kings had the same record as the 3rd seeded Denver Nuggets.
Source: (1) (2)
The following verbiage from NBA.com will also help in regards to understanding seeding:

Teams 1 to 4 in each conference are the three division winners and the
  team with the next best regular-season record, with the seeding of
  these four teams determined by regular-season record. The playoffs
  seedings of Teams 5 to 8 are based upon regular-season record.

NOTE: I believe the verbiage above was put into place after the 2005-2006 season.


É possível usar IF dentro do FROM no MySql?

Question: Seria possível fazer IF dentro do FROM?
Procurei mas não consegui achar nada a respeito.
Segue um exemplo do que quero fazer:
SELECT usuario.* FROM (
  SELECT
  IF(
    (SELECT COUNT(*) FROM pessoa) > 0,
    SELECT  FROM pessoa,
    SELECT * FROM clliente,
  ) AS usuario
)

OBS: Como a arquitetura do banco foi desenvolvida da pior forma, estou tendo que fazer umas loucuras no SQL.
Comment: Eu tenho quase certeza que não (porque eu acabei de testar aqui), mas tenho certeza do que o que você precisa pode ser feito de outra maneira. Você tem algum exemplo real do que você precisa fazer com isso?
Answer: Uma solução pode ser criar uma view
create or replace view v_pessoa_cliente
as
select cpf , nome from pessoa
union
select cpf,nome from cliente

Na aplicação faça
select *
from v_pessoa_cliente
where nome = 'Daniel Dutra'

Answer: Simplificando assim já não resolveria o seu caso?
SELECT IF(COUNT(p.*) > 0, p.*, c.*) as usuarios_maior_volume
FROM pessoas p, clientes c;

E para pegar global:
SELECT * FROM pessoas, clientes;

E para trazer tudo:
SELECT * FROM pessoas
union all
SELECT * FROM clientes;

Comment: Não obtive sucesso, apresenta erro de versão do MySql.
version: 5.0.95-log; version_bdb: Sleepycat Software: Berkeley DB 4.1.24: (December 16, 2011)


Decrypting data with Rsa Private Key/Function

Question: I'm just trying to encode/decode data (decode, firstly)  with RSA.
I don't care of the type of data (string, bytes, or other lolcat-encoded data), I just looking a very simple function doing the job (cryptographic operations) and I can do the rest.
Here is what I tried :
CryptoPP::InvertibleRSAFunction rsa;

rsa.SetModulus( n_factor );
rsa.SetPrivateExponent(d_private_exponent);

rsa.SetPrime1( rsa_params.at(p1) );
rsa.SetPrime2( rsa_params.at(p2) );

// All above inputs are correct. I don't have public exponent, but it's works in other languages (I comprared all inputs/outputs)

bool key_ok = rsa.Validate(CryptoPP::NullRNG(), 15);
/* Returns false, but doesn't tell me why :/ */

CryptoPP::Integer to_decode( my_data, size_of_my_data );
res = rsa.CalculateInverse(rg,to_decode);

This returns:
EXCEPTION : what():  CryptoMaterial: this object contains invalid values

Returned error code corresponds to "INVALID_DATA_FORMAT", which probably doesn't mean a key problem, but an input problem.
If anyone has some experience with this library, or detects a "noob" mistake (I've my mind in code since 4 hours, so it is possible), any help would be appreciated.
Comment: "`bool key_ok = rsa.Validate(CryptoPP::NullRNG(), 15)`" - I'm not sure this is right. I think you need a real PRNG, and not the `NullRNG`. That's because some of the tests are probabilistic. Also, the highest level you can use is 3, not 15. See [Keys and Formats, Validating Keys](http://www.cryptopp.com/wiki/Keys_and_Formats#Validating_Keys).
Comment: Also see [Raw RSA](http://www.cryptopp.com/wiki/Raw_RSA) on the Crypto++ wiki. Its not advised, though.
Answer: Easier than I thought :
CryptoPP::Integer dec_data = a_exp_b_mod_c( enc_data, d_private_exponent, n_modulus );

So 'd' and 'n' were enought. I really don't understand why it didn't work with crypto features.
Comment: `a_exp_b_mod_c` performs an exponentiation, but does *not* apply padding. That means a small exponent could leak information; and if the same message is encrypted twice, then the attacker will learn it. Its probably better to use a higher level object and OAEP padding.


How to convert an LSP into objectarx C# to close Autocad polylines?

Question: I need to create a C# objectarx function that will check if a polyline is connected and open.  If so then close they polyline.  This sample code cannot be used because this will not check if it is connected:
if (polyline.Closed == false)
{
    // Close polyline
    polyline.Closed = true;
}

I found out how to do it but it is in LISP.  Does anyone know how to convert this to C# objectarx .net?
;;  PLsCloseCorners.lsp [command name: PLsCL for PolyLines CLose]
;;  To Close all open lightweight Polylines, with the start/end
;;  vertex at the [apparent] intersection of the starting and
;;  ending segments, without coincident start/end vertices.
;;  If one "looks" closed (i.e. last vertex coincides with first one),
;;  but is not closed in Polyline terms, this will close it from
;;  the next-to-last vertex, not by adding a zero-length segment.
;;  [If beginning and/or ending Polyline segment is/are arcs, and
;;  start/end vertices are not coincident, will locate new corner
;;  as if endpoints of arc(s) are endpoints of line segment(s);
;;  if ending segment is an arc and start/end vertices are not
;;  coincident, will alter arc's path.]
;;  Kent Cooper, July 2009
;;
(defun C:PLsCL (/ plset pl plverts corner)
  (setq cmde (getvar 'cmdecho))
  (setvar 'cmdecho 0)
  (command "_.undo" "_begin")
  (setq plset (ssget "X" '((0 . "LWPOLYLINE"))))
    ; omit the "X" from the above line to let User select them
  (while (> (sslength plset) 0)
    (setq pl (ssname plset 0))
    (if (not (vlax-curve-isclosed pl))
      (progn
        (setq
          plverts (cdr (assoc 90 (entget pl))); number of vertices
          corner
            (inters
              (vlax-curve-getStartPoint pl)
              (vlax-curve-getPointAtParam pl 1)
              (vlax-curve-getPointAtParam pl (1- plverts))
              (vlax-curve-getPointAtParam pl (- plverts 2))
              nil
            ); end inters & corner
        ); end setq
        (command
          "_.pedit"
          pl
          "_edit"
          "_move"
          corner
        ); end command
        (repeat (- plverts 2)
          (command "_next"); move to next-to-last vertex
        ); end repeat
        (command
          "_break"
          "_next"
          "_go"
          "_eXit"
          "_close"
          ""
        ); end command
      ); end progn
    ); end if
    (ssdel (ssname plset 0) plset)
  ); end while
  (command "_.undo" "_end")
  (setvar 'cmdecho cmde)
  (princ)
); end defun

Update #1
What I am actually trying to do is determine if a polyline should be closed.  Picture a polyline shaped as the letter C and another polyline as the letter O. In this case, I would like to close the one shaped as the letter O.
Example:
public bool IsPolylineConnected(Polyline pline)
{

  // Convert the code from the LSP to C#
  // A polyline with the shape of the letter C would return false
  // A polyline with the shape of the letter O would return true

}

Comment: Can you provide a test drawing ?
Answer: If you cast the polyline as a curve object you can check if the start point and end point are the same.
Casting the polyline as a curve saves you the trouble of dealing with the different polyline types.
Comment: Miir, I am trying to convert the above code from LSP to C# (ObjectArx).  If you have the actual code on how to do this please let me know!  Thank you for your contribution.
Answer: Can you provide a test drawing ?
And, if you really want to use the logic in lisp, you can always call LISP function from .NET.
For example you have lisp function
;(defun DoIt()

;Define the Lisp function as a command using c:
(defun c:DoIt()

    (setq    pntA (getpoint "\nPick A")
            pntB (getpoint pntA "\nPick B")
    )
    (grdraw pntA pntB 1 2)

)

C#:
[CommandMethod("DoIt", CommandFlags.Session)]
public void DoItMethod()
{
DocumentCollection acDocMgr = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager;
Document acDoc = acDocMgr.Open(@"C:\SampleDrawings\Lights.dwg", false);
using (DocumentLock dl = acDoc.LockDocument())
{
Editor ed = acDoc.Editor;
using (ResultBuffer rb = new ResultBuffer())
{
rb.Add(new TypedValue((int)LispDataType.Text, "c:DoIt"));
ResultBuffer rbRes = Application.Invoke(rb);
if (rbRes != null)
{
TypedValue[] tvalues = rbRes.AsArray();
foreach (TypedValue tv in tvalues)
ed.WriteMessage("\n" + tv.ToString());
rbRes.Dispose();
}
else
ed.WriteMessage("\n Result buffer is null.");
}
}
}

Comment: Madhukar, very nice post!  But I would actually like to convert the code to C# instead of calling LISP code.  Thank you.


Undesirable behavior of javascript operator

Question: I do not understand why this is happening,
console.info("") //(an empty string)

console.info(0)  //0

console.info(typeof "") //string

console.info(typeof 0) //number

console.info(""==0) //true

console.info(0=="") //true

console.info (0>="") //true

console.info ("">=0) //true

Shouldn't it return false for last four statements.
I did all these in FireBug, a firefox addons.
Comment: http://stackoverflow.com/q/1998224/576139
Answer: The ECMAScript Equals Operator (==) uses the Abstract Equality Comparison Algorithm, see ECMA-262 §11.9.3.
Comment: If anyone wants to know how all possible comparisons work, you have to go read this spec.
Comment: Thank you so much for the reference link.
Answer: The last 4 statements involve implicit type casting via the logical comparison operators. Because a String and Number are being compared, the String is converted to a Number. "" turns into 0 which is equal to 0.
You can find it in the specification which is not an easy read IMO:

The comparison x == y, where x and y are values, produces true or false. Such a comparison is performed as follows:

If Type(x) is different from Type(y), go to step 14.
If Type(x) is Undefined, return true.
If Type(x) is Null, return true.
If Type(x) is not Number, go to step 11.
If x is NaN, return false.
If y is NaN, return false.
If x is the same number value as y, return true.
If x is +0 and y is -0, return true.
If x is -0 and y is +0, return true.
Return false.
If Type(x) is String, then return true if x and y are exactly the same sequence of characters (same length and same characters in corresponding positions). Otherwise, return false.
If Type(x) is Boolean, return true if x and y are both true or both false. Otherwise, return false.
Return true if x and y refer to the same object or if they refer to objects joined to each other (see 13.1.2). Otherwise, return false.
If x is null and y is undefined, return true.
If x is undefined and y is null, return true.
If Type(x) is Number and Type(y) is String, return the result of the comparison x == ToNumber(y).
If Type(x) is String and Type(y) is Number, return the result of the comparison ToNumber(x)== y.
If Type(x) is Boolean, return the result of the comparison ToNumber(x)== y.
If Type(y) is Boolean, return the result of the comparison x == ToNumber(y).
If Type(x) is either String or Number and Type(y) is Object, return the result of the comparison x == ToPrimitive(y).
If Type(x) is Object and Type(y) is either String or Number, return the result of the comparison ToPrimitive(x)== y.
Return false.
Comment: Type casting does not explain all of it, e.g. `2. If x is null and y is undefined, return true`—no type casting there, just a straight rule for the result of a particular comparison. Nor does it explain how the types are cast, e.g. if x is Boolean and y is String, both are converted to Number before comparison.
Comment: @Hoque - yes, the values are different types, but as zzzzBov said, the `==` operators attempts to convert them to the same type - if it can do so and after conversion they are equal it returns true. An empty string can be converted to 0, so...
Comment: @nnnnnn, does javascript changes the comparer type to number when comparing with any number like 0 (here)?
Comment: For example ""==0, according to the steps above I should go 1-->then 14 and then no decision...
Comment: No, it goes to 14 which doesn't apply, then 15 which doesn't apply, then 16 which doesn't apply, then 17 which _does_ apply. An empty string is still a string.
Answer: well you have run into javascripts falsey and truthy value concept. In javascript
Truthy: Something which evaluates to TRUE.
Falsey: Something which evaluates to FALSE.

It's mostly logical. One (1) is truthy, Zero (0) is falsey. An object of any kind (including functions, arrays, RegExp objects, etc.) is always truthy. The easiest way to determine if something is truthy is to determine that it's not falsey. There are only five falsey values in JavaScript:
undefined, null, NaN, 0, "" (empty string), and false.

Thus when you end up comparing two falsey values using the Abstract Equality Comparer it returns true.
To get around the problem use the typesafe comparison by using the === operator
Comment: If one operand is a string and the other is a number, `==` will convert the string to a number and then do a number comparison. Falsey and truthy don't come into it.
Comment: I have tested for console.info("Apple"==4) //returns false.
Comment: well you are correct in saying that there is a conversion I am just saying after the conversion what is the comparison like.. I think the conversion part is discussed already


Como funciona o .pipe() no Node.js?

Question: Estou com uma dúvida sobre como funciona o .pipe(). Vi vídeos e li a documentação, mas não tenho certeza de como ele funciona.
Pelo o que eu entendi, ele basicamente pega as informações de uma readableStream e repassa isso para uma writeableStream, mas não tenho certeza se sei utilizar ele da maneira correta. Para esclarecer melhor o que estou dizendo vou colocar um código meu que deu errado:
const fs = require('fs')
const http = require('http')

const port = 8000
const file = './file.txt'

const readStream = fs.createReadStream(file)

const server = http.createServer((req, res) => {
  res.on('pipe', fileContent => console.log(fileContent.toString()))
  readStream.pipe(res)
})

server.listen(port, () => console.log('Server is Runing...'))

Meu objetivo nessa parte era criar um servidor http e passar como resposta o conteúdo de dentro do arquivo pelo console (obs: no arquivo só tem um texto qualquer de uma linha). Meu servidor roda, porém nada aparece no console. Eu queria entender o que pode estar dando de errado pois não sei como receber o conteúdo do arquivo que enviei.
Answer: Basicamente, o método pipe "direciona" o fluxo de uma readable stream para uma writable stream. No caso da pergunta, o pipe está enviado os "pacotes" da read stream do arquivo para a write stream do servidor HTTP.

Na verdade, a stream funciona corretamente na primeira requisição.
Note que você está criando a read stream fora do server handler, de modo que, na primeira requisição, a stream será totalmente consumida. Assim, a partir da segunda requisição, não haverá mais o que ler, uma vez que todos os dados já terão sido esgotados.
É ideal, portanto, que você crie uma read stream para cada requisição. Algo assim:
const server = http.createServer((req, res) => {
  res.on('pipe', () => console.log('Pipe chamado.'));

  const readStream = fs.createReadStream(file);
  readStream.pipe(res);
});

Note agora que uma nova read stream será criada para cada requisição. Observa também que modifiquei o console.log uma vez que o método toString não faz, nesse caso, o que você pensa.
O evento pipe é chamado com um parâmetro do tipo stream.Readable. Portanto, se você quiser imprimir no console os dados lidos, poderá fazer algo como:
const server = http.createServer((req, res) => {
  res.on('pipe', (src) => {
    src.on('data', (chunk) => {
      console.log(chunk.toString('utf8'));
    });
  });

  const readStream = fs.createReadStream(file);
  readStream.pipe(res);
});

Como funciona o .pipe() no Node.js?


Show that ($\gcd(a,b)=c$ and $a+b=d$) and ($c|d$) are equivalent

Question: I haven't been able to figure out this question for a while though I'm sure it's pretty straightforward. (It's intuitive to me and difficult to write into a proof).
Show that these statements are equivalent
I) $\gcd(a,b)=c$ and $a+b=d$
II) $c|d$
Comment: Right, so that shows an example wherin $I \implies II$.  But you asked to show that the two are equivalent.  the implication $II \implies I$ is false, see my posted solution below.
Comment: The statements are not equivalent.  $5$ divides $2+3$ but $5$ is not gcd$(2,3)$.
Comment: Gcd(2,3)=1... 2+3=5... 1 divides 5.
Comment: $d$ can never equal $c$.  Assuming both $a$ and $b$ are greater than $0$, then $d$ is greater than either of them, hence can't be a divisor.  But, generally, the divisors of $a+b$ include the common divisors of $a$ and $b$ but it will have lot's of others as well.  Think of the divisors of $12=11+1$.
Answer: If all you meant was "show that $I \implies II$" that is straightforward:
Let $c=\gcd(a,b)$.  Write $a=cA$,$b=cB$.  Then $$d=a+b=cA+cB=c(A+B)$$ so $c$ divides $d$.
But the other implication is not even remotely true.  After all $1$ always divides $d$ yet $1$ isn't always the gcd of two specified numbers.  Similarly, $d$ always divides $d$ but $d$ is larger than either $a$ or $b$, hence is not a divisor of either.


Is there a limit in the number of simultaneous users in R shiny?

Question: I am preparing a survey of some 1,000 participants (net sample) in R shiny. It may well be that 100 users or so will participate simultaneously once the survey is launched. My problem is that I cannot simulate this situation beforehand but have to trust that it works, otherwise I will be in deep trouble. So my question is, if there is any limit in the number of parallel users (aside from the computational burden, which is a different issue).
I thought that there is no limit but then I realized that I can only open up to 5 shiny tabs in my browser (but another 5 in another browser and so on). Furthermore, I realized that Shiny Server Pro comes with a limit of 20 concurrent users, which makes no sense given that it should be more advanced than the free version. These things make me a bit uneasy if there are further limits, which I am not aware of.
Thank you for your help, Reinhard
Answer: The free version of Shiny server is single threaded, there is not limit in the number of users but your app could be slower with multiple users at the same time. Here are more details about it.
The Pro version is multi threaded and the limit of concurrent users is defined by the license that you buy (and the hardware resources).
If your app is just a survey without any strong computation, it should be able to handle many users at the same time with a minimal delay.


Is this acceptable for passing data from a module to a template?

Question: I'm attempting to pass some data from a block module into a template. I've found that I can make up a render array property and then access it in the template. Here is an example of my code:
class MyBlock extends BlockBase {
      return [
        '#firstname' => 'John',
        '#lastname' => 'Doe',
      ];
    }

I can access this data in the twig templeate by using:
{{ elements.myblock.content['#firstname'] }}
{{ elements.myblock.content['#lastname'] }}

Is this an acceptable means for passing data into a template? All the other examples I've found have the render arrays being picked up by a hook_theme function and then getting passed to the template. The method I show above seems simpler and I'm wondering if there is something problematic with doing it this way.
Thanks!
Comment: I think your approach is fine, except best practice would be that your twig template would exist in the same module as where you are creating the block.
Answer: If you pass the variables like the following:
class MyBlock extends BlockBase {
  public function build() {
    return [
      '#firstname' => 'John',
      '#lastname' => 'Doe',
    ];
  }
}

You can access to your variables #firstname and #lastname like:
{{ content['#firstname'] }}
{{ content['#lastname'] }}

Comment: Thank you, this is helpful.


Como passar valores javascript para C#

Question: Possuo uma classe Cliente, onde um cliente pode ter varios beneficiarios como podem ver na ultima propriedade.
public class Cliente
    {
        ///
        /// Id
        ///
        public long Id { get; set; }

        ///
        /// CEP
        ///
        public string CEP { get; set; }

        ///
        /// Cidade
        ///
        public string Cidade { get; set; }

        ///
        /// E-mail
        ///
        public string Email { get; set; }

        ///
        /// Estado
        ///
        public string Estado { get; set; }

        ///
        /// Logradouro
        ///
        public string Logradouro { get; set; }

        ///
        /// Nacionalidade
        ///
        public string Nacionalidade { get; set; }

        ///
        /// Nome
        ///
        public string Nome { get; set; }

        ///
        /// Sobrenome
        ///
        public string Sobrenome { get; set; }

        ///
        /// Telefone
        ///
        public string Telefone { get; set; }

        ///
        /// Cpf
        ///
        public string Cpf { get; set; }

        public List<Beneficiario> Beneficiarios { get; set; }
    }

Classe Beneficiario:
public class Beneficiario
    {
        ///
        /// Id
        ///
        public long Id { get; set; }

        ///
        /// Cpf
        ///
        public string CpfBeneficiario { get; set; }

        ///
        /// Nome
        ///
        public string NomeBeneficiario { get; set; }

        ///
        /// Id do Cliete
        ///
        public int IdCliente { get; set; }

    }

Código JS:
    var rowIndex = -1;
var beneficiarios = [];

$(document).ready(function () {
    $('#formCadastro').submit(function (e) {
        e.preventDefault();
        var lista = document.getElementById('tbLista').rows;
        for (var i = 1; i < lista.length; i++) {
            beneficiarios.push(JSON.stringify({ "cpf": lista[i].cells[0].innerHTML, "nome": lista[i].cells[1].innerHTML }));
        }
        $.ajax({
            url: urlPost,
            method: "POST",
            data: {
                "NOME": $(this).find("#Nome").val(),
                "CEP": $(this).find("#CEP").val(),
                "Email": $(this).find("#Email").val(),
                "Sobrenome": $(this).find("#Sobrenome").val(),
                "Nacionalidade": $(this).find("#Nacionalidade").val(),
                "Estado": $(this).find("#Estado").val(),
                "Cidade": $(this).find("#Cidade").val(),
                "Logradouro": $(this).find("#Logradouro").val(),
                "Telefone": $(this).find("#Telefone").val(),
                "Cpf": $(this).find("#Cpf").val(),
                "Beneficiarios": JSON.stringify(beneficiarios)
            },
            error:
                function (r) {
                    if (r.status == 400)
                        ModalDialog("Ocorreu um erro", r.responseJSON);
                    else if (r.status == 500)
                        ModalDialog("Ocorreu um erro", "Ocorreu um erro interno no servidor.");
                },
            success:
                function (r) {
                    ModalDialog("Sucesso!", r)
                    $("#formCadastro")[0].reset();
                }
        });
    });
});

Controller:
[HttpPost]
        public JsonResult Alterar(ClienteModel model)
        {
            BoCliente bo = new BoCliente();

            if (!this.ModelState.IsValid)
            {
                List<string> erros = (from item in ModelState.Values
                                      from error in item.Errors
                                      select error.ErrorMessage).ToList();

                Response.StatusCode = 400;
                return Json(string.Join(Environment.NewLine, erros));
            }
            else
            {
                var cpf = RemoverCaracteresEspeciais(model.Cpf);
                var existeCPF = bo.VerificarExistencia(cpf);
                if (existeCPF)
                {
                    Response.StatusCode = 400;
                    return Json("O Cpf já está cadastrado.");
                }
                else
                {
                    if (Validacoes.ValidaCpf(cpf))
                    {
                        bo.Alterar(new Cliente()
                        {
                            Id = model.Id,
                            CEP = model.CEP,
                            Cidade = model.Cidade,
                            Email = model.Email,
                            Estado = model.Estado,
                            Logradouro = model.Logradouro,
                            Nacionalidade = model.Nacionalidade,
                            Nome = model.Nome,
                            Sobrenome = model.Sobrenome,
                            Telefone = model.Telefone,
                            Cpf = cpf
                        });

                        return Json("Cadastro alterado com sucesso");
                    }
                    else
                    {
                        Response.StatusCode = 400;

                        return Json(string.Join(Environment.NewLine, "O cpf digitado é inválido."));
                    }
                }
            }
        }

Tenho uma tabela onde adiciono Cpf e nome de cada beneficiario para aquele respectivo cliente, consigo passar todos os dados para minha controller porem nao tenho ideia de como seria para passar os valores da tabela tb. Minha duvida é essa, como posso passar valores de uma tabela no front end via ajax para minha lista de beneficiarios da classe Cliente no c#?
Comment: Você quer saber como passar alguma informação de uma tabela "Front End" para a controller "Back End"?

Qual seria a informação?

Pode mostrar o código HTML?
Comment: isso mesmo, ao chegar no back end que é c# a lista está vindo zerada
Answer: Para fazer o parse corretamente, você deve colocar o mesmo nome nos atributos (Model/View).
Esta linha: beneficiarios.push(JSON.stringify({ "cpf": lista[i].cells[0].innerHTML, "nome": lista[i].cells[1].innerHTML }));
deveria ficar assim: beneficiarios.push(JSON.stringify({ "CpfBeneficiario": lista[i].cells[0].innerHTML, "NomeBeneficiario": lista[i].cells[1].innerHTML }));
Comment: Isso eram os nomes mesmo obrigado.

Como passar valores javascript para C#


How to detect if form-building function is called for the first time?

Question: In my form building function I need to render some things basing on user's actions. But if the form building function is called for the very first time I want to put a form deliberately in slightly inconsistent state (I have my reasons, long story).
How can I reliably detect if the form building function was called for the first time, or if the form was already presented to the user and now it's built due to AJAX call or to allow user to fix input errors?
Currently I'm using empty($form_state['input']) but I have this feeling there is a better, more reliable way and I forgot it.
Answer: You can add our own value to $form_state in a hook_form_alter().  If it doesn't already exist (eg., !isset($form_state['my_var'])), then you know it is the first build.
Comment: Yes, i guess node form also does something in similar way check this link https://api.drupal.org/api/drupal/modules!node!node.pages.inc/function/node_form/7
Comment: +1 from me. If the Form API does not have any built-in mechanism, will do it that way. Let's see if anyone knows a better way. Will accept this, if there appears to be none.
Answer: At least in Drupal 9, your form_alter function() will run at least twice without the value you add to form_state being defined. Now that it is an object and not an array, the only mechanism I know of to set an arbitrary value is get() and set(), and the values live in the storage property of form_state. According to this issue:

form_state['storage'] is ought to be changed in submit handler not in builder.

That comment is 15 years old, so maybe it isn't so definitive nowadays. When I try it, I find that my values need to be initialized at least twice.
The only reliable indication I have found for "the beginning of this form process" (ie if you are editing a node, and you reload the URL, that starts a new form process, even though it's the same entity) is that both form_state values and input are empty. I hope to eventually find something better.


Change weight of CSS file loaded in custom module with #attached?

Question: Im working on a custom module which loads a CSS file:
<code>$content['#attached']['css'] = array(
  path_to_theme() . '/new.css',
);
</code>
How can I change the weight of the file so that its loaded after the other CSS files? I thought it would be something like this:
<code>$content['#attached']['css'] = array(
  path_to_theme() . '/new.css',
  'weight' => 1000,
);
</code>
Or this:
<code>$content['#attached']['css'] = array(
  path_to_theme() . '/new.css',
  '#weight' => 1000,
);
</code>
Comment: May I ask why would you do that?
Comment: As its a custom module it has some custom styles that I would like loaded after the base styles of my theme. Eg if my theme has a class of button and this module's style has a class of button--large, then I need button--large to be loaded after button.
Comment: it would be much easier to override base styles with ´! important´ I think
Comment: @Benone_ Nope, if you see `!important` in CSS, 99% of the time it means the developer wasn't quite sure what they were doing
Comment: @Clive with proper selector it would not do any unwanted changes
Comment: @Benone_ I'd encourage you to type "css important bad" into Google and read the top 5 or so pages that come up - they should clear up without question why it shouldn't be used, except for the purpose it was actually designed for in the first place (user style sheets)
Answer: You want something more like this:
<code>$content['#attached']['css'] = array(
  array(
    'data' => path_to_theme() . '/new.css',
    'type' => 'file',
    'weight' => 1000,
  ),
);
</code>


Query data from firebase with parameters - React

Question: I have a React application which is using firebase as the back-end.  Here is an snapshot of my data structure.
The numbers 1001, 1002, 1003 represent the ID of each entry.  I'm looking to query this structure and return only the nodes whose city attribute is "Tarzana".
I have been able to grab all of the nodes from firebase and then iterate through them to select and store the ones that match my filter criteria into an array.  However, I am almost certain there has to be a more efficient way as I shouldn't have to grab ALL of the data.
Could someone please point me in the direction of how to efficiently query my data with parameters.
Comment: You've included a picture of the JSON tree in your question. Please replace that with the actual JSON as text, which you can easily get by clicking the Export button in your Firebase database. Having the JSON as text makes it searchable, allows us to easily use it to test with your actual data and use it in our answer and in general is just a Good Thing to do.
Answer: Try this:
<code>Data.orderByChild("city").equalTo("Tarzana");
</code>
Comment: Also, I would index the city field if there's a lot of data there.
Comment: @MotiAzu What do you mean by index the city field?
Comment: You will need a database index on that field if you are going to query by it. Firebase has indexing available through the rules.


Mathematical induction for inequalities: $\frac1{n+1} + \frac1{n+2} + \cdots +\frac1{3n+1} > 1$

Question: Prove by induction: $$\frac1{n+1} + \frac1{n+2} + \cdots +\frac1{3n+1} > 1$$
adding $1/(3m+4)$ as the next $m+1$ value proves pretty fruitless. Can I make some simplifications in the inequality that because the $m$ step is true by the inductive hypothesis, the 1 is already less than all those values?
Comment: You are adding three instead of one terms when you proceeding to $(m+1)$.
Comment: Please learn a bit of LaTeX and use it. And when you do write inline fractions like $1/(n+1)$, don't omit the parentheses. It will confuse your readers no end. I fixed it for you this time around.
Comment: I agree with @Regret's comment--the general term is not at all obvious. My first inclination was to express the LHS using $\sum$-notation, but I can't do this without knowing how the terms look in general.
Comment: Possible duplicate of [Prove that $1<\frac{1}{n+1}+\frac{1}{n+2}+...+\frac{1}{3n+1}$](https://math.stackexchange.com/questions/534117/prove-that-1-frac1n1-frac1n2-frac13n1)
Answer: Hint: When you increase $n$ by $1$, the sum loses one term and gains three. What is the sum of the three gained terms minus the lost one?
Comment: hmm. Are you referring to something like: 1/(3n+2)+1/(3n+3)+1/(3n+4)−1/(n+1)
Comment: That's it, indeed. The sum of the middle positive term and the one negative term is easily simplified, so start there. You can get fancy and use the AM-HM inequality, or you can get the needed inequality by hand.
Answer: More generally
(one of my favorite phrases),
let
$s_k(n)
=\sum\limits_{i=n+1}^{kn+1} \frac1{i}
$.
I will show that
$s_k(n+1)>s_k(n)$
for $k \ge 3$.
In particular,
for $n \ge 1$
$s_3(n)
\ge s_3(1)
=\frac1{2}+\frac1{3}+\frac1{4}
=\frac{6+4+3}{12}
=\frac{13}{12}
> 1
$.
$\begin{array}\\
s_k(n+1)-s_k(n)
&=\sum\limits_{i=n+2}^{kn+k+1} \frac1{i}-\sum\limits_{i=n+1}^{kn+1} \frac1{i}\\
&=\sum\limits_{i=n+2}^{kn+1} \frac1{i}+\sum\limits_{i=kn+2}^{kn+k+1} \frac1{i}
-\left(\frac1{n+1}+\sum\limits_{i=n+2}^{kn+1} \frac1{i}\right)\\
&=\sum\limits_{i=kn+2}^{kn+k+1} \frac1{i}-\frac1{n+1}\\
&=\sum\limits_{i=2}^{k+1} \frac1{kn+i}-\frac1{n+1}\\
&=\frac1{kn+2}+\frac1{kn+k+1}+\sum\limits_{i=3}^{k} \frac1{kn+i}-\frac1{n+1}\\
\end{array}
$
$\sum\limits_{i=3}^{k} \frac1{kn+i}
\ge \sum\limits_{i=3}^{k} \frac1{kn+k}
= \frac{k-2}{kn+k}
$.
If we can show that
$\frac1{kn+2}+\frac1{kn+k+1}
\ge \frac{2}{kn+k}
$,
then
$s_k(n+1)-s_k(n)
\ge \frac{2}{kn+k}+\frac{k-2}{kn+k}-\frac1{n+1}
= \frac{k}{kn+k}-\frac1{n+1}
= \frac{1}{n+1}-\frac1{n+1}
=0
$.
But
$\begin{array}\\
\frac1{kn+2}+\frac1{kn+k+1}-\frac{2}{kn+k}
&=\frac{kn+k+1+(kn+2)}{(kn+2)(kn+k+1)}-\frac{2}{kn+k}\\
&=\frac{2kn+k+3}{(kn+2)(kn+k+1)}-\frac{2}{kn+k}\\
&=\frac{(2kn+k+3)(kn+k)-2(kn+2)(kn+k+1)}{(kn+2)(kn+k+1)(kn+k)}\\
\end{array}
$
Looking at the numerator,
$\begin{array}\\
(2kn+k+3)(kn+k)-2(kn+2)(kn+k+1)
&=2k^2n^2+kn(k+3+2k)+k(k+3)\\
&-2(k^2n^2+kn(k+3)+2(k+1)\\
&=2k^2n^2+kn(3k+3)+k(k+3)\\
&-2k^2n^2-2kn(k+3)-4(k+1)\\
&=kn(3k+3)+k(k+3)\\
&-kn(2k+6)-4(k+1)\\
&=kn(k-3)+k(k+3)-4(k+1)\\
&=kn(k-3)+k^2-k-4\\
&> 0 \quad\text{for $k \ge 3$}
\end{array}
$
and we are done.
Answer: Hint: use that
$$\frac1{3n+2}+\frac1{3n+3}+\frac1{3n+4}-\frac1{n+1}=\cdots >0.$$


Is the empty set internal?

Question: Is the empty set internal or not?
And is there a proof (either way), or is it just a convention? If it's just a convention, why was that particular convention chosen?
Comment: Can you write a first order formula characterising membership in $\emptyset$?
Comment: $ Ø = \{ x : x \neq x \} $, so it's internal
Answer: The answer given in the comments can be simplified.  Every finite set is internal.  In particular, so is the empty set. Moreover the empty set is standard because it is already contained in the standard universe before a nonstandard enlargement is defined.  Recall that all standard things are internal but not vice versa.  For example, an infinitesimal number is an internal object but obviously it is not standard.

Is the empty set internal?


If $\{x_{2n}\}$ , $\{x_{2n+1}\}$ and $\{x_{3n}\}$ converge, does $\{x_n\}$ converge?

Question:
If $\{x_{2n}\}$ , $\{x_{2n+1}\}$ and $\{x_{3n}\}$ converge, does $\{x_n\}$ converge?

Are these sufficient conditions for convergence in any metric space? Thanks.
Comment: Yes. $ $ $ $ $ $
Answer: Yes.

Suppose
\begin{align*}
&x_{2n}\;\text{converges to}\;a\\[4pt]
&x_{2n+1}\;\text{converges to}\;b\\[4pt]
&x_{3n}\;\text{converges to}\;c\\[4pt]
\end{align*}

Since $(x_{2n})$ and $(x_{3n})$ share a common infinite subsequence, it follows that $a=c$.

Similarly, since $(x_{2n+1})$ and $(x_{3n})$ share a common infinite subsequence, it follows that $b=c$.

Thus, $a = b = c$.

Since $x_{2n}$ converges to $c$, and $x_{2n+1}$ converges to $c$, it follows that $x_n$ converges to $c$.
Comment: More details needed for the last sentence in your proof though. I think you should write out the details of this critical part.
Comment: I regard my answer as a sufficient outline. At the level of the OP, he should be able to supply those details. If not, he can ask, and I'll supply them.
Answer: Let $a=\lim x_{2n}, b=\lim x_{2n+1}$ and $c=\lim x_{3n}$.
$(x_{6n})$ is a subsequence of $(x_{2n})$ and of $(x_{3n})$. Hence: $a=c$
$(x_{6n+3})$ is a subsequence of $(x_{2n+1})$ and of $(x_{3n})$. Hence: $b=c$.
Its now your turn to show that $(x_n)$ has the limit $a$
Answer: Yep. Let
$$\lim_{n\to\infty} x_{2n} = a_1,$$
$$\lim_{n\to\infty} x_{2n+1} = a_2,$$
$$\lim_{n\to\infty} x_{3n} = a_3$$
Now, $\{x_{6n}\}$ is a subsequence of both $\{x_{2n}\}$ and $\{x_{3n}\}$. So $a_1=a_3$. And $\{x_{6n+3}\}$ is a subsequence of both $\{x_{2n+1}\}$ and $\{x_{3n}\}$. So $a_2=a_3=a_1.$ Let $a=a_1=a_2=a_3.$ Then
$$\lim_{n\to\infty} x_{n} = a.$$
because
$$\lim_{n\to\infty} x_{2n} = a = \lim_{n\to\infty} x_{2n+1}$$
and as $n \in \mathbb{N}$ is either even or odd, $n=2k$ or $n=2k+1$ so
$$\lim_{n\to\infty} x_{n} =
\left\{\begin{array}{lr}
\lim_{k\to\infty} x_{2k} & \text{n even}\\
\lim_{k\to\infty} x_{2k+1} & \text{n odd} \end{array}\right\} = a.$$


Centos 6.10 Swap File Issue Wrong size

Question: I have Centos 6.10 Server with initial swap of 3.81 GB working ok no issue.
I noticed wrong swap today amount of 4kb. I tried removing the partition and recreate entry on fstab and remount but no avail. Also tried creating swapfile 8GB using fallocate -l 8G /home/swapfile and added on fstab swapon -a. Still doesn't work.
Below are some info on system:

mkswap command
Comment: Have you run `mkswap /home/swapfile` after file creating?
Comment: yes I did i will add another screen cap to be sure
Answer: You should create swap file system and enable swap with swapon. Swap could be created by command mkswap.
mkswap /home/swapfile for file and mkswap /dev/sdX for partition, see this answer.
Comment: yes I did i will add another screen cap to be sure
Comment: still same issue

Centos 6.10 Swap File Issue Wrong size


Stata Margins tool

Question: How does Stata create their margins dy/dx output? I would like to recreate some Stata output in SAS. The results of a logistic regression give a coefficient of 1.4921 for my dummy variable, and an odds ratio of 4.447 (or the exponentiation of 1.4921). Stata has a margins dy/dx tool that gives a value of 0.1309 for this variable. I interpret this to mean there is a 13.9% difference between the probability of each outcome for this 0 1 indicator.
How can I generate this 13.9% difference outside of Stata?
Comment: I might be able to have a go at answering if you put your whole output here.
Comment: I'd recommend checking Stata manuals. They are freely available online as pdf files.
Answer: For a continuous variable, the marginal effect of $x_k$ in a logit is
$$\Lambda(X'\beta)\cdot \left[1-\Lambda(X'\beta)\right]\cdot\beta_k,$$ where
$$\Lambda(z)=\frac{\exp{z}}{1+\exp{z}}.$$
By default, Stata actually calculates the average of this over the estimation sample, but I will use the mean value of x in what follows (marginal effect at the mean rather than average marginal effect) to get the point across:
<code>. sysuse auto, clear
(1978 Automobile Data)

. logit foreign mpg

Iteration 0:   log likelihood =  -45.03321
Iteration 1:   log likelihood = -39.380959
Iteration 2:   log likelihood = -39.288802
Iteration 3:   log likelihood =  -39.28864
Iteration 4:   log likelihood =  -39.28864

Logistic regression                               Number of obs   =         74
                                                  LR chi2(1)      =      11.49
                                                  Prob > chi2     =     0.0007
Log likelihood =  -39.28864                       Pseudo R2       =     0.1276

------------------------------------------------------------------------------
     foreign |      Coef.   Std. Err.      z    P>|z|     [95% Conf. Interval]
-------------+----------------------------------------------------------------
         mpg |   .1597621   .0525876     3.04   0.002     .0566922     .262832
       _cons |  -4.378866   1.211295    -3.62   0.000    -6.752961   -2.004771
------------------------------------------------------------------------------

. di _b[mpg] * exp(_b[mpg]*21.2973+_b[_cons])/(1+exp(_b[mpg]*21.2973+_b[_cons]))* (1-exp(_b[mpg]*21.2973+_b[_cons])/(1+exp(_b[mpg]*21.2973+_b[_cons])))
.03175262

. margins, dydx(*) atmean

Conditional marginal effects                      Number of obs   =         74
Model VCE    : OIM

Expression   : Pr(foreign), predict()
dy/dx w.r.t. : mpg
at           : mpg             =     21.2973 (mean)

------------------------------------------------------------------------------
             |            Delta-method
             |      dy/dx   Std. Err.      z    P>|z|     [95% Conf. Interval]
-------------+----------------------------------------------------------------
         mpg |   .0317526   .0103945     3.05   0.002     .0113798    .0521254
------------------------------------------------------------------------------
</code>
For dummy variables, Stata uses a finite difference method (average of predicted probabilities with $x_i$ set to 1 minus predicted probability with $x_i$ set to zero).
Standard errors are a bit more complicated.
Comment: Useful answer, although I'm not sure about the clarity of the link between the opening equations and the formula actually used in the `di` part of the Stata code. It took me 10 good minutes to decompose the code to reconstitute the equation :)
Comment: @Fr. What was confusing about it? Is it the means? I suppose the index function coefficient in the code comes first rather than last, but that is the only difference. Please feel free to propose an edit that you think works better.
Comment: I think one way to make the code easier to parse is (1) to define $z$: `sca de z = _b[mpg] * mu_x + _b[_cons]`, (2) then $\lambda_z$: `sca de lambda_z = exp(z) / (1 + exp(z))`, and finally (3) `di lambda_z * (1 - lambda_z) * _b[mpg]` to display the estimated effect.

Stata Margins tool


Dimensionality of datasets in multiple regression

Question: As an example, let's say that a linear regression is performed of the form
$$Y = \beta_0 + \beta_1X_1 + \beta_2X_2 + \cdots + \beta_nX_n +\varepsilon$$
where $Y$ is a vector of $10,000$ measurements of peak acceleration of different car models, and the regressors correspond to different technical features of the cars.
From a linear algebra standpoint $Y$ lives in $\mathbb R^{10000}$, and the coefficients are found by minimizing the sum of the square distances of this vector on a hyperplane.
Now, from the point of view of dimension being the number of linearly independent vectors that span a space, this vector $Y$ is just $1$ dimension.
If it is truly $1$-dimension of a $\mathbb R^{10000}$ ambient space, the Euclidean projection on the hyperplane that underpins the process of finding the coefficients does not have any dimensionality issues (collinearity between the regressors being a separate topic). Otherwise, $L^2$ norms in high dimensions do pose problems.

So is $Y$ (the vector of $10,000$ observations) $1$-mimensional or high dimensional?
Answer: Consider the function $$f(X_1,X_2) = \beta_0 + \beta_1 X_1 +\beta_2 X_2. $$ This is a plane in 3 dimensions no matter how many times you evaluate the function. Thus, your problem "lives" in a $2$-dimensional space.
As for using the $L^2$ norm, you are correct. This link might be useful in that regard Link
Comment: This helps a lot, and I did upvote your answer, but I wonder if you can elaborate on why the fact that **in the process of calculating the coefficients** and optimization of distances is made in high dimensions and with Euclidean distances does not pose a problem (as in the link in your answer). After all, in your answer you **already have the equation as a given. You didn't have to calculate it**.
Answer: The issue of dimensionality is the context of regression analysis is the ratio between $n$, number of observations, and $p$, number of estimated parameters. As closer $n$ to $p$, the less reliable your estimated model is. Assume that your model is
$$
y = \beta_0 + \sum_{j=1}^px_j\beta_j + \epsilon,
$$
hence in order to find the OLS estimators of $\beta = (\beta_0,...,\beta_p)$ you project the vector $y$ on the affine space spanned by $(1,x_1,...,x_p)$, hence it is a $p$ dimensional space. The number of observations, $n$, is not count as dimension. If you have a continuous stochastic process, then you can sample from it infinitely many times, i.e., $n\to \infty$, that is usually a good feature because you can safely use asymptotic results. Notably, in such a case, there is another problem of artificially low p.values, but this is unrelated to the dimension of the model or the embedded space.


Função em C que apaga determinada string

Question: Preciso criar uma função que apaga em s1 a primeira ocorrência de s2.
char *StrlDelStr(char *s1,char *s2)

Exemplo:
char *s = "O rato roeu a rolha da garrafa";
StrlDelStr(s, "xy"); -> "O rato roeu a rolha da garrafa"
StrlDelStr(s, "ra"); -> "O to roeu a rolha da garrafa"

Meu código está assim:
char *StrlDelStr(char *s1,char *s2)
{
    int i, j;
    for(i = 0, j = 0; i < strlen(s1); i++)
    {
        for(j = 0; j < strlen(s1); j++)
        {
            if(s1[i] == s2[j])
                s1[i] = ' ';
        }
    }
    return s1;
}

int main()
{
    char palavras[100] = "Hello World";
    char palavra2[100] = "lo";

    StrlDelStr(palavras, palavra2);
    printf("\n%s\n", palavras);
    return 0;
}

Está exibindo "He    W r d". Preciso de uma função em que, em vez de substituir por ' ' todas as ocorrências do caracter/string, apenas apague
onde ocorre a string específica (s2).
Comment: Sua pesquisa pela segunda string está errada. Além disso após localizar a segunda string na primeira você não tem que substituir por espaço e sim mover para a esquerda tantas posições quanto forem o total de caracteres da string fornecida no segundo parâmetro.
Answer: Apagar, não tem como. Não tem como fazer as variáveis nas posições que você quer, por exemplo na posição 6,7,8 simplesmente deixarem de existir, o que dá para fazer é identificar onde ocorre s2 (neste caso, somente a primeira vez), e copiar s1 até o último caractere antes da primeira ocorrência de s2, depois continuar copiando de s1 a partir do primeiro caractere que segue após s2 que está contida em s1 até o final.
#include<stdio.h>
#include<string.h>
#define TAMANHO 100
char *StrlDelStr(char *s1,char *s2)
{
  char *pt_pos = strstr(s1, s2);
  if(pt_pos == NULL) printf("s1 nao contem s2.\n");
  else
  {
    char aux1[TAMANHO], aux2[TAMANHO];
    *pt_pos=0;
    strcpy(aux1, s1); // a cópia para em pt_pos
    strcpy(aux2, pt_pos+(int)strlen(s2)); // a cópia para no antigo final de s1
    //printf("%s\n%s", aux1,aux2); // para testes
    strcat(aux1, aux2);
    strcpy(s1, aux1);
  }
  return s1;
}

int main(void)
{
    char palavras[TAMANHO] = "O rato roeu a rolha da garrafa";
    char palavra2[TAMANHO] = "ra";

    StrlDelStr(palavras, palavra2);
    printf("\n%s\n", palavras);
    return 0;
}

Veja funcionando no repl.it.
Answer: A resposta aceita tem algo que funciona, mas não é eficiente tendo diversos laços escondidos que tornam a execução bem lenta, assim faz o mesmo de forma eficiente (isto é um mini parser):
#include<stdio.h>

void StrlDel(char *s1, char *s2) {
    int i = 0;
    int notFound = 1;
    while (s1[i]) {
        int j;
        for (j = 0; s2[j] && s2[j] == s1[i + j]; j++);
        if (!s2[j] && notFound) {
            int k;
            for (k = i; s1[k + j]; k++) s1[k] = s1[k + j];
            s1[k] = 0;
            notFound = 0;
        } else i++;
    }
}

int main(void) {
    char palavras[] = "O rato roeu a rolha da garrafa";
    StrlDel(palavras, "ra");
    printf("\n%s\n", palavras);
}

Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.


Series versus dataframe

Question: I've just begun learning some pandas, so apologies if I'm not the best at explaining my question.
# creating a range of times starting from '1/1/1' going forward hourly for 100 units.
longTimeRange = pd.date_range('1/1/1', periods=31, freq='H')
# Creating a random number for each time unit as a Series
aTimeSeries = pd.Series(np.random.randn(len(longTimeRange)), index=longTimeRange)

aTimeSeries.head()

The above code creates a series object shown below.
2001-01-01 00:00:00   -0.657026
2001-01-01 01:00:00   -1.244964
2001-01-01 02:00:00   -0.016981
2001-01-01 03:00:00    1.817097
2001-01-01 04:00:00   -0.419140
Freq: H, Length: 31, dtype: float64

My question is that the output has TWO columns. Why is it still considered a series?
Why is this not a dataframe?
If series can have more than one column, then how is that differentiated from a dataframe?
Are series and dataframes just container of holding the data in a way that it can be specifically accessed?
Comment: It's the index. Check `aTimeSeries.index`.
Comment: Then a N columns DataFrame would have N+1 "columns" in the output ;)
Comment: [refer here](https://www.tutorialspoint.com/pandas-series-vs-single-column-dataframe#:~:text=As%20noted%20in%20the%20table,to%20have%20an%20index%20defined)
Comment: Thank you so much! Love that explanation!
Comment: I get it now that I was confusing index with column, but that's not the case. I'm going to keep probing and check all my series to convince myself, haha!
Answer: Yes, it's unambiguously a Series.
The first "column" is the Index (you could even have more levels with a MultiIndex).
What matters is the number of dimensions:
aTimeSeries.ndim
# 1

If you convert to_frame, the number of dimensions is now 2:
df = aTimeSeries.to_frame(name='col')

df.ndim
# 2

You will immediately notice the column name(s) as header:
print(df)

                          col   # column name(s)
2001-01-01 00:00:00 -0.943661
2001-01-01 01:00:00 -0.959935
2001-01-01 02:00:00 -0.211081
...
2001-01-02 04:00:00  0.245525
2001-01-02 05:00:00 -0.285114
2001-01-02 06:00:00 -0.105460

For a Series, the name (if existing) is at the bottom:
print(aTimeSeries)
                                # no header
2001-01-01 00:00:00    0.308899
2001-01-01 01:00:00   -0.475546
2001-01-01 02:00:00    0.240019
...
2001-01-02 04:00:00    0.254641
2001-01-02 05:00:00    0.845304
2001-01-02 06:00:00   -1.636668
Freq: H, Name: col, dtype: float64  # here

Comment: That's so interesting! Thanks for that tip! Makes complete sense!
Answer: Your question is valid and shows that you're thinking critically about the structure of data in Pandas. See if the following explanations are useful to you.
Series:
A Pandas Series is a one-dimensional labeled array that can hold data of any type (integer, string, float, etc.). It has an index that provides labels for the data points, allowing for easy and efficient data access and manipulation.
In your example, when you create aTimeSeries, you are indeed creating a Series. The data you generated (random numbers) is associated with a datetime index. Each row of your output represents a single data point (number) associated with a specific timestamp. The two columns you see in the output are the index (timestamps) and the data values (random numbers).
A Series can be thought of as a single column of data, where each element is associated with a label (index). In your case, the index is the datetime, and the data is the random numbers.
DataFrames:
A DataFrame, on the other hand, is a two-dimensional labeled data structure with columns that can be of different types. It's similar to a table in a relational database or an Excel spreadsheet. Each column in a DataFrame is a Series. A DataFrame allows you to store and manipulate data in a structured and tabular format.
The distinction between Series and DataFrames is essentially about the dimensionality of the data:
Series: One-dimensional labeled array (single column of data).
DataFrame: Two-dimensional labeled data structure (multiple columns, each of which is a Series).
In your example, if you were to create a DataFrame, you could do so like this:
# Creating a DataFrame with a single column
df = pd.DataFrame({'data': aTimeSeries})

This would create a DataFrame named df with one column named data, and each row would represent a timestamp along with the associated random number.
Comment: Thank you so much for saying that! And your answer helped so much! I understand now that I was confusing index with a column. It's still one dimensional data accessed through specific indices, appreciate the clarity here, thank you!

Series versus dataframe


How can I make a textarea with character limit highlighting like Twitter?

Question: Twitter's submit tweet textbox highlights the characters that are over the character limit:

As you can see, the characters that overrun the character limit are highlighted in red. How can I achieve something like this?
Comment: Can you show your HTML and what you've tried?
Comment: $(document).ready(function() {

  $("#post-infinity").keyup(function() {

    var maxLength = 200;
    var length = $(this).val().length;

    $("#message-count").text(maxLength - length);

    if (length > maxLength) {

      $("#message-count").css({
        "color": "#ccc"
      });

      $("#button-send").attr({
        "disabled": "disabled"
      });

    } else {

      $("#message-count").css({
        "color": "#6B6B6B"
      });

      $("#button-send").removeAttr("disabled");

    }

  });

});

So red highlight ? I do not know how.
Comment: How can we get in the red?
Comment: No, please show the code in the question.
Answer: You'll find the necessary solution and required code here:
How to insert  tag when exceeding 140 limit i.e. going negative?
...and here:
REGEX - Highlight part over 19 chars
Your question appears to be duplicitous.
Note: I didn't have the option to post the above links as a comment (i.e. privilege contingent on reputation).
Here's the code as per Simon Kuang's recommendation (see comments):
HTML:
<!DOCTYPE html>

<meta charset=utf-8 />
<title>JS Bin</title>

Your text here

edit me

Stuff over 19 characters

Sample output

CSS:
.highlight {
 color:red;
}

JavaScript:
$(document).ready(function() {
  $('#myDiv').keyup(function() {
    var content = $('#myDiv').html();
    var extra = content.match(/.{19}(.*)/)[1];

    $('#extra').html(extra);

    var newContent = content.replace(extra, "" + extra + "");
    $('#sample').html(newContent);
  });
});

Comment: You'll want to reproduce that material in your answer.
Comment: So, duplicate of http://stackoverflow.com/questions/16950016/how-to-insert-em-tag-when-exceeding-140-limit-i-e-going-negative
Comment: Don't forget to place your JavaScript code within the necessary script tags: ``
Comment: @Popnoodles - Effectively, yes though it's noteworthy to mention that the code is derived from the second link and that the CSS has been nominally adapted.
Comment: I made an example with the code from this answer: https://codepen.io/felipealbuquerq/pen/QWBOYGM
Answer: Here is the example, show alert when the  limit is reached  and thereafter highlight all the characters entered.

$(document).ready(function() {
  var input = $('#text_text');
  var warning = $('#warning');
  var char_limit = 30;
  input.on('keyup', function() {
    var val = $(this).val();
    if (val.length > parseInt(char_limit)) {
      alert("limit reached");
      warning.html('hello').css('display', 'block');
      l = val.length
      var input = document.getElementById("text_text");
      input.setSelectionRange(char_limit, l);
      input.focus();
    } else {
      warning.css('display', 'none');
    }
  });

});
#warning {
  display: none;
}

  <textarea name="msg" cols="50" rows="5" id="text_text"></textarea>

Answer: Try this (pattern)
html
<data></data>

<textarea maxlength="20" placeholder="20 character limit"></textarea>

js
$(function () {
    $(document).on("keyup", "textarea", function (e) {
        if ($(e.target).val().length >= 20) {
            $("data").text($(e.target).attr("placeholder"))
            .fadeIn(1000).fadeOut(9000);
        };
    });
});

jsfiddle http://jsfiddle.net/guest271314/8RScd/


nginx and Mysql Server Load limits (depend on Server config)

Question: my server config is
Technology: Ivy Bridge
Processor:  Intel Xeon E3 1245v2
            Intel Smart Cache: 8MB
Cores:  4
Threads:    8
Frequency:  3.4GHz+
Turbo Boost:    3.8GHz
Virtualization: yes
RAM :        32 GB DDR3
Hard drive: Intel SSD 2 x 120GB
RAID:           SOFT - 0/1
                (RAID-1 by default)
NIC:    GigaEthernet
Bandwidth: 200 Mbps guaranteed
Version:    Parallels Plesk Panel v11.5.30_build115130819.13 os_CentOS 6
OS: CentOS 6.4 (Final)
Server Soft: Apache \ PHP

Now i need to know what i set (Set Max Value which is my server take well) for
Nginx
worker_connections (what i set here);
worker_processes (what i set here);

MySql
set-variable=max_connections= (what i set here)
set-variable=max_user_connections= (what i set here)

Any other thanks for mysql,Nginx and any other help me to gate more load pleas tell me
i really need help pleas help
Thanks
Answer: In the end all of these values have to be set according to what you are going to run on your Nginx and MySQL servers, so there is no silver bullet formula to answer your question and be correct in every possible use case. Still I tried to pull some data together that can lead you to the answer for your questions:
Nginx
Regarding Nginx worker_processes the documentation says this:
If Nginx is doing CPU-intensive work such as SSL or gzipping and you have 2 or
more CPUs/cores, then you may set worker_processes to be equal to the number
of CPUs or cores.

If you are serving a lot of static files and the total size of the files is
bigger than the available memory, then you may increase worker_processes to
fully utilize disk bandwidth.

Regarding worker_connections, consider this formula that I got from here:
max_clients = worker_processes * worker_connections

So after you know your worker_processes value, you can calculate the worker_connections based on the maximum number of concurrent clients that you might need to serve.
MySQL
Regarding the max_connections value on MySQL you should try to figure out how many connections you will need on your MySQL concurrently at peak time. For example if your application runs on PHP and you have 32 PHP worker processes, and PHP is the only application accessing MySQL, it's probably safe to assume that you won't need more than 32 connections on MySQL. You also don't want to set this value too high, because a whole bunch of buffers has to be allocated for each connection, so if the max_connections value is too high you are taking the risk that something kills your MySQL by creating connections to it until it runs out of memory.
max_user_connections is basically the same thing, just on a per MySQL user base, instead of a global value for the whole MySQL server.
In case you haven't looked at it already, here are the relevant docs:
max_connections / max_user_connections


Extra template name suggestions for main-menus based on regions

Question: In the first look, the process of solving this problem maybe seems very easy, but this problem makes me really confused.
Imagine that I want to have two main-menu one in the header (primary menu/ top bar) and another in the footer region of my site with different style and template.
By default, there is no file suggestion that differentiates which twig file to be used for a menu based on the region.
That's why I follow below article to add block region as the id of main-menu and make block's template name suggestion unique and dedicated for next customization.
Drupal 8: Theming menus by KristianKaa
function THEMENAME_preprocess_block(&$variables) {
  $variables['content']['#attributes']['block'] = $variables['attributes']['id'];
}

function THEMENAME_theme_suggestions_menu_alter(array &$suggestions, array $variables) {
  if (isset($variables['attributes']['block'])) {
    $hook = str_replace(array('block-', '-'), array('', '_'), $variables['attributes']['block']);
    $suggestions[] = $variables['theme_hook_original'] . '__' . $hook;
  }
}

But the following HTML comments, are the theme hook suggestions added by the debug function, for the Main navigation blocks after adding those codes.
Header section:

Footer section:

As you can see from the suggestions, there is nothing to distinguish the two menus from one another based on regions.
I think this template name suggestion hasn't any efficiency in this case because what's that suggested isn't semantic.
So my main question is: How can I add extra filename suggestions for main-menu based on regions not block Id? Or
How to get the current region inside the Hook_theme_suggestions_menu_alter, to add my own suggestion?
I read below posts also but all of those add block Id as twig suggestions for menus:
Additional twig suggestions for menus
How to create a custom Twig Template for Menu Block
How to make a theme hook suggestion for menu according to the region?
Answer: You should install the Menu Block module, which will let you dictate the name of the instance of the menu for easy theming. It is then up to you to give it a name.
TBH you don't want to get in the game of trying to manipulate region suggestions based on what it may or may not contain.
Answer: in Drupal 9.5 for some reason i was struggling to pass variable from the block preprocess function:
My solution was by $GLOBALS so in Preprocess block I'm getting the region from configuration variable
/**
 * Implements hook_preprocess_block().
 *
 */
function THEMENAME_preprocess_block(array $variables)
{

  if (isset($variables['elements']['#id'])) {

    // Access the block configuration.
    $region = $variables['configuration']['region'];

    if (!empty($region)) {
      $variables['content']['#attributes']['region'] = $region;
      $GLOBALS['my-region'] = $region;

    }
  }
}

Than getting this in hook_theme_suggestions_menu_alter()
/**
 * Implements hook_theme_suggestions_HOOK_alter().
 */
function THEMENAME_theme_suggestions_menu_alter(array &$suggestions, array $variables)
{

  //dpm($variables);
  $menu_id = $variables['attributes']['id'];
  $region = $GLOBALS['my-region'];
  if (isset($menu_id)) {
    $suggestions[] = 'menu__' . $menu_id;
  }
  if (isset($region)) {
    $suggestions[] = 'menu__' . $region;
  }
}

so output i have :

I Hope it will help someone :)
Comment: This is related to Drupal 9.5 latest version in THEMENAME.theme file


What are the On and Off beats?

Question: I'm very new to music theory and I've seen this taught two ways:

The On beat is on every 1 and 3 beat while the Off beat is every 2 and 4 (in 4/4 time)
The On beat is on every Strong/Secondary Strong and Weak beats in the bar (S w s w in 4/4) while the Off beat is any note in between these.

I personally think the first one is right while I think the second is actually talking about the Up and Down beats but it's kinda unclear to me.
Comment: @ToddWilcox people do use the terms like that - https://en.wikipedia.org/wiki/Beat_(music)#On-beat_and_off-beat. But then my experience is that different people do tend to use these kinds of terms in various different ways. Incidentally the same article states that '1' is the downbeat and '4' the upbeat, which follows the most common 4/4 conducting pattern...
Comment: 1 and 3 are *downbeats*, 2 and 4 are *upbeats*. Being "on the beat" means playing at the same time as a beat. Playing "off the beat" means playing in between two beats. I'm not familiar with the terms "on beat" or "off beat" on reference to specific beats in a measure.
Answer: On and off beats really exist on a spectrum, and determining whether beats 2 and 4 are on or off is really a question of tempo.
If the music is fast enough, we can start to feel the 4/4 time in (as we say) a large 2, meaning that 1234 starts to sound like 1&2&. In such cases, 2 and 4 are definitely heard as off the beat, with 1 and 3 being on.
But if the music is slow enough, 2 and 4 are so far away from their surrounding beats that we really perceive them as being beats in their own right; as such, we then view 1234 as all being on the beat, and it's the material in between those beats (the &s, for instance) that are viewed as off the beat.
This is one reason why using the strong/weak terminology can be more helpful: beat 2 will (basically) always be viewed as weaker than beat 1, but sometimes beat 2 is on the beat and sometimes it's off. In other words, the on/off dichotomy is often too black and white, but the strong/weak spectrum is much more malleable.
Comment: In my opinion, there is no aural distinction between a fast-enough 4/4 and a half-that-tempo 2/4. (Some may disagree.) There may be some historical distinctions, but they're minimal.
Comment: So would it be valid to say 4/4 in a fast enough tempo would be no different from 2/4?
Comment: In a sort of indirect way, I feel this answered my question. I understand that you can't get too bogged down by the "rules" in music. However, it's nice to know the guide lines. Thanks (^-^)b
Comment: @Brandon I'm glad to help, but other answers may answer you more directly; feel free to save the accepted arrow until you see some other answers if you like. Welcome to [music.se]!
Answer: It seems that these definitions can change depending on the school of thought that the speaker learned from and from regional variations.
For example (in my experience) people in the classical world say:

"downbeat" to mean beats 1 and 3,
"upbeat" to mean beats 2 and 4, and
"off beat" to mean the beats directly between all four beats

But in jazz they would say:

"downbeat" to mean beats 1 and 3,
"backbeat" to mean beats 2 and 4, and
"and beat" to mean the beats directly between all four beats
Answer: I think it probably depends somewhat on the exact rhythmic feel of the song. The system of time signatures in music doesn't fully specify the relative strength of each beat, and 3 songs each with a 4/4 time signature might have very different feels to them. Compare a slow rock ballad to a house or techno piece, and a reggae song - all typically 4/4, but very different strength patterns to the beats.

The On beat is on every 1 and 3 beat while the Off beat is every 2 and 4 (in 4/4 time)

I would say this would be 'correct' (i.e. an appropriate and non-confusing thing to say) for a style of music that has a strong 1 and 3 - think of a classic rock beat, for example.

The On beat is on every Strong/Secondary Strong and Weak beats in the bar (S w s w in 4/4) while the Off beat is any note in between these.

I think that idea - of having 4 'on' beats in a 4/4 bar - would be correct in a '4 to the floor' type of rhythm - think of a house or techno piece (though in this context it might not be correct to say that the pattern is 'S w s w' - it might be more 'S s s s').
I agree with Richard's answer too, so I hope I've not contradicted it!
Comment: So in the end, it's up to me where the on and off beat end up aka where I put the accents
Comment: @Brandon when it's just a question of you alone with your own thoughts, yep, pretty much (though 'accents' might mean something slightly different to 'on' and 'off' beat)! When you're talking to others, you need to just look out for how they are understanding the words - unfortunately, 'informal' musical terms like these are often used differently by different people - which I guess is why you asked the question in the first place..!
Comment: It's confusing xD. My listening background may be the thing colouring my opinion on where the beat lies.
Comment: @Brandon that's a common experience in music - theory that fits one genre perfectly might suddenly not be so useful for another genre.
Answer: Don't confuse 'The on beat/off beat'  with 'on/off the beat'.    The first refers to the strong and weak beats in each bar.  In 4/4 one and three are 'on beats', two and four are 'off beats'  The second refers to notes which aren't positioned on ANY of the beats.

Paradoxically, you're most likely to hear 'off beats' mentioned in reference to swing and rock styles where the 'off beat' is played louder than the 'on beat'.
Here's an audience which insists on clapping the 'on beat' being skilfully manoeuvered into clapping the 'off beat' instead.
Comment: Harry very cleverly plays a bar of 1/4 - I think! What is it? +1 for the clip at least.
Comment: Wow! +1 for finding and spotting that. Amazing skill on the part of Harry. For those who haven't spotted it, the change happens just after 0:39
Comment: That is a great clip ;)

What are the On and Off beats?


Suggestions on how to implement this layout on android

Question: Here is what I want:
My layout has 3 main layouts, all having TextViews and ImageViews in them.

The Yellow layout remains at same position all the time
the green layout will slowly start to move up/down as the user scrolls the list. When it reaches the top of the screen, it will remain sticky, allowing the list to scroll. When scrolling back, it will scroll down to original position and then stop.
the red yellow is a list view.
when the list is scrolled up, the user can still tap on buttons on yellow layout

How should I implement this ? First thing that comes to my mind is FrameLayout in order to allow the layouts to overlap. For the green layout, I am thinking that maybe something like https://github.com/emilsjolander/StickyListHeaders would work. But how about list scroll ?
Comment: Maybe this helps: If this is working: http://sdchang.com/wordpress/2014/03/10/how-to-pin-a-sticky-header-to-the-top-of-androids-listview/ you could create a linearview for the first layer and then put the PinnedSectionListView in a fragment above it
Answer: <code><?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <Button
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:layout_gravity="bottom"/>

    <ListView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom"
        android:layout_marginTop="100dp" />

</FrameLayout>
</code>
Programatically, use the size of your list and the item height to set the bottom margin of the Button.
Comment: Note the "marginTop" of the ListView is the height of your button.
Comment: I tried to play with detecting scroll direction of the List and increase/decrease marginTop based on scroll offset. Long story short, this kind of goes when the user scrolls up, HOWEVER, when scrolling back, the List does not fire onScroll because the first item is already visible... so I can't move down the list to original position.
Answer: In the end I went with an implementation inspired by http://flavienlaurent.com/blog/2013/11/20/making-your-action-bar-not-boring/ and it does work for my purpose


how to convert wchar_t to string in swift

Question: I'd like to get a wchar_t array from C library, and convert it to swift data structure, my code is here:
    func getResults(recognizer: UnsafeMutablePointer<Void>, stroke: UnsafeMutablePointer<Int32>, touchState: Int32) -> [String] {
    var bufLen : Int32
    var buf = UnsafeMutablePointer<wchar_t>.alloc(Int(bufLen))
    getRecognition(recognizer, stroke, touchState, buf, bufLen)

    var results = String.fromCString(buf)! //this line has an error, cause the buf is wchar_t*, not char*
}

how could I convert buf to swift data structure?
I know if buf is UnsafeMutablePointer<Int8>.alloc(Int(bufLen)), we can use String.fromCString(buf)! to convert it.
If I println(buf[0]), it's print an integer 67, which is the ascii value of 'C', how can I println(buf[0]) as 'C' instead of 0?
Thanks!
Answer: wchar_t is an alias for Int32 and contains a UTF-32 code point
in host byte order (which is little-endian on all current iOS and OS X
platforms).
Therefore you can convert the buffer to a Swift string as follows:
if let str = NSString(bytes: UnsafePointer(buf),
    length: wcslen(buf) * sizeof(wchar_t),
    encoding: NSUTF32LittleEndianStringEncoding) as? String {
        println(str)
} else {
    // encoding problem ...
}

(This assumes that the wchar_t string from the C library function
is zero-terminated.)
Comment: You certainly know your `wchar_t`s
Answer: use:
var char = Character(UnicodeScalar(Int(buf[idx])))

can interpret wchar_t to Character