Wrong codecvt result in ViualStudio 2010

Question: The following code prints "failed" to console:
<code>#include "stdafx.h"
#include <locale>
#include <memory>
#include <string>
#include <cstring>
#include <iostream>

int main(int argc, char* argv[])
{
    typedef std::codecvt<wchar_t, char, mbstate_t> cvt;

    // string to convert
    const char cstr[] = "тест";
    size_t sz = std::strlen(cstr);

    mbstate_t state;
    const char *cnext;
    wchar_t *wnext;

    // buffer to write
    wchar_t *buffer = new wchar_t[sz + 1];
    std::uninitialized_fill(buffer, buffer + sz + 1, 0);

    // converting char* to wchar*, using locale
    cvt::result res;
    std::locale l(std::locale("Russian_Russia.1251"));
    res = std::use_facet<cvt>(l).in(state,
                                    cstr, cstr + sz, cnext,
                                    buffer, buffer + sz + 1, wnext);

    if(res == cvt::error)
        std::wcout << L"failed" << std::endl;
    else
        std::wcout << buffer << std::wcout;
    delete [] buffer;
    return 0;
}
</code>
I looked into sources and found out that function in() fails because function _Mbrtowc (wmbtowc.c) returns -1:
<code>        if (___mb_cur_max_l_func(locale) <= 1 ||
            (MultiByteToWideChar(codepage,
                                 MB_PRECOMPOSED|MB_ERR_INVALID_CHARS,
                                 (char *)pst,
                                 2,
                                 pwc,
                                 (pwc) ? 1 : 0) == 0))
        {   /* translation failed */
            *pst = 0;
            errno = EILSEQ;
            return -1;
        }
</code>
because ___mb_cur_max_l_func() (initctyp.c) returns 1 for Russian_Russa.1251 locale. What it means? I think it is not normal, that codecvt can't convert char* into wchar_t*.
Answer: <code> mbstate_t state;
</code>
You forgot to initialize that.  Fix:
<code> mbstate_t state = { 0 };
</code>


How to play a movie on iOS

Question: So I created a view that has a button in it that will play the movie.
Here is the action for that button:
<code>- (IBAction)playMovie {

    NSBundle *bundle = [NSBundle mainBundle];
    NSString *moviePath = [bundle pathForResource:@"sample_iPod" ofType:@"m4v"];
    NSURL *movieURL = [NSURL fileURLWithPath:moviePath];
    MPMoviePlayerController *theMovie = [[MPMoviePlayerController alloc] initWithContentURL:movieURL];
    theMovie.scalingMode = MPMovieScalingModeAspectFill;
    [theMovie play];
}
</code>
However when I test the App and try to play the video the screen stays blank and in the log it shows this:
[Switching to process 9333 thread 0x13c03]
Any Idea what's up?
Thanks
Answer: You need to set the bounds of the player, and add the player's view to self.view:
<code> [theMovie.view setFrame: self.view.bounds];  // player's frame must match parent's
 [self.view addSubview: theMovie.view];
</code>
Comment: where is myView initialized? I'm getting "use of undeclared identifier, myView" I tried the class name of the .m file but that didn't work either.
Comment: sorry, quick cut 'n paste error.  You need to add theMovie view to the view of whatever view controller you're in, namely `self.view`
Comment: That kind of works except for the Controls for the video don't work, so they can't click done on the video and go back to the previous screen.  Any idea how to get that to work?
Comment: Hmmm, your original post was about getting the view to show up, which is now happening.  I will make one suggestion here, but if it doesn't work, please accept this answer and open a new question.  Try changing the scalingMode to MPMovieScalingModeNone;

How to play a movie on iOS


Ubuntu dpkg broken

Question: I have an Ubuntu installation where /var/lib/dpkg  is empty. Every apt-get command fails with this error :
E: Impossible de verrouiller /var/lib/dpkg/status - open (2: Aucun fichier ou dossier de ce type)

(can not lock /var/lib/dpkg/status)

Which is not unexpected as the folder is empty.
How can I totally uninstall and reinstall dpkg?
Comment: Please run `LANG=C apt-get update` and update your question with the error message in a locale everybody here can read.
Answer: You don't need to reinstall dpkg, what you need to do is to recover the database of package selections.
This is a use case where a backup might be useful.
If you don't have backups, you can try to copy an old status file from var/backups/dpkg.status.* to the original location in /var/lib/dpkg and run
# apt-get clean && apt-get update

If you can't recover an old status file, you can still try to rebuild one:
# ls /usr/share/doc | grep -Ev '([A-Z]|^texmf$|^debian$)' | awk '{print $1 " install"}' | dpkg --set-selections
# dselect --expert

Ubuntu dpkg broken


How can I create an option element using javascript and set it's value

Question: const currencies = [
  {
    id: 'USD', name: 'US Dollars'
  }, {
    id: 'UGX', name: 'Ugandan Shillings'
  }, {
    id: 'KES', name: 'Kenyan Shillings'
  }, {
    id: 'GHS', name: 'Ghanian Cedi'
  }, {
    id: 'ZAR', name: 'South African Rand'
  }
];

I have an issue with my code. I want to create an option element using javascript. I have done something like this below. What is my issue?
I want each item in the currencies arrays to populate into populateCurrencies function. And it should also create an option element. And also set it's value to the item id.
const populateCurrencies = () => {

            var ans = document.getElementById('USD').value;
}

Comment: what's the output you want ?
Comment: I want when users click an option and the value of  what the user selected should show in the browser.
Comment: Possible duplicate of [JavaScript - populate drop down list with array](https://stackoverflow.com/questions/9895082/javascript-populate-drop-down-list-with-array) and [Filling out Combobox Using JSON value](https://stackoverflow.com/questions/19560054)
Answer: it has to do with DOM manipulation;
currencies.forEach((x)=>{
let selectElt = document.querySelector('.select-text');
let newElt = document.createElement('option');
let newText = document.createTextNode(x.name);
newElt.setAttribute('value', 'x.id');
newElt.appendChild(newText);
selectElt.appendChild(newElt);
})


Print leading zeros with C++ output operator?

Question: How can I format my output in C++? In other words, what is the C++ equivalent to the use of printf like this:
printf("%05d", zipCode);

I know I could just use printf in C++, but I would prefer the output operator <<.
Would you just use the following?
std::cout << "ZIP code: " << sprintf("%05d", zipCode) << std::endl;

Answer: This will do the trick, at least for non-negative numbers(a) such as the ZIP codes(b) mentioned in your question.
#include <iostream>
#include <iomanip>

using namespace std;
cout << setw(5) << setfill('0') << zipCode << endl;

// or use this if you don't like 'using namespace std;'
std::cout << std::setw(5) << std::setfill('0') << zipCode << std::endl;

The most common IO manipulators that control padding are:

std::setw(width) sets the width of the field.
std::setfill(fillchar) sets the fill character.
std::setiosflags(align) sets the alignment, where align is ios::left or ios::right.

And just on your preference for using <<, I'd strongly suggest you look into the fmt library (see https://github.com/fmtlib/fmt). This has been a great addition to our toolkit for formatting stuff and is much nicer than massively length stream pipelines, allowing you to do things like:
cout << fmt::format("{:05d}", zipCode);

And it's currently being targeted by LEWG toward C++20 as well, meaning it will hopefully be a base part of the language at that point (or almost certainly later if it doesn't quite sneak in).

(a) If you do need to handle negative numbers, you can use std::internal as follows:
cout << internal << setw(5) << setfill('0') << zipCode << endl;

This places the fill character between the sign and the magnitude.

(b) This ("all ZIP codes are non-negative") is an assumption on my part but a reasonably safe one, I'd warrant :-)
Comment: Note that you can also just use `cout << left` or `cout << right` for alignment.
Comment: @Nadav, do you live in an area that has negative ZIP codes? :-) On a more serious note, I'll edit the answer to make that clear.
Comment: Thanks. I actually found your answer looking for a general solution for any integer, including negatives, found your nice highly-ranked answer and I didn't realize that because zip codes were mentioned, the answer assumed the integer was positive. Thanks for editing the answer, it will probably help more people in the future.
Comment: Note that this solution does NOT work correctly for negative numbers! Trying to print "-5" this way results in: "000-5"
Comment: Adding std::internal will make this code correct for negative numbers.
Answer: In C++20 you can do:
std::cout << std::format("{:05}", zipCode);

On older systems you can use the {fmt} library, std::format is based on.
Disclaimer: I'm the author of {fmt} and C++20 std::format.
Comment: More info at: https://stackoverflow.com/questions/2342162/stdstring-formatting-like-sprintf/57286312#57286312
Answer: Use the setw and setfill calls:
std::cout << std::setw(5) << std::setfill('0') << zipCode << std::endl;

Comment: I think this answer should mention that, unlike the setting from `std::setw`, the setting of `std::setfill` will stick after the output is performed, in other words the fill character for `std::cout` will be permanently changed (until modified by another `std::setfill`). As it is unlikely this is desirable, it would seem best to save and restore the previous fill character.
Comment: Re-activated and +1'ed since it shows how to do it in any namespace (also added setfill, sqook, hope you don't mind).
Comment: Fair enough.  "using namespace std;" is definitely evil. ;)
Answer: cout << setw(4) << setfill('0') << n << endl;

from:
http://www.fredosaurus.com/notes-cpp/io/omanipulators.html
Answer: or,
char t[32];
sprintf_s(t, "%05d", 1);

will output 00001 as the OP already wanted to do
Comment: The OP explicitly asked for a way that uses the `<<` operator instead of (s)printf.
Comment: @jankes that would be :  std::cout << "ZIP code: " <<sprintf_s(t, "%05d", 1)<< endl;
Answer: Simple answer but it works!
ostream &operator<<(ostream &os, const Clock &c){
// format the output - if single digit, then needs to be padded with a 0
int hours = c.getHour();

// if hour is 1 digit, then pad with a 0, otherwise just print the hour
(hours < 10) ? os << '0' << hours : os << hours;

return os; // return the stream
}

I'm using a ternary operator but it can be translated into an if/else statement as follows
if(c.hour < 10){
 os << '0' << hours;
}
 else{
  os  << hours;
 }


Mapping substr of dataframe to new column

Question: I would like to map the first/second characters of the column ï..Order.Date to a new column called Order.Month.
ï..Order.Date is a column in the data frame with string dates in M/D/YY or MM/DD/YY format:
"12/1/17" "9/1/17" "9/19/17" "9/1/17" "9/29/17"

I need to create a new column which uses the substring containing the first 1 or 2 characters, and map it to the month:
months = c('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December')

Still new to r and not sure the best way to approach this.
Answer: We can convert the column to Date class, get the month extracted, convert to numeric and use as index to get the value that corresponds to from the built-in vector month.name
df1$Order.Month <- month.name[as.integer(format(as.Date(df1[["ï..Order.Date"]],
        format =  "%m/%d/%y"), "%m"))]

