Ruby Minesweeper

Question: I am trying to get this Ruby game I made to loop after the first round, and end with a "game over" if the player hits a mine. I have it to where it will build the board, which is a pre-built layout in a .txt file, and it will loop, but the game doesn't end. Here is my code
def load_board
    mine_field = []
    File.open("mines.txt", 'r') do |f|
    f.gets
    f.each_line do |line|
      mine_field.push line.chomp.split('')
     end
   end

    return mine_field
end

def create_hint_board(board)
    hint = Array.new

  for i in (0..board.size-1)
    hint[i] = []
    for j in (0..board[i].size-1)
      hint
      if board[i][j] == '*'
        hint[i].push '*'
      else
        bombs = 0
        for x in (-1..1)
          for y in (-1..1)
            if i-x >= 0 &&
              i-x < board.size &&
              j-y >= 0 &&
              j-y < board[i].size &&
              board [i-x][j-y] == '*'
              bombs += 1

            end
          end
        end
        hint[i][j] = bombs
      end
    end
  end
    return hint
end

def print_board (board)
    board.each do |row|
      p row
    end
end

def pp_board (board)
    puts Array.new(board[0].size*2+1, '-').join('')
    board.each do |row|
      puts "|" + row.join('|') + "|"
      puts Array.new(row.size*2+1, '-').join('')
    end
end

def copy_to_blank(board)
    blank = Array.new
    for i in 0..(board.size-1)
        blank << Array.new(board[i].size, '.')
    end
    blank
end

def play(board)
  puts "Welcome to Minesweeper!"
  puts
  puts
  puts
    hint = create_hint_board(board)
    game = copy_to_blank(board)
    puts "Starting"
    pp_board game
  #copy coords user puts in
  coords = gets.chomp.split(' ')
  i = coords[0].to_i
  j = coords[1].to_i
  game[i][j] =
    hint[i][j]

  pp_board game

    puts
    puts "Hint"
    pp_board  hint
end
end

#start the game
play load_board

Also, mines.txt looks like this...
4 3
*...
..*.
....

I would appreciate any feedback you can give.
Answer: This will get you looping:
# start while loop
while true
  coords = gets.chomp.split
  i = coords[0].to_i
  j = coords[1].to_i

  if hint[i][j] == "*"
    puts "you lose"
    break
  end

  game[i][j] = hint[i][j]

  pp_board game

  puts "\nHint"
  pp_board hint
end
#end while loop

Ctrl-c to bust out. You can also use break to exit the loop:
break if game_over?

Comment: Thanks for the info, i was doing that with 'loop{}' to just keep going. What I am hung up on is getting the game to end when the user lands on a "mine" or in my case, ' * '.

Ruby Minesweeper


Will adoption of SMuFL change Lilypond's text input?

Question: On a Lilypond page under the section, "Adopt the SMuFL music font encoding standard" section, there were plans to transition to the SMuFL format which may become part of a W3C standard.
Would this change anything about Lilypond input files used to produce Lilypond output files?
For example, here is some code I found on the website which produces various notes using a treble clef:
<code>{
  c' e' g' e'
}
</code>
Would code like this need to be changed, if SMuFL were to be adopted or would the adoption be a purely something that happens without end users noticing anything?
Comment: I don't know for certain, but I'm sure the intent is for end users to be unaware of any changes. LilyPond has years of history with their text-input syntax, and changing this input would only serve to frustrate and disenfranchise a pretty loyal user base.
Answer: Just for posterity's sake, I wanted to highlight the lilypond-user listserv response to OP's question when they asked it there. (You can find the thread here.)

SMuFL support would not change input syntax. It is about allowing the
use of many alternative music notation fonts that follow this
standard.
There was a blog post on Scores of Beauty explaining the project;
unfortunately that website is down at the moment. Meanwhile, you can
read
lilypond.org/google-summer-of-code.html


List users is null

Question: I am trying to get the friends list of the current logged-in user.
Here's how I am trying to get it:
private void fetchFriends(Session session) {
            Request.newMyFriendsRequest(session, new GraphUserListCallback() {

                @Override
                public void onCompleted(List<GraphUser> users, Response response) {
                    if (users != null) {
                        friendsList = new ArrayList<FriendInfoHolder>();
                        for (GraphUser u : users) {
                            friendsList.add(buildFriendInfoHolder(u));
                        }

                        Intent intent = new Intent(parentActivity,
                                FriendListActivity.class);
                        intent.putParcelableArrayListExtra("friends_list",
                                friendsList);
                        parentActivity.startActivity(intent);
                    } else {
                        Log.i("users_status", "null");
                    }
                }
            }).executeAsync();
}

The problem is the users list (List<GraphUser> users) is always null.
I previously set the read permission as follows:
authButton.setReadPermissions(Arrays.asList("read_friendlists"));

So, I am not sure what's wrong. Here is the full Code:
Solved: I didn't add the INTERNET permission in my manifest file.
package home.example.logintest;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import com.facebook.Request;
import com.facebook.Request.GraphUserListCallback;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.UiLifecycleHelper;
import com.facebook.model.GraphUser;
import com.facebook.widget.LoginButton;

import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.Signature;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.util.Base64;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;

public class MainActivity extends FragmentActivity {

    private MainFragement mainFragement;

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

        if (savedInstanceState == null) {
            // Add the fragment on initial activity setup
            mainFragement = new MainFragement();
            mainFragement.setParentActivity(this);

            getSupportFragmentManager().beginTransaction()
                    .add(android.R.id.content, mainFragement).commit();
        } else {
            // Or set the fragment from restored state info
            mainFragement = (MainFragement) getSupportFragmentManager()
                    .findFragmentById(android.R.id.content);
        }

        // try {
        // PackageInfo info = getPackageManager().getPackageInfo(
        // "home.example.logintest", PackageManager.GET_SIGNATURES);
        // for (Signature signature : info.signatures) {
        // MessageDigest md = MessageDigest.getInstance("SHA");
        // md.update(signature.toByteArray());
        // Log.d("KeyHash:",
        // Base64.encodeToString(md.digest(), Base64.DEFAULT));
        // }
        // } catch (NameNotFoundException e) {
        //
        // } catch (NoSuchAlgorithmException e) {
        //
        // }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    public static class MainFragement extends Fragment {
        private UiLifecycleHelper uiHelper;
        private ArrayList<FriendInfoHolder> friendsList;
        private Activity parentActivity;

        public Activity getParentActivity() {
            return parentActivity;
        }

        public void setParentActivity(Activity parentActivity) {
            this.parentActivity = parentActivity;
        }

        private Session.StatusCallback callback = new Session.StatusCallback() {
            @Override
            public void call(Session session, SessionState state,
                    Exception exception) {
                onSessionStateChange(session, state, exception);
            }
        };

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            View view = inflater.inflate(R.layout.activity_main, container,
                    false);

            LoginButton authButton = (LoginButton) view
                    .findViewById(R.id.authButton);
            authButton.setFragment(this);

            authButton.setReadPermissions(Arrays.asList("read_friendlists"));

            return view;
        }

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

            uiHelper = new UiLifecycleHelper(getActivity(), callback);
            uiHelper.onCreate(savedInstanceState);
        }

        @Override
        public void onResume() {
            super.onResume();

            Session session = Session.getActiveSession();
            if (session != null && (session.isOpened() || session.isClosed())) {
                onSessionStateChange(session, session.getState(), null);
            }

            uiHelper.onResume();
        }

        @Override
        public void onActivityResult(int requestCode, int resultCode,
                Intent data) {
            super.onActivityResult(requestCode, resultCode, data);
            uiHelper.onActivityResult(requestCode, resultCode, data);
        }

        @Override
        public void onPause() {
            super.onPause();
            uiHelper.onPause();
        }

        @Override
        public void onDestroy() {
            super.onDestroy();
            uiHelper.onDestroy();
        }

        @Override
        public void onSaveInstanceState(Bundle outState) {
            super.onSaveInstanceState(outState);
            uiHelper.onSaveInstanceState(outState);
        }

        private void onSessionStateChange(Session session, SessionState state,
                Exception exception) {
            if (state.isOpened()) {
                Log.i("msg", "Logged in...");

                fetchFriends(session);

            } else if (state.isClosed()) {
                Log.i("msg", "Logged out...");
            }
        }

        private void fetchFriends(Session session) {
            Request.newMyFriendsRequest(session, new GraphUserListCallback() {

                @Override
                public void onCompleted(List<GraphUser> users, Response response) {
                    if (users != null) {
                        friendsList = new ArrayList<FriendInfoHolder>();
                        for (GraphUser u : users) {
                            friendsList.add(buildFriendInfoHolder(u));
                        }

                        Intent intent = new Intent(parentActivity,
                                FriendListActivity.class);
                        intent.putParcelableArrayListExtra("friends_list",
                                friendsList);
                        parentActivity.startActivity(intent);
                    } else {
                        Log.i("users_status", "null");
                    }
                }
            }).executeAsync();
        }

        private FriendInfoHolder buildFriendInfoHolder(GraphUser user) {
            String profilePictureUrl = "graph.facebook.com/" + user.getId()
                    + "/picture?type=square";

            return new FriendInfoHolder(user.getFirstName(),
                    user.getLastName(), profilePictureUrl);
        }
    }
}

Comment: Is the Response returning an error?
Comment: Post it as an answer, and accept your own answer. So the question can be removed from list of Unanswered questions :)
Comment: @Submersed Thank you. Tracing the Response helped in finding the problem.
Answer: The problem was that I didn't add the INTERNET permission in the manifest file.

List users is null


Is the Brier Score appropriate for ordered categorical data?

Question: According to Wikipedia, the "original definition" of the Brier Score is:
$$BS=\frac{1}N\sum_{t=1}^N\sum_{i=1}^R(f_{ti}-o_{ti})^2 $$
Where $R$ is the number of classes, $N$ is the number of forecasting instances, $f_{ti}$ is the forecast probability of the $t$-th instance belonging to the $i$-th class, and $o_{ti}$ is the outcome (either $0$ or $1$).
I've got some data in which people predict whether the unemployment rate in the next quarter will be <2.5%, 2.5-5%, 5-7.5%, or >7.5%. So it's ordered categorical data. The subjects need to predict the probability the unemployment rate will fall into these categories, and their probabilities need to sum to 1. I've been encouraged to use the Brier Score to assess the performance of individual forecasters, but there's something that bothers me.
Consider Person 1:

Person 1 really had no clue about how to forecast unemployment. This person just assigned all four categories an equal probability, and ended up with a Brier Score of 0.06 + 0.06 + 0.06 + 0.56 = 0.75.
Then compare Person 2:

Person 2 had some knowledge suggesting that unemployment would be high. The correct category was ">7.5% unemployment" and Person 2 thought there was a .3 probability of that happening - thus Person 2 did better than Person 1 in this regard. Person 2 assigned a .7 probability to there being 5-7.5% unemployment.
The Brier Score for Person 2 is 0 + 0 + 0.49 + 0.49 = 0.98. So according to the Brier Score, Person 2 is worse than Person 1.
I find this very counterintuitive because Person 2 actually has some clue what they are doing, and furthermore assigned the correct category a higher probability than did Person 1 (0.3 vs 0.25).

