Getting color from pixel and returning color code (in hexadecimal)

Question: I want to be able to get the color from an image pixel and to display the color "code" on the screen in hexadecimal.
This is my code:
<code>public class MainActivity extends Activity {
TextView touchedXY, invertedXY, imgSize, colorRGB;
ImageView imgSource1;
Button b, bOpenFromGallery;
static final int CAMREQUEST = 1;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    touchedXY = (TextView) findViewById(R.id.xy);
    invertedXY = (TextView) findViewById(R.id.invertedxy);
    imgSize = (TextView) findViewById(R.id.size);
    colorRGB = (TextView) findViewById(R.id.colorrgb);
    b = (Button)findViewById(R.id.Button01);
    bOpenFromGallery = (Button)findViewById(R.id.button_openFromGallery);
    imgSource1 = (ImageView)findViewById(R.id.source1);

    b.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
            startActivityForResult(cameraIntent, CAMREQUEST);

        }

    });

}

 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode == RESULT_OK) {
        if (requestCode == CAMREQUEST) {

            Bitmap bitmap = (Bitmap) data.getExtras().get("data");
            Bitmap newBitmap = BITMAP_RESIZER(bitmap, 1280, 768);

            imgSource1.setImageBitmap(newBitmap);
            imgSource1.setOnTouchListener(imgSourceOnTouchListener);
        }
    }
}

OnTouchListener imgSourceOnTouchListener
        = new OnTouchListener() {

    @Override
    public boolean onTouch(View view, MotionEvent event) {

        float eventX = event.getX();
        float eventY = event.getY();
        float[] eventXY = new float[]{eventX, eventY};

        Matrix invertMatrix = new Matrix();
        ((ImageView) view).getImageMatrix().invert(invertMatrix);

        invertMatrix.mapPoints(eventXY);
        int x = Integer.valueOf((int) eventXY[0]);
        int y = Integer.valueOf((int) eventXY[1]);

        touchedXY.setText(
                "touched position: "
                        + String.valueOf(eventX) + " / "
                        + String.valueOf(eventY));
        invertedXY.setText(
                "touched position: "
                        + String.valueOf(x) + " / "
                        + String.valueOf(y));

        Drawable imgDrawable = ((ImageView) view).getDrawable();
        Bitmap bitmap = ((BitmapDrawable) imgDrawable).getBitmap();

        imgSize.setText(
                "drawable size: "
                        + String.valueOf(bitmap.getWidth()) + " / "
                        + String.valueOf(bitmap.getHeight()));

        //Limit x, y range within bitmap
        if (x < 0) {
            x = 0;
        } else if (x > (bitmap.getWidth() - 1)) {
            x = bitmap.getWidth() - 1;
        }

        if (y < 0) {
            y = 0;
        } else if (y > (bitmap.getHeight() - 1)) {
            y = bitmap.getHeight() - 1;
        }

        int touchedRGB = bitmap.getPixel(x, y);

        colorRGB.setText("touched color: " + Integer.toHexString(touchedRGB));
         colorRGB.setTextColor(touchedRGB);

        return true;
    }
};

public Bitmap BITMAP_RESIZER(Bitmap bitmap,int newWidth,int newHeight) {
    Bitmap scaledBitmap = Bitmap.createScaledBitmap(bitmap, newWidth, newHeight, true);

    float ratioX = newWidth / (float) bitmap.getWidth();
    float ratioY = newHeight / (float) bitmap.getHeight();
    float middleX = newWidth / 2.0f;
    float middleY = newHeight / 2.0f;

    Matrix scaleMatrix = new Matrix();
    scaleMatrix.setScale(ratioX, ratioY, middleX, middleY);

    Canvas canvas = new Canvas(scaledBitmap);
    canvas.setMatrix(scaleMatrix);
    canvas.drawBitmap(bitmap, middleX - bitmap.getWidth() / 2, middleY - bitmap.getHeight() / 2, new Paint(Paint.FILTER_BITMAP_FLAG));

    return scaledBitmap;

}

}
</code>
The problem with that is that it returns something like "ff930d14" for red, which isn't the correct value of red. I want it to display "ff0000", the correct value of red.
Comment: How can I make it display the code without transparency? (instead of "ff930d14", to display "930d14")
Answer: First off, your "correct" red is wrong.  It would be FFFF0000, as the first 2 characters are the transparency.  Secondly, there is no one "correct" red.  Very rarely is pure red used as a color.  It usually isn't maximum red (FFXY0000 is red for any value of XY, just different amount of brightness).  For that matter, mixing in small amounts of other colors like you see there is very common.  About the only time you'd get a pure color value is in a specially made example bitmap.  Real images use a variety of colors, that's why we have 32 bit color.
Basically what you want is wrong.  Its returning the right thing-  the actual color being used.  If you want to turn that into a human description of that color, like "red" or "magenta", you're going to need to create a mapping function.
Comment: How can I make it display the code without transparency? (instead of "ff930d14", to display "930d14")
Comment: Mask it off.  Use color= color & 00FFFFFF;
Comment: I am kinda newbie, can you please tell me exactly how to do it based on my code right here?


Converting to and from epoch time

Question: I often find myself needing to convert from one type of time to another, and haven't found a way I'm consistently happy with. Every time I do a quick google search, I come up with different (sometimes painfully complex) answers.
I'm happy with
date -d "Sep 5 1986" "+%s"

for converting a standard date to epoch time, but I can't seem to make the reverse work (and the man pages I've browsed aren't helping much.)
date -d "526276800" "+%m/%d/%y"

yields an error on my RHEL 5 install.
Can the community offer me some strategies for easily converting back and forth? I'll take all forms: awk, perl, date. What are the pros and cons of each method?
Answer: date -d @526276800 "+%m/%d/%y"
Comment: For the Red Hat centered here, like myself: this works from RHEL4 and up. The date command in RHEL3 is of the 4.x branch, which does not have this functionality.
Comment: Ah ha! That's the notation I was looking for, thanks! I can't believe this didn't come up for me in my google searches.
Comment: I can't believe it's not in the man page for date.
Comment: I wondered that myself -- after a quick look at the bottom of the man page, I noticed that (at least on my RHEL 5 system) there is further documentation available in the info pages and the syntax is listed there (though I did have to follow something like 4 links to get there)
Answer: On my Mac OS X box, I use:
date -r 526276800 +%m/%d/%y

Comment: This is on at least Mac OS X and OpenBSD. May be present on other BSD derived systems, too.
Answer: With GNU date:
date  -d '1970-01-01 946684800 seconds'
Comment: That's a nice trick!
Answer: Or in Ruby:
% ruby -e 'puts Time.now.to_f'
1243620267.8988

% ruby -e 'puts Time.now.to_i'
1243620267

% ruby -e 'puts Time.at 1243620270'
Fri May 29 11:04:30 -0700 2009

% ruby -e 'puts Time.at(1243620270).strftime "at %I:%M%p"'
at 11:04AM

Here are the strftime formats, taken from the ruby Time class documentation:
  %a - The abbreviated weekday name (``Sun'')
  %A - The  full  weekday  name (``Sunday'')
  %b - The abbreviated month name (``Jan'')
  %B - The  full  month  name (``January'')
  %c - The preferred local date and time representation
  %d - Day of the month (01..31)
  %H - Hour of the day, 24-hour clock (00..23)
  %I - Hour of the day, 12-hour clock (01..12)
  %j - Day of the year (001..366)
  %m - Month of the year (01..12)
  %M - Minute of the hour (00..59)
  %p - Meridian indicator (``AM''  or  ``PM'')
  %S - Second of the minute (00..60)
  %U - Week  number  of the current year,
          starting with the first Sunday as the first
          day of the first week (00..53)
  %W - Week  number  of the current year,
          starting with the first Monday as the first
          day of the first week (00..53)
  %w - Day of the week (Sunday is 0, 0..6)
  %x - Preferred representation for the date alone, no time
  %X - Preferred representation for the time alone, no date
  %y - Year without a century (00..99)
  %Y - Year with century
  %Z - Time zone name
  %% - Literal ``%'' character

Answer: $ perl -le 'print scalar localtime 1243620900'
Fri May 29 11:15:00 2009

Answer: It may be a little heavy duty, but in perl there's a great module called DateTime that'll convert back and forth between a myriad of date & time formats, including epoch.  It's very simple to use:
http://datetime.perl.org/
Answer: Personally, I alternatively use Python and bash for this. But since you are annoyed with it ;-) I'd go for making a small script that takes a date as a parameter and write it so as to have --2epoch and --2normal options.
That way, you can convert from epoch to normal with
./script.sh --2normal 1243609635

and the other way around with
./script --2epoch "20090529 17:07"

Is the input date always formatted the same way? That would make the script a lot easier to write.
Answer: Perl one-liner:
$ perl -MDate::Manip -le 'print UnixDate(ParseDateString("epoch ".shift()),"%c")' 946684800
Answer: FROM epoch:
dump epoch timestamps to readable forms from stdin (first example)
or as args (second example), and dont forget the power of strftime!
perl -pe '$_=~s/(\d{10})/scalar localtime($1)/eg'
perl -e '$s=join(" ",@ARGV);$s=~s/(\d{10})/scalar localtime($1)/eg;print"$s\n"'
perl -pe 'use POSIX qw(strftime);s/(\d{10,10})/strftime("%Y%m%d-%H:%M:%S",$1)/eg'
TO epoch:
If you have Date::Manip module installed for perl (which usually ISNT there by default), you can use:
perl -MDate::Manip -e '$stamp=UnixDate(ParseDate(join(" ",@ARGV)),"%s");printf"%d %s\n",$stamp,scalar localtime($stamp)' sep 9 2006
Sometimes it's hard to decide if you want to REPLACE the timestamps in your 'filter',
or if you want to preface the line with the timestamp found.  I flip back-n-forth on that one.

Converting to and from epoch time


Is there a map of culturally popular time signatures by region?

Question: In watching this video we had a discussion about how certain cultures and regions prefer a certain structure to music.  Time signatures is just one aspect of how a region may vary from another.
Is there any research into how time signatures, or other category, is strongly identified with a culture, region, or era?
Comment: I do not see any reference to time signatures in the link you provide.
Answer: Well, the book on Musical Forms that we used in vocational music school has an overview of "dances", attached to which are regional denominations.
So, focus on "folk" dances, which will open up a whole new world of viewing meter, rhyhtm and timing. They all seem to come from some bodily movement as an expression.


How whatsapp handle APNS notifications even if the app was not launched?

Question: So I am trying to handle the APNS notification even if the app was not launched in iOS,Same like in whatsapp...But ended with failure...Can anyone explain how i can archive this ?
Comment: All apps (Including Whatsapp) need to launch and ask for Push notifications and save device token once , after that push notification can be sent regardless of the state of app.
Comment: "after that push notification can be sent regardless of the state of app." Thats incorrect - an app that has been terminated will not receive a push.
Comment: @BhumitMehta Please compare a APNS Push notification in Whatsapp...Whatsapp will receive notifications even if the app was not launched...I just wonder how they did that ?
Comment: @SausageModulationMatrix Any idea regarding this ?
Comment: whatsapp uses voip pushes. I've not used them myself, but I'm sure a voip push must have to be launched once in order to start receiving them . Are you sure if you uninstall the app, then re-install it and don't start it then it can still receive pushes> I have to say I am very very very skeptical about,  I can't believe any app could receive any type of push or similar without running at least once.
Comment: @SausageModulationMatrix I had founded the solution but if i use Voip permission in my app which is doesn't have VOIP features,It will be rejected in the App Store
Comment: Is your problem resolved? then close this question.
Comment: @Hasya How to close this question ?
Comment: @radkrish accept any answer which helped you. So it will close.
Answer: PushKit can be send to send notification for VOIP app which will silently launch app even if it is terminated by user.
Answer: You can use PushKit (VoIP notification) to achieve this. App should be launched once after that regardless of state of the app notification will appear on device. For this type of notification, app will not ask user confirmation about sending notifications.
Answer: When you download app from app store and don't launch then you cant have push notification.
Try this