Or use lubridate - convert to Date class with mdy, extract the month, use as index in month.name
library(lubridate)
month.name[month(mdy(df1[["ï..Order.Date"]]))]

Comment: @Joeyboy that was just a guess.   I updated with the actual column name.  it is just that there are some unusual characters in the name, that I was not sure whether it is a typo or not
Comment: Works perfectly +10 for speedy reply. How did you know Order.Date was the first column in my DataFrame? Was it because of the prefix?
Answer: Once you create a date object you can use format(..., '%B') to get the month name.
x <- c("12/1/17", "9/1/17", "9/19/17", "9/1/17", "9/29/17")
format(lubridate::mdy(x), '%B')

#[1] "December"  "September" "September" "September" "September"


B-Spline how to create control points for a curve to pass through knot values

Question: I want to create a b-spline curve that will pass through all the (knot) points I give it. How do I construct it? Do I need to find the control points for that curve? And if so - how?
Comment: Is the knot vector fixed in advance, and if yes what knots are used? Also please add an example of 'knot' points
Answer: Follows a MATHEMATICA script showing how to construct a special spline type. (Bézier curves) In the script $BL, BQ,BC$ are Bézier curves of first, (linear), second (quadratic) and third (cubic) order and also how them are recursively built. The points $p_1,p_2,p_2,p_4$ can be considered as control points. By properly positioning these control points, we can cause the curve to pass through determined points
$$
\begin{array}{l}
{\text{BL}[\text{p0$\_$},\text{p1$\_$},\text{t$\_$}]\text{:=}(1-t)\text{p0}+t \text{p1}}\\
{\text{BQ}[\text{p0$\_$},\text{p1$\_$},\text{p2$\_$},\text{t$\_$}]\text{:=}(1-t)\text{BL}[\text{p0},\text{p1},t]+t \text{BL}[\text{p1},\text{p2},t]}\\{\text{BC}[\text{p0$\_$},\text{p1$\_$},\text{p2$\_$},\text{p3$\_$},\text{t$\_$}]\text{:=}(1-t)\text{BQ}[\text{p0},\text{p1},\text{p2},t]+t \text{BQ}[\text{p1},\text{p2},\text{p3},t]}
\end{array}
$$
$$
\begin{array}{l}
{p_1=\{0,0\};}\\
{p_2=\{1,1\};}\\
{p_3=\{-1,2\};}\\
{p_4=\{-2,0\};}\\
{\text{gr1}=\text{ParametricPlot}\left[\text{BC}\left[p_1,p_2,p_3,p_4,t\right],\{t,0,1\},\text{PlotStyle}\to \{\text{Blue},\text{Thick}\}\right];}\\
{\text{grp}=\text{Table}\left[\text{Graphics}\left[\left\{\text{Red},\text{Disk}\left[p_k,0.05\right]\right\}\right],\{k,1,4\}\right];}\\
{\text{grl}=\text{ListLinePlot}\left[\left\{p_1,p_2,p_3,p_4\right\},\text{PlotStyle}\to \{\text{Dashed}, \text{Red}\}\right];}\\
{\text{Show}[\text{gr1},\text{grp},\text{grl},\text{PlotRange}\to \text{All}]}
\end{array}
$$
Attached a plot for this setup
Answer: Suppose that your knot points (not to be confused with the B-spline knots!) are ordered in a sequence $(x_1, \dots, x_m)$. Then you can compute a B-spline of order $n$ between each ordered pair $(x_i, x_{i+1})$. You can adjust $n$ in order to set the B-spline regularity.
Comment: can you maybe show an example? say I have (x1,y1) (x2,y2) and (x3,y3). How do I construct a B-spline that passes through all these points ?
Comment: I am also curious about the answer to Maverick Meerkat's comment


Possible to detect the decibel level on the sound card?

Question: My main goal is to change the volume on one sound card based on the decibel level of the audio  on another sound card (both on the same computer). Is it possible to detect the DB level?
PS: I am writing this in C#
Answer: This is possible, but not easy.  The decibell sound pressure level (SPL) is going to depend on your speakers, external amplifiers, and microphones as much as the soundcard.  Converting from the numbers that you give your sound card (in a wav file, for example) to dB SPL is almost entirely a question of how well you can calibrate your entire system.  The problem is that the calibration requires special equipment, most notably a sound level meter; and if you don't have one of these, I don't know of any way to estimate the values you would need to know.
(This assumes that what you mean by decibells is the sound pressure level, which is often measured in dB.  dB, though, is just a particular formulation of a logarithmic scale, so many different things can be reported in dB.)
Comment: Not only that but you need to know the amplification on your output as well.  Remember that many external sound devices have their own volume control!


Applying a Scale AffineTransform to a UIView changes its center

Question: I'm running this code to shrink a UIView when the user taps on its superview. However, when applying the CGAffineTransformScale(), it also changes the centre. Is that the expected behaviour?
<code>-(void) onTap:(UITapGestureRecognizer *)tap{

    [UIView animateWithDuration:1.2
                          delay:0
                        options:0
                     animations:^{
                         CGAffineTransform transform = self.icon.transform;
                         NSLog(@"Previous center: %@", NSStringFromCGPoint(self.icon.center));

                         self.icon.transform = CGAffineTransformScale(transform, 0.5, 0.5);

                         NSLog(@"Next center: %@", NSStringFromCGPoint(self.icon.center));
                     } completion:^(BOOL finished) {
                         //
                     }];

}
</code>
Comment: The center of the view is moved down and to the left
Comment: Would you mind editing the code to output the Bounds and center before the animateWithDuration call and in the completion:^ block? And add the actual NSLog output? I use MonoTouch and I did not see this behavior. The center stayed in place and the view scaled about the center point.
Answer: I finally found out what was going on: Autolayout was repositioning the subview and changing the center.
Comment: I've written a little essay on this problem and some possible solutions: http://stackoverflow.com/questions/12943107/how-do-i-adjust-the-anchor-point-of-a-calayer-when-auto-layout-is-being-used/14105757#14105757
Comment: I'm not using Autolayout and still have the same outcome.
Answer: I tested with this code in the ViewController using ObjC:
<code>- (void)viewDidLoad
{
    [super viewDidLoad];

    // Create a subview
    CGRect bounds = CGRectMake(10, 10, 100, 100);
    UIView* v = [[UIView alloc] initWithFrame: bounds];
    [v setBackgroundColor:[UIColor yellowColor]];
    [self.view addSubview:v];

    icon = v;
}
</code>
And kicked off an animation in viewDidAppear:
<code>- (void)viewDidAppear:(BOOL)animated
{
    NSLog(@"Previous center: %@", NSStringFromCGPoint(self.icon.center));

    [UIView animateWithDuration:1.2
          delay:1.0
        options:0
     animations:^{
         NSLog(@"Before center: %@", NSStringFromCGPoint(self.icon.center));

         CGAffineTransform transform = self.icon.transform;
         self.icon.transform = CGAffineTransformScale(transform, 0.5, 0.5);

         NSLog(@"After center: %@", NSStringFromCGPoint(self.icon.center));
     }
     completion:^(BOOL finished){
         // nothing
         NSLog(@"Completion center: %@", NSStringFromCGPoint(self.icon.center));
     }];
}
</code>
And the center was the same in every call (60,60):
<code>2012-09-24 10:22:11.776 ScaleView[19611:f803] Previous center: {60, 60}
2012-09-24 10:22:11.778 ScaleView[19611:f803] Before center: {60, 60}
2012-09-24 10:22:11.779 ScaleView[19611:f803] After center: {60, 60}
2012-09-24 10:22:13.979 ScaleView[19611:f803] Completion center: {60, 60}
</code>
So I would say no, that's not the expected behavior.


activeadmin and acts_as_taggable_on generates ambiguous_column_name error

Question: I am using active_admin and acts_As_taggable_on and I am trying to make a filter.  Here is the model code:
class Person < ApplicationRecord
    acts_as_taggable_on :expertise, :industry
end

Here is the filter:
filter :industry, as: :select, collection: Person.industry_counts.pluck(:name, :name)

and here is the error i get when submitting the filter:
SQLite3::SQLException: ambiguous column name: created_at: SELECT COUNT(DISTINCT "people"."id") FROM "people" LEFT OUTER JOIN "taggings" ON "taggings"."taggable_id" = "people"."id" AND "taggings"."context" = ? AND "taggings"."taggable_type" = ? WHERE "taggings"."tag_id" = 0 AND (created_at > '2017-01-17 00:22:53.923894')

How do I fix this?
Comment: the problem is the `created_at > '2017-01-17 00:22:53.923894'`

`created_at` exists on both `taggings` and `people`
Comment: can you post the code where the call to that is made? seems like something is missing
Answer: It turns out active_admin uses the ransack gem to handle it's filters.  I had to make custom "ransackers" in the model to make this work:
def self.in_industry(industries)
  Person.tagged_with(industries, :any => true, :on => :industry).select{|a| a} #use select to convert relation to array
end

ransacker :by_industry, formatter: proc{ |v|
  data = Person.in_industry(v).map(&:id)
  data = data.present? ? data : nil
} do |parent|
  parent.table[:id]
end

I got this from the following article and the corrections made in the comments:
http://nikhgupta.com/code/activeadmin/custom-filters-using-ransacker-in-activeadmin-interfaces/


Using Asynctask to check if Internet is Accessible