Is this a problem in my particular case?
Assuming it is a problem in my particular case, would it have been OK if the categories were truly nominal as opposed to ordered categorical?
Assuming it is a problem in my case, what should I use instead of the Brier Score?
Answer:
In your case, the Brier score still "works" in that it incentivizes you to state the true forecast distribution (it is a proper scoring rule, see Gneiting and Raftery, 2007). For example, if the true probabilities were 0, 1/4, 1/4, 1/2, you would minimize your expected Brier score by actually stating these probabilities.
and 3. The Brier score is proper for both nominal and ordered data. However, as your example shows, it does not care about the forecast probabilities in the bins next to the one that realized. Whether this is problematic or not is largely a philosophical question. If you dislike this feature of the Brier score, you might use the Ranked Probability Score, defined as
$$RPS = \sum_{i=1}^r BS(i),$$ where $BS(i)$ is the Brier score for the event that the outcome lies within the first $i$ categories (loosely quoting from the post linked above). In your example, Person 1 gets an RPS of $$RPS_1 = 0.25^2 + 0.5^2 + 0.75^2 + 0^2 = 0.875,$$ whereas Person 2 attains an RPS of $$RPS_2 = 0^2 + 0^2 + 0.7^2 + 0^2 = 0.49,$$ thus outperforming Person 1. Note that like the Brier score, the RPS is also a proper scoring rule (and thus justified from a stats theory perspective).
Comment: Great answer. I'll just add that I found the following paper very helpful in providing addition discussion of these issues: Jose, V. R. R., Nau, R. F., & Winkler, R. L. (2009). Sensitivity to distance and baseline distributions in forecast evaluation. Management Science, 55(4), 582-590.


Image shows on home page, but not on article page

Question: I am using Open Outreach. When I create an article the image I uploaded appears on the home page, but does not appear when I click the link for that article.
From what I've read, it looks like it has something to do with Configuration/Media/File System. My public file system path is set as sites/openoutreach-7-x-1-19.dd/files. Do I need to change this? If so, what do I change it to?
Log message:
Type    page not found
Date    Thursday, June 4, 2015 - 9:43am
User    admin
Location    http://openoutreach-7-x-1-19.dd:8083/sites/openoutreach-7-x-1-19.dd/files/styles/medium_large/public/Portulaca%20grandiflora.jpg?itok=OP-6w24x
Referrer    http://openoutreach-7-x-1-19.dd:8083/article/june-3-2015-newsletter
Message sites/openoutreach-7-x-1-19.dd/files/styles/medium_large/public/Portulaca grandiflora.jpg
Severity    warning
Hostname    127.0.0.1
There is no medium_large folder in my styles folder. Do I need to create one?
Thanks!
Answer: When contrib images are missing in drupal the cause more often than not is that you have permissions problems with regards to your filesystem.
Make sure that your webserver can write to your files and files/styles directories.
If permissions are ok then drupal will create your medium_large directory and subdirectories.
Check the drupal setup documentation here (see the paragraph "Create the files directory").
As mentioned there make sure that you have write permissions on your sites/default/files directory.
Comment: Comments have been removed. Please don't use them for extended discussion.
Answer: I was rumaging through the module listing and found Debut Article. On the oft-chance that this might be causing problems I went to the debut article page on drupal.org and found drupal.org/node/1473574. It states that because fields are not true exportables, the resulting approach may be fragile and prone to breakage if, e.g., debut_media is not enabled prior to the article implementing the hook_alter, i.e., in this case, debut_article. I enabled debut media and it worked!


SQL State to Find Record that meets certain date criterion

Question: I am use ADO SQL in VBA to try and need the solution to the following example:
Table
ID   Effective Date of Documentation
1    1/1/2015
2    6/1/2015
3    1/1/2016
4    6/1/2016

In the example above the documentation for the ID 1 is in effective from 1/1/2015 through 5/31/2015, for ID 2 its in effect from 6/1/2015 through 12/31/2015, and so forth. So if I have a date say 8/1/2015, then I need to return the record which the documentation is in effect for. So in this example the record for ID 2 would be returned. I need some SQL to accomplish this and I cant figure out how! Any ideas? Is this possible to do with this structure or do I need to create some artificial column first for the end date and query that?
Comment: Tag your question with the database you are using.
Answer: You can do this by doing:
select t.*
from table t
where effdate < @date
order by effdate desc
fetch first 1 row only;

This is the SQL standard syntax.  Different databases might have different syntax for selecting one row.
EDIT:
In MS Access you would do:
select TOP 1 t.*
from t
where effdate < @date
order by effdate desc;

Comment: The fetch first 1 row only seems to draw an error in ado sql. Any other ways to do this last line that might work with ado sql which seems to use more basic sql commands.
Comment: @IrishRedneck . . . Use whatever equivalent method is appropriate for your database.
Comment: Yea im a bit of a noob with figuring out what works for ado sql but il figure it out. thanks for the overall solution tho!
Comment: @IrishRedneck . . . It is not ADO.  It is the underlying database.  Either `SELECT TOP 1` or `LIMIT 1` should work.
Comment: TOP 1 AND LIMIT seem to draw an error. I am using an access database.
Comment: Nevermind I was doing Select Top 1 * From (the query you originally made minus the fetch) . Just adding in Top 1 works to your query works
Comment: Actually I would think the sign should change to less than but for some reason its returning no values. In theory I  would want to take all values less than the @date then order by descending.


Change From on Admin Order Emails

Question: In the Drupal Commerce module is there a way to change the ADMIN ORDER EMAIL sender to the customers email instead of it being from the administrators email?
Thanks!
Answer: You can just edit the Rule that controls that admin email and there is a From field for you to enter in the token or data selector for the customers billing email.

Change From on Admin Order Emails


Two versions of Lax-Milgram theorem

Question: I'm having some troubles differentiating between two versions of Lax-Milgram theorem, one shown in my class and one that I saw is common on the internet.
Let $H$ be hilbert space, $B$ bilinear form on $H$ which is bounded and coercive.

(my class): There is a unique bounded linear operator $S$ with an invertible bounded operator such as $B(Sx,y)=<x,y>$.
(interenet): let $\phi$ be a linear functional on $H$. so there is a unique $x \in H$ that maked $\phi(y)=B(y,x)$ for every $y\in H$