Keep distribution certificates
Edit scheme
Select "Wait for executable to be launched"
Now run app in device
Keep debug pointer on didFinishLaunchingWithOptions

Your app will install on device, send push notification it will not come ( Because app not registered for APNS, device token did not reached to server ).
Now tap on app debug pointer at didFinishLaunchingWithOptions will become active, let appDelegate to do rest of work, now send push notification it will come ( Because app is now registered for APNS, device token also reached to server ).
Using pushkit is different thing, would not help you to get push notification without launching an app.


Get attendees for a TryBooking event as an organizer through API

Question: I am developing an application which needs to periodically sync data from TryBooking's API. I have a developer key pair and I can act as the event organizer through the API. I need to get the basic data of the attendees for a given event (name, e-mail address), but I am having trouble getting this from the API.
Querying the event works fine, but in the response there is no trace of this data. I could not find a separate endpoint to directly query the attendees either.
What I found was that apparently the API calls a booking of an attendee for an event a 'transaction', and there are endpoints to query transactions either by an ID or by a date. Reference: https://developer.trybooking.com/#get-by-transactionid
Apparently I can get transaction ids if I set up webhooks and that way when a booking happens, my API will be called with the appropriate transaction id which I can store and then use to query the attendee data. This is fine as I wanted to set up webhooks anyway to reduce the sync delay, but I need to have an alternative. What happens if I don't get the transactionid due to intermittent network or devops issues, or during an app deployment? It seems to me that I have no other way to get it later.
As for the other endpoint, I cannot figure out what the date parameter does. I tried calling it with various values (the date of the event and the date of the booking included), but I always get an empty response.
I'm hoping that someone who already used the API can point me in the right direction.
Answer: You are correct, the expected use case is to setup webhooks (called 'Notify URL' in the TryBooking) so you recieve an request every time a booking occurs.
Note that you will receive a notify call anytime the booking is edited or refunded as well as the initial booking.
Then use the get by transaction id endpoint as to get by transaction details.
As a 'reconciliation' to confirm you have received every transaction you can use the get by date endpoint which will return all transactions on a given date. The date format is yyyy-MM-dd
For example: /au/reporting/v1/bookings?date=2023-11-14
If you have further issues, TryBooking has a customer support team referenced on their website I've found quite helpful with details or help to any specific issues encountered.


How to configure Dev, stage and production Env in Cloudfoundry?

Question: Recently I moved my Spring MVC application from local server to CloudFoundry environment.
In my application I have an environment variable I set at server startup. i.e.
PROJ_ENV=-Dcom.abc.app.env=local

which is used spring config: <util:properties id="appProps" location="classpath:${com.abc.app.env}.application.properties" /> and the same is available in DEV, Stage and Production Servers and having respective application.properties file which contains environment specific values.
How I can maintain same setup in CloudFoundry? Is there any way to define environment/system variables?
Answer: You can set ENV variables with the vmc command line tool using vmc set-env appname varname value.
Have a look at vmc help --all for more info. Also, be aware that env variables names with dots in them are sometimes problematic, this is why Spring sometimes uses capital with underscores as alternatives.
Answer: Just an update, vmc has been deprecated since Cloud foundry v2. instead of VMC now its recommended to use
cf --help

Here is a detail link from vmc source..


how to interpret gradient boost model & results in R?

Question: I'm using R to model votes. I've found that the extreme gradient boost xgbTree algorithm gives nice results. I'm a newbie and don't really know how to interpret the model. My understanding is xgbTree is simply a gradient boost model, which runs fast.
If I use the caret package, I know there is a nice varImp() function that shows me the relative importance of features.
I can also compute the MSE to judge the prediction results.
Other than that, I don't have an idea how to interpret the model and judge predicted results. Was hoping someone could help me understand this in a general sense.
m1<-train(votes~.,data=trainset,method="xgbTree")
p1<-predict(m1,newdata=testset)

I found the following information about the model in R, but not sure how to interpret it from a high-level perspective.
>summary(m1)
            Length Class              Mode
handle          1  xgb.Booster.handle externalptr
raw         68304  -none-             raw
xNames         11  -none-             character
problemType     1  -none-             character
tuneValue       3  data.frame         list
obsLevels       1  -none-             logical

> m1$bestTune
  nrounds max_depth eta
8     100         3 0.3

> print(m1)
eXtreme Gradient Boosting

70001 samples
   11 predictor

No pre-processing
Resampling: Bootstrapped (25 reps)
Summary of sample sizes: 70001, 70001, 70001, 70001, 70001, 70001, ...
Resampling results across tuning parameters:

  max_depth  nrounds  RMSE       Rsquared   RMSE SD      Rsquared SD
  1           50      1.0130456  0.7681330  0.010918047  0.007353824
  1          100      1.0038036  0.7723058  0.010863621  0.007558934
  1          150      0.9989381  0.7744915  0.010900582  0.007602353
  2           50      0.9851318  0.7806992  0.010356168  0.007234972
  2          100      0.9752206  0.7850671  0.010193392  0.007342830
  2          150      0.9711467  0.7868439  0.010170191  0.007324614
  3           50      0.9723670  0.7863109  0.010728093  0.007085609
  3          100      0.9676703  0.7883940  0.010288853  0.006705919
  3          150      0.9674846  0.7884925  0.009959612  0.006718457

Tuning parameter 'eta' was held constant at a value of 0.3
RMSE was used to select the optimal model using  the smallest value.
The final values used for the model were nrounds = 150, max_depth = 3 and eta = 0.3.

What's the best way to analyze the prediction results besides MSE? Can we compute confidence intervals? etc.?
Answer: Ch.8 of "Introduction to Statistical Learning with R" not only discusses gradient boosting but has actual code on using gbm.
Comment: That is the right link.  There is more than one page devoted to gbm.  I would actually read the discussion on bagging and probably rf too.  There is also implementation in the "R lab' section.  Have a look at this video (Tibshirani) for a nice explanation https://www.youtube.com/watch?v=wPqtzj5VZus&list=PL0FVxN48mhgcin_Tv6zmwIIS6Fa5Sm9Tp .  Since it's about 35 min (as I recall) it should give you more information.
Comment: I'm loath to say, "Oh you want more details, just look at Elements of Statistical Learning", so I won't .  It will have a more mathematical approach with more details.
Comment: Thanks @aginensky, I think this is right link (correct me if not): http://www-bcf.usc.edu/~gareth/ISL/  in particular, page 331 relates to GBM. Was hoping there'd be more details.
Comment: Yes, thanks, I'm really new here so only looking for high-level information.


Johansen test conditions and Breusch-Godfrey LM test

Question: I am writing a thesis about the relationship between credit aggregates and property prices. I examine the Granger causality between the two variables and I also do some cointegration tests. I have a question about the latter.
What are the conditions for doing a Johansen cointegration test? Do the residuals need to be tested for serial correlation before you can do the test? Because sometimes I just don't find a model where this is the case. Or do the residuals don't need to be uncorrelated?
Are there other conditions regarding the Johansen test?
When I test for residual autocorrelation I use the Breusch-Godfrey LM test. What is the lag-order that I need to choose for this test? I have 158 observations in my time series. If I do the var-selection in levels I always used a maximum lag of 12 and for the Breusch-Godfrey LM test I always used 6. Is this correct?
If so: where do I find references to support these conclusions?
Answer: For your first question, yes, you need to have uncorrelated residuals. In general, your need to determine the lag order of the VAR THEN your perform a cointegration test. This means that there must be no residual autocorrelation in your VAR model (if there still is, you need to increase the lag order. Which lag order to increase to will depend on your information criteria such as AIC, BIC, etc.). Once the VAR lag order is selected, you perform the cointegration test (assuming normally distributed residuals of course). Also note that the Johansen test statistic converges very slowly (even a sample size of 300 is considered to be small) hence the test result may not be reliable.
For your second question, there are only some general rules. Some may use lag of 12 since one may have yearly data. There may be other general rules btu I was taught to choose the maximum PACF. I have also heard of performing different LM tests with different lag then choose the one with the highest adjusted R-squared or the lowest AIC or SC.


How to put vertical lines left and right of logo

Question: I would like to put vertical lines left and right of this Logo text, but both lines need to touch the bottom border, this is what I have now: Here's a codepen:
http://codepen.io/anon/pen/ZBMXbw

.header-container {
  /*padding: 8px;*/
  border-bottom: 2px solid lightgrey;
  margin-top: 20px;
}
.logo {
  font-size: 12px;
  font-weight: bold;
  position: relative;
  bottom: -10px;
}
.col-md-1 {
  border-left: 1px solid grey;
}
h4 {
  font-weight: bold;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />

Logo here

lorem ipsum lorem lorem

Comment: Would be helpful if you can add an image showing what exactly you want
Comment: depending on the screen size, the second column may be below the first. Would you want the vertical lines to go through that text?
Answer: Use pseudo-elements on .logo. Like this:
.logo:before {
  content: '';
  position: absolute;
  left: 0; /* adjust as you need */
  top: 0;
  width: 1px;
  height: 30px;
  background-color:grey;
}

.logo:after {
  content: '';
  position: absolute;
  right: 0; /* adjust as you need */
  top: 0;
  width: 1px;
  height: 30px;
  background-color:grey;
}

Demo
UPDATED: Thanks to comment by besciualex
Comment: On .logo:after remove **left** property and add **right: 0;** . This way you are not forcing the line to be always after 55px, but rather where the logo ends.
Answer: You can use CSS Flexbox for this. Make your .header-container a flex container. Have a look at the snippet below:

.header-container {
    /*padding: 8px;*/
    border-bottom: 2px solid lightgrey;
    margin-top: 20px;
  display: flex;
  align-items: center;
}

.logo {
    padding: 0 10px;
    margin-right: 10px;
    font-size: 12px;
    font-weight: bold;
    position: relative;
    border-right: 1px solid;
    border-left: 1px solid;
    align-self: stretch;
    display: flex;
    align-items: center;
}

h4 {
    font-weight: bold;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

Logo

                    lorem ipsum lorem lorem

Hope this helps!
Answer: it seems to me that what you need is to use the pseudo selectors ::before and ::after. Try the following:
.logo::before {
   content: '';
   display:inline-block;
   width: 1px;
   height: [put the desired height here];
   margin: [adjust margins];
}
.logo::after{
   content: '';
   display:inline-block;
   width: 1px;
   height: [put the desired height here];
   margin: [adjust margins];
}

Let me know if this works.
Answer: Updated copen.
You can use line-height :
.logo {
    font-size: 12px;
    font-weight: bold;
    position: relative;
    bottom: -10px;
    line-height: 30px;
}

.col-md-1 {
  border-left: 1px solid grey;
  border-right: 1px solid grey;
}


Brauer groups, Milnor k theory and group cohomology

Question: Can anyone suggest some basic material for learning connections between Brauer groups, Milnor k theory and group cohomology. I am an undergraduate. So, I find most of the sources available very hard.
Comment: You want to learn the connections. Do you already know the subjects separatey?
Comment: There aren't many basic sources becausse it is not a basic subject.
Comment: As I wrote, it is **not** a basic subject in any possible sense of the term.
Comment: I know just the definitions of Brauer groups and Milnor k groups and some homological algebra. I know stuff like Hilbert 90th theorem. But, still I want to know some basic things. The most basic source I could find was notes by Sridharan given at ETH Zurich. But, I am looking for more basic sources .
Comment: may be...because i have tried so hard but still cannot find a basic source.
Answer: A rather nice approach is in Pierce's Associative Algebras book. You will not find there anything about $K$-theory, but you can safely leave that for later.
Comment: Thanks. Is there anything else you can suggest? I particularly want to study connections between Milnor k2 groups, 2 torsion of Brauer groups and group cohomology.
Comment: Milnor's book on K-theory.
Comment: ok..thanks..i will check that.


how to parallel hadoop job running in stand hadoop distritbuion 0.20.0

Question: I have such a headache for a long time, current my hadoop cluster is like this, I have 40 salve nodes to run, each slave node I configure 25 mappers 10 reducers, so maixumally I can launch 40*25=1000 mappers and 400 reducers simultaneously. Ok, now I have following jobs:
job1: I configure to run 5 mappers and  5 reducers
job2: I configure to run 20 mappers and 10 reducers
job3: I configure to run 975 mappers and 385 reducers
Suppose I use default FIFO job sheduling, if I submit the 3 mappers consecutively, is it possible that the 3 jobs can run simultaneously?  so that the cluster is maximumly utilized?
Currently, I test it that at the mapper phase, it seems 1000 mappers can launched after submit the 3 jobs, however, at the reducer phase, it become very very slow, so that I wait a long time, none of the above job finish, it seems they are hang at the reducer phase.
I am not very understand the inherent reason for this, can anyone help me on this issue so that I can submit the job and sleep, then tomorrow morning I see all my jobs are finish by order? Do I need to use fair scheduling to make it work????
Answer: It is a bit hard to give solution - but I will try to give directions to find one.
1. If you have enough reduce slots in the cluster - probably your problem is not related to parallel job execution. At least I would not suspect it in the first place.
2. I would suggest to use Fair Scheduler - it is specifically built for the parallel execution and resource sharing.
3. I would suggest testing each job separately and only after each one running good - start parallel run.
4. Slow reduce can have number of reasons but I would check the following (what I know):
a) A lot of data passed (and thereof serialized) between mapper and reducer.  Take a look on File system bytes written counter to identify it.
b) There is serious data skew and a lot of data come to the single reducer.