Question: I have this Class to check if Internet is accessible:
public class NetworkAvailability extends AsyncTask<Context, Boolean, Boolean> {

Context mContext;

private static boolean isNetworkAvailable() {
    ConnectivityManager connectivityManager = (ConnectivityManager) ListViewActivity.getAppContext().getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
    if (activeNetworkInfo != null && activeNetworkInfo.isConnectedOrConnecting()) {
        Log.i("Netzwerkstatus: ", "Netzwerk-Verbindung verfügbar");
        return true;
    }
    return false;

}

public NetworkAvailability(Context mContext) {
    this.mContext = mContext;
}

public NetworkAvailability() {
}

@Override
protected Boolean doInBackground(Context... params) {
    if (isNetworkAvailable()) {
        try {
            HttpURLConnection urlc = (HttpURLConnection) (new URL("http://www.google.de").openConnection());
            urlc.setRequestProperty("User-Agent", "Test");
            urlc.setRequestProperty("Connection", "close");
            urlc.setConnectTimeout(1500);
            try {
                urlc.connect();
            } catch (IOException e) {
                e.printStackTrace();
            }
            //i ist 200 bei Internetverbindung
            int i = urlc.getResponseCode();
            return (i == 200);
        } catch (IOException e) {
            Log.e("IsInternetAccessible: ", "Konnte Internetverbindung nicht prüfen");
        }
    } else {
        Log.d("IsInternetAccessible:", "Internet nicht verfügbar");
    }
    return false;
}

Now i want to check if internet is accessible BEFORE parsing a xml.
Here is the snippet where i want to use this class.
if (networkAvailability.execute()) {
            XMLParser parser = new XMLParser();
            String xml = parser.getXMLFromUrl("http://XXXXXX.de/XX.xml");
            Document doc = parser.getDomElement(xml);

            NodeList nl = doc.getElementsByTagName(KEY_SYSTEM);

            for (int i = 0; i < nl.getLength(); i++) {

                // Neue HashMap erstellen
                HashMap<String, String> map = new HashMap<String, String>();
                Element e = (Element) nl.item(i);

                // Jedes Kind-Knoten zur HashMap
                map.put(KEY_UUID, parser.getValue(e, KEY_UUID));
                map.put(KEY_NAME, parser.getValue(e, KEY_NAME));
                map.put(KEY_JOBTITLE, parser.getValue(e, KEY_JOBTITLE));
                map.put(KEY_JOBINFO, parser.getValue(e, KEY_JOBINFO));
                map.put(KEY_IMAGE, parser.getValue(e, KEY_IMAGE));

                //Hashmap zur ArrayList hinzufügen
                menuItems.add(map);
            }
        } else {
            Log.i("doInBackground:", "Keine Internet-Verbindung");
            return null;
        }

how can i use the result of my NetworkAvailability class in my if loop as condition?
Comment: well best way to handle it in onPostExecute rather than .execute().get, because it will put your calling thread to waiting state.
Comment: i think the problem is that my xml-parsing code is on a inner class at my mainactivity. This class is also a asynctask. Could this be a problem?
Comment: You don't have to do it on AsyncTask, you can create a new activity for it and that activity for result than do the parsing. [Here, take a look](http://developer.android.com/training/basics/intents/result.html)
Comment: then you can access it with fully qualified name packagename.ClassName.
Answer: what you can do is to create a seperate class to check internet connection and then create object of that class and the call the function this will also clean your code.
public class ConnectionDetector {

    private Context _context;

    public ConnectionDetector(Context context){
    this._context = context;
    }