hope you could show me at least why the first definition leads to the second. I really tryed and had absolutely no idea (I used riesz' theorem and took $x$ such that for every $y \in H$ $\phi (y)=<y,x>=\overline{<x,y>}=\overline{B(Sx,y)}$, and from here i can't unfortunately lose the conjuget and replace the order of $Sx$ and $y$, which would leed to the solution.
Thanks
Comment: The second is not Lax-Milgram, but the Riesz representation theorem http://en.wikipedia.org/wiki/Riesz_representation_theorem.
Comment: @gerw: you are right of course, i fixed my questions.
It should be $\phi(y)=B(y,x)$ instead of $\phi(y)=$
Answer: The problem is that the $B$ in the second formulation does not equal the $B$ in the first one.
Let us proof the second one by using the first one.
Set $\hat B(x,y) = \overline{B(y,x)}$.
By using the first theorem, you find an operator $\hat S$
associated to $\hat B$.
Then,
\begin{equation*}
 \phi(y) = \langle y,x\rangle
 =
 \overline{\langle x, y \rangle}
 =
 \overline{\hat B(\hat S x, y)}
 =
 B(y, \hat S x).
\end{equation*}

Two versions of Lax-Milgram theorem


C++ and const - accessing a member function of a const reference

Question: I have this snippet of code here. The intention is to make a copy of initialData. Since I am not modifying initialData in any way, I figure that I should pass it as a const reference. However, I keep getting this message when compiling.

.\src\Scene\SceneAnimationData.cpp(23)
  : error C2662:
  'SceneTrackerData::getRect' : cannot
  convert 'this' pointer from 'const
  SceneTrackerData' to 'SceneTrackerData
  &'

#include "SceneTrackerData.h"

void SceneAnimationData::SetupData(const SceneTrackerData &initialData)
{
    // getRect(), points() and links() all return const pointers
    CloneRect(initialData.getRect());
    ClonePoints(initialData.points()->values());
    CloneLinks(initialData.links()->values());
}

void SceneAnimationData::CloneRect(const QGraphicsRectItem * initialRect)
{
    if (initialRect != NULL)
    {
        QPointF position = initialRect->scenePos();
        QRectF rect = initialRect->rect();

        initialRect = new QGraphicsRectItem(rect);
        initialRect->setPos(position);
    }
}

void SceneAnimationData::CloneLinks(const QList<QGraphicsLineItem*> links)
{
    links_ = new QList<QGraphicsLineItem*>(*links);
}

void SceneAnimationData::ClonePoints(const QList<QGraphicsEllipseItem*> points)
{
    points_ = new QList<QGraphicsEllipseItem*>(*points);
}

Answer: Without the definition of SceneTrackerData, it's hard to say, but likely that function (SceneTrackerData::getRect) is not marked as const.
That is, what is (guessing):
const Rect& SceneTrackerData::getRect(void)

Should be:
const Rect& SceneTrackerData::getRect(void) const
                        //                     ^
                        //                     |
                        // does not logically modify the object

Comment: As long as getRect does not call any of those other non-const methods of Rect, or do any other modifications, then getRect can guarantee that it does not modify the Rect. That means that I can call getRect on a const Rect object -- however, there would be a compile error if I tried to call another non-const method on the same object. That's how constness is preserved: by having non-const method calls fail, while const method calls are allowed.
Comment: one question - doesn't const for getRect(void) imply that I can not change Rect? I know the compiler can't "see" this - but my guess is that not all methods of Rect are const. Without all of them being const, you can not rely on getRect not changeing the Rect. Would it be clearer (in this case) to cast away constness in the other function instead of adding it here?
Answer: It's not clear which is line 23 here; but my guess is that you are calling methods on the object that are not themselves declared as const and thus are not usable by a const object reference.
Answer: I'm not sure as I am no expert C++ programmer, but are your functions getRect() and so on declared const? If not but you know the way you use them is const, you can still use a const_cast to remove the const from your initialData reference.
See for example here: http://docs.oracle.com/cd/E19422-01/819-3690/Cast.html
Or Scott Meyers excellent C++-Books Effective C++ and More Effective C++. At least one of them has an item about constness.
Answer: I am thinking lines like these are illegal:
links_ = new QList<QGraphicsLineItem*>(*links);

points_ = new QList<QGraphicsEllipseItem*>(*points);

in that the passed in links and points are not defined as pointers, but defined values. In order to compile the code, You probably need to either define them like this
const QList<QGraphicsLineItem*>* links

or, instead use them like this
links_ = new QList<QGraphicsLineItem*>(&links);  // don't actually do this

However the latter one is potentially a run-time bug, because you are accessing the address of a temp value, which dies after the function body.
Unless QList uses a deep-copy, your app may very likely crash.
Comment: Thanks. You've helped me to track down 2 more bugs!
Answer: links_ = new QList<QGraphicsLineItem*>(*links);

This could potentially be legal if the * operator is overloaded for the QList class, though I don't think it is. Although as mentioned above, you're probably trying to do
links_ = new QList<QGraphicsLineItem*>(links);

Depending on what the actual constructor takes.
Also, each of those functions should take in the QList by reference, for performance reasons. Right now you copy the entire object twice for each time you call the function. Once to pass it in by value, then once for the construction of the copy.
One thing to remember when dealing with const'ness is that const is NOT guaranteed. Structures exist such as "const_cast" to strip away the const'ness of an object. Having a const object, and using const functions is helpful to signify to other developers that the code should not change the object, not that it cannot change it. See the difference?
void bar(const Foo& f) {
     f.setX(5); // compile error, f is const
     Foo &f2 = const_cast<Foo&>(f);
     f2.setX(5); // compiles just fine
}

The useful part is that unintentional attempts to change the object will result in compiler errors, a determined programmer can easily circumvent these protections.


Dynamically display table

Question: I'm trying to make some sort of "timesheet" where the user inputs 2 dates

and it calculates each month/year and display on a combobox.
I wanted to DYNAMICALLY (no need to refresh the page or anything) update the amount of days and fill the table with Day Number and Day Name(monday,etc..)
I managed to calculate the amount of days in a month but how can I display my table without reload the page?
Also maybe change isn't the right thing because it will not load first time because the combobox didn't change.
JavaScript
$(document).ready(function() {
    $('#dates').change(function() {
        var splitDate = $('#dates').val().split("/");
        var month = splitDate[0];
        var year = splitDate[1];
        var days = daysInMonth(month,year);
        alert(days);
    });

    function daysInMonth(month,year) {
        return new Date(year, month, 0).getDate();
    }
});

HTML

                        #
                        Day
                        Number of Clients

                        <input name="amountOfClients[]" type="number">

Answer: Well, not a complete answer, but for your question about change event, try alter your code to smth like this. This way you can trigger the method for the first time
$(document).ready(function() {
   $('#dates').change(datesChanged);
   datesChanged();
}

function datesChanged() {
   var splitDate = $('#dates').val().split("/"),
      month = splitDate[0],
      year = splitDate[1],
      days = daysInMonth(month,year);
   console.log("days:", days);
}

function daysInMonth(month,year) {
   return new Date(year, month, 0).getDate();
}

For the dynamic build, you can use the datatables library, it is simple and fast. Basic principal is that you just give it an object and it parses it to html table

Dynamically display table


Hypothesis on means of two Pareto distributions

Question: I have two independent groups and they seems to form a Pareto distribution when the histograms are looked at. Is there a particular hypothesis test that is specifically made to compare the means of such distributions?
I should also mention that the distributions are highly unbalanced (one group has 1000 instances and the other has 35,000 instances).
I want to check if the mean of one group is greater than the mean of the other group.
Answer: With such huge sample sizes, you will certainly reject the null; it may be better to focus on measuring the size of the difference than testing for it.
In the case that the lower limit of both Pareto distributions ($x_m$ Wikipedia's parameterization) is the same, the test is straightforward -- it amounts to testing equality of the $\alpha$ parameter.
The mean, when it exists, is $\frac{\alpha x_m}{\alpha-1}$, which increases as $\alpha$ decreases toward 1.
Note that the log of a Pareto random variable is a shifted exponential whose lower limit (shift parameter) is $\log(x_m)$, and $\alpha$ is the rate parameter. So let's proceed this way -- by working with the logs.
In the case that $x_m$ is common to both groups but unknown, you could estimate its log by the smallest observation in either group, subtracting it from all other log-values (and then discarding that observation from whichever sample it occurred in).
You could then compare the means of the resulting exponentials via an F-test, as here (the ratio of the means of the shifted logs $\bar{X}/\bar{Y}$ should be $\sim F_{2n_x,2n_y}$), or you could do a straight likelihood ratio test. They should give very similar results (at considerably smaller sample sizes than yours they can differ more).
Comment: @MichaelM Since the hypothesis was that the means were equal, rather than that the parameters were equal or that the medians were equal or that the distribution functions were the same, we have to worry about the existence of the population mean. The test I discuss would work for comparing samples from two Pareto-distributed populations even when $\alpha\leq 1$ but it would no longer be possible to test the hypothesis that was being asked about. Whether the OP really meant to test means as such or something more general is really a question for the OP, I think.
Comment: How much do we have to worry about non-existing true means here?
Answer: Pareto might not have a finite mean, so this comparison simply might not be reasonable.
You could make a simulation by bootstrapping from your samples and get a pretty good idea of if one group is larger than the other.


Solicitar postagem reversa API Correios

Question: Estou tentando utilizar a API dos Correios para realizar o método de postagem reversa. Estou usando o seguinte link para acessar esse método:
http://webservicescol.correios.com.br/ScolWeb/WebServiceScol?wsdl
Sempre que tento acessar esse método pelo script eu tenho esse error:
<code>requests.exceptions.HTTPError: 503 Server Error: Service Temporarily Unavailable for url: http://webservicescol.correios.com.br/ScolWeb/WebServiceScol?wsdl
</code>
Aparentemente esse link que estou tentando realizar o request está com problemas. Já fiz testes de outros métodos que funcionaram nesse outro link:
https://apps.correios.com.br/SigepMasterJPA/AtendeClienteService/AtendeCliente?wsdl
Vocês sabem se teria algum outro método equivalente ao de solicitar postagem reversa ou outro link para eu acessar esse método?
Answer: Experimente uma olhada no wrapper da API dos correios mantido pela Olist - é um projeto bem legal que usa muita coisa dos correios. Se não quiser usar o projeto todo, pode explorar o código e ver como são feitas as requisições de postagem reversa -
https://github.com/olist/correios

Solicitar postagem reversa API Correios


referecia id do usuario logado se perdendo

Question: Estou fazendo um projeto de cartão ponto Net Core MVC, em que tenho cadastro de usuario, empresa e funcionario. Pra cadastrar a empresa preciso pegar o id do usuario logado, ja tenho um função que faz isso e funciona pq uso pra cadastrar endereços.
<code>// GET: Empresas/Create
    public async Task<IActionResult> Create()
    {
        _logger.LogInformation("Nova empresa");
        var usuario = await _usuarioRepositorio.PegarUsuarioLogado(User);
        var empresa = new Empresa {UsuarioId = usuario.Id}; //aqui tem a referencia do ID certinho
        return View();
    }

    // POST: Empresas/Create
    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Create([Bind("EmpresaId,CNPJ,RazaoSocial,NomeFantasia,RamoAtividade,InscEstadual,InscMunicipal,Telefone,Email,Rua,Numero,Bairro,Cidade,Estado,UsuarioId")] Empresa empresa)
    {
        if (ModelState.IsValid)
        {
            await _empresaRepositorio.Inserir(empresa);//mas quando passa pra cá ela se perde e fica como "NULL"

            _logger.LogInformation("Novo empresa cadastrado");
            return RedirectToAction("Index", "Usuarios");
            //return RedirectToAction(nameof(Index));
        }
        _logger.LogError("Informações inválidas");
        return View(empresa);
    }
</code>
na declaração de empresa tem o UsuarioID, mas quando passa pela view e vai inserir perde a referencia (consigui confirmar isso atraves do debugger), qual sera o motivo de ter perdido?
na views->Empresa->Create tenho a vizualização de todos os campos, e o usuarioID esta oculto
<code><input asp-for="UsuarioId" type="hidden" />
</code>
Comment: No método `Create()` vc não está passando o objeto empresa, tente `return View(empresa)`
Comment: @VanderleiPires era isso mesmo, obrigada!
Answer: Você não está retornando a empresa para a View.
Tente fazer assim:
<code>// GET: Empresas/Create
    public async Task<IActionResult> Create()
    {
        _logger.LogInformation("Nova empresa");
        var usuario = await _usuarioRepositorio.PegarUsuarioLogado(User);
        var empresa = new Empresa {UsuarioId = usuario.Id};
        return View(**empresa**);
    }
</code>
Após isto, certifique-se de que sua view esteja retornando o objeto empresa para a controller no POST.


$QQ$-plot - Why do we choose the empirical distribution $F_n(x) = \frac {\#\{y \in S \mid y \le x\}} n$, $S$ is sample, for comparison with normal?

Question: $QQ$-plot - Why do we choose the empirical distribution $F_n(x) = \frac {\#\{y \in S \mid y \le x\}}  n$, $S$ is sample, for comparison with normal ?
Let $S$ be our sample of size $n$. Then we form the empirical distribution  $F_n$ as defined above. We then use a $QQ$-plot to compare $F_n$ to $N(0,1)$ to see if there might be a linear relationsship.

Why do we choose $F_n$ as the emperical distribution for our sample ?
Could we get other results if we did not choose $F_n$ as the emperical distribution ?
For the fractile of $p \in (0,1)$ we choose the midpoint $x$ of the interval corresponding to $p$. Why do we choose the midpoint ?

I would appreciate your help.
Comment: Just to mention that there is another SE site for statistics: http://stats.stackexchange.com/
Answer: Suppose $X_1,X_2,\ldots$ is an i.i.d. sequence of $N(0,1)$-distributed random variables. If
$$
F_n(x)=\frac{\#\{1\leq i\leq n\mid X_i\leq x\}}{n}=\frac1n \sum_{i=1}^n \mathbf{1}_{\{X_i\leq x\}}
$$
denotes the empirical distribution function then
$$
F_n(x)\to \Phi(x) \quad\text{almost surely as}\;n\to\infty,
$$
for all $x$, where $\Phi$ is the CDF of an $N(0,1)$-distribution.
This means that if you have an i.i.d. sample following an $N(0,1)$-distribution and $n$ is large enough, then $F_n$ must be "close" to $\Phi$. This is checked by plotting $F_n(x)$ against $\Phi(x)$ and checking if the points lie on the identity line.
Comment: Can this convergence of $F_n(x)$ to $N(0,1)$ be proven ? If yes, how ?
Comment: Yes, this is a consequence of the law of large numbers since $${\rm E}[F_n(x)]=\frac1n \sum_{i=1}^n {\rm E}[\mathbf{1}_{\{X_i\leq x\}}]=\Phi(x)$$
Comment: But what if our random variable was a coin with $50/50$ probability or a dice, then this would be false ?
Comment: Those aren't $N(0,1)$-distributed.
Comment: Oh so our assumption is that $X_i$ for $i = 1,2..$ are $N(0,1)$ distributed. And then we use the Law of Large Numbers to make a sequence of random variables that are $1$ if the appropriate event of $S$ happens for each of the values in our sample (that is $X \le k$ where $k$ is a sample value) ? And each of these sequences converge to the probability of the standard normal ?
Comment: More or less, so _if_ your sample was indeed from a normal distribution, then by the law of large numbers, the empirical distribution function would be "close" to $\Phi$ or in other words, the points in a QQ-plot would lie close to the identity line. This means that if your points does _not_ lie close to the identity line, then your sample cannot come from a normal distribution. The empirical distribution function is just a step function that, at each $x$, gives the frequency of how many in the sample that are less than $x$.
Comment: If $x_1<x_2<\ldots<x_n$ is your ordered sample, then $F_n(x)=0$ for $x<x_1$, $F_n(x)=\frac1n$ for $x_1\leq x<x_2$, $F_n(x)=\frac2n$ for $x_2\leq x<x_3$ and so on.
Comment: Sorry if I'm a little slow here. You view $F_n(x)$ as a random variable for every $x\in \mathbb R$ ? $F_n(x)$ is the sum of $n$ random variables (RV's that equal $1$ if the corresponding $N(0,1)$-RV has value less or equal than $x$, otherwise $0$) divided by $n$. Then the expectation of $F_n(x)$ indeed yields $\Phi(x)$ and from the sample $x_1, x_2, \ldots, x_n$ we obtain a realization (value) of every RV $F_n(x)$ for $x \in \mathbb R$ ?
Comment: Correct! $F_n(x)$ is a random variable since, for fixed $n$, it's a function of the random variables $X_1,\ldots,X_n$. Another way to say it, is that for each $x\in\mathbb{R}$: $F_n(x)=\frac1n \sum_{i=1}^n Y_i$, where $Y_i=\mathbf{1}_{\{X_i\leq x\}}$. Now, $Y_1,Y_2,\ldots$ are i.i.d. with mean $\Phi(x)$ and by the law of large numbers $F_n(x)\to {\rm E}[Y_1]=\Phi(x)$ almost surely as $n\to\infty$. Note also that this argument works for any distribution (not just the normal distribution).
Answer: The emipirical distribution function is the maximum likelihood estimator of the underlying distribution. Chosing anyting else will distort your data. The midpoint is chosen essentially by convention, since the empirical distribution is a step function. A simple example is the estimator for the median: if N=even, you are selecting the midpoint. Depending on the underlying distribution, (if you knew it), it might make more sense to take something besides the midpoint, but you will normally not have a good for doing something other than the midpoint.
Comment: How do you show the emperical distribution function is the maximum likelihood estimator ?
Comment: @NicolasLykkeIversen The actual proof requires Lagrange multipliers (see: http://www.stat.tamu.edu/~suhasini/teaching613/ED.pdf. )However, an intuiitively, the most likely distribution for an observed sample is one that looks exactly like the sample; hence, it will assign a probability of 1/N to each sample point, resulting in the empirical distribution function


Backup script to FTP with timed subfolders

Question: I want to make a backup script, that makes a .tar.gz of a folder I define, say fx /root/tekkit/world
This .tar.gz file should then be uploaded to a FTP server, named by the time it was uploaded, for example: 07-10-2012-13-00.tar.gz
How should such backup script be written?
I already figured out the .tar.gz part - just need the naming and the uploading to FTP.
I know that FTP is not the most secure way to do it, but as it is non-sensitive data, and FTP is the only option I have, it will do.
Edit:
I ended up with this script:
#!/bin/bash

# have some path predefined for backup unless one is provided as first argument
BACKUP_DIR="/root/tekkit/world/"
TMP_DIR="/tmp/tekkitbackup/"
FINISH_DIR="/tmp/tekkitfinished/"
# construct name for our archive
TIME=$(date +%d-%m-%Y-%H-%M)

if [ $1 ]; then
    BACKUP_DIR="$1"
fi

echo "Backing up dir ... $BACKUP_DIR"
mkdir $TMP_DIR
cp -R $BACKUP_DIR $TMP_DIR
cd $FINISH_DIR
tar czvfp tekkit-$TIME.tar.gz -C $TMP_DIR .

# create upload script for lftp
cat <<EOF> lftp.upload.script
open server
user user password
lcd $FINISH_DIR
mput tekkit-$TIME.tar.gz
exit
EOF

# start backup using lftp and script we created; if all went well print simple message and clean up
lftp -f lftp.upload.script && ( echo Upload successfull ; rm lftp.upload.script )

Answer: First you create cron job that is invoked at time you want to have backup created
after backup is created script will generate lftp script to upload file via FTP.
#!/bin/bash

# have some path predefined for backup unless one is provided as first argument
BACKUP_DIR="/tmp/test"
# construct name for our archive
TIME=$(date +%d-%m-%Y-%H-%M)

if [ $1 ]; then
    BACKUP_DIR="$1"
fi

echo "Backing up dir ... $BACKUP_DIR"
tar czvfp $TIME.tar.gz $BACKUP_DIR

# create upload script for lftp
cat <<EOF> lftp.upload.script
open ftp.server.tld
user username password
cd /target/directory
lcd /local/dir/where/tar/gz/archive/is
mput $TIME.tar.gz
exit
EOF

# start backup using lftp and script we created; if all went well print simple message and clean up
lftp -f lftp.upload.script && ( echo Upload successfull ; rm lftp.upload.script )

Comment: Thanks - your script was what got me onto the right track.
Comment: I am curious...why does it have to "create upload script for lftp"?
Comment: because script is different every time since it has dynamic component "$TIME" which needs to be redefined every time and then supplied to FTP client to do slightly different set of commands than last time.
Answer: As simple as:
DATE=`date +%d-%m-%Y-%H-%M`
tar cfz ${DATE}.tar.gz /root/tekkit/world

Or, with less typing:
tar cfz $(date +%d-%m-%Y-%H-%M).tar.gz /root/tekkit/world

What happens?
$ DATE=`date +%d-%m-%Y-%H-%M`
$ echo $DATE
07-10-2012-13-15

Comment: Good answer, but misses the FTP upload part.


Connections will not close when using Transaction Binding=Explicit Unbind; in connection string

Question: I´m using Transaction Binding=Explicit Unbind in the connection string as recommended here since I´m also using TransactionScope with timeout. The problem is that the connections does not seem to close after being disposed and eventually there are no more connections available in the connection pool. I got the same result when I modified the TransactionTimeoutIssueDemo (see the link) and ran TransactionScopeTest() (with the explicit unbind connection string) enough times in a loop to use up all available connections in the connection pool. Default value for connections in the pool is 100 but this can be changed by using the setting Max Pool Size =10 for instance. It seems that the connections will not be released when using explicit unbind even though both the SqlConnection and the TransactionScope are used with the using clause. Anyone know how to handle this?
Answer: The connections only seem to stay in the pool and not being reused in case you get an exception, just like the example. If you increase the timeout the connection will be reused.
A workaround to this problem is to clear the connection pool in case you get an exception like this:
using (SqlConnection con = new SqlConnection(connectionString))
{
    con.Open();
    try
    {
        Console.WriteLine("Server is {0}", con.ServerVersion);
        Console.WriteLine("Clr is {0}", Environment.Version);
        for (int i = 0; i < 5; i++)
        {
            using (SqlCommand cmd = con.CreateCommand())
            {
                cmd.CommandText = "insert into TXTEST values ( " + i + " )";
                cmd.ExecuteNonQuery();
            }
            Console.WriteLine("Row inserted");
        }
        Thread.Sleep(TimeSpan.FromSeconds(1));
    }
    catch
    {
        SqlConnection.ClearPool(con);
        throw;
    }
}

In most cases the transaction will complete within the timeout and everything will be fine and dandy. When the transaction actually do timeout you clear the pool in order to clean up the dirty connections that won't get reused. This will of course affect other connections in the pool that isn't affected by this problem.
This is a ugly workaround but it seems to work.
Answer: For what it's worth, this issue was fixed in .Net 4.0.


Logged in user can only access 1 page?

Question: Using Orchard 1.6 Iv created a new role 'FactoryWorker'. When this user logs in from the front end I want them to be navigated to one page only.
OrchardLocal/System/ManufacturedProducts
I have set this page to be a print screen of the order details so the factory worker will know what products to get ready for ship out & they wont be able to navigate as no menu appears, but also need the other pages blocked incase the user decides to enter the URL of a page they arnt allowed access to.
This is the only page I want this particular user to be able to access(after they login), and I have added a logout button, which logs out the user and returns them to the home page.
So iv been looking through editing a role, with permissions and content etc...but this all seems to be applying to forms and content in general. where the user can access any content type etc...
So can someone advise me on how to do this?
thanks for any replies
UPDATE
I forgot to mention that this is not a content type, item or part I am talking about.
I have created my own controller & View & VM which is accessible from the dash board (using the AdminMenu, which brings the admin user to OrchardLocal/System/ManufacturedProducts)
I have looked at Orchard.ContentPermissions Feature but it only seems to allow me to 1)Grant permissions for others or 2)Grant permission for own content
any ideas?
Answer: You can use a Request Filter, (I do not know if it is the best way) :

FilterProvider – defines the filter applied to each request. Resembles the way default ASP.NET MVC action filters work with the difference that it's not an attribute. All FilterProvider objects are injected into the request pipeline and are applied to all requests (so you need to check if the current request is suitable for your filter at the beginning of an appropriate method).

From : http://www.szmyd.com.pl/blog/most-useful-orchard-extension-points
So you could implement something like this
<code>public class Filter : FilterProvider, IAuthorizationFilter {

    private readonly IAuthenticationService _authenticationService;

    public Filter(IAuthenticationService authenticationService) {
        _authenticationService = authenticationService;
    }

    public void OnAuthorization(AuthorizationContext filterContext) {

        //If route is the restricted one
        if (filterContext.HttpContext.Request.Url.AbsoluteUri.Contains("OrchardLocal/System/ManufacturedProducts")) {

            //Get the logged user
            IUser loggedUser = _authenticationService.GetAuthenticatedUser();

            if (loggedUser == null)
                return filterContext.Result = new HttpUnauthorizedResult();

            //Get the Roles
            var roles = loggedUser.As<IUserRoles>().Roles;

            if (!roles.Contains("FactoryUser")) {
                //User is not authorized
                return filterContext.Result = new HttpUnauthorizedResult();
            }
        }
    }
}
</code>
Note: Untested code!
EDIT: Also you could invert the logic and check if the logged user has the role 'FactoryUser' and restrict its access to every page except the one they should see.
Answer: Your module can create a new permission (look at one of the permissions.cs files for examples), then create a role that has only that permission. Have your controller action check that permission (again, many examples found by finding usage of the permissions defined in one of the permissions.cs).
Comment: But this restriction applies only to that view, no?
Answer: You can use the Content Permissions module. Using this module you can attach a content item permission part to a content type. This part allows you to choose which roles can see the content when you create it.
Comment: thanks for the reply but just read a review: Took a while to figure out how to use this (add the part to content types). It is working great for Pages. Unfortunately, navigating directly to a Blog with restricted permissions does not show the "Access Denied" error, but instead show the contents in their entirety.
Comment: I've only it with pages and my own custom content types. I've not tried it with a blog though.

Logged in user can only access 1 page?


Number of different ways you can place positive integers into an array of size N such that the product of the integers is K

Question: To find the number of ways to place positive integers into an array of size $N$ such that the product of the numbers is $K$. So the problem boils down to finding the numbers of ways to place the prime factors of $k$ into $N$ slots. For Example, if $N = 2$ and $K = 24$
Prime Factors of $24$:  $2^3 \times 3^1$
So we have to find the number of ways of placing three 2's and one 3 in 2 slots. I saw the problem in the discussion forums and came to know that this can be done with the stars and bars concept. It is stated that the number of ways of placing three 2's and one 3 in 2 slots is equal to placing three 2's in 2 slots multiplied by placing one 3 in 2 slots.
placing three 2's in 2 slots (stars and bars) = $\binom{3+2-1}{3}$ = $\binom{4}{3}$
placing one 3 in 2 slots (stars and bars) = $\binom{1+2-1}{1}$ = $\binom{2}{1}$
So the total number of ways = $ \binom{4}{3} $ * $\binom{2}{1}$ = 4 * 2 = 8
The parts which I didn't understand is

how the number of ways of placing three 2's and one 3 in 2 slots is equal to placing three 2's in 2 slots multiplied by placing one 3 in 2 slots
why can't we apply the stars and bars concept to all of the prime factors like placing 4 (three 2's and one 3) into 2 slots.
Answer:
Because these choices are independent. You can divide the three twos as either $(2\times 2\times 2,-)$, $(2\times 2, 2)$, $(2, 2\times 2)$ or $(-, 2\times2\times 2)$. You can put the three either as $(3,-)$ or $(-,3)$. Now you can take any of the options for twos and combine it with any of the options for three, to get $4\times 2$ possibilities. E.g., taking the first option for each gives $(2\times2\times 2\times 3,1)$ (since there are no factors of $2$ or $3$ in the second slot), whereas taking the third and second gives $(2,2\times2\times3)$.

If you place four things in two slots, there are $5$ ways to do this, but this doesn't distinguish which things go where, just how many. So splitting as three things in the first slot is just counted as one way by this method, but actually this could correspond to $(2\times2\times2, 3)$ or $(2\times 2\times3,2)$, which are different.
Comment: So by point **2.**, you mean to say that order is preserved so all ways won't get counted?
Comment: @Turtle Not all ways are counted because the formula assumes you are trying to distribute identical objects, but here the objects are not all the same (one is special, so you need to know where that one goes).
Comment: Thank you for the answer.


What are Kick Lines?

Question: I'm reading a drum notation book and it talks about "kick lines"?
Is there a precise definition somewhere? (searching doesn't help since it thinks I'm talking about the kick drum)
Answer: Kick lines (or just "kicks") indicate a rhythm being played by another instrument in an ensemble. They will usually be shown just above the staff, along with the name of the instrument that is playing that rhythm. They may be used as cues or just a guide to interpreting the drummer's part.
Reference: Norman Weinberg, "Guide to standardized drum notation", 1994 - a summary is here: http://www.propercussion.org/filer/notation.pdf
Comment: I'm pretty sure it's not just to show what other instruments are playing, but instead to notate the kick line which you may want to show other instruments if it's important to what the kick plays. If it was to show someone else's line then you would just give someone that instruments sheet music and cut out the middle man.
Comment: I think it really depends on the notator.
Comment: @JBarry Welcome to SE! If you quote material from a book or the web in your answer, please reference the original source in your posts (I've edited your post for you this time).
Comment: From your source :It is recommended that all
kick lines be written above the staff in
cue-size notes. When kick lines are
written in cue-size notes above the
staff, their meaning is clear. It would
be difficult to interpret kick lines as
rhythms for any specific instrument in
the drumset. In addition, it is recom-
mended that all kick lines include a
written indication that identifies the
instrument or section performing the
rhythm. This knowledge is vital to an
intelligent, musical decision concerning
how the performer will interpret the
kick on the drumset."
Comment: Yes, this is where I read about it. It doesn't explain much!
Comment: Or, it does't explain how one is suppose to interpret it. Is the drummer suppose to play the rhythm if he wants(play with the other players)?
Answer: JBarry's answer seems to define what a kick is, your comments seem to be asking what to do with it.
Percussion parts, especially drumset parts, are very rarely notated beyond general sketches, but it is expected that the player will blend with the ensemble and play tasteful, appropriate patterns accentuating what is happening throughout the ensemble.
That is the percussionist's responsibility, whether he doesn't get music at all, gets a blank page, or gets every stroke written out.
I'm mostly a classical guy, and this notation is very common in classical notation (though it isn't called a kick).
Traditionally, this notation was used as cues to prepare the drummer who had just played the same pattern 128 times that something new was coming. It's a signal to help keep count, track themes, and generally "have a clue."
In more modern times with the score left mostly blank, the notation also helps the percussionist figure out what type of thing to play in that location. The "kick" is still a cue but it also helps to guide your performance, hinting at what part should be accented. This is especially useful when music is performed with minimal rehearsal.
To answer your question, notation like this isn't prescriptive (defining what do do), but descriptive. There's nothing you "have to" do, and different performers will use the kick in different ways. The purpose is to make the artistic percussionist's job easier.
Comment: Thanks. I figured it it was something like this but wanted to confirm. Basically the way I understand it is that the "kick" lines are the rhythms for "special" musical lines played by the ensemble(e.g., horns) and the percussionist can play along with them to increase the effectiveness of the lines. Another question: do drummers usually use the kick as part of emphasizing the line? Is that why the are called "kick lines"? (e.g., should I get into the habit of playing the lines on the kick when I see them?)
Comment: Like I said, I'm not primarily a set guy. maybe @JBarry would know? In any case, it would be up to the conductor/arranger/etc to determine the instrumentation of the line. You may be able to determine this by listening to authoritative recordings.

What are Kick Lines?


Racing jibe in windsurfing

Question: How to do a racing jibe in windsurfing ? What is the better type of sail to try to do is first racing jibe (wave sail or slalom sail) ?
You can see a video of the professional windsurfer Anders Bringdal here.
Waves sail pro:

strong
maneuvrability

Waves sail cons:

heavy

Slalom sail pro

stable
accelerate in the gust

Slalom sail cons

fragility
less maneuverability.
Comment: Tagged as "windsurfing." Welcome to Sports SE! What have you tried? What are racing jibes? More detail will help us answer your question. Also, answers may have different opinions about wave vs. slalom sails...perhaps it would be helpful to ask the pros/cons of type of sail vs. "what is better." Please see our [FAQ](http://sports.stackexchange.com/questions/how-to-ask) for more information.
Comment: The tag sail is not adequate, a tag windsurf would be better.
Comment: Seems like your in the process to answering your own question?
Comment: Good edit. As Zack says, if you can answer your own question, by all means, you are free to do so.
Answer:
Slalom sail
These sails are all about speed. If you want to travel fast, get a Slalom sail. They reach such high speed because they have special "chambers" that are inside the sail and clip onto the mast. Although speed comes with a price since you do have to exert a little more effort to turn this type of sail
Tuning a Slalom sail to extract maximum speed is great fun and can become a technical as you'd like.   Many of the pro's record measurements such as boom height, downhaul and outhaul after each session so they can accurately reproduce a sweet setting.   Most slalom/speed sails are from 6.0 to 10.0 meters.
Wave sail
Wave sales are built for somebody who is starting out in the sport. They are meant to get beat up. generally reinforced to be able to handle the beating they'll receive when you get it wrong. If you wreck with this type of sail, it will come out of the water perfectly fine, unlike the slalom which might be in pieces. Wave sails are also very easy to handle, which makes turning a lot easier. The rear of the sale is also cut high to avoid getting it caught in surf. The downside for wave sails is that you don't get the speed of a slalom sail. But it is more sturdy, easier to handle and great for beginners. Sizes are generally 3.5 to 5.5 meters

Racing jibe in windsurfing


i want to do the animation on Image view to change width of the Image view as below

Question: I want to do animation on imageview as below

Need to animate to like this.
Comment: what is the increment rate of your image length? i mean is that only 3 steps?
Comment: Whenever i enter in this activity then it will take max value as reference i.e. 6085 and then it animate all image view of colors by 0 to its respective percentage value of max value ..and increment rate would as in like gradual an smooth increase to is respective max value from 0.
Comment: hi vnShetty u have any idea how can i do it ....Adavance thanks for help!!
Answer: Find the solution
ScaleAnimation solved the issue
int maxValue = 6085;
final float scale = this.getResources().getDisplayMetrics().density;
linearLayout1 =(LinearLayout) findViewById(R.id.iv1);linearLayout2 =(LinearLayout) findViewById(R.id.iv2);

linearLayout1.setLayoutParams(new LinearLayout.LayoutParams(calculatePercentage(maxValue,3853),(int) (20 * scale + 0.5f)));
        linearLayout2.setLayoutParams(new LinearLayout.LayoutParams(calculatePercentage(maxValue,3026), (int) (20 * scale + 0.5f)));

ScaleAnimation anim1 = new ScaleAnimation(0.0f, 10.0f, 1.0f, 1.0f, Animation.RELATIVE_TO_SELF,1.0f, Animation.RELATIVE_TO_SELF, 0.5f);
        ScaleAnimation anim2 = new ScaleAnimation(0.0f, 10.0f, 1.0f, 1.0f, Animation.RELATIVE_TO_SELF,0.0f, Animation.RELATIVE_TO_SELF, 1.0f);
            anim1.setDuration(7000);
            anim2.setDuration(7000);
           linearLayout1.startAnimation(anim1);
           linearLayout2.startAnimation(anim2);

and code for calculate percentage
public int calculatePercentage(int maxValue,int value)
    {
        Log.v(TAG, "maxValue  :  "+maxValue);
        Log.v(TAG, "Value  :  "+value);
        float division =(float)(value)/(float)maxValue;
        int percenatgeValue =(int) (division*100);
        Log.v(TAG, "percenatgeValue  :  "+percenatgeValue);
        return percenatgeValue;
    }


Why hazelcast can not read data from treemap with generic record?

Question: I have example in my local hazelcast:
    Map<Integer, TreeMap<Long, GenericRecord>> map = hzInstance.getReplicatedMap(TEST_MAP);
    TreeMap<Long, GenericRecord> zmeny = new TreeMap<Long, GenericRecord>();
    zmeny.put(1l, GenericRecordBuilder.compact("test").setString("string", "stringvalue").setInt32("integer", 123)
            .build());
    map.put(1, zmeny);

    Map<Integer, TreeMap<Long, GenericRecord>> a = hzInstance.getReplicatedMap(TEST_MAP);
    for (Entry<Integer, TreeMap<Long, GenericRecord>> ccc : a.entrySet()) {
        GenericRecord record = ccc.getValue().get(1l);
        System.out.println(record); // here I got exception
    }

so I am inserting map of treemap to hazelcast. Problem is when I want to read this data from hazelcast. I got example:
Caused by: java.io.EOFException: Cannot read 4 bytes!
    at com.hazelcast.internal.serialization.impl.ByteArrayObjectDataInput.checkAvailable(ByteArrayObjectDataInput.java:670)
    at com.hazelcast.internal.serialization.impl.ByteArrayObjectDataInput.readInt(ByteArrayObjectDataInput.java:293)
    at com.hazelcast.internal.serialization.impl.compact.CompactInternalGenericRecord.getInt32(CompactInternalGenericRecord.java:255)
    ... 59 common frames omitted

when I debug I see that record is DefaultCompactReader which can not read data. It looks like it is empty. Any advice what I am doing wrong ?
UPDATE1
compact serialization is enabled. Without it I can not even put treemap to hazelcast:
            Config hzConfig = new Config();
    NetworkConfig network = hzConfig.getNetworkConfig();
    network.setPortAutoIncrement(false);
    network.getInterfaces().setEnabled(true).addInterface("127.0.0.1");
    network.getJoin().getMulticastConfig().setEnabled(false);
    hzConfig.getUserCodeDeploymentConfig().setEnabled(true);
    hzConfig.getSerializationConfig().getCompactSerializationConfig().setEnabled(true);
    HazelcastInstance hzInstance = Hazelcast.newHazelcastInstance(hzConfig);

UPDATE2
When I debug code I can see this not working because of:
com.hazelcast.internal.serialization.impl.bufferpool.BufferPoolImpl.returnInputBuffer(BufferObjectDataInput)
which clear input buffer. StreamSerializerAdapter with TreeMap is used instead of CompactStreamSerializer
Answer: thx to mdumandag this is bug which will be fixed in 5.2
Answer: For the time being, you should enable Compact serialization explicitly, as it is still in BETA. (It will be promoted to stable status in the upcoming 5.2 release).
When you enable Compact serialization with a configuration like the below, the code snippet you shared works as expected, which I tested .
config.getSerializationConfig().getCompactSerializationConfig().setEnabled(true);

Comment: it is enabled. Without it I can not put data to hazelcast
Comment: What Hazelcast version are you using? I tried the code snippet you shared with Compact serialization enabled on master, and it worked just fine.
Comment: 5.1.1 hz version
Comment: with java 17  version
Comment: OK, see my answer here https://github.com/hazelcast/hazelcast/issues/21902#issuecomment-1204937590
Comment: wow thx a lot what a quick response


Yii - remove smart quotes for all active records

Question: I have an application that allows a user to import/enter information, which gets saved to the MySQL database using a Yii active record, and I have a few users who copy/paste text that has Microsoft smart quotes.  This is an issue when the data is parsed on the iPhone implementation of the site, so I need a way to get rid of all the smart quotes everywhere.
I found a php function that will remove these characters from a piece of text, but I was wondering if there is a way in Yii to have the function get called every time text is saved to the database.
Answer: You can extend CActiveRecord overriding beforeSave method in the following manner:
class ActiveRecord extends CActiveRecord
{
    protected function removeMagicQuotes($value)
    {
        return your_function_remove_magic_quotes($value);
    }

    protected function beforeSave()
    {
        $attributes = array_keys($this->getAttributes());
        foreach ($attributes as $attribute)
            $this->$attribute = $this->removeMagicQuotes($this->$attribute);
        return parent::beforeSave();
    }
}

This one will remove magic quotes for all attributes declared in active record. As an alternative you can override beforeValidate method instead of beforeSave to remove quotes just before validation.
Answer: I recommend creating getter/setter for fields where it can occur and filter it there.
Something like this in case of field comment:
// Make field $comment private so get/set will work
private $comment = '';
public function getComment()
{
    return clear_function($this->comment);
}

public function setComment($value)
{
    // Could clear here too if you want, so it will be stored clean in db
    $this->comment = $value;
}


On asymptotics for the number of ways to write $2n$ as the sum of two primes

Question: Let $g(n)$ be the number of ways to write $2n$ as the sum of two primes. Define $G(n) = g(2) + \cdot \cdot \cdot + g(n)$. Are there any conjectured or known asymptotics or bounds for $G(n)$? Especifically, is it known or conjectured that $G(n) \sim \frac{n^2}{\log(n)^2}$?
Comment: Not enough meat to justify a proper answer, so I'll just put it here. Looking at the heuristics section on the Wikipedia page for [Goldbach's conjecture](http://en.wikipedia.org/wiki/Goldbach%27s_conjecture#Heuristic_justification), $g(n)$ would be estimated to be around $\frac{n}{2\ln^2n}$, so I wouldn't be too surprised.
Answer:
Unconditionally we have that
  $$G(N)\sim\frac{2N^2}{\log^2(2N)}.$$

To see why, let $1_{\mathcal{P}}(n)$ denote the indicator function for the odd primes. Then $$G(N)=\sum_{n=1}^{2N} \sum_{a+b=n} 1_{\mathcal{P}}(a)1_{\mathcal{P}}(b).$$ Since $1_{\mathcal{P}}(m)=0$ when $m<0$, we may extending the inner sum to obtain
$$G(N)=\sum_{n=1}^{2N} \sum_{a=1}^{2N} 1_{\mathcal{P}}(a)1_{\mathcal{P}}(n-a),$$ and then by switching the order of summation
$$G(N)=\sum_{a=1}^{2N} 1_{\mathcal{P}}(a)\sum_{n=1}^{2N} 1_{\mathcal{P}}(n-a)$$
$$=\sum_{a=1}^{2N} 1_{\mathcal{P}}(a)\sum_{n=1}^{2N-a} 1_{\mathcal{P}}(n)$$
$$=\sum_{a=1}^{2N} 1_{\mathcal{P}}(a)(\pi(2N-a)-1),$$ and by using the prime number theorem, this is asymptotic to $$\frac{2N^2}{\log^2(2N)}.$$
Comment: Can you detail the last step a little more, that is, how do you use the prime number theorem to arrive at the final asymptotic? Also, doesn't this imply that every sufficiently large number is the sum of two primes by noting $G(n) - G(n-1) \rightarrow \infty$?


I am getting a SQUID Error

Question: What exactly is wrong here
Entry in SQUID File---
httpd_accel_host virtual
httpd_accel_port 80
httpd_accel_with_proxy on
httpd_accel_uses_host_header on
acl lan src 192.168.1.1 192.168.2.0/24
http_access allow localhost

Error after: service squid restart
2010/02/01 14:24:29| Processing Configuration File: /etc/squid/squid.conf (depth 0)
2010/02/01 14:24:29| cache_cf.cc(361) parseOneConfigFile: squid.conf:10 unrecognized: 'broken_vary_encoding'
2010/02/01 14:24:29| WARNING: Netmasks are deprecated. Please use CIDR masks instead.
2010/02/01 14:24:29| WARNING: IPv4 netmasks are particularly nasty when used to compare IPv6 to IPv4 ranges.
2010/02/01 14:24:29| WARNING: For now we assume you meant to write /0
2010/02/01 14:24:29| WARNING: (B) '::/4294967200' is a subnetwork of (A) '::'
2010/02/01 14:24:29| WARNING: because of this '::' is ignored to keep splay tree searching predictable
2010/02/01 14:24:29| WARNING: You should probably remove '::/4294967200' from the ACL named 'all'
2010/02/01 14:24:29| WARNING: Netmasks are deprecated. Please use CIDR masks instead.
2010/02/01 14:24:29| WARNING: IPv4 netmasks are particularly nasty when used to compare IPv6 to IPv4 ranges.
2010/02/01 14:24:29| WARNING: For now we assume you meant to write /128
2010/02/01 14:24:29| aclParseIpData: unknown netmask '255.255.255.255' in '127.0.0.1/255.255.255.255'
FATAL: Bungled squid.conf line 25: acl localhost src 127.0.0.1/255.255.255.255
Squid Cache (Version 188.8.131.52): Terminated abnormally.
CPU Usage: 0.013 seconds = 0.006 user + 0.007 sys
Maximum Resident Size: 0 KB
Page faults with physical i/o: 0

Also please provide me with the simplest squid script for the proxy to run.  Restrictions can be entered.
Comment: It's fine asking for specific help with a problem you have. However, asking to "provide simplest squid script" is very broad and sounds like you're asking others to do your job for you instead of helping you understand the issue at hand.
Answer: http_port 3128 transparent
hierarchy_stoplist cgi-bin ?
acl QUERY urlpath_regex cgi-bin \?
cache deny QUERY
acl apache rep_header Server ^Apache
access_log /var/log/squid/access.log squid
hosts_file /etc/hosts
refresh_pattern ^ftp: 1440 20% 10080
refresh_pattern ^gopher: 1440 0% 1440
refresh_pattern . 0 20% 4320

# 1000MB max cache size (default is 100MB):
cache_dir ufs /var/spool/squid 1000 16 256

acl manager proto cache_object
acl localhost src 127.0.0.1/255.255.255.255
acl to_localhost dst 127.0.0.0/8
acl SSL_ports port 443 563 # https, snews
acl SSL_ports port 873 # rsync
acl Safe_ports port 80 # http
acl Safe_ports port 21 # ftp
acl Safe_ports port 443 563 # https, snews
acl Safe_ports port 70 # gopher
acl Safe_ports port 210 # wais
acl Safe_ports port 1025-65535 # unregistered ports
acl Safe_ports port 280 # http-mgmt
acl Safe_ports port 488 # gss-http
acl Safe_ports port 591 # filemaker
acl Safe_ports port 777 # multiling http
acl Safe_ports port 631 # cups
acl Safe_ports port 873 # rsync
acl Safe_ports port 901 # SWAT
acl purge method PURGE
acl CONNECT method CONNECT

http_access allow manager localhost
http_access deny manager
http_access allow purge localhost
http_access deny purge
http_access deny !Safe_ports
http_access deny CONNECT !SSL_ports
http_access allow localhost
acl lan src 192.168.0.0/32
http_access allow localhost
http_access allow lan
http_access deny all
http_reply_access allow all
icp_access allow all
visible_hostname sumardilamoha.com
always_direct allow all
coredump_dir /var/spool/squid

Answer: Just erase the netmask from acl localhost src 127.0.0.1/255.255.255.255 to CIDR mask, it's 127.0.0.0/8 instead of 127.0.0.1/255.255.255.255, or any acl with this /255.255.255.255 mask and that's it...
Answer: Could you post your squid.conf (preferably through a pastie.org link for formatting purposes) ? In addition, it might be helpful (though not necessarily required) to share some environment information in case anybody has relevant tutorials to get you pointed in the right direction. I am assuming you might be using a redhat based distro with your reference to the service command. If this is correct, this tutorial might help you get started with a simple example to get up and running, then you can expand outward from there.

I am getting a SQUID Error


Algorithms for symbolic manipulation

Question: If you take a look at WolframAlpha, or other computer algebraic system, you will find that it is able to do symbolic manipulation like real humans.
For example, if you type in an integral, it can show you step by step on how to solve the integration.
What are the algorithms behind all this?
Answer: The algorithms behind symbolic integration (due to Liouville, Ritt, Risch, Bronstein et al.) are discussed in prior questions here, e.g. the transcendental case and algebraic case.
For general references on symbolic computation see any of the standard texbooks, e.g. Geddes et al. Algorithms for computer algebra, Grabmeier et al: Computer algebra handbook,von zur Gathen: Modern computer algebra, and Zippel: Effective polynomial computation, and many other books. See also the Journal of Symbolic Computation and various conferences: SIGSAM ISSAC, EUROCAL, etc.
Comment: @Yuval: I didn't mention books devoted to specific topics since the OP didn't mention their specific interests (besides integration). Note that my list of general textbooks is far form complete - it's off the top of my head, late at night (and probably biased since I was a Macsyma developer).
Comment: Don't forget A=B, which can be downloaded for free at http://www.math.upenn.edu/~wilf/AeqB.html.
Comment: I don't think the WolframAlpha step-by-step integration is using the Risch algorithm. It's likely just using a rules based system with pattern matching.

Algorithms for symbolic manipulation


Existence of Riemann–Stieltjes integral

Question: How to prove that for existence of Riemann–Stieltjes integral $\int\limits_a^b f(x) \, \mathrm{d}g$, where  $g \in V([a,b])$, it is required that function $f$ is continuous in the point of discontinuity of function $g$?
It sounds obvious, but how to prove that carefully?
Answer: If $\int_{a}^{b}fdg$ exists, then, for every $\varepsilon > 0$, there exists $\delta > 0$ such that
$$
            \left|\sum_{\mathcal{P}}f(x_k^{\star})\{g(x_k)-g(x_{k-1})\}-
       \sum_{\mathcal{P'}}f(x_k'^{\star})\{g(x_k')-g(x_{k-1}')\}\right| < \varepsilon
$$
whenever $\|\mathcal{P}\| < \delta$ and $\|\mathcal{P'}\| < \delta$. If you use the same partition points for $\mathcal{P}$ and $\mathcal{P'}$ and allow one of the evaluation points to vary, one consequence of the above is that
$$
                |f(x_k^{\star})-f(x_{k}'^{\star})||g(x_{k})-g(x_{k-1})| < \varepsilon \;\;\;\; (\dagger)
$$
whenever $x_k \le x_k^{\star},x_k'^{\star} \le x_{k+1} <x_k+\delta$. Suppose $g$ is discontinuous at some $x \in (a,b)$; $g$ has limits from the left and the right of $x$, which means that either $g(x+0)\ne g(x)$ or $g(x-0)\ne g(x)$, or both. There are two cases to consider

Case 1: $g(x-0)=g(x+0)$.Then $g(x+0)\ne g(x)$ and $g(x-0)\ne g(x)$, which means there exists $\sigma > 0$ such that $|g(x_l)-g(x)| > \sigma$ and $|g(x)-g(x_r)| > \sigma$ for all $x-\delta_0 < x_l < x < x_r < x+\delta_0$, provided $\delta_0$ is chosen sufficient small. Let $\varepsilon > 0$ be given, and choose $\delta$ so that $(\dagger)$ holds with $\varepsilon$ replaced by $\sigma\varepsilon$. Let $\delta_1$ be the minimum of $\delta_0$ and $\delta$.
Then
$$
         |f(x')-f(x)|\sigma < \sigma\varepsilon,\;\;\; x-\delta_1 < x' < x \\
         |f(x)-f(x'')|\sigma < \sigma\varepsilon,\;\;\; x < x'' < x+\delta_1.
$$
Hence, $f(x-0)=f(x)=f(x+0)$, making $f$ continuous at $x$.
Case 2: $g(x-0)\ne g(x+0)$. In this case there exists $\sigma > 0$ such that $|g(x_l)-g(x_r)| > \sigma$ for all $x-\delta_0 < x_l < x < x_r < x+\delta_0$, provided $\delta_0$ is chosen sufficiently small. Let $\varepsilon > 0$ be given. Choose $\delta > 0$ so that $(\dagger)$ holds with $\varepsilon$ replaced by $\sigma\varepsilon$. Let $\delta_1$ be the minimum of $\delta_0$ and $\delta$. Then
$$
          |f(x')-f(x'')|\sigma < \sigma\varepsilon,\;\;\; x-\delta_1 < x' , x'' < x+\delta_1
$$
Set $x''=x$ in order to concluded that $\lim_{x'\rightarrow x}f(x')=f(x)$.

I'll leave the endpoint cases at $x=a$, $x=b$ to you.

Existence of Riemann–Stieltjes integral


What is the advantage of bagging for k-NN?

Question: Is there an advantage to use bagging with k-NN? I constantly get better performances while doing it. Can it be that it is because of resampling with repeated instances, which will therefore be classified in the same neighborhood?
Is this some kind of cheating or is it legitimate?
Answer: If by bagging you mean taking the average over bootstrap-resampled training samples: that's certainly not cheating if you only build them off the single training sample.
As an illustration, let's think about $1$-NN. For a test point $x$, the predicted label for $1$-NN is the label of the nearest training set point. For bagging, let $q_\ell(x)$ denote the $\ell$th nearest neighbor in the training set. Then the expectation of the predicted label is
\begin{align}
\mathbb{E}[\hat{y}(x)]
&=\sum_{\ell=1}^n \Pr(q_1(x), \dots, q_{\ell - 1}(x) \text{ not in sample and } q_\ell(x) \text{ in sample}) \, y_{q_\ell(x)}
\\&= \sum_{\ell=1}^n \underbrace{\left( \frac{n-\ell+1}{n} \right)^n \left( 1 - \left( \frac{n-\ell}{n-\ell+1} \right)^n \right)}_{a_{\ell,n}} y_{q_\ell(x)}
\end{align}
where the coefficients $a_{\ell,n}$ satisfy
$$
a_{\ell,n} \stackrel{n\to\infty}{\longrightarrow} \frac{e - 1}{e^\ell}
.$$
So, this effectively turns the hard-assignment $1$-NN into a soft-assignment approach, weighting the nearest neighbor's labels by $0.63, 0.23, 0.09, 0.03, \dots$. I don't know if there's anything special about those weights, but it makes sense that smoothing out the labels like this would often perform somewhat better than the hard-assignment approach of 1-NN.
The same kind of argument applies to $k > 1$, it's just a little harder to calculate the smoothing weights.


different colors for different order statuses

Question: Is it possible on store/orders page to use different colors for different order statuses?
This feature can be handy. Or doe's someone know how to implement it?
thank you
Answer: Here's a possible Drupal-only solution that can get you there. You're going to need access to your theme css file to add a class for each of your order statuses, ex something like this:
.order-status-pending { color: yellow; }
.order-status-closed { color: green; }
.order-status-problem { color: red; }

Now go to views and edit the 'orders' view that is added by Ubercart and then select the field for 'order statuses' from the Fields display section. Next, select 'Style Settings', 'customize field HTML', 'Create a CSS class' and then use the tokens to add your custom class there, ex:
order-status-[status]

You could also rewrite the output of the field using the replacement tokens to something like this:
[status]

This won't work on multiple word order statuses, but you could use jquery instead to do this kind of conditional styling, using their much more powerful selectors.
Comment: hi, thank you for reply. Where exactly should I select 'style settings' and 'customize field html'... ? Where can I use the tokens?
Comment: whoops - forgot to add the edit 'orders' view line. Fixing now
Comment: oh:) I apologise. Your advice is for drupal 7. I use drupal 6:)
Comment: are you familiar with drupal views theming? its not that much different from 6.x to 7.x -- if you click the field under the fields section in your orders view you're going to see most of these same options
Comment: Yes I am familiar with themng views. Are you using ubercart views module? I use default admin/store/orders screen. Is it possible to create orders list without additional modules using views? Thank you.
Comment: as far as I know ubercart 2.x for drupal 6 doesn't provide any view to show orders.


Tela de edição não carrega os dados na tela

Question: Ao entrar em modo de edição, deveria os edit virem preenchidos e apenas a dropdownlist de cidade vem. Veja me cshtml abaixo.
@model TreinamentoCrud.FuncViewModel.FuncionarioViewModel

@{
    ViewBag.Title = "EditVM";
}

EditVM

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

FuncionarioViewModel

        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        @Html.HiddenFor(model => model.id)

            @Html.LabelFor(model => model.nome, htmlAttributes: new { @class = "control-label col-md-2" })

                @Html.EditorFor(model => model.nome, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.nome, "", new { @class = "text-danger" })

            @Html.LabelFor(model => model.dataNascimento, htmlAttributes: new { @class = "control-label col-md-2" })

                @Html.EditorFor(model => model.dataNascimento, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.dataNascimento, "", new { @class = "text-danger" })

            @Html.LabelFor(model => model.cpf, htmlAttributes: new { @class = "control-label col-md-2" })

                @Html.EditorFor(model => model.cpf, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.cpf, "", new { @class = "text-danger" })

            @Html.LabelFor(model => model.cidade, htmlAttributes: new { @class = "control-label col-md-2" })

                @Html.DropDownList("cidade", (SelectList)ViewBag.ViewCidade, "- Selecione a cidade -", new { @class = "form-control" })

                <input type="submit" value="Save" class="btn btn-default" />

}

    @Html.ActionLink("Voltar", "IndexVM")

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

e esse é a controller
public async Task<ActionResult> EditVM(int id)
        {
            GetCidadesAsync cidade = new GetCidadesAsync();
            var _cidade = await cidade.GetCidades();

            ViewBag.ViewCidade = new SelectList
            (
                _cidade,
                "id",
                "nome" ,
                id
            );

            return View();
        }

        // POST: FuncViewModel/Edit/5
        [HttpPost]
        public async Task<ActionResult> EditVM(int id, FuncionarioViewModel funcionario)
        {
            PutFuncionarioAsync putFuncionario = new PutFuncionarioAsync();

            try
            {
                await putFuncionario.PutFuncionarioVM(funcionario);

                return RedirectToAction("IndexVM");
            }
            catch
            {
                return View();
            }
        }

Answer: Faltou retornar o objeto para a View, seu código seria mais ou menos assim:
public async Task<ActionResult> EditVM(int id)
{
    GetFuncionarioAsync funcionario = new GetFuncionarioAsync();
    var _funcionario = await funcionario.GetFuncionario(id);

    GetCidadesAsync cidade = new GetCidadesAsync();
    var _cidade = await cidade.GetCidades();

    ViewBag.ViewCidade = new SelectList
    (
        _cidade,
        "id",
        "nome" ,
        id
    );

    return View(_funcionario);
}

Não sei se o nome dos objetos estão corretos, foi um palpite, talvez você tenha que ajustar


Error : Type 'struct a` does not provide a call operator

Question: I am writing the following code and creating an object of the struct CPuTimeState:
struct CpuTimeState
  {
    ///< Field for time spent in user mode
    int64_t CS_USER = {};
    ///< Field for time spent in user mode with low priority ("nice")
    int64_t CPU_TIME_STATES_NUM = 10;

    std::string cpu_label;

    auto sum() const {
      return CS_USER + CS_NICE + CS_SYSTEM + CS_IDLE + CS_IOWAIT + CS_IRQ + CS_SOFTIRQ + CS_STEAL;
    }
  } cpu_info_obj;  // struct CpuTimeState

i declared a vector of struct objects like :
std::vector<CpuTimeState> m_entries;

I want to call it in a function like this :
  {
    std::string line;
    const std::string cpu_string("cpu");
    const std::size_t cpu_string_len = cpu_string.size();
    while (std::getline(proc_stat_file, line)) {
      // cpu stats line found
      if (!line.compare(0, cpu_string_len, cpu_string)) {
        std::istringstream ss(line);

        // store entry
        m_entries.emplace_back(cpu_info_obj());
        cpu_info_obj &entry = m_entries.back();

        // read cpu label
        ss >> entry.cpu_label;

        // count the number of cpu cores
        if (entry.cpu_label.size() > cpu_string_len) {
          ++m_cpu_cores;
        }

        // read times
        //for (uint8_t i = 0U; i < CpuTimeState::CPU_TIME_STATES_NUM; ++i) {
          ss >> entry

        }
      }
    }

Its throwing this error on compilation : Type 'struct CpuTimeState does not provide a call operator.
Answer: On the line
m_entries.emplace_back(cpu_info_obj());

cpu_info_obj is a variable, not a type.  You are trying to invoke an operator() on a variable that does not implement that operator.  That is what the compiler is complaining about.
To construct a new instance of your struct, you need to call the struct's constructor instead:
m_entries.emplace_back(CpuTimeState());

However, by passing in an argument, you are telling emplace_back() to invoke the struct's copy constructor.  A better option is to simply omit the argument altogether and let emplace_back() invoke the struct's default constructor for you:
m_entries.emplace_back();


Interpretation of two glm model summaries

Question: I am using the Titanic dataset to understand glm model. These are the two models,
titanic.glm       <- glm(survived ~ pclass,         family=binomial, data=titanic.train)
titanic.glm.title <- glm(survived ~ pclass + title, family=binomial, data=titanic.train)

I have two summaries. Since it has categorical variables, I am not able to interpret it properly and compare it. Can anybody help me in comparing both the models and find out which one is better? following is the summaries of both the models,
> summary(titanic.glm)

Call:
glm(formula = survived ~ pclass, family = binomial, data = titanic.train)

Deviance Residuals:
    Min       1Q   Median       3Q      Max
-1.3652  -0.7779  -0.7779   1.0006   1.6388

Coefficients:
            Estimate Std. Error z value Pr(>|z|)
(Intercept)   0.4313     0.1272   3.391 0.000696 ***
pclass2      -0.7086     0.1852  -3.826 0.000130 ***
pclass3      -1.4715     0.1593  -9.237  < 2e-16 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

(Dispersion parameter for binomial family taken to be 1)

    Null deviance: 1393.6  on 1046  degrees of freedom
Residual deviance: 1301.5  on 1044  degrees of freedom
AIC: 1307.5

Number of Fisher Scoring iterations: 4

> summary(titanic.glm.title)

Call:
glm(formula = survived ~ pclass + title, family = binomial, data = titanic.train)

Deviance Residuals:
    Min       1Q   Median       3Q      Max
-2.2066  -0.6462  -0.4263   0.6521   2.2106

Coefficients:
             Estimate Std. Error z value Pr(>|z|)
(Intercept)    1.5336     0.3356   4.570 4.88e-06 ***
pclass2       -0.9028     0.2259  -3.997 6.41e-05 ***
pclass3       -1.7950     0.2037  -8.814  < 2e-16 ***
titleMiss      0.4701     0.3207   1.466 0.142706
titleMr.      -2.0911     0.3131  -6.679 2.40e-11 ***
titleMrs.      0.8092     0.3507   2.308 0.021011 *
titleNothing  -1.7024     0.5157  -3.301 0.000964 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

(Dispersion parameter for binomial family taken to be 1)

    Null deviance: 1393.58  on 1046  degrees of freedom
Residual deviance:  990.66  on 1040  degrees of freedom
AIC: 1004.7

Number of Fisher Scoring iterations: 4

I tried the following,
anova(titanic.glm,titanic.glm.title, test = "Chisq")

Analysis of Deviance Table

Model 1: survived ~ pclass
Model 2: survived ~ pclass + title
  Resid. Df Resid. Dev Df Deviance  Pr(>Chi)
1      1044    1301.47
2      1040     990.66  4   310.81 < 2.2e-16 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

I am not able to compare both the models. I read somewhere AIC is one of the parameter to compare it. Can anybody help in comparing both the models and decide which one is better? Also how can we find whether a particular model is stable or not?
Answer: Your models are nested; the former model differs from the latter only by lacking a term (title). Thus, it is possible and appropriate to test them against each other.  (That is what your anova() call did.) The nested model test is a test of the variable that differs between the two models.  That is, the test is telling you that title is significant.
Comment: I am not sure what to infer from the anova model. Can you please let me know what to infer from that?
Comment: @haimen, you can infer that title is significant. And by extension, that the latter model is better.


Heat Equation identity with dirichlet boundary condition

Question: Show an energy identity for the heat equation with convection and Dirichlet boundary condition.
$$u_t -ku_{xx}+Vu_x=0 \qquad 0<x<1, t>0$$
$$u(0,t) = u(1,t)=0 \qquad t>0$$
$$u(x,0) = \phi(x) \qquad 0<x<1$$
Attempt: I think I can apply maximum principle, but dont know how to approach it.
Thanks!!
Comment: You can use separation of variables techniques.
Answer: You can use the separation of variables techniques, but you should pay more attention about choosing the suitable separation parameter.
Let $u(x,t)=X(x)T(t)$ ,
Then $X(x)T'(t)-kX''(x)T(t)+VX'(x)T(t)=0$
$X(x)T'(t)=kX''(x)T(t)-VX'(x)T(t)$
$X(x)T'(t)=(kX''(x)-VX'(x))T(t)$
$\dfrac{T'(t)}{T(t)}=\dfrac{kX''(x)-VX'(x)}{X(x)}=-\dfrac{4k^2n^2\pi^2+V^2}{4k}$
$\begin{cases}\dfrac{T'(t)}{T(t)}=-\dfrac{4k^2n^2\pi^2+V^2}{4k}\\kX''(x)-VX'(x)+\dfrac{4k^2n^2\pi^2+V^2}{4k}X(x)=0\end{cases}$
$\begin{cases}T(t)=c_3(s)e^{-\frac{t(4k^2n^2\pi^2+V^2)}{4k}}\\X(x)=\begin{cases}c_1(s)e^{\frac{Vx}{2k}}\sin n\pi x+c_2(s)e^{\frac{Vx}{2k}}\cos n\pi x&\text{when}~n\neq0\\c_1xe^{\frac{Vx}{2k}}+c_2e^{\frac{Vx}{2k}}&\text{when}~n=0\end{cases}\end{cases}$
$\therefore u(x,t)=C_1xe^{\frac{2Vx-V^2t}{4k}}+C_2e^{\frac{2Vx-V^2t}{4k}}+\sum\limits_{n=0}^\infty C_3(n)e^{\frac{2Vx-t(4k^2n^2\pi^2+V^2)}{4k}}\sin n\pi x+\sum\limits_{n=0}^\infty C_4(n)e^{\frac{2Vx-t(4k^2n^2\pi^2+V^2)}{4k}}\cos n\pi x$
$u(0,t)=0$ :
$C_2e^{-\frac{V^2t}{4k}}+\sum\limits_{n=0}^\infty C_4(n)e^{-\frac{t(4k^2n^2\pi^2+V^2)}{4k}}=0$
$\sum\limits_{n=0}^\infty C_4(n)e^{-\frac{t(4k^2n^2\pi^2+V^2)}{4k}}=-C_2e^{-\frac{V^2t}{4k}}$
$\sum\limits_{n=0}^\infty C_4(n)e^{-kn^2\pi^2t}=-C_2$
$C_4(n)=\begin{cases}-C_2&\text{when}~n=0\\0&\text{otherwise}\end{cases}$
$\therefore u(x,t)=C_1xe^{\frac{2Vx-V^2t}{4k}}+C_2e^{\frac{2Vx-V^2t}{4k}}+\sum\limits_{n=0}^\infty C_3(n)e^{\frac{2Vx-t(4k^2n^2\pi^2+V^2)}{4k}}\sin n\pi x-C_2e^{\frac{2Vx-V^2t}{4k}}=C_1xe^{\frac{2Vx-V^2t}{4k}}+\sum\limits_{n=1}^\infty C_3(n)e^{\frac{2Vx-t(4k^2n^2\pi^2+V^2)}{4k}}\sin n\pi x$
$u(1,t)=0$ :
$C_1e^{\frac{2V-V^2t}{4k}}=0$
$C_1=0$
$\therefore u(x,t)=\sum\limits_{n=1}^\infty C_3(n)e^{\frac{2Vx-t(4k^2n^2\pi^2+V^2)}{4k}}\sin n\pi x$
$u(x,0)=\phi(x)$ :
$\sum\limits_{n=1}^\infty C_3(n)e^{\frac{Vx}{2k}}\sin n\pi x=\phi(x)$
$\sum\limits_{n=1}^\infty C_3(n)\sin n\pi x=\phi(x)e^{-\frac{Vx}{2k}}$
$C_3(n)=2\int_0^1\phi(x)e^{-\frac{Vx}{2k}}\sin n\pi x~dx$
$\therefore u(x,t)=2\sum\limits_{n=1}^\infty\int_0^1\phi(x)e^{-\frac{Vx}{2k}}\sin n\pi x~dx~e^{\frac{2Vx-t(4k^2n^2\pi^2+V^2)}{4k}}\sin n\pi x$
Answer: You can use the separation of variables techniques. Basically, we assume the solution to have the form

$$ u(x,t)= X(x)F(t), $$

and subs back in the pde to get the following ode's

$$ X'' \left( x \right) = \frac{V }{k} X'\left( x \right)+\frac{\lambda}{k} X(x),\quad F'(t)=\lambda F(t).  $$

Now, you can follow the technique in this problem.


Counterexample about composition of function

Question: Problem :
Assume that two functions $f(x), g(x)$ are differentiable function.
(And, no one of them has interval which makes them constant function.)
And consider a function $f(x)$ has local maxima(or local minima) at $x=a$.
Then $f(g(x))$ also at $g(x)=a$?

I saw a function which as oscillation property works well for counterexample about increasing/decreasing and local maximum, minimum.
And, It also works if I switch the problem for 'if $g$ has local max, $f(g)$ also?'
The counterexample for switched problem is :
$$f(x)=x^2\left(1+ \sin\left(\frac{1}{x}\right)\right),\quad f(0)=0 \\
g(x)=x^2$$
Then we know $g$ has local minimum at $x = 0$ but $f(g(x))$ isn't.
So, I wonder how can I find a counterexample about the original problem?
Or, I want to know the proof about original problem if that's true.
Thanks for help.
Comment: $f(x)=x^2, g(x)=x, a=0$.
Answer: When $f(x)$ has a local maximum at $x=a$, it means that you can choose $r>0$ so that $f(a)\geq f(x)$ whenever $x\in(a-r,a+r)$.
Suppose $g(c)=a$. Because $g$ is continuous, there is some $\delta>0$ such that $g(x)\in(a-r,a+r)$ whenever $x\in(c-\delta,c+\delta)$.
Therefore, for such $\delta$ and for $x\in(c-\delta,c+\delta)$, you have $f(a)\geq f(g(x))$.
So $f(g(x))$ has a local maximum at $x=c$.
Comment: Should I use inverted inequality for local minimum case, right?
Comment: yes that is correct


$aH=Ha$ implies $a$ commutes with every element in H

Question: I was trying to prove this question:

Let $G$ be a group and $H \le G$. Let $a,b \in G$. Now, if $aH=Ha$ and
  $bH=Hb$, then show that $(ab)H=H(ab)$.

It appears to me that if I can show that $a,b$ commutes with every element of $H$, then it is quite easy to show $(ab)H=H(ba)$.
However, how do I prove that $aH=Ha$ implies $a$ commutes with every element in $H$? Suppose $x\in H$ be arbitrary. Then $ax \in aH$ and $xa \in Ha$. Also by their equality, it follows that $xa \in aH$ and $ax \in Ha$. But does it necessarily mean $ax=xa$ in any of the cosets?
Comment: Let $G$ be non-Abelian and $H=G$...
Comment: If $a$ and $b$ were commuting with any elements of $H$ it would be true that $abH=Hab$ however you cannot prove that $aH=Ha$ implies $a$ commutes with every element in $H$ because the implication is false. Actually the proof is simple, I begin $(ab)H=a(bH)=a(Hb)=$...
Comment: @ClémentGuérin Thanks, I got confused because of this page: http://www.math.wisc.edu/~mstemper2/Math/Pinter/Chapter13E . He claims the above but doesn't prove it.
Comment: You are welcome, it is quite common for people knowing well the theory to be a little too quick in their argumentation when doing such fundamental material. My professor used to say "it is not a mistake from me, it is just to see if you are following!" The point is that by doing again the proof and realizing that there is a mistake you end up learning much more than with a correct proof.
Answer: No, it doesn't mean that. Given any $h_1\in H $, there exists  $h_2\in H $ such that $bh_1=h_2b $. There exists  $h_3\in H $ such such that  $ah_2=h_3a $. Then  $$abh_1=ah_2b=h_3ab. $$ As you can also do this backwards, you get  $abH=Hab $.
Answer: We don't have $a$ commutes with every elements of $H$. But, we have the following statement:
If $A,B,C$ are subsets of a group $G$, then $(AB)C=A(BC)$. Here, $AB = \{ ab \in G| a \in A, b \in B \}$.(This fact is easy to prove by proving they have same elements form $abc$)
So,we have $(ab)H = a(bH)$(as above) $= a(Hb) = (aH)b = (Ha)b = H(ab)$ (use above statement twice.)


Dígitos em uma string java

Question: Como faço para descobrir quantos dígitos tem uma String em java ?
Por exemplo, usuário entrou com "exemplo123", a string tem 3 dígitos.
Estou usando esta função mas não está funcionando:
private static int digitos(String text) {
        char[] digitos = new char[9];
        int digitosTotal = 0;
        for (int i = 0; i != 9; i++) {
            digitos[i] = (char) i;
        }
        for (int i = 0; i < digitos.length; i++) {
            if (text.indexOf(digitos[i]) != -1) {
                digitosTotal++;
            }
        }
        return digitosTotal;
    }

Answer: Pode descobrir quantos dígitos existem na string pode iterar ela e comparar o código ascii de cada elemento, caso ele esteja na faixa de 48 e 57 é um número.
Exemplo - ideone
Wikipedia - tabela ascii
import java.util.*;
import java.lang.*;
import java.io.*;

class Ideone
{
    public static void main (String[] args) throws java.lang.Exception
    {
        String text = "Digito123";

        char[] digitos = new char[9];
        int digitosTotal = 0;

        for(char caracter : text.toCharArray()){
            int asciiCode = (int)caracter;
            if(asciiCode >= 48 &&  asciiCode <= 57) digitosTotal++;
        }

        System.out.print(digitosTotal);
    }
}

Comment: Dá pra trocar `48` por `'0'` e `57` por `'9'`.
Comment: https://www.cs.cornell.edu/andru/javaspec/3.doc.html
Comment: @Piovezan legal :D não sabia disso.
Comment: @Piovezan quando vc faz `if(asciiCode >= '0') ..` o `'0'` é convertido para automáticamente para 48, seria isso?
Comment: Eu não sei em que passo o Java faz isso, acho que é na análise léxica. Mas o caracter que estiver entre as aspas simples é convertido para seu valor Unicode (se não estou enganado). Também dá para entrar códigos \u0048 por exemplo mas eu não estou acostumado a usá-los.
Comment: @rray, um caracter em Java é um tipo numérico. Então, '0' é considerado o caracter 0, que tem valor 0x30
Answer: Utilizando o método isDigit da classe Character     exemplo - ideone
import java.util.*;
import java.lang.*;
import java.io.*;

class Ideone
{
    public static void main (String[] args) throws java.lang.Exception
    {

        String text = "Digito123";

        int count = 0;
        for (int i = 0, len = text.length(); i < len; i++) {
          if (Character.isDigit(text.charAt(i))) {
           count++;
          }
        }

        System.out.print(count);

    }
}

O método charAt mostra-se mais rápido (Success #stdin #stdout 0.04s 4386816KB) do que o método toCharArray (Success #stdin #stdout 0.06s 2841600KB)
Answer: String str = "123123asdasdas" ;
String aux = str;
aux = aux .replaceAll("\\D+","");
System.out.println("Quantidade de dígitos: " + aux .length());

Comment: Não quero deletar, quero saber quantos dígitos tem
Comment: Editado meu caro, não tinha necessidade de dar um negativo.
Comment: Estava procurando por exatamente essa resposta para dar um +1! Seu uso de expressões é admirável
Answer: Pode utilizar expressão regular para contar o número de dígitos e para extraí-los do texto, caso for necessário:
import java.util.*;
import java.util.regex.*;

class Main {

  public static void main(String[] args) {

    // Total de dígitos:
    int count = 0;

    // Lista de dígitos:
    List<Integer> digits = new ArrayList<Integer>();

    // Expressão regular para obter um dígito:
    Pattern p = Pattern.compile("\\d");

    // Texto a ser analisado:
    Matcher m = p.matcher("exemplo123");

    // Conta quantos dígitos há no texto:
    while (m.find())
    {
      // Incrementa a quantidade de dígitos:
      count++;

      // Insere o dígito na lista:
      digits.add(new Integer(m.group()));
    }

    // Exibe o total:
    System.out.println(count);

    // Exibe a lista de dígitos:
    System.out.println(digits);

  }

}

Veja funcionando no Ideone.

A saída do código é:
3
[1, 2, 3]

Onde 3 indica a quantidade de dígitos e [1, 2, 3] a lista dos mesmos.
Answer: public static int contaDigitos(String arg) {
    int nums = 0;
    for(char ch : arg.toCharArray()){
        if(Character.isDigit(ch)) nums++;
    }
    return nums;
}

Dígitos em uma string java