Must the $\forall$ statement be used in front of the consequent statement?

Question:
Must the $\forall$ statement be used in front of the consequent statement?

For example, must we write $\forall x\in\mathbb{Z}^{+}, x>0$, or can we also write $x>0, \forall x\in\mathbb{Z}^{+}$
In proofs, the 1st one is most common, but I have a personal preference to write the 2nd one. I just wanted to ask which one (or both) is accepted, and which one is preferred. Thanks in advance.
Comment: It's up to you, as soon as it is understandable and unambiguous. Remember that such a sentence is just a translation in formal language of a real-life spoken sentence, and that "All positive integers are positive" and "A number is positive as soon as it is a positive integer" are both valid.
Comment: Usually the quantificator has to be on the left of the statement (1st one). Using them in a "natural language" way is bad practice (my teacher would give penalties for such use ahah... ). Use english words if you want a formulation like the second statement, not logical quantificator that have to obey rules. Also, if you have multiple quantificators, the order is critical and it can be even more misleading if you do not respect this.
Comment: Besides the issue of hanging quantifiers (do a site search), I also suggest [omitting that comma](https://math.stackexchange.com/a/4412936/21813); both issues relate to your quantifiers' scope ambiguity. By the way, there is no consequent in your displayed statement; consequent means the right side of a conditional statement. Finally: *"I have a personal preference to write the 2nd one"*: I feel that peppering mathematical prose with symbols decreases readability; however, when writing in symbols is actually helpful (e.g., to clarify meaning), there's no point doing so ambiguously, right?
Answer: In every formal system I have ever encountered, only $\forall x \in \mathbb{Z} \ , \ x > 0$ makes sense. The reason is that quantifiers bind what is on their right - if the statement comes first and the quantifier second, the variable in the statement would be free.
Assuming that your math is written in a context where reading happens from left to right, it is also confusing if the variable gets introduced only later. As such, even in informal writing, I'd consider the second very bad style.
You are of course free to introduce your own idiosyncratic notation.
Answer: The scope of a quantifier should be very clear. This is especially true with statements that have nested quantifiers of different types. If you get in a habit of mixing the positions of quantifiers around, sometimes before and sometimes after, your reader will be unable to correctly detect the scope of the quantifier, and may misread the statement, and the sh** hits the fan.
This issue of making the scope clear, by the way, is independent of whether you use symbols or words for your quantifiers. I'll use words, but feel free to substitute $\forall$ for my words "for all" and $\exists$ for my words "there exists" in what follows.
Let's take, for example, the definition of continuity of a function $f : \mathbb R \to \mathbb R$ at $a \in \mathbb R$, correctly written at first, with quantifiers preceding their scope:

For every $\epsilon > 0$ there exists $\delta > 0$ such that for every $x \in \mathbb R$, if $|x-a|<\delta$ then $|f(x)-f(a)|<\epsilon$.

Suppose now you that you decide you like to put your first universal quantifier at the end.

There exists $\delta > 0$ such that for every $x \in \mathbb R$ if $|x-a| < \delta$ then $|f(x)-f(a)| < \epsilon$, for every $\epsilon > 0$.

Big trouble. What's the scope of that $\epsilon$ quantifier? As written, it could easily be interpreted to be the same as the scope of the $x$ quantifier. Which, if that intepretation were correct, would then be equivalently the the following statement with quantifiers in their correct position preceding their scope:

There exists $\delta > 0$ such that for every $\epsilon > 0$ and every $x \in \mathbb R$, if $|x-a| < \delta$ then $|f(x)-f(a)| < \epsilon$.

BIG BIG BIG trouble. This statement is NOT equivalent to the definition of continuity.
Answer: We need to distinguish between the formal syntax of the predicate calculus, and prose exposition.
Predicate calculus has precise syntax rules for good reasons, and these dictate that the quantifiers come in front. (Examples below.) But in prose exposition, people often put them afterwards. On the other hand, in textbooks and such, you won't usually find the symbol $\forall$ used as a shorthand for the words "for all". (In handwritten notes or on the blackboard, sure.)
The formal syntax handles alternating universal and existential quantifiers without ambiguity. Consider the distinction between uniform and pointwise convergence of a sequence of functions, $f_n\to f$, say on the interval $(0,1)$. First, uniform:
$$\forall \epsilon\; \exists N\; \forall n\!\!>\!\!N\;\forall x\!\!\in\!\!(0,1)\;
|f_n(x)-f(x)|<\epsilon$$
and then pointwise:
$$\forall \epsilon\;\forall x\!\!\in\!\!(0,1)\; \exists N\; \forall n\!\!>\!\!N\;
|f_n(x)-f(x)|<\epsilon$$
The distinction is subtle enough that Cauchy initially got it wrong. (Slight oversimplification of the history; see Jeremy Gray's The Real and the Complex: A History of Analysis in the 19th Century for the full story.)
Of course, you can make any chain of quantifiers clear enough in regular prose, but authors don't always do a good job of this.
By the way, "consequent" has a technical meaning in logic. It's the $B$ in an implication $A\Rightarrow B$, with $A$ be the antecedent.
Finallly, a personal opinion: I think of Aristotle's logic as "always, sometimes, never" logic. The premises and conclusions of his syllogisms can always be cast in the form $\forall x P(x)$ or $\exists x P(x)$, where $P(x)$ is a boolean combination of some sort. Formal logic first advanced decisively beyond Aristotle when it learned to handle the alternation of quantifiers.
Answer: If $x>0$ is understood to mean $x\in\{z\in\mathbb R : z>0\}$, then $x\in\mathbb Z^+$, $x>0$ and $x>0$, $x\in\mathbb Z^+$ virtually mean the same: $x\in\mathbb Z^+$, $x>0$ $\iff$ $x\in(\mathbb Z^+\cap \{z\in\mathbb R : z > 0\})$. Since the set intersection is commutative, it holds that $\mathbb Z^+\cap \{z\in\mathbb R : z > 0\} = \{z\in\mathbb R : z > 0\} \cap \mathbb Z^+$, and $x>0$, $x\in\mathbb Z^+$ $\iff$ $x\in(\{z\in\mathbb R : z > 0\} \cap \mathbb Z^+)$.


Getting Soap Fault on hitting a WebService using JMETER

Question: I'm trying to contact a webservice via Jmeter (3.0), and I get the following error:
<?xml version="1.0" encoding="UTF-8"?>
<s:Envelope xmlns:s="http://www.w3.org/2003/05/soap-envelope">
   <s:Body>
      <s:Fault>
         <s:Code>
            <s:Value>s:Sender</s:Value>
            <s:Subcode>
               <s:Value xmlns:a="http://schemas.microsoft.com/ws/2005/05/addressing/none">a:ActionNotSupported</s:Value>
            </s:Subcode>
         </s:Code>
         <s:Reason>
            <s:Text xml:lang="es-AR">The message with Action '' cannot be processed at the receiver, due to a ContractFilter mismatch at the EndpointDispatcher. This may be because of either a contract mismatch (mismatched Actions between sender and receiver) or a binding/security mismatch between the sender and the receiver.  Check that sender and receiver have the same contract and the same binding (including security requirements, e.g. Message, Transport, None).</s:Text>
         </s:Reason>
      </s:Fault>
   </s:Body>
</s:Envelope>

I haven't encountered any issues contacting the web service from SoapUI, so I'm wondering what could cause this problem.
You can see the screen shots here:
The HTTP Request within the tree, first part of the HTTP Request data, the HTTP Header Manager settings: https://i.stack.imgur.com/6HxIK.jpg

Here are the results on SoapUI (works just fine):
Results and log

Is it possible that the way that SoapUI sends the requests differs from the way Jmeter does and that's why it works?
Please help. Thanks!
Comment: couldyou show your test plan ?
Answer: I think you have some trivial error in the value of http header SOAPAction.
Happened to notice(in the image you attached) that there are double quotes in its value.
Just remove the double quotes " from the SOAPAction value.
UPDATE:
It is noticed, while editing the question, that soapui has sent an additional http header action with a value (you masked the value).
So, please add action header in the jmeter request as well the right value in the jmeter plan.
Answer: You need to put this action bit to be a part of the Content-Type header like:

I would also recommend adding HTTP Cookie Manager to your Test Plan

Out of interest, why don't you just record the request originated from SoapUI using JMeter HTTP(S) Test Script Recorder like:

Configure JMeter for recording. The easiest way of doing this is using JMeter Templates feature

From JMeter main menu: File - Templates - Recording - Create
Workbench - HTTP(S) Test Script Recorder - Start

Configure SoapUI for recording

From SoapUI main menu: Preferences - Proxy Settings
Proxy Settting: manual, host: IP address or hostname of machine where JMeter is running, port: 8888

Execute request in SoapUI
Inspect the recorded request in JMeter under Workbench -> Recording Controller.
Comment: Thank you, that solved the issue, after editing the Content Type settings, I was able to send the request properly. I really appreciate your help!


fwrite fails depending on previous fwrite

Question: I have a problem with some fwrite that fail in way I do not understand.
In this piece of code both fwrite fail and give tmp = 0.
<code>  if ((file = fopen(filenameout, "wb")) != NULL)
  {
    bmpheader->filesz += bmpdib->bmp_bytesz;
    bmpdib->bmp_bytesz *= 2;
    bmpdib->height *= 2;
    tmp = fwrite(bmpheader, sizeof(bmp_header_t), 1, file);
    tmp = fwrite(bmpdib,    sizeof(bmp_dib_t),    1, file);
    tmp = fwrite(bmpdata1,  bmpdib->bmp_bytesz,   1, file);
    tmp = fwrite(bmpdata2,  bmpdib->bmp_bytesz,   1, file);

    fclose(file);
  }
  else
    return 1;
</code>
But if I comment one single line of code everything goes fine:
<code>      if ((file = fopen(filenameout, "wb")) != NULL)
      {
        bmpheader->filesz += bmpdib->bmp_bytesz;
//        bmpdib->bmp_bytesz *= 2;
        bmpdib->height *= 2;
        tmp = fwrite(bmpheader, sizeof(bmp_header_t), 1, file);
        tmp = fwrite(bmpdib,    sizeof(bmp_dib_t),    1, file);
        tmp = fwrite(bmpdata1,  bmpdib->bmp_bytesz,   1, file);
        tmp = fwrite(bmpdata2,  bmpdib->bmp_bytesz,   1, file);

        fclose(file);
      }
      else
        return 1;
</code>
I double checked every detail in my code:

bmpdata1 and bmpdata2 contain valid bmp bitmap data, they produce both a correct image if used alone.
bmpheader and bmpdib are data structures read from a valid bmp file and they are untouched until my code.
all files have been opened in binary mode "rb" for input and "wb" for output.
bmpdata1 and bmpdata2 are copies of the same image, so their byte size is identical.

The goal of my code is to write an image plus a modified copy of it to obtain a final image twice higher than the original one. The original bitmap is a 570 x 363 x 24bit bmp image.
What am I doing wrong?
Any help is very appreciated, thanks.
Comment: If this is a release (optimised) build then you can't assume that `tmp` is valid - the compiler can see that it is not used so may just optimise it away. Add a temporary printf after each fwrite to stop this happening and to be certain that you're chasing the right problem.
Comment: Hi Paul. No, it'a debug release.
Comment: When you comment out that code then the two last calls to `fwrite` write half as much data. Are bmpdata1 and bmpdata2 big enough? What is the `errno` after `fwrite` returns 0?
Comment: You are right Art. That's a stupid error. I used the modified byte size value to write a unmodified size bitmap. I feel I just embarrassed myself. Thank you a lot. Case closed.
Answer: This solved the problem. Thanks to Art.
<code>  if ((file = fopen(filenameout, "wb")) != NULL)
  {
    bmpheader->filesz += bmpdib->bmp_bytesz;
    bmpdib->bmp_bytesz *= 2;
    bmpdib->height *= 2;
    tmp = fwrite(bmpheader, sizeof(bmp_header_t),   1, file);
    tmp = fwrite(bmpdib,    sizeof(bmp_dib_t),      1, file);
    tmp = fwrite(bmpdata1,  bmpdib->bmp_bytesz / 2, 1, file);
    tmp = fwrite(bmpdata2,  bmpdib->bmp_bytesz / 2, 1, file);

    fclose(file);
  }
  else
    return 1;
</code>
I erroneously used the updated bitmap data size to write each part of the final image. The resulting image has double the height because it is composed bay two stacked images which are written each in a separate 'fwrite' operation with half of the resulting bitmap data size each.


Reply buttons not showing in telegram bot

Question: I use pyrogram for my bot
I want to send a messages with buttons:
from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton,ReplyKeyboardMarkup
from pyrogram import types

def cmd_start(self, chat_id, message):
    with Client("my_acc", api_id=self.api_id,api_hash=self.api_hash,proxy=self.proxy) as app:

        start_service = types.InlineKeyboardButton(text='but1', callback_data='service')
        start_system = types.InlineKeyboardButton(text='but2', callback_data='system')
        start_check = types.InlineKeyboardButton(text='but3', callback_data='check')
        start_other = types.InlineKeyboardButton(text='but4', callback_data='other')
        start_keyboard = types.ReplyKeyboardMarkup(keyboard=[[start_service, start_system], [start_check, start_other]])

        app.send_message(chat_id, 'test', reply_markup=start_keyboard)

The sending is successfull, but I see only simple text message 'test' in the chat instead of 4 buttons
Answer: Don't use ReplyKeyboardMarkup for inline keyboards - use InlineKeyboardMarkup instead.
Do something like this:
start_service = types.InlineKeyboardButton(text='but1', callback_data='service')
start_system = types.InlineKeyboardButton(text='but2', callback_data='system')
start_check = types.InlineKeyboardButton(text='but3', callback_data='check')
start_other = types.InlineKeyboardButton(text='but4', callback_data='other')

start_keyboard = types.InlineKeyboardMarkup(inline_keyboard=[[start_service, start_system], [start_check, start_other]])

app.send_message(chat_id, 'test', reply_markup=start_keyboard)

Answer: inline keyboard can be send only by a Bot! you should set bot_token=<token> in kwargs of Client


Array dentro de Array PHP

Question: Estou criando um sisteminha onde pode ser adicionar medicamentos por protocolos.
Ex:
   NOME DO PROTOCOLO
<code>    [ARRAY]
    NOME DO REMÉDIO
    [ARRAY 2]
    NOME DO ITEM        QUANTIDADE         TEMPO DE INFUSÃO [ARRAY]
    NOME DO ITEM 2      QUANTIDADE 2       TEMPO DE INFUSÃO 2 [ARRAY]
    [ARRAY]
    NOME DE UM NOVO REMÉDIO
    NOME DO ITEM        QUANTIDADE         TEMPO DE INFUSÃO   [ARRAY]
    NOME DO ITEM 2      QUANTIDADE 2       TEMPO DE INFUSÃO 2 [ARRAY]
    NOME DO ITEM 3      QUANTIDADE 3       TEMPO DE INFUSÃO 3 [ARRAY]
</code>
Estou fazendo da seguinte maneira:
<code>$codigo = rand(5, 50000);
  // $codigo = uniqueAlfa(6);
  $itemA = $_POST['item'];
  $nomePres = $_POST['nome-item'];
   foreach ($itemA as $itemB):
     foreach (array($_POST['nome']) as $val1):
       foreach (array($_POST['tmp']) as $tmp):
    foreach (array($_POST['qtd']) as $val2):
      for ($i = 0; $i < count($val1); $i++):
        if($cadastra = $mysqli->query("INSERT INTO ifro_prescricao_medicamentos
                  (id_prescricao, nome, item_padrao, item, quantidade, tempo_infusao)
                  VALUES
                 ('$codigo','$nomePres', '$itemB', '".$val1[$i]."', '".$val2[$i]."', '".$tmp[$i]."')")) {

          }
        endfor;
      endforeach;
    endforeach;
  endforeach;
 endforeach;
</code>
Mas ele esta sempre cadastrando todos os itens iguais, não esta separando os nome do remédios
veja a imagem:

Seguem as imagens em como é o meu form de cadastro das informações:
Esta imagem esta com apenas 1 medicamento

Esta imagem já com 2 medicamentos
Answer: A variável $código é a mesma porque está fora do foreach, ela deveria ser colocada dentro para que seja gerado um novo número aleatório a cada iteração.
O mesmo vale para a variável $nomePres, ela tem que ir para dentro do foreach.
Agora quanto ao restante, me parece que a lógica não está boa. Estou vendo que você recebe 5 valores via método POST: item, nome-item, nome, tmp e qtd. Esses 5 POSTS recebem arrays do mesmo tamanho? Deveriam receber para que uma tabela fosse corretamente preenchida. Outra coisa, os valores recebidos via POST saíram de inputs de formulário HTML? Se sim, o atributo name deve conter o nome seguido de colchetes. Por exemplo o valor recebido tmp deve estar em um input name="tmp[]".
Reescrevendo o código:
<code>$itemA = $_POST['item'];

  $nomePres = $_POST['nome-item'];

  $nome = $_POST['nome'];

  $tmp = $_POST['tmp'];

  $qtd = $_POST['qtd'];

  $contador = 0;

  foreach ($itemA as $itemB) {

    $codigo = rand(5, 50000);

    $mysqli->query("INSERT INTO ifro_prescricao_medicamentos
            SET id_prescricao = '$codigo',
            nome = '$nome[$contador]',
            item_padrao = '$itemB',
            item = '$nome[$contador]',
            quantidade = '$qtd[$contador]',
            tempo_infusao = '$tmp[$contador]'");

    $contador++;

  }
</code>
Comment: Mas ele não faz o array dentro de cada um deles, vou mandar a foto do meu form.
Comment: Segue o link da imagem

https://i.stack.imgur.com/z8tOx.png
Comment: A variável `$codigo` é realmente necessária? não se pode apenas alterar a coluna `id_prescricao ` para `AUTO INCREMENT` ?
Comment: Sim ela é necessária, pois preciso recuperar ela depois, tipo o a prescrição 1029 tem o item 1, 2, 3 com medicamentos 4, 6 , 7, entendeu?
Answer: Desculpa a demora, talvez já tenha conseguido resolver. De qualquer forma vamos lá.
Só me confirme o seguinte quanto aos POSTS recebidos:

'item' vem do input 'protocolo';
'nome-item' vem do input 'remedio 1, remedio 2, etc';
'nome' vem do input 'nome do remédio';
'qtd' vem do input 'quantidade';
'tmp' vem do input 'tempo infusão'.

Outra coisa, deve ser gerado um código para cada protocolo ou para cada remédio?
Realmente deve haver um foreach dentro de outro, acho que o código fica da seguinte forma:
<code>$itemA = $_POST['item'];

$nomePres = $_POST['nome-item'];

$nome = $_POST['nome'];

$tmp = $_POST['tmp'];

$qtd = $_POST['qtd'];

$contador = 0;

foreach ($itemA as $itemB) {

    $codigo = rand(5, 50000);

    foreach ($nomePres as $nomeRemedio) {

        $mysqli->query("INSERT INTO ifro_prescricao_medicamentos
            SET id_prescricao = '$codigo',
            nome = '$nome[$contador]',
            item_padrao = '$itemB',
            item = '$nome[$contador]',
            quantidade = '$qtd[$contador]',
            tempo_infusao = '$tmp[$contador]'");

        $contador++;

    }

}
</code>
O primeiro foreach dá conta do protocolo, o segundo foreach da conta do remédio, e o contador dentro desse segundo foreach dá conta de ler ao mesmo tempo os arrays item, quantidade e tempo de infusão.
Apesar que se o protocolo sempre for um só de cada vez, nem precisava desse primeiro foreach.
Só uma observação, sempre procure usar nomes de variáveis o mais próximo possível do que elas representem, porque senão fica muito fácil se perder. Por exemplo, nos POSTS você recebe item, nome-item e nome, e chama elas de $itemA, $itemB, $nome, $nomePres é muito fácil confundir e difícil saber a que correspondem.
Comment: Leandro, desculpe minha ignorância, mas esta dando o seguinte erro Warning: Invalid argument supplied for foreach() in F:\wamp\www\froc\sistema\acao\insere-prescricao-medicamento.php on line 48
Comment: Vamos lá,não havia entendido sua pergunta:

'nome-protocolo' - seria o nome do PROTOCOLO

'medicamento[]' - nome do remédio
'nome-item[]' - seria o nome do item
'qtd' - quantidade do item
'tmp' - tempo de infusão

Lembrando que todos ele pode ter vários remédios (medicamentos) com outros itens dentro deles
Medicamento 1
                      ITEM A         QUANTIDADE A      TEMPO INFUSÃO A
                      ITEM A-1      QUANTIDADE A-1      TEMPO INFUSÃO A-1

MEDICAMENTO 2
                      ITEM 2          QUANTIDADE B      TEMPO INFUSÃO B
Comment: estou fazendo o cadastro mas esta cadastrando o nome dos itens repetidos
Cmo recebo:
string 'medicamento' (length=11)

string 'ITEM 1' (length=6)
string 'item 2' (length=6)
string 'item 3' (length=6)
string 'item 1-a' (length=8)
string 'medicamento 2' (length=13)
string 'ITEM 1' (length=6)
string 'item 2' (length=6)
string 'item 3' (length=6)
string 'item 1-a' (length=8)

Sendo que o MEDICAMENTO 2 apenas cadastrei um 1 item, e ele trás todos os outros.

Obrigado pela ajuda em tentar resolver essa condição

Array dentro de Array PHP


ESXi host losing connection to vCenter

Question: I'm having a very odd issue with a single ESXI host.
I have 2 identical hosts, core i3, 6 nics, 16g ram.   4 of the nics are used for Management, vmotion, vm network, all on different vlans.  They all go to a HP Procurve 24 port gig switch in a static trunk.  The other two nics are iSCSI.
There are 2 VSS's, the one with 4nics, and the second with just the 2 and iSCSI traffic.
Configuration on both hosts is identical, hardware is identical. Both hosts are running at about 30% utilization both cpu and memory. They are running ESXI v. 5.1.
What is happening is that all of the sudden host 2 will drop out of vCenter. ( vCenter is hosted on a physical machine ). No error, it just loses connection.
If I try to ping the host from vCenter I cannot. If I try to ping from my workstation I can most of the time and I can SSH into it.    If I "test management network" from the DCUI it can ping the gateway and the dns servers. If I restart the management network I still cannot get to it from vCenter.
If I do a services.sh restart it all completes with no error but doesn't help, host is still not able to register with vCenter nor be pinged by vCenter.
The only thing so far that remedies this is to completely restart the host.   I did a log export but I'm not really even sure what to look for at this point.   What logs should I be looking at?  The only other piece of information I can add is that this seems to happen at the same time of the day, early in the morning. There is nothing running at this time, no backup jobs etc.
Comment: Can you describe the hardware? We need to know server make/model, storage configuration (local disk? RAID controller? USB/SD card boot?)
Comment: Sure. Intel DH61CR board, core i3, 16g ddr3 ram, single sata internal drive. 4 intel pro ports and 2 syba per host.  All VM's are on a FreeNAS, 10 disk SAN, running through iSCSI.
Comment: Can you give me the specific model of the NIC and the BUILD VERSION/NUMBER of the ESXi install?
Comment: Intel PRO/1000 Pt Dual Port Server Adapter, Syba SD-PEX24009 PCI-Express x.  VMware ESXi 5.1.0 build-1065491
VMware ESXi 5.1.0 Update 1
Comment: What is the network config for the vCenter physical machine?  Also when you say you have 4 nics for management, etc.. How are those nics configured?  Are these in an Active-Active configuration or Active-Passive?
Comment: On the vCenter server there is a single nic connected directly to the switch.  The 4 nics are all active using IP Hash and the 4 physical ports on the switch are in a static trunk group.   There are 2 vss's.  The first has 2 vmkernels, 1 for vmotion ( vlan 5) One for management ( vlan 1 ) , it also has 3 port groups. Outside ( vlan 2), DMZ ( vlan 3 ) , and vm network (vlan 1).  The second vswitch has 2 vmkernel ports both iscsi. Multipath iSCSI as per vMware instructions.
Comment: Has this ever worked 100% of the time or is this a new machine - just thinking it might be worth checking your firewall as I've seen that happen on boxes that don't have VC-to-Host UDP 902 allowed
Comment: I've had this setup running for almost 7 months now.  I just verified that port was allowed.  Granted this is not only my home production but also my home lab so it's in an ever changing state but it runs perfectly.  This issue has been over the last few weeks.  Which log would point me to a firewall issue? I was attempting to get smtp working by creating an smtp.xml file but that was removed and the sytem back to normal.  Plus all actions done on 1 host have been done on both and host 1 is stable.
Comment: @TheEditor Please post the relevant hostd.log snippet from the affected host/time.
Answer: Whenever I see these issues on whitebox hardware, I check the drivers (and firmware) of the critical components involved (NIC, storage) and then suggest updating to the newest revision of the ESXi distribution using the VMware Patch Portal or Update Manager.
Lab or no lab, you're running an old build: ESXi 1065491 versus the current ESXi 1483097.
Go ahead and run the updates as a first start: Are VMware ESXi 5 patches cumulative?
Following that, I would dig into the actual hosts' logs to see what's happening near the vCenter disconnection time. Check /var/log/hostd.log and /var/log/vmkernel.log.
If you're certain that there aren't any firewalling, DNS or other networking issues, this is your best bet to understand what's happening.
If all else fails, this is ESXi, and you have shared storage. Spending time troubleshooting a build like this isn't always useful, especially if the other host is performing well. Copy your settings off via PowerCLI, rebuild and restore the host.
Comment: I think I'm going to run all updates then check back and see if that fixes it.  I see that PR1012837 seems to address something along these lines with networking disconnecting.  I'll do that later today and if I still have issues pull logs and check back. Thanks @ewwhite
Comment: Just an update:  That fixed the issue.  The random network crashes have stopped.
Comment: @theeditor The patch fixed the issue?
Comment: Yep seemed to.  Haven't had any issues since then. Rock solid. It was my own fault for not doing it sooner.

ESXi host losing connection to vCenter


render full form

Question: I need to render a full form, including the <form>....</form> tags. Any ideas how can I do that?
I tried drupal_render() and render(). The form elements are rendered but there is no <form> tag in the markup.
Answer: You need a properly formatted form array to render, which you get by calling drupal_get_form(). After that you just run it through render() as you're currently doing:
$form = drupal_get_form('form_id');
print render($form);

Comment: @MariusIlie It would be improbable a Drupal form is rendered without `` tags.
Comment: apparently the tag was there but the chrome inspector did not see it. Unfortunately this doesn't seem to work as I expected.
Answer: You need theme_form() in your form theme: drupal_render() your #children, then theme_form().
And you can put HTML around the elements.
$buildform = '
'. drupal_render($form['element1']) .'
';
$buildform .= drupal_render($form['element2']);
$buildform .= drupal_render($form['form_build_id']);
$buildform .= drupal_render($form['form_id']);
$buildform .= drupal_render($form['form_token']);
$form['element']['#children'] = $buildform;
$output = theme_form($form);

render full form


How to insert date from a coldfusion variable to a sql field?

Question: Because of an unusual setup of code, instead of using cfquery with cfparam tags, I am instead building a sqlInsertCols list and a sqlInsertValues list and using those in an insert statement. Code something like this:
<cfscript>
   var sqlInsertCols = "";
   var sqlInsertValues = "";
   // some looping and other processing here to fill the lists
   ...
</cfscript>

<cfquery datasource="..." name="insert">
   INSERT INTO MyTable(#sqlInsertACols#)
   VALUES (#sqlInsertVals#)
</cfquery>

Firstly, are there any security issues with this, considering that both sql strings are populated within this code and not based on any user input?
And this has worked for several fields that I was inserting, but I just tried to add a date field and can't get the insert to work. The date is in the format "mm/dd/yyyy". Code to add date to sql lists:
sqlInsertCols = ListAppend(sqlInsertCols, "MyDateField");
sqlInsertValues = ListAppend(sqlInsertValues, myDateVar);

This runs with no errors but the value in the db is 1900-01-01 00:00:00.000.
I've tried adding quotes around the date but can't seem to get it to insert properly. Is there any way to accomplish this?
Comment: Try `sqlInsertValues = ListAppend(sqlInsertValues, CreateODBCDateTime(myDateVar));`.
Comment: @xpa1492 - that worked! Thank you! If you post it as an answer I'll accept it
Comment: Slightly more efficient than @xpa1492's recommendation is to create date variables in the first place instead of string variables which you then convert.
Comment: *not based on any user input* What exactly is the source? If this data comes from another table in your db, why not just use INSERT INTO/SELECT? Otherwise, the code may still be at risk of sql injection. Also, why not use the cfscript version of cfquery? Then you can use cfqueryparam and gain the performance benefits of bind variables.
Comment: @DanBracuk - we get the date as a string. It's scraped from a web page.
Comment: @Leigh - it's being scraped from a web page. How would the cfscript version of cfquery allow this functionality?
Comment: If it's being scraped from a web page you probably want to validate it first.  I would do something like this:  if (isDate() and something to check the format) myDateVar = parseDateTime(), or myDateVar = CreateDate().
Comment: @froadie - Then it is not really safe. The [cfscript version](http://help.adobe.com/en_US/ColdFusion/9.0/CFMLRef/WSe9cbe5cf462523a0693d5dae123bcd28f6d-7ffb.html) allows you to build a parametrized sql string, dynamically, and use addParam to fill in the values. Side note, since you cannot use cfqueryparam on object names (table/column), be sure the column list consists of value *you* hard code in your app.
Answer: SQL Sever uses single quotes around dates. Have you tried those?
Comment: I have tried, but CF seems to translate those to double quotes in the insert statement and then it causes an error.
Comment: @froadie: You'd need to use the `preserveSingleQuotes()` function.
Comment: *SQL Sever uses single quotes around dates* Not exactly. Quotes are required around string literals. In this case a date string. Depending on target column, that string *may* be implicitly converted to `date/time`, but it is still a string. @froadie - The reason the quotes are doubled is a security feature of CF. Queries that do not use cfqueryparam are at risk for sql injection, so CF automatically doubles quotes in an attempt to prevent that. `preserveSingleQuotes` reverses that behavior, but in doing so **exposes your db to the very thing CF tried to prevent**. So use it with caution.
Comment: Plus 1 to get Eric's reputation high enough to post comments.
Answer: First let me say that I simply don't like this approach. It appears that you are trying to use cfquery as a generic wrapper - a way to "plug in" lists of variables. That makes your queries obscured by other code. Seeing as how queries are the most vulnerable vector, not to mention usually containing user input, it makes everything harder to troubleshoot. Moreover, cfquery is a strength of the CF language - one of the few languages that you can cut and paste from a DB IDE and simple change the variable inputs (adding cfqueryparam of course).
Finally, your query NEEDS cfqueryparam to protect from SQLi - so in answer to the last part of your question - yes this code is vulnerable. There is rarely if ever a case for not using cfqueryparam.
So... here's a solution (which again, I don't like or recommend :) that you can use as a starting point:
<cfscript>
   var sqlInsertCols = "";
   var sqlInsertValues = "";
   // some looping and other processing here to fill the lists
   ...
</cfscript>

<cfquery datasource="..." name="insert">
   INSERT INTO MyTable(#sqlInsertACols#)
   VALUES (
    <cfloop list="#sqlinsertValues#" index="colVal">
        <cfif isDate(colVal)>
            <Cfqueryparam cfsqltype="CF_SQL_DATE" value="#colval#"/>
        <cfelse>
            <cfqueryparam cfsqltype="CF_SQL_CHAR" value="#colval#"/>
        </cfif>
    <cfif colVal IS NOT listlast(sqlInsertValues)>
              ,
       </cfif>
    </cfloop>

   )
</cfquery>

This assumes that a field identified as a date is being inserted into a column in the DB of type "date". It also assumes that all the "other" non date fields are character fields. You might need to add checks for numbers or ints or whatever is in your data.
Additionally if you need to check the column name against the value you can use listgetat as follows:
<cfscript>
   var sqlInsertCols = "";
   var sqlInsertValues = "";
   // some looping and other processing here to fill the lists
   ...
</cfscript>

<cfquery datasource="..." name="insert">
   INSERT INTO MyTable(#sqlInsertACols#)
   VALUES (
    <cfloop from="1" to="#listlen(sqlinsertValues)#" index="x">
        <cfif listgetat(sqlInsertCols,x) IS 'dateadded'>
            <Cfqueryparam cfsqltype="CF_SQL_DATE" value="#listgetat(sqlInsertValues,x)#"/>
        <cfelseif listgetat(sqlInsertCols,x) IS 'userid'>>
            <cfqueryparam cfsqltype="CF_SQL_INTEGER" value="#listgetat(sqlInsertValues,x)#"/>
        </cfif>

       <cfif x IS NOT listlen(sqlInsertValues)>
            ,
          </cfif>

    </cfloop>
   )
</cfquery>

Finally, for the completely not recommended quick and dirty solution you can try this:
<cfscript>
   var sqlInsertCols = "";
   var sqlInsertValues = "";
   // some looping and other processing here to fill the lists
   ...
</cfscript>

<cfquery datasource="..." name="insert">
   INSERT INTO MyTable(#sqlInsertACols#)
   VALUES (
    <cfloop list="#sqlinsertValues#" index="colVal">

        '#colval#'
            <cfif colVal IS NOT listlast(sqlInsertValues)>
                  ,
           </cfif>
    </cfloop>

   )
</cfquery>

This may work because of your RDBMS implicit conversion - which can convert down from character to date, int or numeric in many/most cases. of course you may just as easily get a syntax error.
One final note: the first and third samples above use some simple methods to insert commas in the list - comparing the value to the last value in the list and inserting if they don't match. So this assumes that any item coming not last in the list is not the same as the last item in the list. If that last item is duplicated elswhere in your query, then you will get a syntax error for a missing comma. Good luck!
ERRATA:
FYI - on that last snippet - the single quotes OUTSIDE the variable are not escaped by CFQUERY .. so when you use '#varName#' - the single quotes are preserved, but when they are inside the variable they are escaped - because CF naturally assumes (and best practice dictates) that you are handling the contents to be inserted in variable form, and not query language itself.
Comment: Thanks for the detailed answer. Some of this is very useful. I'm going to be restructuring the way I do it somewhat (I'll have a sort of "lookup" struct for the column names so that I can pull it based on the html but it's still controlled). I'll likely be using cfqueryparams in a loop.


AlertDialog unit testing - java.lang.VerifyError: Bad type on operand stack

Question: I have an activity MyActivity.java in which I am generating an AlertDialog using AlertDialog.Builder(this);.
Now I am trying to write a unit test (junit) for MyActivity.java by treating is as a simple java class and creating shadow classes for Android's framework classes.
When I try to run the test, I get an error while trying to instantiate the class : java.lang.VerifyError: Bad type on operand stack
java.lang.VerifyError: Bad type on operand stack
Exception Details:
  Location:
    com/domain/myApp/MyActivity.myMethod()V @31: invokespecial
  Reason:
    Type 'com/domain/myApp/MyActivity' (current frame, stack[2]) is not assignable to 'android/content/Context'
  Current Frame:
    bci: @31
    flags: { }
    locals: { 'com/domain/myApp/MyActivity', 'android/content/res/Resources' }
    stack: { uninitialized 26, uninitialized 26, 'com/domain/myApp/MyActivity' }
  Bytecode:
    0x0000000: 120f 123a b800 112a b400 03c6 000a 120f
    0x0000010: 123b b800 3c2a b600 184c bb00 3d59 2ab7
    0x0000020: 003e 4d2a 2c2b 123f b600 40b6 0041 2b12
    0x0000030: 42b6 0040 b600 432b 1244 b600 402a b700
    0x0000040: 45b6 0046 2b12 47b6 0040 bb00 4859 2ab7
    0x0000050: 0049 b600 4abb 004b 592a b700 4cb6 004d
    0x0000060: b600 4eb5 0003 2ab4 0003 b600 4f2a b400
    0x0000070: 0312 51b6 0052 c000 534e 2db6 0054 57b1
    0x0000080:
  Stackmap Table:
    same_frame(@21)

    at com/domain/myApp/MyActivityTest.before(MyActivityTest.java:93)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:24)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.mockito.internal.runners.DefaultInternalRunner$1.run(Unknown Source)
    at org.mockito.internal.runners.DefaultInternalRunner.run(Unknown Source)
    at org.mockito.junit.MockitoJUnitRunner.run(Unknown Source)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
    at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)

From what I researched, this error is happening because I am trying to reference this in a static context (AlertDialog.Builder). So basically I am trying to reference MyActivity before it has been fully constructed.

I figured if in my AlertDialog's shadow class I made AlertDialog.Builder class non-static, the problem would not occur during test. But that is not the case. Does anyone have any clue how can I get a workaround for this ?
Answer: This is happening because you must have a shadow class for Activity. The actual Activity class extends ContextThemeWrapper class which extends ContextWrapper class which extends the abstract Context class.
Just create a shadow Context class and use that to extend your shadow Activity class.

This whole error is basically incompatible types error.


Does the pickleball serving number reset when a point is won at the second serve?

Question: The score during a game of pickleball doubles is 4-7-2.
For those unfamiliar, this means that:

the serving team has 4 points,
the opposing team has 7 points, and
this is the second serve for the serving team.

Now suppose that the serving team wins the point. The score becomes 5-7. That much is clear, but:
Does the pickleball serving number reset when a point is won at the second serve?
Concretely, does the score become:

5-7-1 (with the serving number resetting to 1), or does it become
5-7-2 (with the serving number remaining 2 despite that this is the first serve to be made at the 5-7 score?
Answer: In a game of pickleball doubles, the score 4-7-2 means that the serving team has 4 points, the opposing team has 7 points, and it is the serving team's second serve. If the serving team wins the point, the score becomes 5-7.
The question is whether the serving number resets to 1 after a point is won on the second serve. The answer is no, the serving number does not reset. The score would become 5-7-2, with the serving team still serving their second serve. The serving number only resets at the start of a new game or if the serving team loses a point.
Comment: @Sam The downvotes were due to the unnecessary link causing the post to be marked as spam.
Comment: Welcome to Stack Exchange - however, please note that unnecessary links to your site are likely to get your answer flagged as spam and deleted by the community; I've removed the link in this case.
Comment: Not sure why there are vote-downs.  Thanks for settling this puzzle, but are you sure of this answer? Could you add a few words to describe why you think so?
Comment: @PhilipKendall I see. Aside from SE rules, including the rule preferring answers to be self-contained, I have no issue with external references (including self-referencing), but only if the reference sheds more light on an issue, which is not the case here.


Find rank of linear transformation.

Question: If $T_1$ ,$T_2$ , $T_3$ , mapping from $\mathbb{R}^2$ to $\mathbb{R}^3$. Then find rank of:
P. $T_{1}(x,y)=(x,x,0)$
Q. $T_{2}(x,y)=(x,x+y,y)$
R. $T_{3}(x,y)=(x,x+1,y)$
My textbook's answers are

$P$ is linear transformation of rank 1,
$Q$ is linear transformation
of rank 2
$R$ is not a linear transformation.

Please explain how this result came out? I am so confused.
Comment: Can you at least show $T_3$ is not linear? Do you know about matrices associated to linear maps?
Comment: yes I know. and I think it is a linear transformation of rank 2. May be my textbook is wrong
Comment: The book is right.
Answer: For part a
Find Kernel which is by putting $x=0$. Use Rank Nullity theorem
For part b
Same as part a.Remember Kernel lives in $R^{2}$ (For this question !)
For part c
Use fact that linear transformation send  o vector to corresponding 0 vector
Comment: yes I sort it out sir. But I didn't get part c How it is it not linear? plz explain
Comment: what is T(0)...
Comment: i didn't get you.
Comment: let (x,y) in kernel then T_{1}(x,y)=(0,0) \Rightarrow (x, x, 0) = (0,0,0) \Rightarrow x=0, y=0 and z is arbit. therefore dim ker T = 1..is that ok
Comment: No, $(x,y)\in ker(T_1)$ only requires that $x=0$, so that the kernel is the $y$-axis. $T_1$ is a map from $\mathbb{R}^2$ to $\mathbb{R}^3$ so there are only two variables, $x$ and $y$, and "there is no $z$".
Comment: @T.Noor Kernel is that stuff which LT sends to identity. Since x=0 so kernel is (0,y). It means L.T sends all stuff of form (0,y) to (0,0,,0). So we have y as a free variable here.  It means we can take any value for y and it will be in kernel provided x=0.
Comment: @T.Noor Also for part c check that T(x+y)=T(x) = T(y), where x and y are of form (a,b)
Comment: Well for part c it is really enough to see that $T(0)\neq 0$
Answer: Here's an alternative way to come about the same solution.
For $T_i$, try and find a $2 \times 3$ matrix that represents the transformation $T_i$. If a matrix is not possible, then the transformation cannot be linear (because every linear transformation by definition can be written as $Mx=y$). If a matrix is possible, the number of non-zero rows in the row reduced matrix will be the rank of the matrix and therefore the rank of the transformation.
I'll only do Part (P) for you.
$T_1(x,y) = (x,x,0)$. Written in Matrix form, this is:
$$\begin{pmatrix}1 & 0\\ 1 & 0\\ 0 & 0\end{pmatrix}\begin{pmatrix} x\\y\end{pmatrix} = \begin{pmatrix}x\\x\\0\end{pmatrix}$$
Row reducing this transformation matrix, you get:
$$\begin{pmatrix}1 & 0\\ 0 & 0\\ 0 & 0\end{pmatrix}$$
which only has one non-zero row. Therefore, $T_1$ is a linear transformation of rank 1.
I'll feel confident that you can do Part (Q) by yourself. For Part (R), note that there would be no way to get $x+1$ in the second dimension as merely a sum of $x$s and $y$s. Thus, no matrix can represent the transformation $T_3$, and it is not linear.

Find rank of linear transformation.


Product measure with a Dirac delta marginal

Question: Let $(S,\mathcal F)$ be a measurable space, and let $\nu \in\mathcal P(S,\mathcal F)$ be a probability measure on $(S,\mathcal F)$. Fix some $x\in S$ and consider Dirac measure $\delta_x$. Would like to prove
If $\mu \in \mathcal P(S×S,\mathcal F\otimes \mathcal F)$ and has marginals $ν$ and $δ_x$  $then$ $μ=ν×δ_x$
So we should show $μ(A×B)=ν(A)δ_x(B)$ for $∀A,B∈\mathcal F$.
If $x∉B$ then right-hand side is $0$ but so is the left-hand side since $μ(A×B)≤μ(S×B)=δ_x(B)=0$.
How to deal with the case $x∈B$ ?
Answer: If $x\in B$, then for each $A\in\mathcal F$, $$\nu(A)=\mu(A\times S)\geqslant \mu(A\times B)\geqslant \mu(A\times \{x\}).$$
Since all the involved measures are probability measures, applying the previous inequality with $S\setminus A$ gives that
$$
1-\nu\left(A\right)\geqslant \mu\left(S\times \{x\}\right)-\mu\left(A\times \{x\}\right),
$$
and since the marginal in the second coordinate is $\delta_x$, we got that
$$
-\nu\left(A\right)\geqslant-\mu\left(A\times \{x\}\right)
$$
hence $\nu\left(A\right)\leqslant \mu\left(A\times \{x\}\right)\leqslant \mu\left(A\times B\right)$ which proves that
$\mu\left(A\times B\right)=\nu\left(A\right)\delta_x\left(B\right)$. This identity is also true for $x\notin B$, and it can be extended to disjoint finite unions of cartesian products of elements of $\mathcal F$, which is sufficient to ensure the equality of two measures.
Answer: For any measurable set $B\subset S$, $\mu(S\times B)=\delta_x(B)=\mathbb{1}_B(x)$.  In particular, $\mu(S\times\{x\})=1$, and if $x\notin B$,
$$\mu(A\times B)=0=\nu(A)\delta_x(B),\qquad A\in\mathcal{F}$$
for $\mu(A\times B)\leq\mu(A\times(S\setminus\{x\})=0$.
Suppose now that $x\in B$. Then, $\delta_x(B)=1$, and $\mu(A\times(S\setminus B))=0$. Consequently,
$$\begin{align}
\nu(A)\delta_x(B)=\nu(A)&=\mu(A\times S)=\mu((A\times B) \cup (A\times(S\setminus B))\\
&=\mu(A\times B)+\mu(A\times(S\setminus B))=\mu(A\times B)
\end{align}$$
Putting things together, we have that
$$\mu(A\times B)=\nu(A)\times\delta_x(B),\qquad A,B\in\mathcal{F}$$
From this (why?) it follows that $\mu=\nu\otimes\delta_x$.


Formatting output of token

Question: I have Drupal Commerce, and it sends confirmation emails after product is sold. In those emails are tokens. I have token [commerce-order:created] and I'm interested if is there any conveniant way to change a formatting of that date.
Answer: If [commerce-order:created] is a date token, then you can use [commerce-order:created:custom:<the format you want to apply>], where <the format you want to apply> is the string format accepted by date().
Otherwise, the more generic way to alter tokens implemented by other modules is implementing hook_tokens_alter().
function mymodule_tokens_alter(&$replacements, $context) {
  $options = $context['options'];

  $sanitize = !empty($options['sanitize']);
  $langcode = !empty($options['language']->language) ? $options['language']->language : NULL;

  if ($context['type'] == 'commerce-order') {
    foreach ($context['tokens'] as $name => $original) {
      switch ($name) {
        case 'created':
          // Set a value for $sanitized and $new_value.
          $replacements[$original] = $sanitize ? $sanitized : $new_value;
      }
    }
  }
}

Notice that in my code:

$sanitized is the sanitized value to assign to the token, used only when $sanitize is TRUE
$new_value is the new value for the token, used to obtain the value of $sanitized
Answer: You can do this with hook_tokens_alter

Alter replacement values for placeholder tokens.

Eg:
/**
* Implements hook_tokens_alter().
*/
function mymodule_tokens_alter(&$replacements,  $context){
  // May be you can do some more ifs to reduce the load :)
  if(isset($replacements['[commerce-order:created]'])){
    $replacements['[commerce-order:created]']  = check_plain('YOUR-CUSTOM-REPLACEMENT');
  }

}

Formatting output of token


Are multiple "params" parameters possible?

Question: Is it possible to have multiple params parameters in C#? Something like this:
void foobar(params int[] foo, params string[] bar)

But I'm not sure if that's possible. If it is, how would the compiler decide where to split the arguments?
Comment: I have been hit by lack of this feature :(
Comment: Welcome to [so] Gary, 5 answers listed in almost as many seconds. Why dont you pass in a param of classes? or a `>`
Comment: What do you mean by passing in a param of classes?
Comment: This is not allowed (params must be last argument). The compiler would decide to 3x int, because the default type of a number (without .) is int32. You'd neet do case Mult((long)1,(long)2) to get it to long.
Answer: You can only have one params argument.  You can have two array arguments and the caller can use array initializers to call your method, but there can only be one params argument.
void foobar(int[] foo, string[] bar)

...

foobar(new[] { 1, 2, 3 }, new[] { "a", "b", "c" });

Comment: Thanks, exactly the answer I was looking for :)
Comment: Upvoting for your 10th vote (giving you a badge) just because the OP didn't accept your answer. :)
Answer: No this is not possible. Take this:
void Mult(params int[] arg1, params long[] arg2)

how is the compiler supposed to interpret this:
Mult(1, 2, 3);

It could be read as any of these:
Mult(new int[] {         }, new long[] { 1, 2, 3 });
Mult(new int[] { 1       }, new long[] {    2, 3 });
Mult(new int[] { 1, 2    }, new long[] {       3 });
Mult(new int[] { 1, 2, 3 }, new long[] {         });

You can take two arrays as params like this however:
void Mult(int[] arg1, params long[] arg2)

Comment: if type of the params groups are different then eachother, compiler can interpret.. for example lets say method(params int[] numbers, params string[] texts){}
 . method(34,76, "hi", "how are ya!");
Comment: I wouldn't support something like that because implicit type casting is already a thing in c# and would royally mess things up. But supporting multiple params and just add an ambiguity warning just like with overloads and optional parameters wouldn't be hard.
Comment: Mult(1 , 2 , (long)3 , 5 , 6); after "3" it could be long parameters,
Comment: because you state that as a reason for lack of this feature.
Answer: I know this is a super old post, but here:
In C# 7, you actually can. You can use System.ValueTuple to do this:
private void Foobar(params (int Foo, string Bar)[] foobars)
{
    foreach (var foobar in foobars)
        Console.WriteLine($"foo: {foobar.Foo}, bar: {foobar.Bar}");
}

private void Main() => Foobar((3, "oo"), (6, "bar"), (7, "baz"));

Output:
Foo: 3, Bar: foo
Foo: 6, Bar: bar
Foo: 7, Bar: baz

The only downside is you have to do this: foobars[0].foo; instead of foos[0];, but that's really a tiny tiny issue.
EDIT:
Using deconstructers, this becomes the previous "downside" goes away:
private void Foobar(params (int Foo, string Bar)[] foobars)
{
    // Deconstruct the tuple into variables
    foreach (var (foo, bar) in foobars)
        Console.WriteLine($"foo: {foo}, bar: {bar}");
}

Comment: @anatol I guess that's worth noting but no one had mentioned attributes.
Answer: From MSDN - params

No additional parameters are permitted after the params keyword in a
  method declaration, and only one params keyword is permitted in a
  method declaration.
Answer: No, only  a single param is allowed and even that has to be the last argument. Read this
This will work
public void Correct(int i, params string[] parg) { ... }

But this won't work
public void Correct(params string[] parg, int i) { ... }

Answer: It's not possible. It could be only one params keyword per method declarations - from MSDN - http://msdn.microsoft.com/en-us/library/w5zay9db(v=vs.71).aspx
Answer: void useMultipleParams(int[] foo, string[] bar)
{
}

useMultipleParams(new int[]{1,2}, new string[] {"1","2"})

Comment: You did not use the params key word as it was asked in the question.


limit of sequence integrable

Question: Let $(\Omega,\mathcal A,\mu)$ be a measure space and $(f_n)$ a sequence of $\mu$-integrable functions, which converges uniformly to $f:\Omega\to\mathbb R$.
1) If $\mu$ is finite, $f$ is also integrable.
2) If $\mu$ is $\sigma$-finite, $f$ needn't be integrable. In case $f$ is integrable, $\lim_{n\to\infty}\int f_n d\mu$ and $\int f d\mu$ needn't be the same.
I tried showing 1) like this:
Since $f_n\to f$ uniformly we have $\forall x\in\Omega \forall\varepsilon>0\exists N_0\in\mathbb N$ such that $\forall n\geq N_0$:
$$|f_n-f|<\varepsilon$$
From this I got the following estimate:
$$\left|\int f_nd\mu -\int fd\mu\right|\leq \int |f_n-f|d\mu<\int \varepsilon d\mu\leq \varepsilon\mu(\Omega)$$
Since this holds for all $\varepsilon>0$ (and $\mu(\Omega)$ is finite) we deduce $\lim_{n\to\infty}\int f_nd\mu = \int fd\mu$.
To show that $f$ is indeed integrable I tried showing that $|f|$ is integrable:
$$\int |f|d\mu=\int |f-f_n+f_n|d\mu\leq \int |f-f_n|d\mu + \int |f_n|d\mu\leq \varepsilon\mu(\Omega)+c<\infty$$
Since $f_n$ is integrable, $|f_n|$ is integrable, too, and the integral is finite and hence the integral over $|f|$ is finite and hence $f$ is integrable.
Is this correct?
And how do I show 2)? I tried thinking of some counter-examples, but I couldn't think of any. Can anyone else help me out here?
Thanks!
Answer: Your proof that $f$ is integrable by the approximation $\int|f| \leq \int|f-f_n| + \int|f_n|$ looks good, though on the previous estimate, you should start with $\int|f-f_n|$ without the previous term $\left| \int f - \int f_n\right|$ since before proving integrability of $f$, it doesn't make sense to write $\int f$ (and that term is unneeded for your conclusion).
For a counter-example, consider $f(x) = 1/x$ on $[0, \infty)$ and let $$f_n(x) = \begin{cases} f(x) & 0 \leq x \leq n \\ 0 & x > n \end{cases}$$
Then $\sup_{x \in [0,\infty)} |f(x)-f_n(x)| = \frac{1}{n} \to 0$, but $f$ isn't integrable (using Lebesgue measure and the standard Borel $\sigma$-algebra on $[0,\infty)$ ).
Answer: Let $\phi_n = \frac{1}{n} 1_{[n,2n)}$. Note that $\int \phi_n = 1$.
Let $f_n = \sum_{k=1}^n \phi_{2^k}$, and $f = \sum_{k=1}^\infty \phi_{2^k}$.
Then $\int f_n = n$, $f_n \to f$ uniformly, but $\int f = \infty$.

limit of sequence integrable


Some templates are not properly compiled to Twig

Question: I have a few templates that are failing when compiling them in twig.
What is happening is that the \Drupal\Component\PhpStorage\MTimeProtectedFastFileStorage::save method will create a temporary file like files/php/twig/.0c781c5196 and then it tries to rename this file into something like files/php/twig/DIRECTORY/FILE.php but it fails with No such file or directory.
The target directory exists, it even has .htaccess. On each page refresh, I get different temporary and target file names.
I tried to manually copy and rename the file but on each page load the ID's change so it never works.
The template hasn't been edited and it always worked just fine(it renders properly  even without compiled twig). Any idea what can be causing this?

It looks like this is only a single template issue. Due to the ever changing IDs, I thought there were more.
This is happening on my local windows machine right now so I though there might be an issue with those crazy long directory and file names but I can manually rename the file.
The length of the directory name is 134 characters which are well below 260 maximum.

UPDATE 27.6: I have experienced this same issue on another Drupal 8 project. So it looks like it is not a unique problem but rather universal but I still haven't figured out what the issue is.
Comment: If this is a bug, you should add it as an issue on Drupal.org so some core maintainers will definitely see it.
Answer: OK!
So I have figured it out. I think this is a Windows-specific bug because, on another project where I have experienced this as well, people with macs do not have this issue.
Anyway, what is causing it is \Drupal\Component\PhpStorage\MTimeProtectedFastFileStorage::getFullPath, specifically return $directory . '/' . hash_hmac('sha256', $name, $this->secret . $directory_mtime) . '.php';
If the template name is too long, which can easily happen with theme suggestions, it will cause PHP to fail to perform the rename() operation successfully. I don't know why it stores the code in a temporary file and then it copies it into target directory instead of creating it directly in the target directory and/or file but that's how it is.
I have no idea why we need so freaking long directory and file names when they only hold a single file but beside this, Drupal 8 is great.
Answer: Something lower than the PHP level is obstructing rename() from moving the temp file to a PHP file. Without knowing more details about the hosting environment (e.g. is WIMP/WAMP, VM, etc.?), one could only guess at what's causing the problem.
It sounds like something is preventing the PHP/server process from writing *.PHP to your server directory. For example, a naive security mechanism, seeing a server process writing PHP files to your web server, might be stopping it as potential code injection attack. But again, that's a guess.
Since you know where it's occurring (and presumably how to recreate it), the battle is already half won. The next step is to look at anything in your hosting environment that might be causing the problem, and try to tweak/relax restrictions until PHP is able to perform the operation.
Comment: That would make sense only if that would be happening with all templates + the temp file is being created as well in the same directory.
Comment: Yeah, it's a guess. It sounds like you know the conditions when it _does_ and _does not_ happen. From that you should work on some PHP code that you can trigger (e.g. `rename()` calls using static filenames that failed/passed in the past) so you can compare/contrast what triggered a failure in the rename function. That might give you some clue to what is going on in your environment that's triggering the failure.
Answer: I'm glad you figured out the main culprit, I believe the solution here is to limit windows native stuff as much as possible, unless, and only, if your online server will also be windows?
Try Aquias dev box app
https://www.acquia.com/products-services/dev-desktop
The awesome Kalabox (still in heavy development).
http://www.kalabox.io
Create your own (or use existing) drupalized virtual server similar to your online environment with the VirtualBox app. https://www.virtualbox.org
With all of the above free options, you can still use Drush, git, git-bash and windows CLI or puTTy to manipulate your sites.
The only caveat...
if your chosen setup from above uses shared folders synched between the two os's, which is useful for easy edits and locally running SASS compilers, grunt, and all the other CLI and NPM goodies.  Sometimes with these shared folders you can have trouble trying to delete long named directories if for some reason the virtual server didn't delete directories leaving behind garbage on your windows os.
First try to log into your virtual server and delete the files from that CLI, if you cannot for some reason, then you'll have to use windows command line tools to overcome the limit, or bulk rename all the folders to short name etc.  Windows can deal with deep large named directories just fine, but for some odd reason they put a cap for simple user delete functionalities.
Comment: LAMP, WAMP, MAMP, are all cool & fun, but....... you open yourself to a lot of weird inconsistencies & broken stuff that's not worth the trouble.  The key in most situations is to get your development environment as close as possible to what your online server will be so you're debugging and fretting over the important stuff effecting the actual site & infrastructure.


A symmetric random walk on a finite line from 0 to up to x

Question: A symmetric random walk ( probability of moving left by 1 = probability of moving right by 1) on a subset of the integers from $0$ up to $x$. Take some $y$ s.t. $0 \leq y < x$ and let the random walk be considered a success if starting at some $y < x_0 \leq x$ we are in the '$0$ up to $y$ subset' after $n$ steps. What is the probability of success after $n$ steps starting at $x_0$?
edit : At the boundary the walker is guaranteed to move back inwards for its next step. It simply bounces back.
Comment: What happens if we hit one of the boundaries?
Comment: At the boundary, the next step is guaranteed to be the integer one away from it. So essentially the walker bounces away from the boundary once hit.
Answer: Since the walk is reflected at the boundaries, it's equivalent to an unbounded random walk in which the target for success is $T=[-y,y]+2x\mathbb Z$. In this unbounded walk, the position after $n$ steps is binomially distributed, so the probability for success is
$$
2^{-n}\sum_{k=0}^n\binom nk\mathbb1_T(x_0+n-2k)\;.
$$
Comment: Wow! Thank you very much for this, I am struggling to understand the intuition behind the $(x_0 + n - 2k)$ term in the series?
Comment: @AlexHill: Ah, perhaps I should have explained the notation. $\mathbb 1_T$ is the [indicator function](https://en.wikipedia.org/wiki/Indicator_function) on the target set $T$, and $x_0+n-2k$ is its argument. That's where you end up if you start at $x_0$ and take $k$ steps to the left and $n-k$ steps to the right. So only those binomial coefficients are being summed that correspond to ending up in the target.
Comment: Ah that makes so much sense now! so the indicator function gives one iff $(x_0 + n -2k) \in T$ and $0$ otherwise? Thank you for the help!
Comment: @AlexHill: Yes, that's right. While I'm defining notation, I might also add that $[-y,y]+2x\mathbb Z$ is the set of all numbers $a+b$ with $a\in[-y,y]$ and $b\in2x\mathbb Z$, and $2x\mathbb Z$ is the set of all numbers of the form $2kx$ with $k\in\mathbb Z$.
Comment: perfect!! Thankyou!


dovecot says that userdb has missing details

Question: When I try to connect to dovecot via outlook I get this error:

ERR:[AUTH]:authentication failed

here is the log files:
Sep 16 12:23:32 hostname9727 dovecot: auth: Error: passwd-file /etc/maillpass: User aaaa is missing userdb info
Sep 16 12:23:35 hostname9727 dovecot: pop3-login: Disconnected (auth failed, 1 attempts in 2 secs): user=<aaaa>, method=PLAIN, rip=184.108.40.206, lip=126.96.36.199, session=<oF81YqI83gBNfC8L>
Sep 16 12:26:02 hostname9727 dovecot: master: Warning: Killed with signal 15 (by pid=14751 uid=0 code=kill)
Sep 16 12:26:02 hostname9727 dovecot: master: Dovecot v2.2.10 starting up for imap, pop3 (core dumps disabled)
Sep 16 12:26:11 hostname9727 dovecot: auth: Error: passwd-file /etc/maillpass: User aaaa is missing userdb info
Sep 16 12:26:13 hostname9727 dovecot: pop3-login: Disconnected (auth failed, 1 attempts in 2 secs): user=<aaaa>, method=PLAIN, rip=126.96.36.199, lip=18.104.22.168, session=<ykSja6I8AQBNfC8L>

and here is the password database:
aaaa:1234

Thanks!
Comment: Please provide information on your configuration, for example the output of `doveconf -n`.
Answer: aaaa:1234

That is not a user database, as the error message states you're clearly missing more than a few fields there for that.
That format could indeed be a password database but then you still need to define in your configuration file the other required fields that are normally found in the user database.  Please refer to the manual: http://wiki.dovecot.org/AuthDatabase/PasswdFile how to use the password database as the template to derive the userdb fields from.
Lastly, you may have obfuscated your password hash, but if the clear text password for user aaaa is supposed to be 1234 I would expect something like:
aaaa:{plain}1234

Comment: see also https://wiki.dovecot.org/Authentication/PasswordSchemes for securely hashing your passwords with `dovecot`. For example to hash with `bcrypt` use `doveadm pw -r 15 -s BLF-CRYPT`


Can Date attribute allow null value?

Question: I have created a Model file for my MVC project that contains the following:
Public Class Player

    Public Property FirstName As String
    Public Property LastName As String
    Public Property GoesBy As String
    Public Property Birthdate As Date

End Class

I didn't mark the Birthdate field as a Required field, but it won't accept nulls.  How can I add a validation or something else to allow for nulls?  Or is that not possible and I have to just insert 1900-01-01 or something similar?
Comment: use Public Property Birthdate as  Nullable(Of Date)
Comment: Umm... how about `Nullable(Of Date)`. Did you even bother to look at any documentation?
Comment: possible duplicate of [Insert null/empty value in sql datetime column by default](http://stackoverflow.com/questions/13934621/insert-null-empty-value-in-sql-datetime-column-by-default)
Comment: @ChrisPratt, yes I did, my apologies on not finding the answer. Thanks for providing it.
Answer: Just make your property Public Property Birthdate As Date as nullable like shown below:
Public Property Birthdate As Nullable(Of Date)

and just make your database field which accepts Birthdate as nullable so that it can accept null values also.
Comment: Sorry for the delay. I believe it would work; however, I can't get the add-migration to pick it up just yet so I'm investigating how to correct that.

Can Date attribute allow null value?


Loop Custom Content based on the taxonomy term they are in

Question: I created a taxonmy vocabulary, added 3 terms in it
Term1, Term2, Term3
Then I created a custom content type, and I associated it with that vocabulary term, so now everytime I create a page I check to which Term they belong to,
What I want to do is
Loop the name of the Term + all the pages titles and body that belong to that term
For example:

Term1

Page 1 title

Page 2 title

Term2

Thanks
Comment: Possible duplicate of [Views: nodes grouped by taxonomy term](https://drupal.stackexchange.com/questions/29711/views-nodes-grouped-by-taxonomy-term)
Answer: This was the answer I was looking for
<?php
$nodes = node_load_multiple(array(), array('type' => 'analize'));
$listAnalize = [];
foreach ( $nodes as $kNod => $vNod ) {
  $term = taxonomy_term_load( $vNod->field_categoria_analizei['und'][0]['tid'] );

  $listAnalize[$vNod->field_categoria_analizei['und'][0]['tid']]['denumire'] = $term->name;
  $listAnalize[$vNod->field_categoria_analizei['und'][0]['tid']]['analize'][] = $vNod;
}
?>


Can a database be tested to see if it is inconsistent?

Question: We all know that Drupal doesn't really support the concept of foreign keys in the database, and likely never will1.
We also know that it is possible for modules to not do the right thing, or that users will periodically do crazy things like
<code>DELETE FROM node_revision
WHERE vid = 123
</code>
in an effort to "keep the database tidy".  When this happens, hooks don't run, and there is orphaned data in the database.  Mostly, this data is harmless, but occasionally it causes really weird behavior and can bring out bugs in code.
Are there any decent methods for detecting whether you have have dead and/or inconsistent data in your database?
1 The Drupal 7 Schema API supports them for documentation, but not enforcement.
Comment: I assume you mean "any decent methods from within Drupal"?  Or are you open to an outside tool?
Comment: Ideally, within Drupal, but I'm open to anything.  I started paper planning a Drupal tool, but don't know how far it will go.
Comment: Can the problem be reduced to a set of SQL queries to find such data?  If you were not building any easy-to-use tool with a nice Drupal UI, but instead sitting at a MySQL client issuing queries manually, how would you find such inconsistencies?
Comment: The queries aren't really the problem.  It is more knowing what tables to query and what keys to join on.  My paper idea is to use the Schema API to get all of the tables, and then try to figure out from each schema whether we can build a query.  This may end up being a holiday project for me.
Comment: Btw, looking like finally some FK support in D8: http://drupal.org/node/911352
Answer: As I was writing up a description for a sandbox project, I ran across a sandbox project for doing this:
http://drupal.org/sandbox/anton_krechetov/1345066
It currently only works for Drupal 6, and there haven't been any commits since Nov 2011, but it looks promising.


Changing existing date time field

Question: I am working on an already existing site that has content.
There is a content type with field date and time. I need to remove the time component and just be Date only without deleting any content along the way. If the time data is lost, that is fine.
Can I simply delete the field and recreate it with date only? Or will that delete the existing data?
Comment: This maybe can be done with config. Export current config, change as desired, reimport. Otherwise create another field, migrate the data, then delete the old field.
Comment: `will that delete the existing data?` yep, any time you delete a field, all the data is deleted as well.
Answer: Unfortunately, as suggested, programmatically changing the config won't work, as all dates will show empty. Which explains why it's locked in the UI.
You'll need to browse your DB and find the node__{field_date} table and manually remove the time part for all values.

Then make a sql export of this table.
Repeat the above with node_revision__{field_date}.
In Drupal, manage fields, delete your field_date. Recreate field_date with Date only. Import your sql db table exports you had made.
Flush cache in Drupal.

Changing existing date time field