    public boolean isConnectingToInternet(){
       ConnectivityManager connectivity = (ConnectivityManager)  _context.getSystemService(Context.CONNECTIVITY_SERVICE);
      if (connectivity != null)
      {
          NetworkInfo[] info = connectivity.getAllNetworkInfo();
          if (info != null)
              for (int i = 0; i < info.length; i++)
                  if (info[i].getState() == NetworkInfo.State.CONNECTED)
                  {
                      return true;
                  }

      }
      return false;
   }
}

and then create object for that ConnectionDetector in your activity globaly like
ConnectionDetector cd=new ConnectionDetector(this);

and then where ever you want to use that function just call
if(cd.isConnectingToInternet()){

     //internet available
}else{

     //internet not available
}

Comment: don't i have to use asynctask for checking up for internet connection?
Comment: No as it is maintained in other class, using its object `ConnectionDetector`  you can check connection.


Do I need multiple AsyncTask classes to connect to network?

Question: I have one(1) AsyncTask class that connects to an API from network.
The API gets user profile from mySQL database based on username and password that is passed via POST.
If I have another API that saves a new User Profile to mySql based on username and password too, do I need to create a new AsyncTask class?
Does this mean that whenever I need to connect to a new API, I will need to create a new class?
Answer: You probably will need to. At least you will need to build separate functions for each API to parse the JSON received.
I recommend you to use some library for the purpose. Retrofit along with Gson is preferred.


Triangle Inequality lower and upper bounds?

Question: I was solving a question for linear algebra today and had a question regarding triangle inequalities. The question is:

If $\Vert \vec{v} \Vert = 5$ and $\Vert \vec{w} \Vert = 3$, what are the smallest and largest values of $\Vert \vec{v} - \vec{w} \Vert$?

The way that I solved it is to draw two circles with the origin as their centers and each having radius $5$ and $3$. In this case, $\vec{v}$ and $\vec{w}$ would be each circle's radius. It's not hard to see that the smallest value we can obtain is $2$ and the largest is $8$.
However, I attempted to try solving this question using the triangle inequality. I noticed that the way to solve it is $| \Vert \vec{v} \Vert - \Vert \vec{w} \Vert | \le \Vert \vec{v} - \vec{w} \Vert \le \Vert \vec{v} \Vert + \Vert \vec{w} \Vert$.
The first part I recognize as being the reverse triangle inequality, but how was the second part derived? In my head the original form of the inequality is:
$$\Vert \vec{v} + \vec{w} \Vert \le \Vert \vec{v} \Vert + \Vert \vec{w} \Vert$$
with addition not subtraction.
Thank you.
Answer: The minimum is $2$ and maximum is $8$. Hint: take $v =cw$ where $c$ is a scalar to see that these values are actually possible.
$\|v-w\|=\|v+(-w)\|\leq \|v\|+\|w\|$ because $\|-w\|=\|w\|$.


Variable transformation under a discontinuous mapping function introduce different bias?

Question: For any real number $x \in R$, consider its randomized version $y \sim \mathcal{N}(x,1)$. Now consider a mapping function of $y$ denote by $f(y)$.  We want to study the following bias term $R(x) = | E[f(y)] - f(x)  |$. My hypothesis here is that if $f$ is a discontinuous function, then $R(x)$ is not a constant w.r.t $x$. I do not know if this hypothesis is correct, or any condition on $f$ to make my hypothesis correct. If it is correct, can you shed some light how to prove this.
For example, if I choose $f = \mathbb{1}\{y \geq 0\}$ (the threshold function), which returns 1 if $y \geq 0$ and return $0$ if $y <0$,   $f$ is a discontinuous  function at $y =0$. Then for x = -10000 or x = 10000 $R(x)$ should be very small, because $-10000, 10000$ is very far from the discontinuous point $y=0$. However, for $x=0.001$ $R(x)$ should be larger because $x=0.001$ is very close to the discontinuous point.
Thanks
Comment: When $R$ is constant, you should have no trouble showing $f$ must be infinitely differentiable and therefore not discontinuous.
Answer: Your hypothesis is correct.
So that we may be notationally clear, let $x$ be a number and let $Y_x$ be its randomized version.  In terms of the density function for a standard Normal variable, $\phi,$ this means $Y_x$ has the density function $y \to \phi(y-x) = \phi(x-y).$  Given any (measurable) mapping $f:\mathbb{R}\to\mathbb{R},$ in terms of the convolution operator $\star$ we may write
$$E[f(Y_x) - f(x)] = E[f(Y_x)] - f(x) = \int_{\mathbb{R}} f(y)\phi(x-y)\,\mathrm{d}y - f(x) = (f\star \phi)(x) - f(x).$$
$R(x)$ is defined to be the absolute value of this expression.  Suppose $R$ is a constant function $R(x)=r$ for all $x.$  Then
$$r = R(x) = \pm\left((f\star \phi)(x) - f(x)\right)$$
implies
$$f(x) \pm r = (f\star \phi)(x).$$
The function $f\star \phi$ is at least as differentiable as $\phi$ is (because we may differentiate it by differentiating $\phi$ in the defining integral).  In particular, because $\phi$ is differentiable, $f\star \phi$ is differentiable, whence it is continuous. Since $f \pm r$ is continuous and the constant function $r$ is continuous, so is $f.$
The contrapositive of this implication is

When $f$ is not continuous, $R$ cannot be constant.
Comment: Thanks @whuber a lot. I think your proof looks quite okay, except the the point where you claim f*phi(.) is at least as differentiable as phi(.). This claim is important for the correctness of the proof. Do you have any backup documents, or more explanation so that it is more convincing.
So here  you meant convolution between a discontinuous function vs a differentiable function is also differentiable ?
Comment: This is a standard -- and very important -- property of convolutions.  I explained the reason why it holds.  Convolution of an arbitrary function (or even of certain "generalized functions") with a Normal distribution is a fundamental tool in mathematical analysis.   See https://en.wikipedia.org/wiki/Mollifier#Properties


Octave shift context

Question: I'm learning this amazing piece of music from Nikolai Kapustin ... although I already play it well (kind of, at least most of it), I'm still unsure about some parts... so I decided I should ask someone.
In the video, this part plays cca around 3:30 ...

The problematic thing is the 8vb ... the -1 octave shift. I don't know whether the shift applies for the left hand only or for both hands since the right hand is playing in the bass key too.
I can't see which keys Mr Kapustin plays and the sounds are too blended...
My guess is that the keys the 8vb applies to are played like a build up from bottom to the accord played in fortissimo...so it goes like:

Left hand: A0 + A1
Right hand: A1 (+ left hand crossing the right hand for C#2)
Right hand: A2
Left hand: C#2
Left hand: F#3
Fortissimo accord

But I have always thought that 8vb for one hand applies for that hand only. With that logic, it would be played like this.

Left hand: A0 + A1
Right hand: A2 (+ left hand almost crossing the right hand)
Right hand: A3
Left hand: C#2
Left hand: F#3
Fortissimo accord

Which is right? To me, the first one sounds more right (8vb applies to right hand too) but this particular composition already confused me so many times until I understood its tonal relations...
(I just realized I probably numbered the keys wrong, in the picture A0 = most bottom key on claviature)
Answer: Think of ottava shifts as of a clef change: where 8vb starts, imagine it's actually a switch into the bass-8 clef, where it ends, the clef switches back to bass (bass-0). Clefs apply to each staff separately, so do ottava shifts.
So your yellow notes are (in order in which they're marked): <a1 a0> a2 a3 c#2 f#3. I'm not sure how would I play it, the c#2 could be easily played by LH with the help of a pedal, to avoid the quick jump a3 c#2 in RH.
As a side note: It of course doesn't matter which hand plays it; it only matters on which staff it's written.
Comment: Wow, this is even better than my solution with hand crossing. With LH playing C#2 and RH playing F#3 I don't need to jump my hands too long distances and I can play the fortissimo accord with no rush... thank you! :)
Comment: @Motig Indeed it is, as long as you don't mind your 16th being dampered by the pedal. If you have a sostuendo (middle) pedal, you can use that one, but it takes some good timing.
Answer: My bet is on the 8vb only applying to the left hand.  The A1 in the left hand is supposed to be held, and if the right hand would then play another A1, this would disrupt the holding of the left hand A1.  While this kind of disruption for voice-leading purposes is not rare in piano music, in this instance it would cause an imbalance in the decay of the left-hand A1 with the left-hand A0 which does not get a similar "refresh".
But even without such a hint I'd lean towards letting the 8vb only apply per-staff.  There is no point in not writing another 8vb when required for the right hand as well.

Octave shift context


Prove that if x is irrational, then sqrt(x) is irrational.

Question:
I believe the contrapositive method should be correct but i get,
The contrapositive of this statement should be,
(If $\sqrt{x}$ is rational, then $x$ is rational)
Then I end up with $x=\frac{m^2}{n^2}$ for $m,n$ to be integers and $n$ does not equal 0.
Is it careless to be done with the proof since we are saying that $x=\frac{m^2}{n^2}$ is a rational number therefore the contrapositive is true, therefore the original statement is also true?
Comment: Is this actually supposed to be a question with a "correct" answer?
Comment: @ZachEffman I meant that there's no "right" way of going about proving it. Each one of those proof methods would be viable (although one may be more clean or efficient than another).
Comment: No, that proof is correct.
Comment: yeah there is suppose to be a correct answer
Comment: oh yeah all three methods can be used to prove it, just whether the proof is correct or not
Comment: @nignog I agree, I was responding to the question of is the OP's proof careless.
Answer: $[p\implies q]\iff [\neg q\implies\neg p]$
If you prove the contrapositive of a statement, that completes the proof of the statement, because a statement is true if and only if its contrapositive is true (draw a truth table and verify this).

The Proof by Contradiction also can be used:
Let $x$ is irrational and assume $\sqrt x$ is rational. Then you can arrive at a contradiction to $x$ is irrational.
Comment: You can always use all three types of proofs. Usually you just need to use LEM ($p \vee \neg p$) somewhere in the direct proof.
Comment: Both the OP's proof and the answer here are wrong. Counterexample: let $x = -\sqrt{2}$, then $\sqrt{x}$ is an imaginary number. Therefore, not rational!
Comment: @user13985 This is not a counterexample to the statement here. Read the assumptions and conclusion carefully.


Remover uma quantidade N de dias em uma data

Question: Como remover uma quantidade de N dias em uma data ?
namespace TesteData
{
  class Program
   {
    static void Main(string[] args)
    {
        var dataAtual = DateTime.Now.Date; // dataAtual 13/09/17
        var qtdDias = 5;

        //Como fazer essa dataAtual 13/09/17 - qtdDias = 08/09/17 ?
        //dataAtual = 08/09/17
      }
    }
}

Answer: Não tem um método de subtração, mas é só usar um truque matemático com o método AddDays():
using System;

namespace TesteData {
    public class Program {
        public static void Main(string[] args) {
            var dataAtual = DateTime.Now.Date;
            var qtdDias = 5;
            var novaData = dataAtual.AddDays(-qtdDias);
            Console.WriteLine(novaData);
        }
    }
}

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

To subtract a particular time interval from the current instance, call the method that adds that time interval to the current date, and supply a negative value as the method argument. For example, to subtract two months from the current date, call the AddMonths(Int32) method with a value of -2.

Documentação.
Answer: simplesmente:
namespace TesteData
{
  class Program
   {
    static void Main(string[] args)
    {
        var qtdDias = 5;
        var dataAtual = DateTime.Now.Date.AddDays(qtdDias*-1); // dataAtual 13/09/17
      }
    }
}


Score Variance of supplementary individuals in PCA

Question: I have posted an almost similar question last week but I want to get some more of the theoretical background Difference in Variance of factor scores for supplementary and active observations PCA.
I am doing PCA on genetic data (number of variables >> number of rows) and all data points take values in {0,1,2}. The aim of doing the PCA is to isolate the effect of different origins (People from Europe have different genetic structure than people from Asia).
I have run the PCA with several different packages on two kinds of different data sets. One with little structure ( all the samples had the same origin) and one including samples from two different world regions.
I use a subset of the data to find PCs and then apply the loading matrix to supplementary samples. What I observe is the following. In the case of the data set with little structure, as expected the eigenvalues are almost similar and so the proportion of total population variance explained by the first principal component is small. Now if I apply the loadings matrix to supplementary individuals that have been standardized using the mean of the active sample the score variance of these supplementary individuals is much smaller (3 to 5 times smaller). I then did the PCA only on the supplementary individuals and it turns out that the PC1 of the two subsets are poorly correlated (~ $0.07$).
When I do the exact same thing on data including samples from two different world regions than the difference in Score Variance between the active and supplementary individuals is much smaller ( $\frac{Var(Score_{passive})}{Var(Score_{active})} = 0.9$) and the PC1 of the two subset are strongly correlated (~ $0.95$). However the the Score Variance of the passive sample is still smaller than the one of the active sample.
Now my question:
Is this a global result? Is the Score Variance of the supplementary individuals always smaller than the one of the active? I'd really like to understand but I'm having trouble getting the mathematics and Intuition behind that straight.
Answer: (This is largely a repetition of your previous question, maybe you should have edited that one instead. But anyway.)
(1) Your datasets seem to be very similar, consist of genetic data and differ only by the regions where the subjects came from. Therefore I guess one can assume that the variance of individual dimensions (loci?) is pretty similar in each dataset, the number of dimensions is the same, and so the total variance is also very similar.
(2) First eigenvalues of covariance matrix of your "active" subset in dataset 1 (same regions) are very similar to each other. As the datasets are also similar, I guess this means that the same is true for the "supplementary" subset of dataset 1 and also for both subsets of dataset 2 (different regions).
(3) In the dataset 2 the PC1 of the "active" subset" and the PC1 of the "supplementary" subset are very highly correlated. This means that it is essentially the same component. The reason PC1_active explains a little bit less variance in the "supplementary" subset than in the "active" subset is simply because this PC is optimized for the active subset. The subsets have slightly different PCs, so no wonder a PC from another subset would explain less variance.
(4) In this sense, yes, it is a global result. However, these comparisons only make sense if the total variance is the same between subsets (which I assume is true based on (1)). In general it makes more sense to compare the variance of the supplementary data projected onto the PC1_active to the variance of the supplementary data (same data) projected onto the PC1_passive (different PC), instead of comparing it to the variance of the active data (different data) projected onto the PC1_active (same PC).
(4) What happens in your dataset 1, I don't know. If (1) and (2) is true, then you should get similar explained variance with both PCs. You get 3-5 times difference, and it is weird. You need to explore this in more detail. I would compute the amount of variance first 5 active PCs explain in the active dataset and passive dataset, and the amount of variance first 5 passive PCs explain in the active and passive dataset (it's usually more convenient to deal with relative variances, i.e. normalized by the total variance, which is sum of all eigenvalues). With these 20 numbers you can maybe better see what is going on.
Finally, I am not sure what you are trying to achieve. If your goal is to "isolate the effect of different origins" (so you suppose that the effect is localised in loci?), then PCA would not help you much. If your goal is to classify subjects by the origin, then you would be better off doing dimensionality reduction with PLS (partial least squares) instead of PCA, see

Barker, M., & Rayens, W. (2003). Partial least squares for discrimination, Journal of chemometrics, 17(3), 166-173.
Comment: Thank you so much for your answer. I am sorry I wasn't very precise on what I am trying to achieve. I want to control for population stratification in my regression model for a genome association study. I.e. I would like to include the first PCA (that represents origin) in the regression. My dataset is gonna bu huge, so I wanted to save computation time and calculate them only for a subsample. I am looking for ways to efficiently compute PCAs for a huge sample (90k x 400k). Thanks a lot for your helo that helped me a lot to get the intuitions right.
Comment: @JohannesEbert: three points come to mind. First, I would really recommend using the first PLS component rather than the first PCA component in your regression (or maybe use PLS regression directly). Second, in either case you will be *much* better off with an iterative method to find the first PC rather than using the standard eigenvalue method; try iterative methods that do not precompute covariance matrix (maybe R can do it for you, this I don't know). Third, if you do want/need to use subsamples, try selecting them randomly (and use several random subsamples, hoping to find the "same" PC).
Comment: Thank you, I didn't know about iterative methods before. I will trz to do randomized SVD and do it on the whole sample.
Comment: For iterative methods google "Power iteration" and also "Lanczos algorithm"; for these algorithms however you will need to compute covariance matrix first, and for huge datasets this can be very costly by itself. Look for "probabilistic PCA" approach, which does not require precomputing covariance matrix. In its simplest form you can even find it on the wiki: http://en.wikipedia.org/wiki/Principal_component_analysis#Iterative_computation


Does this qualify as a covariate in a RMANOVA?

Question: I am confused as to whether a variable qualifies as a covariate in an RMANOVA. How can I find out and how do I use it?
In a (hypothetical) within-subject, counterbalanced order, I present 2 memory tasks - one is a simple word learning in a quiet setting, and the other has a more game like environment. I wish to see if memory for items learnt during the game was better that simple list learning. That makes for a simple RM-ANOVA with the two memory scores as within-subject variables, and order as a between subject variable. Right? But I also believe this effect will depend on how well the person played the game in the second condition. Perhaps, people who play the game well do not show much difference from control condition, but those who don't play the game so well, show a greater advantage.
In conclusion, I have 2 memory scores, and a game-performance score which should correlate with the difference in the two memory scores. Just not sure how to use it.
What do I do to look for such effects?
Thanks!
Answer: This is definitely in a gray zone, at best.

That makes for a simple RM-ANOVA with the two memory scores as
  within-subject variables, and order as a between subject variable.
  Right?

Your underlying design would probably be thought of more usually as a two-period, two-treatment cross-over design.  That would be the area to look for not only the basic statistical methodology, but also to see the various issues around that type of design.
With this design covariates would usually be thought of as either at the subject-level, at the period-level, or at the subject-by-period-level.  (This is my own terminology just to try to bridge the gap.)
Subject-level covariates would be variates that change across subjects that would be thought of as unchanging over the periods of the study --- or perhaps as independent of time.  Examples would include sex, age, intelligence, or similar demographic or baseline characteristics.
Period-level covariates would be variates that change over time that would be thought of as independent of subjects.  Examples could include environmental variables such as temperature or humidity.
Subject-by-period-level covariates would be variates that were subject-specific and period-specific.  In other words, they vary across both subjects and across time.  Examples could include blood pressure, alertness, or other physical or physiological measurements that vary over shorter time frames than the study periods.
In your case, game performance is something that varies across subjects and perhaps also varies across periods, so is probably a subject-by-period-level covariate.  But, you would like to treat it as something like a subject-level covariate, perhaps because you only have one such measurement per subject or perhaps because you see it as reflecting an underlying trait.

What do I do to look for such effects?

Even in the more well-defined cases where measurements are unambiguously subject-level or subject-by-period-level, it is more technical than one might wish.  Kenward and Roger (2009) provide a discussion of the issues.
At best, your case seems like it would raise many questions.
Kenward, Michael G., and James H. Roger (2009) The use of baseline covariates in crossover studies.  Biostatistics 11 (1):1--17.


Difference between points and vectors in $\mathbb{R}^n$ in relation to vector-valued functions

Question: I'm very new to vector calculus, and based on what I read I may be dealing with a trivial distinction, but I want to be completely sure of this.
I know that $\mathbb{R}^n$ contains points, sometimes denoted $\mathbf{x}$, and vectors, denoted $\mathbf{\vec{v}}$. It seems that when we consider a function $\mathbf{f}: \mathbb{R}^n \to \mathbb{R}^m$, we are mapping points in $n$-dimensional space to points in $m$-dimensional space. Similarly, when we consider a limit of this function, it seems that we are interested in the behavior of the function values as points in our domain approach some other point. However, the common terminology seems to be that $\mathbf{f}$ is a "vector-valued function": this would seem to suggest that we are outputting vectors. I have also seen it stated that we are considering the behavior of vectors in the domain of the function when taking limits.
I've read that there is often no distinction made between points and vectors in this respect. I've also seen some conflicting information on whether points are simply "vectors through the origin," but I am having difficulty understanding what is really at work with these functions.
Thanks in advance for any helpful insights.
Comment: The set $\mathbb R^n$ is the set of all ordered $n$-tuples of real numbers. There are two different ways to visualize an ordered $n$-tuple -- as a point (a location in space) or as a vector (a directed line segment, or an equivalence class of directed line segments). When we refer to an $n$-tuple as a point, we are suggesting that you visualize a point. And when we refer to an $n$-tuple as a vector, we are suggesting that you visualize a directed line segment. Either way, it's just an $n$-tuple -- the only difference is in how you visualize the $n$-tuples and which operations we do with them.
Answer: In general, if $x\in\Bbb R^n$ (or $x\in S$), then $x$ is just that: an element of the set $\Bbb R^n$ (or $S$). Depending on context, we may call $x$ a point, a vector, an $n$-tuple, or perhaps a vehicle (e.g., if. $S=\{\text{car},\text{bicycle},\text{truck}\}$). The term "point" is used when we focus on geometry or topology properties of $\Bbb R^n$, the term "vector" when we focus on $\Bbb R^n$ being a vector space, i.e., when we need to know how to add elements or multiply them with a constant. Topology comes into play with $\Bbb R^n$, whenever convergence does.
In the end, $\Bbb R^n$is a "topological vector space", i.e., not only a topological space and a vector space at the same time, but it also plays both these roles in a compatible way (i.e., the vector space operations of adding two vectors or scaling a vector are continuous maps). At any rate, "point" or "vector" are just synonyms for "element" with a bit of contextual connotation added. When we refer to a map to $\Bbb R^m$ as "vector-valued", we want to emphasize that the co-domain is not just $\Bbb R$ and that therefore that we may need to use different tools.
Answer: $\Bbb R^n$ is a vector space (just check the axioms of a vector space), and its elements are therefore called vectors.
However, it can also be seen as an affine space and its elements are then called points.
An affine space $E$ is more or less like a vector space where you "forget the origin": you can get vectors starting from any point $A$, and given two points $A$ and $B$, you can get a vector $\vec{AB}$.
Actually, an affine space has an associated vector space, and the vector space associated to the affine space $\Bbb R^n$ is... $\Bbb R^n$, and that's why this may look confusing. The elements are thus called points or vectors depending on the structure that you want to emphasize. If you don't rely to much on the structure, you can use both terms.


What are ways to keep hashCode/equals consistent with the business definition of the class?

Question: Object javadocs and Josh Bloch tell us a great deal about how hashCode/equals should be implemented, and good IDEs will handle fields of various types correctly.  Some discussion about all that is here.
This question is about the next step: How do you make sure that they remain good?
In particular, I feel that for most Classes, equals/hashCode should be implemented as Bloch suggests (and Eclipse and other IDE's implement), and take in to account all non-derived, business-logic, fields on that class.  While adding new fields to a class as part of continuing work, people often forget to add them to the equals/hashCode implementation.  This can lead to hard-to-find bugs, when two objects appear equal, but in fact differ by the value of a recently introduced field.
How can a team (even of one!) help ensure that the equals/hashCode on a class continue to take in to account all relevant fields, as the member fields change?
I know that Apache's EqualsBuilder and HashCodeBuilder can use reflection, which obviously would take in to account the correct fields, but I want to avoid the performance costs of using them.  Are there other approaches to flag up fields that are not included in equals/hashCode, and should be?  Static code analysis, IDE features, unit test techniques?
Comment: Don't be concerned about the performance of reflection until you have a profiler telling you to be. You're probably using it all over the place without knowing it anyway.
Comment: @RyanStewart Good point, should've been more clear.  For some classes it's not a concern, but for some it is (demonstrated with profiler), and I want a way to ensure equals/hashCode are dealing with fields that doesn't use reflection with the ensuing runtime overhead.
Answer: Never tried it, but how about http://code.google.com/p/equalsverifier/?
Comment: Looks promising, I'll try it out.
Comment: +1 Nice. It looks like it can even suppress fields that you know are not relevant. It seems just like what I've been looking for too.
Comment: I'd like to use this, but to solve my problem I'd want to use the 'allFieldsShouldBeUsed' flag, which unfortunately also includes static, final fields.  I'm sure it'll be fixed soon (http://code.google.com/p/equalsverifier/issues/detail?can=2&start=0#=100&q=&colspec=ID%20Type%20Status%20Priority%20Milestone%20Reporter%20Summary&groupby=&sort=&id=57), but for now it looks like Lombok is my answer.
Answer: A potential answer seems to be offered in this question.
I haven't looked into Project Lombok much, but I immediately thought, hmm annotations would work with a code generator.
Comment: +1 This tool really is great. Automatically generating boiler-plate code such as equals() and hashCode() at compile-time means that any future updates to the class will automatically have those changes incorporated to the implementations of those methods.
Answer: How about you write unittests for each class you want to protect.
The unit tests should

Use reflection to count the number of fields, and compare with locally stored field names (and types).
If a change in number of fields (or type of fields) has been detected, then invoke hashcode. If the value is the same, then fail the test case. Alert the developer that fields of a class have been changed, and that the developer should : Update the equals and Hashcose, and update the unittest.
Make sure the unittest runs in a nightly build.
Comment: This wouldn't help. If the developer who adds a new field also doesn't edit the unit test, the test will continue to pass on the old logic, even though the class fields are now out-of-sync with the equals and hashCode methods.
Comment: The unit test could use reflection to fill all fields of two objects differing on one field and then test `equals`.
Comment: @JoopEggen How about.. UnitTest maintains a list of Fields. Each time the test is executed, it compares them with the Fields it finds at run-time using Reflection. If there is any mismatch in the set of Fields found, then it will fail the test case. The failure msg / java comment, will alert the developer that they have to update update the "Equals+Hashcode" and update this UnitTest, each time a new field is added to the class.
Comment: I think the poster's point is that the value of hashcode should not be the same if the number of fields have changed. There seems to be an implied persistence layer... or the general concept that this unit test would have two hardcoded fields, an int indicating the number of fields in the object being tested when the test was last updated and a long indicating the value of the hashcode. But, yeah, fragile reminder at best.
Comment: @JoopEggen, that seems like a much better approach. You should propose it as an answer. The only way in which it is then fragile is that it relies on every field being integral to the determination of equality (which is not always the case, but sounds like it holds true for the OP).
Comment: @TimBender : thanks, also for pointing out that my solution does not hold where equivalency is taken as equality. Seems that there are sufficient answers.
Comment: @rk2010 yes that would be feasible. Maybe also FindBugs would find incomplete `equals`.
Answer: You don't need to include every field in your hash code method.  If you used more than one field in your hash code algorithm then the chances are it will remain good.  The IDE-generated algorithms I've seen use a random (at the time of implementation, not at execution) prime constant value, so just make sure that classes that could end up in the same map or tree together (e.g. they implement the same interface) have different constant values.  Unless, of course, you want equality at the interface level.
I've never seen a hash code algorithm "go bad" - you're worrying a disproportionate amount about this.
Comment: Solving some problem, definitely. The problem is NOT that equals/hashcode are out of synch with EACH OTHER.  It's that as new business logic fields get added (due to enhancements, say) they should be added to equals().  If you forget to update equals(), than equals() (and hashCode) is out of synch with the class definition.  That's the case I'm trying to catch.
Comment: As the question states, I'm worried about hashCode AND equals.  I prefer that all fields that affect equals also affects hashCode, as then consistency between the two is guaranteed (see the best answer to the question whose link I included).  And for equals(), I want all relevant business fields included.
Comment: Are you trying to follow a standard just because you want to follow a standard or are you solving some problem?  Do you often have your equals and hash code methods go out of sync?  If your team is modifying the attributes of your business objects so frequently that you need an automated way to fix this, then your team has bigger problems. Your first pass at a hash code should be good enough, if you've got a grasp of the objects and processes you're trying to capture.
Answer: Sounds like what you're looking for is an addon or feature in an IDE that performs the analysis of the classes and generates warnings if the equals() and hashCode() methods do not reference all the relevant fields.
This would basically move the reflection overhead to the IDE rather than let it have the cost during run-time.
Unfortunately, I don't know of any addon that does this, though I'll certainly have a look.
On the other hand, how would such an automated tool know which fields are relevant for business logic? You'd probably need to mark irrelevant fields with something like an annotation, otherwise you could find yourself with warnings you can't get rid of, but that you know are incorrect.
Edit: This answer is not useful, so I'm just compiling here the really useful suggestions from better answers:

Project Lombok - Eclipse addon that also works with build tools to provide automatic generation of equals(), hashCode() and other boiler-plate code - since it's generated at compile-time, any changes to the class will automatically update these methods too
equalsverifier - Provides a way to automatically unit test equals() with reflection - doesn't support testing hashCode()
Comment: For such a tool, I'd be fine if it assumed everything was relevant.  Even better would be if I could annotate fields that should not be included.
Answer: You could serialize your objects to a string using a tool that finds your properties using reflection (XStream, for example), and store that string in a repository.  Your unit tests could re-serialize your objects and compare the results to your stored values.
As part of your own process, make the storage of those strings contingent on manually validating that your hashCode and equals correctly capture all relevant values.
Comment: The idea being that tests fail whenever fields get added, as a reminder that one should update hashcode/equals?
Comment: Yes-- added, removed, or renamed.  Also, I submit that not every change to a field necessarily implies an impact to equality.  Your automated test can detect that your class changed, but a proper evaluation of hashcode/equals will require some human intelligence.


afp cannot see zfs mounted folder

Question: on my linux server, I have mounted my zfs pool here: ~/data/homepool and ~/data is shared via afp. My macOS (high sierra) client can correctly see and read/write ~/data and in fact even write in data/homepool.
The problem is that macOS Finder gets the wrong storage capacity of homepool, Finder indicates the storage space of homepool as the storage space of ~/data, while as homepool is mounting a zfs pool, homepool is very large. This is preventing Finder to copy large files and Finder thinks there is no available space. Is it a bug..?
Answer: However, if you share directly ~/data/homepool (instead of ~/data) over AFP the MacOS client gets the correct space size, so this is the workaround.
Answer: Yes, this seems like a bug in AFP. Based on what you're saying, it seems like they aren't looking for additional capacity in filesystems mounted below the shared folder.
In addition to the workaround you cited (share the ZFS filesystem instead of the directory containing the ZFS filesystem), you could also use cp / rsync / dd / some other command line utility to copy files into the share, since I don't think those typically check for space before copying.
In theory, I see how they could do this differently -- I think it would require checking all the mounted filesystems, querying the space available in each of them and then adding that to the space available in the directory that they're all mounted into. However, given that some of those filesystems mounted into this directory could also be network shares (AFP / NFS / etc.), this could be a disaster for performance of the "how much space is available" query.

afp cannot see zfs mounted folder


Are there any type theories in which proper classes are presented?

Question: I'm more of a computer scientist than a mathematician, now studying category theory. In CT, there are categories that are too big to be sets, e.g. the category of all sets/groups/small categories. As far as I know large categories can be constructed with proper classes. I wonder if there's something that roughly corresponds to classes in the sense of NBG set theory. Clearly, classes are not constructive, but maybe it could be added as axioms purely to do math without any computation meaning? How is there (not) such a type theory?
Let's say that the equality or the function arrow forms a (∞-)category, to model itself in the type theory, the set (or whatever you want to call that) of it would definitely be too big considering all of the types including universes. That's why I'm asking for a proper class.
Answer: There's nothing inherent in the notion of "class" that makes it non-constructive. Arguably, the non-reified notion of "class" that would be used in, e.g. ZF, is more constructive than that of a set.  This notion of "class" more or less corresponds to a (unary) logical predicate.  In some cases we may have a set $X$ such that for the predicate $\varphi$, $\varphi(x) \Leftrightarrow x \in X$ in which case we may say that $\varphi$ "is a set". Now why do I say that this may be more constructive than a set?  Well, in this notion as "class" is essentially a formula, i.e. a finite collection of symbols in the formal system within which we're working.  For example, the "class" of all sets is the formula $\varphi(x) \equiv \top$. On the other hand, I can easily postulate the "existence" of all kinds of sets for which there is no (finite) formula corresponding to them.  For example, simply combine the axiom of infinity with the powerset axiom; most elements of $\mathcal{P}(\mathbb{N})$ cannot be described by any (finite) formula $\psi$.  That is, there can be (and are in the "standard" model) elements $X \in \mathcal{P}(\mathbb{N})$ for which there is no formula $\psi$, not containing $X$, such that $\psi(x) \Leftrightarrow x \in X$.  The constant reference to "size" is a bit of a red herring.  A (very) similar situation happens with computability.  For most (Turing-complete) programming languages I can (relatively) easily, possibly even trivially, make a computable function that picks out which bitstrings correspond to programs. I can't, however, make a computable function that picks out which bitstrings correspond to halting programs, even though it's surely the case that a halting program is a program.  Returning to constructivity, with this notion of "class" the "constructiveness" of a "class" depends on the constructiveness of the logic in which we're working, while the constructiveness of a set depends on the logic and the non-logical axioms which we assume.
In a system like NBG, a separate notion of "class", i.e. a specific sort, is formulated.  At this point we can axiomatically declare the existence of classes just like we do with sets.  Whether this is constructive will depend on our logic and the non-logical axioms we assume just as it did for sets in the ZF-like scenario.
Turning to type theory, the first thing to note is that a type theory isn't a theory in FOL (or some other logic) like set theory is; it's a different logical framework entirely.  Cartesian products of sets or function spaces are constructions in set theory which is itself axiomatized in first-order logic.  Product types and function types, on the other hand, are logical connectives of type theory.
Structurally, a "class" in the ZF-like sense, corresponds to a type. More tightly, if $S$ is the type of "sets", then a natural interpretation of a class would be a subset type $\{s \in S\mid \phi(s)\}$ which more or less corresponds to the dependent sum type where $\phi(s)$ is propositionally truncated, i.e. $\Sigma s:S.||\phi(s)||$. The "class" of all "sets" would then essentially be $S$ itself.  In a NBG approach, there'd actually be a separate type $C$ of "classes". However, both of these correspond to what would happen if you axiomatized ZF/NBG set theory in a (dependent) type theory, i.e. a "set" would be an inhabitant of $S$ in this case.
What is typically done, though, is view types as the analogue of sets.  Then the analogue of the problem of the "set" of all sets is a "type" of all types.  The usual solution to this nowadays is a universe. Adding a universe type to a type theory is the analogue of the NBG approach.  There really isn't room for an analogue of ZF-like "classes". You could add judgements for "meta-types" and have a language of "meta-types" whose inhabitants are types.  This would give you more flexibility (as the designer of the logic) than using a universe. You can do this even if you also have universes.
In practice variants on Martin-Löf type theory usually have not just a universe, but a whole infinite hierarchy of them as realized in e.g. Agda and Coq.  This readily allows you to talk about small and large categories.  If an infinite number of universes is still not enough for you, there are notions of superuniverses.  The superuniverse (or a related notion) can then serve as your "proper class" if you want.  Note, all of this is constructive.
Comment: By analogy to formulating the notion of a category of all types in MLTT with a single universe, my guess is that for MLTT with universe polymorphism (but not just typical ambiguity) you could show the universes satisfy the laws of an $\infty$-groupoid, say, but you couldn't make a *type* of $\infty$-groupoids such that the universe hierarchy inhabited it as a carrier. My impression is with a superuniverse, you would be able to make such a type, though it wouldn't apply to the superuniverse itself.
Comment: I guess what I expect is what you call "meta-types". I kind of doubt that a large category like the one presented in HoTT can be formalized because it talks about all types including universes. Does resorting to typical ambiguity or superuniverses deal with the problem properly?


C# Interfaces, Polymorphism and Delegates

Question: I have a mess when I combine interfaces and polymorphism.
Say I have the following interface:
public Interface CanSayHello
{
     String SayHello();
}

The following class:
public Class Person : CanSayHello
{
     public String SayHello() { return "Hey, I'm a person just saying hello to you";}
}

And finally the important Class:
public Class PoshPerson: Person
{
     public String SayHello() { return "Hey, I'm too posh to say hello to you";}
}

My first question is would the following code collect the method of PoshClass or Person Class?
public delegate String Collector();
event Collector CollectorEvent;
void GetMethod(CanSayHello c){CollectorEvent += c.SayHello;}

**GetMethod(new PoshPerson());**

If it will collect the method from Person class, I guess that I should declare the method at Person as virtual and the method at PoshPerson override.
I would really like  that the two method signatures were equal. Is it possible in any way?
Comment: Which of those would you want to happen? If you want the implementation in `PoshPerson` to be called, why would you want to avoid making the methods `virtual` / `override`? Personally, I'd avoid method hiding whenever possible, precisely because compile-time polymorphism is not very intuitive.
Comment: Btw, the coding guidelines say that you should indicate interfaces by putting an I as first letter.
Comment: Take a look here: http://msdn.microsoft.com/en-us/library/ms173153(v=vs.80).aspx
Comment: Should be fairly easy to find out what happens?
Answer: Your example runs Person's method.  If you change PoshPerson to PoshPerson : Person, CanSayHello (which you might think would change nothing, since Person : CanSayHello), it runs PoshPerson's method.
I agree with @millimoose: "I'd avoid method hiding whenever possible, precisely because compile-time polymorphism is not very intuitive."  I would recommend that you change Person.SayHello to virtual, and PoshPerson.SayHello to override.  That way regardless of whether you know of the instance as a CanSayHello, Person, or PoshPerson, the current instance type's method runs.
Comment: Also, the compiler will emit a warning to use the `new` keyword in the method declaration in `PoshPerson` if the hiding is in fact intentional.
Answer: You example will run Person's version. See the explanation here: http://msdn.microsoft.com/en-us/library/aa664593(v=vs.71).aspx. If you redefine the method in a derived class (the compiled treats PoshPerson.SayHello as if you had used new to redefine it), and the base class implements an interface, the redefined method doesn't alter the interface mapping.
If you have PoshPerson re-implement the interface, it will call PoshPerson's SayHello.
public class PoshPerson : Person, CanSayHello
{
    public String SayHello() { return "Hey, I'm too posh to say hello to you";}
}

Or if you  make SayHello virtual in Person, and then override it in PoshPerson, it will call PoshPerson's SayHello.
Comment: "If you have PoshPerson explicitly implement the interface" that's a bit misleading, since you're not talking about "explicit interface implementation", but about reimplementing the interface.
Answer: I think you want something more along the lines of:
public interface ITalkable
{
     string SayHello();
     string SayGoodbye();
     etc...
}

public class Person : ITalkable
{
     public virtual string SayHello() { return "Hey, I'm a person just saying hello to you";}
     public virtual string SayGoodbye() { return "Hey, I'm a person just saying goodbye to you";}
}

public class PoshPerson: Person
{
     public override string SayHello() { return "Hey, I'm too posh to say hello to you";}
     public string MakePersonSayHello() { return base.SayHello(); }

}


When I create a virtualenv, python runs in 64-bit even when already set to 32-bit in OSX

Question: My setup is: 2.6.1 python (apple default, snow leopard), virtualenv, and using virtualenvwrapper
Outside the environment, everything runs in 32-bit which is fine. But with a new project I'm going to work on needs django 1.3 and tons of dependencies, so I made a virtualenv.
I've managed to install everything well, except that mysql-python (via pip) gets an error of "mach -o wrong architecture". I've checked my python interpreter with "import sys; sys.maxint" inside the virtualenv and python runs in 64-bit.
I've already set systemwide for python to run in 32-bit via "defaults write com.apple.versioner.python Prefer-32-Bit -bool yes"
Does anyone know why this happens inside the virtualenv?
Answer: Much of the "magic" that Apple used to implement their Prefer-32-bit for the system Pythons in OS X 10.6 is in /usr/bin/python which then calls the real Python interpreters which are symlinked at /usr/bin/python2.6 and /usr/bin/python2.5.  virtualenv copies the real interpreter into the virtualenv bin directory so the Prefer-32-bit processing is bypassed.
Among the options to ensure 32-bit operation:

Use the arch command to invoke the interpreter.
$ virtualenv -p /usr/bin/python2.6 ./p
$ ./p/bin/python -c 'import sys;print(sys.maxsize)'
9223372036854775807
$ arch -i386 ./p/bin/python -c 'import sys;print(sys.maxsize)'
2147483647

Use lipo to extract only the 32-bit arch from the universal binary.
$ file ./p/bin/python
./p/bin/python: Mach-O universal binary with 3 architectures
./p/bin/python (for architecture x86_64):   Mach-O 64-bit executable x86_64
./p/bin/python (for architecture i386): Mach-O executable i386
./p/bin/python (for architecture ppc7400):  Mach-O executable ppc
$ cp ./p/bin/python ./p/bin/python-universal
$ lipo ./p/bin/python-universal -thin i386 -output ./p/bin/python
$ file ./p/bin/python
./p/bin/python: Mach-O executable i386
$ ./p/bin/python -c 'import sys;print(sys.maxsize)'
2147483647

Install and use a newer 32-bit-only Python 2.6 or 2.7 (installers available from python.org)
Comment: Thanks for this.

I've done the second option (using lipo) for the executable in the virtualenv as using arch commands doesn't work in running the django mini server (arch -i386 python manage.py runserver) for some unknown reason.
Comment: Yes, the `arch` trick won't work if the program you run spawns other Python processes via `subprocess`, et al, so using `lipo` or a 32-bit-only Python are safer.


How to modify list property without affecting other list property of same type?

Question: Here is my sample code,
List<myClass> myclass1 = new List<myClass>();
List<myClass> myclass2 = new List<myClass>();
//add data to myClass1 from source
foreach (myClass data in source)
  myclass1.Add(data);
//add data to myClass2 from source
foreach (myClass data in source)
  myclass2.Add(data);

//Change name property only for myclass1
foreach (myClass data in myclass1)
data.Name = "Test";

After changing name property for myclass1 object, its also modfiying the value of name property of myclass2 to 'Test'. What is the reason & how do I avoid it?
Comment: you are adding a reference to each of those lists, so they both point to the same object. To achieve what you want you need to create a new instance of the object and add it to the second list.
Answer: This is because you put the same thing into both lists!
If you want the contents of each list to be different, then don't put the same thing into it.
If myClass implements IClonable, then you can use
foreach (myClass data in source)
  myclass1.Add((myClass)data.Clone());

Answer: It is because data is same in both lists.
To achieve you need to put different data in second list as below :-
var source2 = source.clone();

    foreach (myClass data in source2 )
      myclass2.Add(data);

Answer: It's because you use reference types which means you only put the reference of the instance to the list so basicly you have to list containing the same elements. You can use value types but if it has reference type fields it will still reference to the same object instance in it.
You colud try to clone or serislise and deserislize the object but after the list won't contain the elements from the source just the copy of them.
Answer: myClass is reference type. For solving this problem you should add to second list copies of data.
Answer: List is storing by reference, make temp object and add to the list.
foreach(myClass data in source)
{
    myClass tmpData = new myClass(){
        Something = data.Something;
    };
    myClass1.Add(tmpData);
}

Answer: Learn more about difference between value types and reference types and how they work in c#.
Check this : What is the difference between a reference type and value type in c#?


mvn test dando erro 'cannot find symbol'

Question: Tenho um projeto spring-boot e estou programando alguns testes usando o Junit, no Eclipse eu executei os testes sem ter problemas, porem, no terminal, ao tentar executar o comando mvn test ou mvn build ocorre um erro na minha classe TestUtil que nunca aconteceu no Eclipse dizendo  'cannot find symbol'.
Sera que não esta encontrando a classe ?
O erro é esse:
<code>[ERROR] COMPILATION ERROR :
[INFO] -------------------------------------------------------------
[ERROR] /home/andre/Documentos/workspace-sts/ecommercespringboot/src/main/java/br/eti/krebscode/ecommercespringboot/utils/TestUtil.java:[8,20] package org.hamcrest does not exist
[ERROR] /home/andre/Documentos/workspace-sts/ecommercespringboot/src/main/java/br/eti/krebscode/ecommercespringboot/utils/TestUtil.java:[9,20] package org.hamcrest does not exist
[ERROR] /home/andre/Documentos/workspace-sts/ecommercespringboot/src/main/java/br/eti/krebscode/ecommercespringboot/utils/TestUtil.java:[61,54] cannot find symbol
  symbol:   class TypeSafeDiagnosingMatcher
  location: class br.eti.krebscode.ecommercespringboot.utils.TestUtil
[ERROR] /home/andre/Documentos/workspace-sts/ecommercespringboot/src/main/java/br/eti/krebscode/ecommercespringboot/utils/TestUtil.java:[70,54] cannot find symbol
  symbol:   class Description
  location: class br.eti.krebscode.ecommercespringboot.utils.TestUtil.ZonedDateTimeMatcher
[ERROR] /home/andre/Documentos/workspace-sts/ecommercespringboot/src/main/java/br/eti/krebscode/ecommercespringboot/utils/TestUtil.java:[86,32] cannot find symbol
  symbol:   class Description
  location: class br.eti.krebscode.ecommercespringboot.utils.TestUtil.ZonedDateTimeMatcher
[ERROR] /home/andre/Documentos/workspace-sts/ecommercespringboot/src/main/java/br/eti/krebscode/ecommercespringboot/utils/TestUtil.java:[69,9] method does not override or implement a method from a supertype
[ERROR] /home/andre/Documentos/workspace-sts/ecommercespringboot/src/main/java/br/eti/krebscode/ecommercespringboot/utils/TestUtil.java:[85,9] method does not override or implement a method from a supertype
[INFO] 7 errors
[INFO] -------------------------------------------------------------
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 2.309 s
[INFO] Finished at: 2018-06-24T00:15:51-03:00
[INFO] Final Memory: 31M/285M
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.7.0:compile (default-compile) on project ecommercespringboot: Compilation failure: Compilation failure:
[ERROR] /home/andre/Documentos/workspace-sts/ecommercespringboot/src/main/java/br/eti/krebscode/ecommercespringboot/utils/TestUtil.java:[8,20] package org.hamcrest does not exist
[ERROR] /home/andre/Documentos/workspace-sts/ecommercespringboot/src/main/java/br/eti/krebscode/ecommercespringboot/utils/TestUtil.java:[9,20] package org.hamcrest does not exist
[ERROR] /home/andre/Documentos/workspace-sts/ecommercespringboot/src/main/java/br/eti/krebscode/ecommercespringboot/utils/TestUtil.java:[61,54] cannot find symbol
[ERROR] symbol:   class TypeSafeDiagnosingMatcher
[ERROR] location: class br.eti.krebscode.ecommercespringboot.utils.TestUtil
[ERROR] /home/andre/Documentos/workspace-sts/ecommercespringboot/src/main/java/br/eti/krebscode/ecommercespringboot/utils/TestUtil.java:[70,54] cannot find symbol
[ERROR] symbol:   class Description
[ERROR] location: class br.eti.krebscode.ecommercespringboot.utils.TestUtil.ZonedDateTimeMatcher
[ERROR] /home/andre/Documentos/workspace-sts/ecommercespringboot/src/main/java/br/eti/krebscode/ecommercespringboot/utils/TestUtil.java:[86,32] cannot find symbol
[ERROR] symbol:   class Description
[ERROR] location: class br.eti.krebscode.ecommercespringboot.utils.TestUtil.ZonedDateTimeMatcher
[ERROR] /home/andre/Documentos/workspace-sts/ecommercespringboot/src/main/java/br/eti/krebscode/ecommercespringboot/utils/TestUtil.java:[69,9] method does not override or implement a method from a supertype
[ERROR] /home/andre/Documentos/workspace-sts/ecommercespringboot/src/main/java/br/eti/krebscode/ecommercespringboot/utils/TestUtil.java:[85,9] method does not override or implement a method from a supertype
[ERROR] -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[
</code>
E o código da minha classe TestUtil é esse:
<code>package br.ecommercespringboot.utils;

import java.io.IOException;
import java.nio.charset.Charset;
import java.time.ZonedDateTime;
import java.time.format.DateTimeParseException;

import org.hamcrest.Description;
import org.hamcrest.TypeSafeDiagnosingMatcher;
import org.springframework.http.MediaType;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;

public class TestUtil {

    /** MediaType para JSON UTF8 */
    public static final MediaType APPLICATION_JSON_UTF8 = new MediaType(
        MediaType.APPLICATION_JSON.getType(),
        MediaType.APPLICATION_JSON.getSubtype(), Charset.forName("utf8"));

    /**
     * Converte um objeto para JSON byte array.
     *
     * @param object
     *            o objeto para converter
     * @return JSON byte array
     * @throws IOException
     */
    public static byte[] convertObjectToJsonBytes(Object object)
        throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);

    JavaTimeModule module = new JavaTimeModule();
    mapper.registerModule(module);

    return mapper.writeValueAsBytes(object);
    }

    /**
     * Crie uma matriz de bytes com um tamanho específico preenchido com dados especificos.
     *
     *
     * @param size tamanho do byte array
     * @param data dados para colocar no byte array
     * @return o JSON byte array
     */
    public static byte[] createByteArray(int size, String data) {
    byte[] byteArray = new byte[size];
    for (int i = 0; i < size; i++) {
        byteArray[i] = Byte.parseByte(data, 2);
    }
    return byteArray;
    }

    /**
     * Um correspondente que testa que a cadeia examinada representa o mesmo instante que a data e hora de referência.
     */
    public static class ZonedDateTimeMatcher extends TypeSafeDiagnosingMatcher<String> {

    private final ZonedDateTime date;

    public ZonedDateTimeMatcher(ZonedDateTime date) {
        this.date = date;
    }

    @Override
    protected boolean matchesSafely(String item, Description mismatchDescription) {
        try {
            if (!date.isEqual(ZonedDateTime.parse(item))) {
                mismatchDescription.appendText("was ").appendValue(item);
                return false;
            }
            return true;
        } catch (DateTimeParseException e) {
            mismatchDescription.appendText("was ").appendValue(item)
                .appendText(", which could not be parsed as a ZonedDateTime");
            return false;
        }

    }

    @Override
    public void describeTo(Description description) {
        description.appendText("a String representing the same Instant as ").appendValue(date);
    }
    }

    /**
     * Cria um correspondente que corresponde quando a cadeia examinada representa a mesma instância que a data e hora de referência
     * @param date datetime de referência em relação ao qual a sequência examinada é verificada
     */
    public static ZonedDateTimeMatcher sameInstant(ZonedDateTime date) {
    return new ZonedDateTimeMatcher(date);
    }

}
</code>
Comment: Talvez valha a pena você adicionar o `pom.xml` também.
Answer: Eu queria executar os testes e depois gerar o .jar do projeto, o erro que cometi foi que em vez de executar o comando mvn package eu executei o mvn build e por isso acontecia o erro, confundi os comandos.
Agora esta funcionando!


Como fazer consulta em um select que tenha dois valores?

Question: Tenho um campo que digito o código referente e ele já seleciona automático o select para facilitar a vida do usuário que já sabe os código.
Tenho esse select com dois valores em uma lista. Gostaria de saber como eu posso fazer uma busca no select cuja o valor de pesquisa está na posição 1.

$('#inputTurno2').change(function () {
  var valSelecionado = $(this).val();
  var turno = JSON.parse(valSelecionado);
  $('#iputTurno1').val(turno[1])
});

<input type="number" class="form-control pular_inclusa" id="iputTurno1" placeholder="cod">
<select name="turno" class="form-control" id="inputTurno2">
  <option value="['', '']">---------</option>
  <option value="[1, 1]">Alvorada</option>
  <option value="[10, 2]">Federal</option>
</select>

O contrario eu consigo, selecionar algum valor no select e ele colocar o valor que preciso no input.
Answer: Conseguir resolver fazend

$('#iputTurno1').blur(function () {
            var codigo = $(this).val();
            $("#inputTurno2 option").each(function () {
                var valores = $(this).val();
                var teste = JSON.parse(valores);
                if(teste[1] == codigo){
                    $('#inputTurno2').val(valores);
                }
            });

o esse código via jquery.
Answer: Vale lembrar que o parse de "['', '']" pode ser problemático e que codigo inicialmente será string.
Aqui tem a documentação $().each
$('#iputTurno1').blur(function () {
  var codigo = Number($(this).val());
  $("#inputTurno2 option").each(function () {
    var rawValues = $(this).val();
    var values = JSON.parse(rawValues);
    if (values && values[1] == codigo) {
        $('#inputTurno2').val(rawValues);
        // aqui ja encontramos a única opção então vamos parar o $().each
        return false
    }
  });
});

Comment: Pois é eu mudei o parse para [0,0], e com isso funcionou.
com alguns acréscimo e ajuste que você propôs no código eu consegui resolver outra parte que não estava conseguindo tratar, que foi colocar um alert para falar que não existe o código digitado.

Muito obrigado pela ajuda, tenho pouco tempo que iniciei no java script ainda aprendendo.


Mostrar sql gerada pelo JPA/Hibernate

Question: Há alguma forma de mostrar a SQL gerada pelo JPA/Hibernate sem ser habilitando a propriedade <property name="hibernate.show_sql" value="true"/>?
A dificuldade é que preciso monitorar apenas uma query e, se eu ligar o show_sql serão logadas todas as queries no console.
Answer: Você pode habilitar e desabilitar o log do SQL usando o código abaixo
Logger sqlLogger = Logger.getLogger("org.hibernate.SQL");
sqlLogger.setLevel(Level.DEBUG);

... código ...

sqlLogger.setLevel(Level.OFF);

Comment: Perfeito! Valeu ;)

Mostrar sql gerada pelo JPA/Hibernate


Maintenance mode and user session

Question: When I put site in maintenance mode and after turn site back all users sessions are not active (is need to log in account), but I put session to work 2 month and it work.
How to prevent users logout when put site in maintenance?
Comment: Did the database change during the maintenance mode? Did you do any updates?
Comment: No, I can use something other to stop access for users to site for some time, but also when make updates the site also is in maintenance. And It also lost  will drop all sessions.
Answer: This is intended behavior, if user does not have "access site in maintenance mode" permission, then user is logged out.
For Drupal 7 take look on user_menu_site_status_alter
For Drupal 8 take look on Drupal\user\EventSubscriber\MaintenanceModeSubscriber
Comment: The question was about losing sessions after the Maintenance mode is turned off, not during it.
Comment: Yes, this is the reason why the session is destroyed - the logged-in user visits the website which is in maintenance mode. The user who visits the website after the maintenance mode is turned off will not be logged out.
Comment: Thanks for linked to the code here. This is shocking behavior, does anyone know if there were technical reasons behind doing this? Users lose all content they were working on if they hit "submit" or refresh the form they were working on. I am looking for some discussions around this to understand the "why" a bit better.

Maintenance mode and user session


I want to copy and run .exe file on a remote Windows machine?

Question: i have copied the exe file and it was no problem, useing the following code, but now i want to run it, can anyboyd help me on this.
NOTE: i have the access to servers through remote desktop, but cant do this manually, coz there are dozens of them, cant get a program running on it like psex or whatever.
WindowsIdentity wi = new WindowsIdentity(token);

//Next I set the WindowsImportsonationContext

WindowsImpersonationContext impctx = wi.Impersonate();
System.IO.File.Copy("C:\\output.html", "\\\\PW42\\c$\\output1.html", true);
System.Diagnostics.Process p = new System.Diagnostics.Process();
try
{
    System.Diagnostics.Process.Start(@"\\PW42\c$\txt.bat");
    //runFile();
}
catch
{
    Console.WriteLine("error");
}

Comment: Wouldn't that be a major security hole?
Comment: @Marko it can be a security whole if i cant access the pc through remote desktop at all, but in my case i can do that, and i am the administrator of all the pcs so know the administrator username and password
Comment: What is token? How to get it?
Answer: Depending on what access you have on the server you can use a program like psexec or using WMI to launch the file remotely.
A sample psexec command would be
psexec \\computername -u remoteusername filepath(on remote computer) arguments

Psexec can copy the file beforehand if requested and can run against a list of computers instead (replacing \\computername with @computer-list.txt). With WMI you need to connect to the Win32_Process class and Create a new object to start it. The second post in this thread could work.
Unfortunately both of these options require multiple firewall rules (like RPC and WMI) to be available from the running workstation. If your company only has RDP access enabled through the firewall, neither of these will probably work.
Comment: psexec doesn't need to be installed, it takes care of that itself when run for the first time. If it can access the remote computer with admin credentials you can run psexec.
Comment: actually there are hundreds of servers so need to do this automatically through code, cant go there to install psexec thanks


Studing rand( ) function

Question: I've tried analize some probabilities involving rand( ) function, so I done this code:
int vetor_aleatorio[2], vetor_aleatorio_2[2], contador_de_atribuicoes = 0;

srand(time(NULL));
do {
     contador_de_atribuicoes += 1;
     for (int i=0; i<1; i++)
     {
        vetor_aleatorio[i] = rand() % 3 + 1;
        vetor_aleatorio_2[i] = rand() % 3 + 1;
     }
   } while (vetor_aleatorio != vetor_aleatorio_2);

int c = contador_de_atribuicoes - 1;
std::cout << "A quantidade de atribuicoes para que o valor das duas arrays fossem iguais, foi: " << c << std::endl;

I done this to try analize how many assignments are necessary for vetor_aleatorio be equal to vetor_aleatorio_2... But, It is never finished, even I using small arrays and a short sample space on the rand( ), indicating that that arrays aren't equal.
Can someone explain me for what this happens ?
Thanks!
Comment: What is the purpose of your `for` loop?
Comment: the one good advice is to use english language for naming
Comment: You should start with a simpler program that allows you to explore how the basic language works. Don't dive right into the deep end.
Comment: fill up the entire vector
Comment: @Blender he's testing how well the compiler optimizes as well ;)
Comment: The for is to insert into array the aleatory values generated by rand( ).
Comment: @TheJoker: But the only value that `i` will have in the body of the `for` loop is `0`, so your arrays will have hold exactly one value. You could've just done `while (rand() % 3 != rand() % 3) { ++loops; }`
Comment: Itsn't the way I'd want, but works.
Comment: when you are filling up the vectors, compare the index to the size, not to one less. when comparing vectors, use the function provided in my answer
Answer: In line
while (vetor_aleatorio != vetor_aleatorio_2)

you are comparing addresses of arrays (because name of the array is a pointer to the first entry), which are different.
while (vetor_aleatorio != vetor_aleatorio_2)
              ^                   ^
//          this is address       and this is address too

You can write:
do {
     contador_de_atribuicoes += 1;
     vetor_aleatorio[0] = rand() % 3 + 1;
     vetor_aleatorio_2[0] = rand() % 3 + 1;

} while ( vetor_aleatorio[0] != vetor_aleatorio[0]);

Comment: So, can you explain me how can I check if the values of the arrays are equals?
Comment: @TheJoker vetor_aleatorio[0] != vetor_aleatorio[0]
Comment: Thus, Cannot I compare the whole array once?
Comment: @TheJoker yes, you can, but your array has one entry only and each time you generate just two new values so why not to compare them directly?
Comment: Man, Firstly, It was a little example. I'd do arrays much longer.
Comment: @TheJoker you can call a function bool cmp() { //iterate over arrays, return true if (condition) }
Comment: If you use `std::vector` or `std::array` then `==` will work as you intended.  If you want to stick with an array, then you can either loop yourself or use e.g. [std::equal](http://en.cppreference.com/w/cpp/algorithm/equal) or even  `memcmp()`.
Answer: You are comparing whether the two arrays are the same incorrectly. What you are comparing is if the pointer to the start of the arrays are the same, which will never be true. You need to explicitly compare each of the elements in each array not the array variables themselves.
Comment: So, can you explain me how can I check if the values of the arrays are equals?
Comment: @TheJoker You could write a function that accepts two arrays and iterates through each of them returning false as soon as the value at the current index is different in one from the other, finally returning true indicating they are equal
Answer: use for comparision: ( place before your main )
bool comp_vec_2( int* v1, int* v2 )
{
    for( int i=0; i<2; ++i )
        if( v1[i] != v2[i] )
            return false;
    return true;
}

Notice that you should compare index less than 2, not 1.
Same goes when you are filling up the vector
replace while condition with
while ( ! comp_vec_2(vetor_aleatorio, vetor_aleatorio_2) ) ;

Comment: You could also use a standard library algorithm instead of writing a one-off function: `std::equal(vetor_aleatorio, vetor_aleatorio + 2, vetor_aleatorio_2)`
Comment: This doesn't really help the OP if you don't tell him where to use it.

Studing rand( ) function


Difficulties tuning an instrumental combo

Question: There are three instruments involved:

A piano.
2 guitars.
 One guitar is tuned to standard E A D G B E.
 The other guitar is tuned to an open D.
 The piano is standard tuning.

Why don't all 3 instruments sounds the same? The 2 guitars sounds the same, but when the piano comes in it is out of tune.
Comment: Did you tune the guitars to match the piano? Generally everyone has to tune to the piano because you can't retune a piano on the fly.
Comment: @ToddWilcox this is the answer
Answer: This is an old problem, where the piano may well be in tune with itself, but not up to concert pitch - assuming it's an acoustic piano, in which case, it may not even be in tune with itself! There is no point in using guitar tuners for the guitars, so the reference point has to be the piano. Play the appropriate notes on the piano, and tune the guitars to those.
Before the days of electronic pianos, my band would use the oft available, oft slightly out of tune piano at the venue, and we all had to re-tune to that. Use the tuners to ascertain what the piano is tuned to as a matter of interest.


Convergence of multivariate ECDF

Question: Gilvenko-Cantelli assures uniform a.s. convergence of univariate ECDF.  My questions are:

Are there similar assurances for multivariate ECDF?
How is the rate of convergence dependent on the dimensions of the r.v.?

Thank you in advance.
Answer: An answer to this question can be found here. In case you cannot get access to the book that is linked, I will repeat the result here:

Suppose $\mathcal{C}$ is a VC class of $\mathcal{X}$. Define,
$$ D_n(\mathcal{C})\equiv ||P_n - P||_\mathcal{C}$$
Then for all $\epsilon>0$,
$$\sup_P \Pr[\max_{m\geq n} D_m(\mathcal{C})\geq\epsilon]=\sup_P \Pr[\max_{m\geq n} ||P_m - P||\geq\epsilon] {\to} 0$$ as $n\to\infty$. That is, $$D_n(\mathcal{C})\overset{a.s.}{\to}0$$ uniformly over $P$.

As noted in the answer we can set $\mathcal{X}=\mathbb{R}^d$ to get at your question. The main motivating condition that we have is that $\mathcal{C}$ must be a VC class. Suppose we take $\mathcal{C}=\{(-\infty,x] : x \in \mathbb{R}^d\}$. Then we will find that the VC-index number of $\mathcal{C}$ is $v_\mathcal{C} = d+1$. For $\mathcal{C}$ to be a VC class we need that $v_\mathcal{C}<\infty$. This should give you some sense of how dimensionality is at work here. For more details, you should try to get a hold of the book of course.

Convergence of multivariate ECDF