Is there a good source of flamenco backing tracks for practice?

Question: After years away from the guitar I wanted to pick it up again, but learning flamenco (for something completely different).
I live half a world away from Andalucia, so getting to play with others is a bit difficult.
Getting the unique tempos/compas of flamenco ingrained is one of the challenges I face, as they are quite unlike anything I've played in the past. If I play unaccompanied, I can stray quite easily.
Ideally I'd like to find some good backing tracks, with palmas & cajon but no guitar. Youtube doesn't yield much of interest, but I see a few companies selling dvd, loops and such. Any recommendations?
Answer: I suspect the elusive part of "good backing tracks" is going to be the "good" part. The kind of stuff you're likely to find for sale is likely to be rather "soulless". It'll sync nicely with a metronome, but you may end up sounding like you have a metronome permanently mounted in your ear.
I think it may be more useful to focus on find "good pieces" that you really want to learn. Then there are gizmos and software to "remove parts". (To the group: Do any of these things work well enough to recommend?)
Recording yourself and listening to playback can be helpfull, too.
Comment: +1.  [Audacity](http://audacity.sourceforge.net/) works well for removing parts using the technique described [here](http://audacity.sourceforge.net/help/faq?s=editing&i=remove-vocals) - I think that's a great idea.
Answer: worldmusictracks.com. You can ask for tracks without guitars.
Answer: If your concern is playing in compas, I would search for a "flamenco metronome". There are many available for download on the internet. Some come as apps for your phone. The more basic ones include the beat for each palos and the more advanced ones include various options such as palmas or jaleos. As far as the visual presentation is concerned, almost all of them use the so-called "flamenco clock" (which is useful for the 12-beat cycles).
Depending on how much you plan to use it, you could opt for apps such as Beatvibe, Doctor Compas or the Graf-Martinez metronome (all around 15 to 20 USD).
On the upper end, the only one I know of is the Oscar Herrero flamenco metronome which is of far better quality but also much more expensive (around 350 USD). I wouldn't recommend it unless you are aiming at becoming a professional flamenco guitarist. For a beginner or an intermediate-level guitarist, many of the features on there would be superfluous.
Once you feel comfortable with the compas, you can also get tracks that include the singer, cajon, palmas, but no guitar. This is a good way to learn how to accompany, especially if there is no real flamenco scene in your area. Most of these tracks (at least that I know of) are found in some of the typical guitar methods that you can purchase. Any on-line search for a flamenco accompaniement method should give you an idea of what's available.


Is there any ideas on webform mutile values on same field?

Question: In webform select components, we can set multiple attributes but not for filed like textfield or numbers.
So I want to ask is there any ideas on that, so let user can add more value  on same field. Such as:
Telephone number, the web visitors may not have only one ,and we should allows multiple for that.
We found that the webform has store multiple  values in database which can come from in the form used like telephone[], but do not in the validation.
We do not want to changes the validation rules but we want to have a multiple attributes on textfied.
Is there any idea?
Thanks.
Answer: There is module for doing this: Try the Multivalue Settings module.

This module adds some useful settings for fields that can contain multiple values. You can specify:

Number of values allowed
Number of values required
Number of empty widgets to display initially (Drupal usually displays all fields for non-unlimited fields. This allows you to only display a few, followed by the 'Add More' button, which will disappear after the maximum number of fields has been filled.)
Number of empty widgets to display on edit forms after the field contains some values (Drupal usually displays one extra.)
Comment: Much Thanks, it seems not for the webform textfiled field.
Comment: Sorry to lead to the misunderstood. Actually,  the Multivalue Settings module is useful in a normal drupal form. While webform is another drupal module which allows we create a form in node not as a content type. And my question is on webform's filed, I'd like to see if any predecessors have done that or give some ideas for that. Thanks again.
Answer: You can just try Webform Multiple.

Webform Multiple (WFM) is a Drupal 7 module allowing Webform
  components to have more than one value.
The user completing the form can add instances of the component with
  an 'Add another item' button.

Hope it can help you


Android GoogleMaps tiles flicker

Question: I just started working with Android and I have a problem with my map.
I created a TabActivity and added MapActivity as one of the tabs with:
<code>spec = tabHost.newTabSpec("map").setIndicator("Map");
intent= new Intent().setClass(this, NavisMapActivity.class);
spec.setContent(intent);
tabHost.addTab(spec);
</code>
In MapActivity I get MapView from xml layout with findViewById.
<code>     <com.google.android.maps.MapView
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/mapview"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:apiKey="my_key_is_here"
        android:clickable="false" />
</code>
When I load the app, everything works perfectly until I switch tabs or call another app. Basically when OnPause/OnStop is called. Then when I return to the map, its tiles start to flicker constantly. Only solution is to force the app to close.
This happens only with satellite tiles and from version 2.3.5 onward(tested it on an actual phone and in the Eclipse emulator).
So far I have tried:

using mapView.destroyDrawingCache() command in onPause function
adding mapView via code instead of xml layout
destroying whole MapActivity with LocalActivityManager when tab is switched and creating a new one

None of this helped. Could anyone please help me?
Thank you
Comment: Have you tried creating a custom tabActivity that extends from MapActivity and then use Fragments for the tabs content frame? This would also reduce the complexity of your main activity, potentially meaning more efficiency . The Google Maps api for Android is a bit lacking, I generally find.
Comment: No, the minimal version requirement is Android 2.1 and if I'm not mistaken the fragments were implemented later. So I cant use them. I have not even worked with them yet.
Comment: You can still use Fragments with the support package: http://developer.android.com/sdk/compatibility-library.html
Comment: Well I transformed the project to use fragments but the result is the same...when OnPause is called the tiles go crazy.
Comment: ok it may actually be a deeper issue: http://code.google.com/p/android/issues/detail?id=19154&q=google%20maps%20tiles&colspec=ID%20Type%20Status%20Owner%20Summary%20Stars
Comment: Btw, did you put the map in the fragment or in the activity? Because if it was attached to the activity instead of the fragment then onPause will not be called.
Comment: Yes, sorry...I found out that OnStop is causing the same problem. Which will happen when user switches to another app or home screen.
The issue you posted looks much like my problem (even though some specifics are different) so I guess I cant do much about it...
But thank you very much for your help! At least now it partially works.
Comment: Glad to help, I want to find an alternative solution for Google Maps API myself since it seems to cause way too many problems.
Answer: As I mentioned in the comments this seems to be a problem with the Google Maps API:
http://code.google.com/p/android/issues/detail?id=19154&q=google%20maps%20tiles&colspec=ID%20Type%20Status%20Owner%20Summary%20Stars
Let's hope that they fix it some time soon.
I want to try some of these alternatives:
Alternatives to google maps api
Will report back if any is worth dealing with :)
This one also seems promising: http://code.google.com/p/mapsforge/

Android GoogleMaps tiles flicker


Sufficient conditions for integer extreme points in linear programming

Question: I was given an exercise that looks as follows:
Given the following linear program:

minimize $\sum_{i=1}^{m} y_{i}x_{i}$

subject to some constraints related to $x_{i}$, prove that any extreme point of the feasible region of this linear program consists of $x_{i}$ that are some discrete numbers (0, 1 or 2 for example).
I wonder how is it possible to infer something about the extreme points mathematically without actually solving the linear program. What should the first step be when solving these type of problems?
I would like to avoid giving the exact definition of the linear program so I don't receive replies that actually solve the entire problem itself. I am just curious if there is a general approach for these type of problems?
Comment: Are the $y_i$ known constants?  It seems strange that you would give the objective function and no other information.
Comment: $y_{i}$ is completely unknown but a real number
Answer: The solution of a linear program of the form $\min \;\{y\cdot x \mid Ax \ge 0, x \ge 0 \}$ is attained at a point $x$ with integer coordinates if the constraint matrix $A$ is totally unimodular. $A$ is totally unimodular iff every square non-singular submatrix is unimodular, i.e. has determinant $\pm 1$. $A$ need not be a square matrix to be totally unimodular.
Totally unimodular matrices arise in a number of contexts, such as the incidence matrix of a bipartite graph. This is the matrix that one needs to formulate weighted bipartite matching problems as linear programs.


Can't extend abstract PHP class

Question: I want a base class to be extended, but I have some errors coming out:

Fatal error: Class 'Api\Services\Base' not found in
  /var/www/html/Api/Services/Example.php on line 7

I searched for typos, tried to use the fully qualified name, made the abstract class empty or just defined it as a simple class; none of these helped.
Using "require" instead of "use" worked, but still...
Any idea (the two files are in the same directory: /var/www/html/Api/Services)?
Thanks in advance...
<?php
    // Base.php
    namespace Api\Services;

    use Api\Classes\ErrorHandler;
    use Api\Classes\ErrorMessage;

    abstract class Base
    {
        public $data = null;

        public function getData()
        {
            return $this->data;
        }

        public function setData($data = null)
        {
            $this->data = $data;
        }
    }
?>

<?php
    // Example.php
    namespace Api\Services;

    use Api\Services\Base;

    class Example extends Base
    {
        public $request = array();

        public function __construct($request = array())
        {
            $this->request = $request;
        }
    }
?>

Comment: Thats the bug. Read here http://www.php-fig.org/psr/psr-4/ and http://www.php-fig.org/psr/psr-4/examples/ and create one.
Comment: Or just include the file with `include_once('Base.php')` in `Example.php` after the `use` line. Than it works without an autoloader. But i thing you should read about Namespaces & Classes & Autoloading a little bit more.
Comment: At witch point is the `autoloader` set up? And you dont need `use Api\Services\Base;` because you are in the same namespace `Api\Services`.
Comment: Note "require" works not like "use". *require* loads a FILE for real, `use` defines only the full namespaced name of a class. Did you know what this does: `use Api\Services\Base as MyBase;` ??
Comment: There is no autoloader. Maybe that is the problem (I'm new to OOP/PHP)?
Comment: Thanks, I'll look into it.
Comment: It's working now, thanks again!
Answer: use Base

instead of
 use Api\Services\Base;

because you are already inside the namespace Api\Services
Actually, you don't even have to write the use statement, you are inside the namespace, you can just call the classes inside the same namespace without including them (use)
Comment: He is in the same namespace `Api\Services`, not need for `use` !

Can't extend abstract PHP class


Ambulance problem with joint random variable

Question: An ambulance travels back and forth, at a constant speed, along a road of length $L$. At a certain moment of time an accident occurs at a point uniformly distributed on the road. [That is, its distance from one of the fixed ends of the road is uniformly distributed over $(0, L)$.] Assuming that the ambulance's location at the moment of the accident is also uniformly distributed, compute, assuming the independence, the distribution of its distance from the accident.
I get the following:
$$\int\int_{|Y-X|\le a} \frac{1}{L^2} $$
However, I am stuck on trying to find the bounds for the next step.
$$\int\int_{-a\le Y-X\le a} \frac{1}{L^2}$$
I know I get $X-a\le Y\le X+a$ for the bounds of $Y$. But I am confused of how I should find the bounds for $X$?
Answer: The problem is that $X-a$ need not be negative and $X+a$ need not be bigger than $L$. We will need to split the integral to consider those possibilities and write the bounds of $Y$ accordingly. Two cases will appear, $a<\frac L2$ and $a>\frac L2$
Case $a<\frac L2$
Here is a visual representation of the region we need to integrate to.

We will split the integral in three parts

When $X$ is smaller than $a$, $Y$ will be between $0$ and $X+a$;
When $X$ is between $a$ and $L-a$, $Y$ will be between $X-a$ and $X+a$;
When $X$ is between $L-a$ and $L$, $Y$ will be between $X-a$ and $L$.

$$\int\int_{|Y-X|\le a} \frac{1}{L^2}dydx = \int_0^a\int_0^{X+a} \frac{1}{L^2} dydx + \int_a^{L-a}\int_{X-a}^{X+a} \frac{1}{L^2} dydx + \int_{L-a}^L\int_{X-a}^{L} \frac{1}{L^2} dydx$$
A bit of algebra give $2aL-a^2$
Case $a>\frac L2$
Here is a visual representation of the region we need to integrate to.

Here, $a$ is bigger than $L-a$. We will still split the integral in three parts, but it will be a bit different.

When $X$ is smaller than $L-a$, $Y$ will be between $0$ and $X+a$;
When $X$ is between $L-a$ and $a$, $Y$ will be between $0$ and $L$;
When $X$ is between $a$ and $L$, $Y$ will be between $X-a$ and $L$.

$$\int\int_{|Y-X|\le a} \frac{1}{L^2}dydx = \int_0^{L-a}\int_0^{X+a} \frac{1}{L^2} dydx + \int_{L-a}^{a}\int_{0}^{L} \frac{1}{L^2} dydx + \int_{a}^L\int_{X-a}^{L} \frac{1}{L^2} dydx$$
Surprisingly, this gives exactly the same answer : $2aL-a^2$.
In conclusion :
$$P(\lvert X-Y\rvert \leq a) = 2aL-a^2$$

Since the position is uniformly distributed, it is a lot simplier to evaluate the area of each region. It is a square minus two triangles and both cases are the same.
$$L^2 - 2\times \frac{(L-a)^2}{2} = 2aL - a^2$$


What's the expected behavior of the Bing Search API v5 when deeply paginating?

Question: I perform a bing API search for webpages and the query cameras.
The first "page" of results (offset=0, count=50) returns 49 actual results. It also returns a totalEstimatedMatches of 114000000 -- 114 million. Neat, that's a lot of results.
The second "page" of results (offset=49, count=50) performs similarly...
...until I reach page 7 (offset=314, count=50). Suddenly totalEstimatedMatches is 544.
And the actual count of results returned per-page trails off precipitously from there. In fact, over 43 "pages" of results, I get 413 actual results, of which only 311 have unique URLs.
This appears to happen for any query after a small number of pages.
Is this expected behavior? There's no hint from the API documentation that exhaustive pagination should lead to this behavior... but there you have it.
Here's a screenshot:
Answer: Each time the API is called, the search API obtains a group of possible matches starting at  in the result set, and then filters out the results based on different parameters (e.g spam, duplicates, safesearch setting, etc), finally leaving a final result set.  If the final result after filtering and optimization is more than the count parameter then the number of results equal to count would be returned. If the  parameter is more than the final result set count then the final result set is returned which will be less than the count parameter.  If the search API is called again, passing in the offset parameter to get the next set of results, then the filtering process happens again on the next set of results which means it may also be less than count.

You should not expect the full count parameter number of results to always be returned for each API call.  If further search results beyond the number returned are required then the query should be called again, passing in the offset parameter with a value equal to the number of results returned in the previous API call.  This also means that when making subsequent API calls, the offset parameter should never be a hard coded value and should always be calculated based on the results of previous queries.

totalEstimatedMatches can also add to confusion around the Bing Search API results.  The word 'estimated' is important because the number is an estimation based on an initial quick result set, prior to the filtering described above.  Additionally, the totalEstimatedMatches value can change as you iterate through the result set by making subsequent API calls with increasing offset values.  The totalEstimatedMatches should only be used as a rough guide indicating the magnitude of the possible result set, and it should not be used to determine the number of results that will ultimately be returned.  To query all of the possible results you should continue making API calls, passing in offset with a value of the sum of the results returned in previous calls, until that sum is greater than totalEstimatedMatches of the most recent API call.

Note that you can see this same behavior by going to bing.com directly and using a query such as https://www.bing.com/search?q=bill+gates&count=50.  Notice that you will get around 34 results with a totalEstimatedMatches of ~567,000 (valid as of June 2017, future searches may change), and if you click the 'next page' arrow you will see that the next query executed will start at the offset of the 34 returned in the first query (ie. https://www.bing.com/search?q=bill+gates&count=50&first=34).  If you click 'next' several more times you may see the totalEstimatedMatches also change from page to page.
Comment: Thanks for the quick response, Matt. You are describing the behavior I'm seeing. But please look carefully at my description: I **am** adding the retuned result count to `offset` each time. (See the screen shot for the actual `offset` values I'm using with each request.) At a certain point, returned results drops precipitously. The original estimate of 114 million seems unobtainable in practice -- even orders of magnitude less than that seems unobtainable in practice. **Does this match the actual expected behavior of the API, or is the API broken?**
Comment: Yes, this is expected behavior.
Comment: Thanks @MattSmall -- just to extra clarify: **is it possible to use the API to exhaustively get 114M results for a single query**? (Or, anything resembling that scale of results for a single query?)
Comment: Here's the important of the information above:

totalEstimatedMatches can also add to confusion around the Bing Search API results.  The word 'estimated' is important because the number is an estimation based on an initial quick result set, prior to the filtering described above.

It is theoretically possible should there be that many actual results after filtering.  In practice I don't know that it is or isn't.
Comment: Thanks Matt, but I feel that... side-steps my actual question about scale. I'm searching for the term "cameras". We both know there are more than 311 unique webpages on the web that pertain to cameras. An estimate of 114M sounds... plausible. Even if there are only 1M in practice... it seems the Bing API will only ever return 300-ish unique results (or thereabouts -- give or take an order of magnitude here) to me?
Comment: What's your goal in understanding this?  It might help me get you a better answer.
Comment: My goal is to understand the expected and actual behavior of the API. I would like to know whether it is possible to exhaustively obtain results at the scale of millions for a single query. Is it?
Comment: I don't know. I can tell you how to get all of the results that are available.  I'm not privy to the algorithm that calculates "totalestimatedmatches".
Comment: Okay, perhaps I'll ask a different way. When *you* use the Bing Search API to get all of the results available for the search query `cameras`, how many unique URLs do you ultimately retrieve? (I realize this number might vary from attempt to attempt, but I'm just curious about the typical number you get.)
Answer: This seems to be expected behavior. The Web Search API is not a crawler API, thus it only delivers results, that the algorithms deem relevant for a human. Simply put, most humans won't skim through more than a few pages of results, furthermore they expect to find relevant results on the first page.
If you could retrieve the results in the millions, you could simply copy their search index and Bing would be out of business.
Search indices seem to be things of political and economic power, as far as I know there are only four relevant search indices world wide: from Google, from Microsoft (Bing), from Russia, and from China.
Those who control the search, control the Spice... ;-)


Heroku postgres connection in PHP

Question: I have tried to connect to postgres the same way I connect to phpmyadmin but it seems that the connection  fails.. What I did was to copy and paste my credentials into the php file.. I was wondering if i need to activate the postgres database before trying to connect?? Any help would be greatly appreciated.. Best..
Comment: PostgreSQL version? Exact error message text?
Comment: For future questions please read the FAQ, particularly http://stackoverflow.com/faq#howtoask
Comment: A really good read for asking questions on any forum: http://www.catb.org/esr/faqs/smart-questions.html
Answer: What error message do you get?
You need to at least add the database to your app before it will be available - see this answer here. Have you been able to add the app and see the database credentials?

Heroku postgres connection in PHP


Trying to save an image field on a user using services, but for some reason it isn't saving in base64

Question: So my server (running Drupal 7) is getting this information:
[field_picture] => Array
    (
        [und] => Array
            (
                [0] => Array
                    (
                        [file] => iVBORw0KGgoAAAANSUhEUgAAAIwAAACMCAYAAA..... (the rest of a huge base64 string)
                        [filename] => test.png
                        [filemime] => image/png
                        [target_uri] => test.png
                        [filepath] => public://
                        [mimeType] => image/png
                    )

            )

    )

This is to a user endpoint, and this is the only field that doesn't update.
The rest of what is sent to the server looks like this:
[field_description] => Array
        (
            [und] => Array
                (
                    [0] => Array
                        (
                            [value] =>
                            [format] =>
                            [safe_value] =>
                        )

                )

        )

[uid] => 22
[roles] => Array
    (
        [2] => authenticated user
    )

And my AJAX to put this up:
    $.ajax({
        url: SITE_URL + "/" + ENDPOINT + "/user/" + localStorage.uid,
        type: 'PUT',
        crossDomain: true,
        headers: {
            'X-CSRF-Token': token
        },
        contentType: 'application/json',
        data: JSON.stringify(json),

...etc

The request doesn't fail (or at least it doesn't go to my error callback) - what is going on here and why isn't it saving?
Comment: Watchdog errors? File system permissions?
Answer: You need to make two requests, the first you will POST the base64 encoded string of the file which in turn will return to you the file id, at which point you can make the second call to save the user entity with the file id on the field in question. I have a blog post about this here: http://tylerfrankenstein.com/code/drupal-services-file-create-example-json-and-jquery
Here's the gist of it (assuming your endpoint path is api):
// Get the file id...
$.ajax({
  type: "post",
  data: {
    "file":{
      "file": my_base_64_encoded_image_string,
      "filename": "my_image.jpg",
      "filepath": "public://my_image.jpg",
    }
  },
  url: 'https://www.example.com/api/file.json',
  dataType: 'json',
  success: function(result) {

    // Now that we have the file id, save it on the user entity.
    var userAccount = {
      field_picture: { und: [ { fid: result.fid } ] }
    };

    $.ajax({
      url: "https://www.example.com/api/user/" + localStorage.uid,
      type: 'PUT',
      crossDomain: true,
      headers: {
          'X-CSRF-Token': token
      },
      contentType: 'application/json',
      data: JSON.stringify(userAccount)
    });

  }
});

Comment: You're pretty much the expert on this, so I'll test this and almost certainly accept your answer, haha.
Comment: Also I'm assuming I need a new token with each request?
Comment: No, you use the same token. Just have your application request a token upon startup, and after login/logout, and set the token aside, then you can use it for all subsequent requests.
Comment: I am getting a 401 unauthorized CSRF validation failed but only from my mobile device. What could possibly be causing that? I've temporarily given permission to create files to everyone, including anonymous to test this and it still won't work. It is happening on file creation.
Comment: I'd recommend trying to fetch a new token right before making the POST call, just to see if that gets it to work. It sounds like the token being sent up has expired.
Comment: Yep, that's exactly what it was. Any idea why that would happen on mobile but not on desktop?
Comment: Well it sounds like you are saving the token somewhere, and it is expiring at some point. I'd ask where you are saving it... then just make sure to fetch a new token upon app start up, during login/logout/registration... and maybe even fetch a new token when the app comes back awake, in case their phone went to sleep.


Calculate new tile coordinates for 90 degree rotated square object

Question: So I have a square (all sides even) with even AxA tiles (for example 3x3). Every tile has its x,y coordinates according its placement. After I rotate the object by 90 degrees around the center, the these world coordinates are no more valid (see image). So what I'm trying to figure out is a formula that takes 3 parameters: 1) old coordinates (x,y), 2) tile count (A) and 3) rotate direction.. and gives new nx,ny after 90 degree rotation. For example 1,1 after rotation becomes 1,3.. 3,2 become 2,1.. 2.2 stays 2.2 and so on. Any help appreciated.
Comment: About which point are you rotating? The centre square?
Comment: Yes center. Will add to description. Sorry for leaving that out.
Answer: You need the rotation matrix centered at $(2,2)$
$\begin{bmatrix}x'\\y'\end{bmatrix} = \begin{bmatrix}2\\2\end{bmatrix} +\begin{bmatrix}\cos \theta & -\sin \theta \\ \sin \theta &\cos \theta\end{bmatrix} \begin{bmatrix}x-2\\y-2\end{bmatrix}$
EDIT
To clarify, this is in the sense that anti-clockwise rotations are positive, for clockwise rotations, just put the same angle, but negative.
EXAMPLE
$$\begin{bmatrix}x'\\y'\end{bmatrix} = \begin{bmatrix}2\\2\end{bmatrix} +\begin{bmatrix}\cos (-90) & -\sin (-90) \\ \sin (-90) &\cos (-90)\end{bmatrix} \begin{bmatrix}1-2\\1-2\end{bmatrix}$$
$$\implies \begin{bmatrix}x'\\y'\end{bmatrix} = \begin{bmatrix}2\\2\end{bmatrix} +\begin{bmatrix}0 & 1 \\ -1& 0\end{bmatrix} \begin{bmatrix}-1\\-1\end{bmatrix} = \begin{bmatrix}1 \\ 3\end{bmatrix}$$
Hence the point (1,1) becomes (1,3) which fits as the above diagram
Comment: Swap $-\sin\theta\leftrightarrow\sin\theta$.
Comment: This is assuming anti-clockwise positive, the standard convention
Comment: Then you should state that the OP has to put $\theta=-90^\circ$.
Comment: How we could make it dynamic? So it takes -90 and 90?
Comment: What do you mean?
Comment: @JanisTaranda It takes any angle, just keep the convention in mind. Btw you should write your attempt to not attract downvotes.
Comment: @DhanviSreenivasan Anyways +1.
Comment: @DhanviSreenivasan can you calculate one example for me. For example with 1,1. I was not lucky to produced required results.
Comment: But clockwise 1,1 becomes 1,3, not 3,1.. and u said -90 is clockwise
Comment: Ah ok. I tried to use +90, and got also 3,1.. this doesn't seem right.
Comment: Oops, my bad.. typo
Comment: It should be correct now
Comment: @DhanviSreenivasan when rotating counter clockwise +90 degree in foruma, 1,1 should become 3,3, but when I do calculations its not the case
Comment: @SameerBaheti it just doesn't work with positive angle - assuming so it goes counter-clock wise.
Comment: I tried with other values. It just doesn't work. Not a solution.
Comment: If you rotate by 180 degrees you'll get (3,3). If you rotate clockwise by 90 you'll get (1,3), which my answer gives
Comment: Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/110970/discussion-between-janis-taranda-and-dhanvi-sreenivasan).


Samba file server on Windows Domain can't authenticate users - gives "credentials chain check failed"

Question: I have two TurnKey Linux Fileserver 13 (basically Debian 7.3) running Samba to share folders on our mostly-Windows LAN. Samba is configured to authenticate users using Active Directory on our domain controller.
This was all working great until recently, now both Samba servers fail to authenticate some users. Other users who have been using the servers can still connect and access files just fine (cached credentials?). The following is a typical example of what is logged in the Samba log on a failed login attempt:
<code>[2016/04/26 20:08:15.768961,  0] rpc_client/cli_netlogon.c:459(rpccli_netlogon_sam_network_logon)
  rpccli_netlogon_sam_network_logon: credentials chain check failed
[2016/04/26 20:08:15.769053,  0] auth/auth_domain.c:331(domain_client_validate)
  domain_client_validate: unable to validate password for user lholdeman in domain meg to Domain controller DC01.MEG.LOCAL. Error was NT_STATUS_ACCESS_DENIED.
</code>
I don't know of anything that changed with our domain controller, and I'm fairly sure our domain controller is allowing Samba to connect to authenticate users as I did a quick setup in VirtualBox of the exact same OS/software, copied all my production configs over, and successfully logged into the temporary Samba setup using the same domain credentials that didn't work on the production machines.
Here's a copy of my Samba config as well:
<code>[global]
    passwd chat = *Enter\snew\s*\spassword:* %n\n *Retype\snew\s*\spassword:* %n\n *password\supdated\ssuccessfully* .
    obey pam restrictions = yes
    admin users = root
    #read prediction = yes
    passwd program = /usr/bin/passwd %u
    dns proxy = no
    netbios name = PAFILES
    default = companyfiles
    workgroup = MEG
    os level = 20
    auto services = companyfiles
    security = ads
    delete user script = /usr/sbin/userdel -r '%u'
    max log size = 1000
    directory mode = 777
    log file = /var/log/samba/samba.log
    read raw = no
    guest account = nobody
    write raw = no
    add group script = /usr/sbin/groupadd '%g'
    socket options = TCP_NODELAY
    delete group script = /usr/sbin/groupdel '%g'
    add user to group script = /usr/sbin/usermod -G '%g' '%u'
    force directory mode = 777
    wins server = DC01.MEG.LOCAL
    #null passwords = yes
    encrypt passwords = true
    winbind trusted domains only = yes
    winbind use default domain = yes
    realm = MEG.LOCAL
    passdb backend = tdbsam
    unix extensions = no
    wide links = yes
    server string = TurnKey Linux FileServer
    password server = DC01.MEG.LOCAL
    unix password sync = yes
    force create mode = 777
    add user script = /usr/sbin/useradd -m '%u' -g users -G users
    syslog = 0
    create mode = 777
    panic action = /usr/share/samba/panic-action %d
    pam password change = yes

[companyfiles]
    shadow:basedir = /srv/storage
    force directory mode = 777
    recycle:keeptree = yes
    shadow:sort = desc
    vfs objects = shadow_copy2
    writeable = yes
    delete readonly = yes
    path = /srv/storage
    shadow:snapdir = ../snapshots/storage
    force create mode = 777
    comment = Public Share
    create mode = 0777
    recycle:repository = Recycle Bin
    recycle:versions = yes
    directory mode = 0777
</code>
Any ideas on what I might try next?
Thanks!
Comment: same issue: http://serverfault.com/q/771163/217522
Answer: There is an upstream bug in Samba that was included in the updates released on April 12 in response to the widely-publicized "Badlock" vulnerability, which results in exactly the behavior you are seeing.  The Debian bug is here: https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=820981
Red Hat has a working patch, but has not yet released it as of today (Apr 27): https://bugzilla.redhat.com/show_bug.cgi?id=1326918
At the moment it looks like your only options are either to downgrade to the previous version of Samba, or wait for a patch from your distro.
Comment: The fix for this bug that seems to be working for me was to install and start winbind. Apparently this gives Samba an alternative way to do its thing instead of the now broken method used before. There's more info at the debian bug report linked above.


Why the line not cut across the data?

Question: I using linear regression model to predict my data.
Orig Data
When I using sns plot; I able to see the line cut's thru to all the data point.
Using snsborn.lmplot
But when I using train_test_split function:
The coeff & interc as below :
Weight =  [0.20504568]
Intercept = -1.0383656275693958
But graph is totally out
graph using train test split
How can I fix this?
Answer: My bad... i using the wrong X value for the line graph.

Why the line not cut across the data?


8 - Views: list pages that are child menu items to the current node

Question: I have three nodes:

Node A
Node B
Node C

In the main menu, these nodes are organized with Node B and C as children of Node A's menu item, like so:

Node A

Node B
Node C

When Node A is viewed, I would like to display/list Node B and C in a block under Node A's content.
I would like to do this without using the Book module. I would also like to do this without adding an extra step to the user (i.e. using entity reference on Node A).
Is there a way to do this views? i.e. to create a relationship to the menu structure?
Here's a drawing of what I'm trying to achieve:

Any insight is greatly appreciated.
Answer: I hate answering my own question here, but just to save the effort anyone might be going through, here is a module that worked for me:
Views Menu Node Children Filter
Using this module I was able to pass the node ID of the current node and filter the node's children in reference to the menu structure. Works perfectly on 8.4.
Comment: @felipep I wish I new which site this module was used on. I'll try and dig that up so I  can share that with you. I vaguely recall using contextual filters to pass nid of the parent or something to that affect.
Comment: @ymdahi thanks, I already find it out how it works, the parent id is necessary as context filter
Comment: Couldn't Menu Block solve this?
Comment: @Kevin not that I'm aware of - I am trying to pass the menu children of the current node in a view.
Comment: Menu Block can read and folllow the active trail of the current uri and make that the starting point for output. https://www.drupal.org/project/menu_block - therefore, no Views needed.
Comment: I added a drawing to illustrate what I'm talking about, I don't think menu block solves this issue. Btw, I'm using menu block to render the menu. The question was regarding the 'subpages' section - see drawing above. Let me know if I've misunderstood what menu block can do.
Comment: Can you specify how did you configured the view to filter using menu node children?


Criar links de "esqueci a senha" em Android

Question: Olá, alguém sabe como faço para criar um botão de link para redefinir senha como o da imagem abaixo, e quando for clicado abrir outra Activity?

Answer: Existem duas opções que resolvem o seu problema, são elas: você pode utilizar um Button ou uma TextView.

Button

O primeiro, que é o mais comum a ser utilizado, você deve ter se deparado com o problema dele ter um background, mas, felizmente, resolver isto também é possível. Você pode substituir o background dele por um outro que já é padrão do android. Primeiro, você vai precisar definir um estilo para o seu botão, e esse estilo vai definir como ele irá se comportar em seu layout. No seu caso, como um botão sem background, mas sem perder os efeitos que um botão tem.
<Button
    style="?attr/borderlessButtonStyle"
    android:layout_width="wrap_content"
    android:layout_height="56dp"
    android:background="?attr/selectableItemBackground"

O código acima nos mostra 2 importantes atributos, que são eles style e background.
O atributo style está apontando para uma resource que está presente na plataforma do Android, ou seja, todas as APIs terão esta resource, e para cada API, ela será diferente. No android L ela tem um comportamento diferente, assim como no Holo ela também tem outro comportamente.
O mesmo serve para o atributo background, com o selectableItemBackground. Ele te oferece um efeito de clique (o ripple effect). Existem outras opções que você pode utilizar, que são selectableItemBackgroundBorderless, é praticamente a mesma coisa, mas os efeitos de cliquem se dispersam, porque é como se o botão não tivesse bordas.
Você também pode sublinhar o texto do seu botão, se caso precisar:
forgotPassword.setPaintFlags(forgotPassword.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);

TextView

Já que o botão herda da classe TextView, isto significa que tudo que você fez com o botão pode ser feito com esta classe. Ou seja, podemos aplicar o estilo e o background da mesma forma.
<TextView
    style="?attr/borderlessButtonStyle"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:clickable="true"
    android:background="?attr/selectableItemBackground"

Como você pode ver, é exatamente a mesma coisa, mas com uma exceção, há um atributo chamado clickable. Ele apenas aponta para o sistema que esta view pode ser clicada e isto faz com que ela execute os efeitos de clique, se caso ela tiver um onClickListener, você pode remover este atributo.
Se quiser deixar o texto sublinhado, é a mesma coisa
forgotPassword.setPaintFlags(forgotPassword.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);

Como você pode ver, o uso vai depender de você. Mas eu recomendo  que você utilize um Button, já que é algo padrão.
Obs: ao utilizar o borderlessButtonStyle em um botão, o atributo background pode ser removido, já que ele se comportará normalmente... como um botão sem bordas e sem background, por causa do estilo atribuído a ele.
Answer: Você precisar primeiro declarar o textview no seu código:
Textview telaperdeusenha = (Textview ) findviewbyid(R.id.telaperdeusenha);

depois você cria um evento de click no textview e envia pra outra activity
textviewperdeusenha.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent telaperdeusenha = new Intent(this, telaperdeusenha.class);
            startActivity(telaperdeusenha);

        }
    });


Determining the values of $c_1$, $c_2$ and $c_3$ in the sum of the series

Question: I have been given this power series:
$$\sum_{n=1}^{\infty}\frac{(-1)^{n}(4+x)^{n}}{4^{n+2}}$$
And I was told that the series converges for $a < x < b$ which I found as well:
$$-8<x<0$$
I have also been told that for $a < x < b$, the sum of the series is:
$$S(x)=-\frac{c_{1}+x}{c_{2}{x+c_{3}}}$$
How can I find the values of $c1, c2, c3$?
Comment: In the exercise, it is states as the one I have written in the question. Can I ask what is wrong with it?
Comment: This is a geometric series, do you know how to evaluate it?
Comment: The formula for $S(x)$ cannot be right, it should diverge to infinity for $x=-8$. (The sum of a geometric series is a rational function of the common ratio.)
Comment: I suppose that it should read $S(x)=-\frac{c_{1}+x}{c_{2}(x+c_{3})}$
Comment: I gave two reasons !
Answer: Note : $$\sum_{n\geq1}\frac{(-1)^n(4+x)^n}{4^{n+2}}\implies\frac{1}{16}\sum_{n\geq1}\left(\frac{-4-x}{4}\right)^n$$
It is nothing but Infinite Geometric Progression . [note : Sum of Infinite GP is $\frac{a}{1-r}$ iff $|r|<1$] $$\frac{1}{16}\left(\frac{\frac{-4-x}{4}}{1+\frac{4+x}{4}}\right) \text{ iff } |-4-x|<4$$
OR $$\implies-\frac{4+x}{128+16x}$$
Finally we need to compare it with $$-\frac{c_1+x}{c_2x+c_3}$$
Hence $\color{red}{c_1=4}$ , $\color{red}{c_2=16}$ and $\color{red}{c_3=128}$
Comment: Thank you very much for the great explanation!
Comment: @DiscoCarl No problem :)
Answer: Hint: With $t:=\dfrac{4+x}4$, we get a familiar series:
$$\dfrac 1{16}\sum_{n=1}^\infty(-t)^n=-\frac t{16(1+t)}\text{ for }-1<t<1.$$

Alternatively, we know that the function has a pole at $x=-8$, and we observe that it vanishes for $x=-4$. Hence it must be of the form
$$S(x)=c\frac{x+4}{x+8}.$$
We get the constant $c$ by evaluating at $x=-5$,
$$S(-5)=\frac1{12}=c\frac{-5+4}{-5+8}.$$
Comment: This might be a stupid question. Why is 16 in the denominator not raised because in S(x) it is raised with x+c3?
Comment: @DiscoCarl: I told you that the formula is wrong.
Comment: @PatBol So , what are your final conclusions for $c_1$ , $c_2$ and $c_3$ ?


How to format a date submission value of a webform?

Question: I need to format a birthday submission value to the short format (01.01.2015) defined under admin/config/regional/date-time on a webform.
This Token is working but it uses the long format (Fr, 01/01/2015):
<code>[submission:values:bday]
</code>
I tried the following token variations :
<code>[submission:values:bday:short]
[submission:values:bday:custom:short]
[submission:values:bday:custom:d.m.Y]
[submission:values:bday:date:short]
</code>
But none of them submits my desired output. Any Ideas?
Answer: I finally found a answer myself.
Instead of changing the date format tokens you can set the date format globally for webforms under admin/config/content/webform.
Answer: You could change it server side with a datetimeformatter or client side. Also if you'd like these kind of things often, you can take a look at moment.js


Deleting data on RealTime Database - Firebase

Question: I'm using firebase realtime database and has following rules setup for the database,
{
  "rules": {
    ".read": "auth !== null",
    ".write": "auth !== null"
  }
}

But when I try to delete an entry, it gives me an error saying permission denied as follows.
Database: Client doesn't have permission to access the desired data. (database/permission-denied).

What should I do? I can't understand why I can do all the reads and writes pretty oki with the current rules and not delete.
Can anyone help me with this?
Note:
Image of the results related to the Firebase Simulator

When checked for the firebase.auth().currentUser :
deleteUserAccount(userId) {
 let knownLocationRef = this.database.ref('lastKnown/' + userId);
 let promises = [];
 console.log('auth details', this.auth.currentUser);
 console.log('auth details null', this.auth.currentUser !== null); //returns true
         knownLocationRef.once('value').then( (data) => {
            console.log('data ', data.val());
            if (data.val() !== null) {
                let prevLat = data.val().lat;
                let prevLong = data.val().long;
                console.log('auth details', this.auth.currentUser);
                console.log('auth details null', this.auth.currentUser !== null); //returns false
                promises.push(knownLocationRef.remove());
            }
        });
         return Promise.all(promises);
 }

Comment: `auth != null` means that the client is authenticated using the [Firebase Auth](https://firebase.google.com/docs/auth/) module.  Auth adds a token to all the requests to show that they are logged in.
Comment: @JamesPoag - Yes, I understand that. And I have configured Firebase Auth and the user who is trying to delete data is authenticated as well. User can read and write data to the database without an issue.
Comment: Hmmm.  Do you know how to use the Database rules simulator in the firebase console?  Try writing a null value to a branch to simulate deleting (removing).
Comment: @JamesPoag: Yes I tried that too. But then am getting Simulated Write allowed. Since I can't add an image on the comment regarding the simulator, I will update the question with an image of the simulated results
Comment: Which client SDK are you using?  Can you perform a write with `null` instead of remove/delete? (For debugging purposes)
Comment: I'm using [react-native-firebase](https://github.com/invertase/react-native-firebase). Will get back to you regarding writing a null value
Comment: @JamesPoag: I tried writing a null. I didn't get any errors, and I didn't see any change in the DB side as well because it's a null
Comment: I'm downloading the starter kit from RNFirebase to try and reproduce.  Are you deploying to iOS or Android?
Comment: Also, are you using Anonymous authentication?
Comment: I'm deploying this on android only. But do not use Anonymous authentication
Comment: what authentication are you using?
Comment: In your code example you posted,`return Promise.all(promises);` will be executed before `promises.push(knownLocationRef.remove());`.  You need to either return the `knownLocationRef.once('value').then ...` promise or push that outer promise into your promises array.
Answer: Here are some issues with your code and how you are handling promises:
function deleteUserAccount(userId) {
  let knownLocationRef = this.database.ref('lastKnown/' + userId);
  let promises = []; // good idea for collecting a list of distinct
                     // promises, maybe not here

  // This is a promise, 'then' is a continuation from which you can return
  // either a data result or another promise
  knownLocationRef.once('value').then((data) => {
    // if data is valid, return another promise
    if (data.val() !== null) {
      // ...

      // If you were looping and collecting promises, then this might help,
      // but you don't want to collect inner promises.
      promises.push(knownLocationRef.remove());
    }
  });

  // This returns before everything in `.then` executes
  return Promise.all(promises);
}

Here's a fixed version:
function deleteUserAccount(userId) {
  let knownLocationRef = this.database.ref('lastKnown/' + userId);
  let promises = []; // For the sake of argument, I will use this to collect
                     // outer promises.

  // normally I would return here, but as an example, I'll uses the
  // promises array
  promises.push(knownLocationRef.once('value').then((data) => {
    // if data is valid, return another promise
    if (data.val() !== null) {
      // ...

      // Return a Promise from a promise
      return knownLocationRef.remove();
    }

    return null; // no data to process
  }));

  // wait on outer promises
  return Promise.all(promises)
    .catch(console.log); // log errors from any promise
}

Here is a version without the extra promises array.
function deleteUserAccount(userId) {
  let knownLocationRef = this.database.ref('lastKnown/' + userId);

  return knownLocationRef.once('value')
    .then((data) => {
      // if data is valid, return another promise
      if (data.val() !== null) {

        // Return a Promise from a promise
        return knownLocationRef.remove();
      }

      return null; // no data to process
    })
    .catch(console.log);
}

Comment: I have updated the issue with the `firebase.auth().currentUser` check results. I can't understand why it becomes null inside the method and not null outside the method
Comment: As an aside, [ESLint for React Native](https://www.npmjs.com/package/eslint-plugin-react-native) is a very useful linter that will catch some of these mistakes.  It tries to encourage proper usage of promises.


Conditions to rule out the existence of a non-zero function vanishing on every closed fibre

Question: Let $X\to S$ be a morphism of schemes. For every closed point $s\in S$, there is a closed fibre $X_s\to X$ over $s$. Intuitively, it is quite natural to claim that $f\in\mathcal O(X)$ is zero iff $f|_{X_s}=0$ for every closed $s\in S$.
However I know it is not true in general. A counter-example is for $X=S=\mathrm{Spec}(A)$ with $A$ a commutative ring with nonzero nilpotent radical.
Under strong conditions such as that $S=\mathrm{Spec}(k)$ for some field, we have that vanishing on every closed fibre implies that the function is zero. However this is too strong.
I want to ask for some conditions on $X\to S$ such that the intuitive claim is true. I am mainly interested when $S$ is a affine (irreducible) $\mathbb C$-variety, but $X$ may not be reduced.
Thanks for any comments.
Answer: In general it is sufficient to require that the union of all closed fibers
$$\bigcup_{s \in S \text{ closed}} X_s$$
is dense in $X$, since $f: X \to \mathbb A^1$ is continuous, so $f^{-1}(0) \subset X$ is a closed subset.
Example. Suppose $X$ is of finite type over a field $k$, and denote $\pi: X \to S$ the given morphism. As closed points are mapped to closed points, any closed point $x \in X$ is contained in the closed fiber $X_{f(x)}$. Hence it is sufficient to show that the closed points of $X$ are dense in $X$. This is Exercise II 3.14 in Hartshorne's Algebraic Geometry.


Displaying multiple nodes inside a single view block

Question: I am somewhat new to drupal.
My goal is to display the 5 most recent nodes with a specific tag ("slideshow") in a, well, slideshow.
I am trying to use a views block in order to do that. But when I add the block to the main page, it shows nothing. I've also tried modifying the template 'archive' view, but it shows a link to a different page with the contents of a specific month instead of the posts themselves:

How can I have it so the content themselves are all displayed in this block?
Answer:
Create a new View (rather than trying to alter an existing one like Archive).
Add a Block display.
Set the "Number of items to display" to 5
Add filter(s) so that only the nodes you want are displayed
Add a sort by the created date of the node, descending, so the ones at the top of the list are the most recent.
Comment: Thanks man! I haven't been able to look deeper into why, but adding a new view from scratch solved my problem really easily
Comment: Sometimes starting fresh is a good way to overcome issues. Good luck! :-)


I would like to split up the fields in the 'create new content' screen into sections

Question: I have a content type with about thirty different fields.  I would like to group them by category and I would also like to split them up so that half of the fields are filled in at the time of creation and the rest are filled in later (as a two-part work flow.)  There is a strong possibility that access to the two field groups will require two different roles.  Is there a good module that can do this?
Answer: You can use the Field Group module to group fields together.
You can use the Field Permissions module to only allow access to certain fields based on users roles.


Getting Unhandled exception error: System.IO.FileNotFoundException:

Question: i'm getting an error when trying to use Selenium w/ c#. I did use selenium yesterday and I had 0 problems. And was wondering what could cause this.
The error
Unhandled Exception: System.IO.FileNotFoundException: Could not load file or assembly 'WebDriver, Version=220.127.116.11, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The system cannot find the file specified.
   at ConsoleApplication1.Program.Main(String[] args)

What I do to recreate the error
  public static void Main(string[] args)
    {
        IWebDriver driver2 = new ChromeDriver();
        driver2.Navigate().GoToUrl("https://google.com")

    }

Comment: From the details of your error, it looks like someone removed the WebDriver DLL from wherever your program is looking for it.
Comment: I use jetbrain's IDA (Rider), and it lets me install packages from the IDA. And I have reinstalled it and I still get the same problem.
Answer: The Webdriver.dll is missing.
The first thing I suggest you to check is the binaries output folder (for example bin/debug folder, which you can check from your visual studio project settings). You will find all your referenced dlls and your project itself in this folder. It is likely that your Webdriver.dll is not being copied to the output folder. This usually happens when you add an external reference (dll) by using the "Add Reference" visual studio dialog box. To fix the issue, click on the Webdriver dll reference, and in the properties window, make sure to set copylocal = true.
Comment: I use jetbrains IDE (Rider)... And Webdriver.dll is in my references tab. Also I can run it in my IDE w/o any problem, it's just when i build it.
Comment: @nooby Adding a dll to your reference tab makes your compiler happy but it does not necessarily mean the dll is being copied to the output directory. You need to make sure your IDE is doing the copy. CLR has a complicated mechanics to locate the dll during the runtime (Here is a document but you do not have to read through this https://msdn.microsoft.com/en-us/library/yx7xezcf(v=vs.110).aspx). If the dll is expected to exist in the target environment's GAC, the IDE will not copy the (Webdriver) dll to the output folder.


ZFS / ZFS send for database replication

Question: Let's say I've got a somewhat important database but one where I don't actually care about every transaction.  Before you get snarky -- it is a database storing zabbix status data, so I honestly don't care if I lose a minute or two of transactions when the ascii control codes hit the TTY.
If I want to replicate that database to another host, I could do traditional database replication that essentially replays the transaction log across a pipe.  There are some issues with that (like I'll have lots of writers to the primary database and the slave will only have one thread inserting the replica data), but I'd also get a "read only slave" for running my reports against.  And someone else coming to town would understand what's going on.  Both are valuable, I completely agree.
But -- what if I want to be clever?  Being clever, I'll run my postgresql database on a ZFS filesystem with compression turned on.  And now that my database is running on ZFS, can I just zfssend that stream to another box and either apply it or just archive the zfs send stream for later replay if I decide I need it?
Would the resulting database be usable after a "clean up after an unclean shutdown and replay the transaction logs" on the target machine?  Let's say now I also want a read-only slave to run my reports against, could I replay the ZFS, make a snapshot, and startup the database against the snapshot?
Comment: What operating system would you be using to support ZFS?
Comment: Let's assume linux and/or freebsd.
Comment: @chris, I look forward your results publishing, man. ;)
Answer: ZFS send/receive works based on ZFS snapshots. Unless you quiesce the database, the snapshot you take to provide the initial source for the ZFS send will be crash-consistent.
You may use ZFS send/receive to send that snapshot to another host or ZFS filesystem. I don't understand what you mean by archiving the send stream. ZFS send/receive is atomic, so I'm not sure that you have an ability to save the stream.
If you need a read-only copy of a ZFS filesystem, you can take a ZFS snapshot and clone that snapshot to a new filesystem mount point.
At that point, you could perform operations on the new mount as needed.
Comment: Indeed, my only point was "nobody" != "not common" and you wrote you weren't understanding what "archiving" the stream meant.
Comment: I think @chris meant to do a zfs send redireted to file instead of piped to a zfs receive command as a way of saving the snapshot.  The resulting file could be then used to re-create the file system to that snapshot point in time by feeding it into the receive command.
Comment: @ThomasG Nobody does that. It's a bit fragile.
Comment: @ewwhite While I agree it is somewhat risky as if for some reason the stream is even slightly corrupted, it would be useless, some people nevertheless store zfs streams on files. It is a documented way to handle them (actually on the second link you posted).
Comment: Oh, I know it's documented, but it's not a common use case.

ZFS / ZFS send for database replication


Building complex chords from Complex figured bass

Question: I did a music exam today.
one of the questions was build chord from the following shapes (with the root given on the staff):

mM2
AugM7
dimdim 6/5
Mm6

what is the algorithm behind this markings. I am especially perplexed form  dimdim 6/5.
EDIT: I think I Added unnecessary confusion: by 6/5 i meant 6 over 5 (First inversion of seventh-chord). I just now realised the other meanings sorry for that:(
Comment: Given that such chord symbols are almost entirely the province of jazz lead sheets, it's surprising that they wouldn't have used commonly accepted chord notations for them. "dimdim 6/5" is just strange.
Comment: What is strange also here, is that AugM7 is directly a chord symbol but the 6 over 5 is a figured bass. @idober: how were the two dim placed relative of the 6 and 5 ? I will have to change my answer (again) :-)
Comment: Given the inconsistencies ("mM" vs "Mm"), I suspect that these chord symbols and figured bass notations are haphazardly remembered from the originals. Can we get some clarification in the OP as to what exactly the notations were? Separate them using * (list items) perhaps.
Comment: @Rein Henrichs: the Mm and the mM is exactly what was written in the test (I actually scribbled those examples on my hand during the test)
Comment: Ah, so they are. Makes sense.
Answer: You can build algorithms to decipher these markings but they are a collection/juxtaposition of many different series of notations. You can describe the same chord in several manners and various level of abbreviations. So this algorithm would be a collection of branching cases.
I think there are already online chord calculators.
The most perplexing one to you is quite a borderline case, and I am not 100% sure because it mixes notations from different traditions (figured bass and chord operators) in a way I have not seen before:

dimdim 6 over 5 Now that we know it was figured bass, let's start from the main symbol (6 over 5) which is the first inversion of a 7-th chord. With root C, we have C-E-G-B, inversed to E-G-B-c. If it is a diminished chord, it would give E♭-G♭-B-c. If the double dim is to mean that the 7th is diminished as well (not merely a minor 7th), it would mean E♭-G♭-B♭♭-c. In semitone count from the root it would give (3,6,9,12). You would write: fully diminished 7th chord first inversion or dim7/b3rd.

The second one is a classic:

AugM7 would be augmented major 7th. Start from the root, add a major third, an augmented fifth and a major 7th. Starting with C: C E G♯ B. You will find as notation among others +M7 or +Δ7
Comment: @ogerard: I had never seen dimdim. I'd have written **E♭-G♭-B♭♭-c** as **E♭°**. All inversions of this chord are also dim chords in their first inversion, so why give **6 over 5** in that case? **dimdim** alone would give the exact same result...
Comment: @ogerard about special chars in comments: low tech... copy and paste :)
Comment: Exactly what I would've answered :)
Comment: It was quite laborious for me but it was fun immersing again in that notational chaos.
Comment: @Gauthier: You are right, if you are free to choose the root **E**  ♭ o is the simplest way for a keyboard since **d**  ♭ ♭ is enharmonic of c. And as they were using figured bass, they should probably have used slashed 7 or little flats and slashes before the **6 over 5**. @idober: When you see this kind of chords, it is very likely that there is a modulation going on.
Comment: @ogerard: uh, I though the root was E♭. If the root is C, C° works as well. Same chord, different root. C°, E♭°, G♭° and A° are inversions of the same chord, that's what I meant. (if you don't care about the actual name of the notes, got you point about enharmonic.)
Comment: @Gauthier : a side note. How did you succeed to have flat and diminished symbol work in comments?
Comment: @ogerard: Diminished: `alt 0186` - º. Flat I can't get to work, but it's *supposed* to be 9837...
Comment: @Gauthier: I naively thought that it would accept entities like it did in the main answer and question cases when I saw your first comment. Now I cannot edit my comment anymore.


Creating Delegates With Lambda Expressions in F#

Question: Why does...
type IntDelegate = delegate of int -> unit

type ListHelper =
    static member ApplyDelegate (l : int list) (d : IntDelegate) =
        l |> List.iter (fun x -> d.Invoke x)

ListHelper.ApplyDelegate [1..10] (fun x -> printfn "%d" x)

not compile, when:
type IntDelegate = delegate of int -> unit

type ListHelper =
    static member ApplyDelegate (l : int list, d : IntDelegate) =
        l |> List.iter (fun x -> d.Invoke x)

ListHelper.ApplyDelegate ([1..10], (fun x -> printfn "%d" x))

does?
The only difference that is that in the second one, ApplyDelegate takes its parameters as a tuple.

This function takes too many arguments, or is used in a context where a function is not expected
Answer: I haven't looked at the spec to confirm, but I am guessing that the implicit conversion from "lambda" to "named delegate type" only occurs in a "member invocations".
You can always make the conversion explicit:
ListHelper.ApplyDelegate [1..10] (IntDelegate(fun x -> printfn "%d" x))

(The error diagnostic is quite poor; I'll file a bug.)
EDIT:
For the wonks...
Yeah, the spec says

8.13.6   Type-directed Conversions at member invocations As described in
  Method Application Resolution (see
  §14.4), two type-directed conversions
  are applied at method invocations.
If a formal parameter is of delegate
  type DelegateType, and an actual
  argument is syntactically a function
  value (fun ...), then the parameter is
  interpreted as if it had been written
  new DelegateType(fun ...).

that lambdas get converted automagically to delegate types only at "member invocations".  In the case of the curried member, the first argument passed is a member invocation, but then that returns a function value to apply the second argument, and function invocations do not have this implicit conversion rule.
Comment: "Members" are things you define with the `member` keyword, e.g. static or instance methods on some type.  These contrast with "functions" which are defined via `let f x = ...` or `fun` and which are comparatively very strict (e.g. you cannot overload a function, but you can overload a member).  Members should probably always take tupled arguments, yes; members are more .NET-y entities, as compared to functions which are F#-specific.
Comment: The 'tupled arguments' makes a difference because when it's tupled, all the arguments are passed 'at once' to the member, so the second argument is an argument to a member.  In the case of curried arguments, the first argument is an argument to the member, and that results in a new (non-member) function value, which then takes the second argument.
Comment: Thank you. What exactly is a 'member invocation' and why does having tupled arguments make a difference?

Should members always take tupled arguments?


fbconnect module invite issue

Question: This is a test site where i have installed fbconnect module I am facing issues while Inviting Friends:
What i am doing:
1. Connect to site through Fbconnect (by clicking on Login with Fb button)
2. Click on Invite Friends link which goes to fbconnect/invite/friends
3. Select Friends i want to invite.
4. Click "Send FB APP NAME Invitation"
Now, the Invited person gets a notification
<code>Naushad Shaikh
Invited you to FB APP NAME. Try Now
</code>
URL Points to : http://www.facebook.com/games#
However nothing happens and the invitation does not succeed as it should.
Please let me know what should i do / what am i doing wrong.
Answer: This issue has been resolved.
After a lot of research, i came to know that the Facebook Application for FbConnect did not have a Canvas URL and Secure Canvas URL
So i did below:

Added Canvas URL to the Application as domain.com
Added Secure Canvas URL as Fb's changed policy required so added https://www.domain.com
Now, i could click the Application and it opened In Fb IFRAME,
I wanted it to redirect on the website, (NOT ALLOWED AS PER FB TERMS & COS)
Solution an Image Pointing to External link (www.domain.com)

Thanks for the viewers of this question. I got a Tumbleweed badge for this question.

fbconnect module invite issue


In football, is the inside of each goal part of the field of play?

Question: I know this is the kind of question that could easily dismissed with a 'No, it is not'. However, the Glossary section of the 2016/17 Laws of the Game reads that (link, p. 163):

Field of play (Pitch).
  The playing area confined by the touchlines and goal lines and goal nets where used.

The 'and goal nets where used' part is what really bugs me. What is it supposed to mean, apart from making the inside of each goal part of the field of play (with the obvious consequences on the restart of play for fouls committed there, etc.)?
Comment: this amussed me. The goal nets are not even mandatory for playing..
Comment: Yeah, Law 1 makes it clear: *'Nets MAY be attached to the goals and the ground behind the goal (...)'*.
Answer: The field of play does not include the goal nets, as defined in the laws of the game.
Law 1.2 states

The field of play must be rectangular

which is only possible if the area enclosed by the goal nets is excluded
And Law 1.12 states

No form of commercial advertising, whether real or virtual, is
  permitted on  the field of play, on the ground within the area
  enclosed by the goal nets or the technical area...

which strongly suggests that the goal nets are not part of the field of play.
This would appear to be in contradiction with the glossary definition you quoted in the question.
I think it is reasonable to assume that the more detailed laws of the game have priority over a glossary, which gives a short and quick definition of various terms as an aid to understanding the laws.
Comment: "I think it is reasonable to assume that the more detailed laws of the game have priority over a glossary" - this is the crux of the answer. If anyone reading has the energy, IFAB has a contact form [here](http://theifab.com/contact). If you point out this discrepancy, they may amend the glossary for the 2017/18 edition of the Laws.
Answer: No, it is not part of the field of play.
We can't talk about a "inside the goal" rule.
According The Laws of the Game, the only rule about the goal frame is about its dimensions : 7.32 m by 2.44 m. There is no rule about the shape of the net (there is no rule about any net at all), so there is no rule about a certain goal surface.
Hower, the definition you are quoting intends to define the field as a surface where only the 22 players and the referees can enter. No ball boys, no fans, no subsitutes even if goalie's water bottle and towel are tolerated.
Sources: Wikipedia, FIFA.


Pyomo update Set and Var to solve again

Question: I am quite new to Pyomo but not to Python.
I have the following problem:
import pyomo.environ as pyo

model = pyo.ConcreteModel()
model.A = pyo.Set(initialize=range(7))
model.B = pyo.Set(initialize=range(7))
model.AB = pyo.Set(initilize= list((a,b) for a in model.A for b in model.B)
model.X = pyo.Var(model.A, model.B, within=pyo.Binary)
model.objective = pyo.Objective(... maximize)
solver = pyo.SolverFactory('glpk')
result = solver.solve(model)

Next I want to update the model.B Set() and as aconsequence modify de model.AB Set and the model.X Var so I can solve it again. For example, I want to set:
model.B = pyo.Set(initialize=range(4)

Then update the model.AB, model.X and solve again.  If done that manually:
model.B = pyo.Set(initialize=range(4)
model.AB = pyo.Set(initilize= list((a,b) for a in model.A for b in model.B)
model.X = pyo.Var(model.A, model.B, within=pyo.Binary)
result = solver.solve(model)

Thats not working, it gives the following error:
RuntimeError: Cannot add component 'X_index' (type <class 'pyomo.core.base.sets._SetProduct'>) to block 'unknown': a component by that name (type <class 'pyomo.core.base.sets._SetProduct'>) is already defined.

Answer: Basically, you need to delete the variable and its index before you create it again. Same goes for the sets.
Thus, essentially, you need to add the following lines before you redefine the new components:
model.del_component(model.B)
model.del_component(model.AB)
model.del_component(model.X)
model.del_component(model.X_index)

Then you can proceed to redefine them:
model.B = pyo.Set(initialize=range(4)
model.AB = pyo.Set(initialize= list((a,b) for a in model.A for b in model.B))
model.X = pyo.Var(model.A, model.B, within=pyo.Binary)

Comment: Or you just use a function to define your model with an argument which indicates model.B's length. This is as I can't figure out why you'd want to redefine a set before solving it. So just use a function that takes one argument and loop the solve statement.

Pyomo update Set and Var to solve again


How to model Hidden markov model with changing transition probability

Question: I have a series of observations that fall into two outcomes, 0 or 1. These observations have an associated time of observation, as well as additional features that I can gather for that observation. I am modeling this as having two hidden states A and B, where both have some probability of observing 0 or 1, and have some unknown transition probability between states. This transition probability varies with time and is correlated with the observation features.
How would I go about modeling this? My experience with HMM is with fixed transition probabilities (e.g. with Viterbi algorithm). Given a new observation, I want to be able to predict the hidden state as well as the transition probability. I would also want to generalize this model/use it as a prior for other similar models, each with different sets of observations.
Edit: I have discovered that what I am looking for is a variant of Baum-Welch that uses other feature data besides different sequences. How can I use my additional data in the prediction of the states?
Comment: Possible duplicate of [Hidden Markov Model and volatile Matrix A](http://stats.stackexchange.com/questions/228955/hidden-markov-model-and-volatile-matrix-a)
Comment: @Taylor for some human behavior modeling in cyber security research.
Comment: please see if my answer is helpful for above link. I would recommend not to do this because you might have overfitting problem
Comment: @hxd1011 interesting. what's your experience with these models? what have you used them on?
Comment: If I understood your problem correctly and the transition probability changes according to the time you have spend in each state, could [Hidden Semi-Markov Models](https://en.wikipedia.org/wiki/Hidden_semi-Markov_model) be another solution?
Answer: What you are after I believe is a maximum entropy the (i.e. logistic regression) Markov model. I.e. you predict the transition probability using logistic regression on previous state and observations. There is apparently a way of training these without knowing the hidden states… I guess by expectation maximisation.
Comment: yeah EM via Baum-Welch https://en.wikipedia.org/wiki/Maximum-entropy_Markov_model
Answer:
This transition probability varies with time and is correlated with the observation features.

Another option is to use a plain old factor graph, which is a generalization of a hidden markov model. You can model the domain knowledge that results in changing transition probability as a random variable for the shared factor.


What is the fastest way to draw an array of lines?

Question: I need to draw an array of lines in overlay. Currently, I use canvas and bitmap and draw about 500 lines. The drawing time is very high - around 200 ms which is bad, but acceptable.
Now I need to add 500 lines more and the time grows significantly. What is the fastest way to do this? Do I need to use OpenGL? and How? What is the best approach?
Answer: Turning off anti-aliasing will speed things up a lot.  Be sure to profile your code to make sure rendering is the place where the time is actually going.  Once you have optimized things and the majority of time is spent in rendering and you have made the rendering as simple as possible, the next step you'll have to take is to move to OpenGL.
Comment: I can not remove the AA because the lines are getting ugly. may be i need to take the next step :(


How can i concatenate FirstName and LastName in xaml using markup extension method to show full name of user

Question: I want to concatencate the firstName and lastName of the user using xaml markup extension.
Here is the code.

Contact

 public class Contact
  {
      public int Id { get; set; }
      public string FirstName { get; set; }
      public string LastName { get; set; }
      public string Phone { get; set; }
      public string Email { get; set; }
      public bool Blocked { get; set; }
  }

Here is the contactService for populating the data

ContactService

  public class ContactService
  {
      public readonly List<Contact> Contact = new List<Contact>()
      {
          new Contact
          {
              Id = 1,
              FirstName = "Malik",
              LastName = "Usama",
              Phone = "123456",
              Email = "email@example.com",
              Blocked = true
          }
      };
  }

MainPage.Xaml.cs

public partial class MainPage
{
    private ICollection<Contact> _contacts;
    private readonly ContactService _contactService = new ContactService();
    public MainPage()
    {
        InitializeComponent();

        listView.ItemsSource = _contactService.Contact;
    }
}

MainPage.Xaml

<ListView x:Name="listView">
    <ListView.ItemTemplate>
        <DataTemplate>
            <TextCell Text="{Binding FirstName}"></TextCell>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

Comment: You'd be better off using a converter.
Answer: You can use a converter as @canton7 said, or you just add another Property inside your Contact class which concatenate the properties for you:
public string NameView
{
  get { return $"{FirstName} {LastName}";}
}

and then, you can easily bind to your NameView-Property. Keep in mind, that you need to trigger NotifyPropertyChanged if you use data changes.
A converter would be looks like this:
public class NameConverter : IValueConverter
{

  public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
  {
    Contact contact = (Contact)value;
    return $"{contact.FirstName} {contact.LastName}";
  }

    ...
}

and in your XAML just use it:
xmlns:base="clr-namespace:<add your namespace here>"

<ResourceDictionary>
    <base:Name x:Key="nameConv" />
</ResourceDictionary>

<TextCell Text="{Binding Path= ., Converter={StaticResource nameConv}}"></TextCell>

Comment: Sorry what does the . signafy I am trying to bind this in a picker
Comment: @csharpdude77 its used to bind to the current source itself: https://learn.microsoft.com/en-us/dotnet/desktop/wpf/data/binding-declarations-overview?view=netdesktop-6.0#binding-path-syntax (see last part). Quote:" `Text="{Binding}" is equivalent to Text="{Binding Path=.}"`". Because we have more than one parameter we need to define the path exclusive.


Prove that $V= \text{Im} f \oplus \ker{g}$

Question: Let $f:U \rightarrow V$ and $g: V \rightarrow W$ be two linear maps between vector spaces above $\mathbb{R},$ such that $g\circ f$ is an isomorphism. Prove that $$V= \text{Im} f \oplus \ker{g}.$$
My attempt: Using the fact that $g\circ f$ is an isomorphism, we have $f$ is injective and $g$ is surjective. So, let $v \in V$ such that $v \in \text{Im} f$ and $v \in \ker{g},$ then $v=f(u)$ for some $u \in U$. Then $g(f(u))=g(v)=0, $ so $u=0$ which implies that $v=0.$ Thus $\text{Im} f \cap \ker{g}={0}.$
Now, let us see that $V=\text{Im} f + \ker{g}.$ Here is my doubt I don't know how to write $v$ as sum of $x+y$ where $x \in \text{Im} f$ and $y \in \ker{g}.$
Comment: $\mathrm{img}~f ⊂ W$, so you should use an isomorphism sign in $V \cong \mathrm{img}~f \oplus \ker g$. Otherwise it gets confusing as there is such a thing as an internal direct sum which should be contrasted to the external direct sum.
Answer: $\newcommand{\im}{\mathrm{im}}$
Let $v \in V$ be given. Then $g(v) \in W$. But $g \circ f:U \to W$ is an isomorphism. So $g(v) = g(f(u))$ with $u \in U$. So $g(v - f(u)) = 0$. So $v - f(u) \in \ker g$ and $v = f(u) + (v - f(u)) \in \im f + \ker g$.
Comment: That is right thank you


Android Firebase createUser() is not Working

Question: I'm trying to create a user in the Firebase console using email and password but it doesn't work showing an error.
Actually we can add users in the console by going to the dashboard and clicking on add user but I want to automate this process.
Here's the full code:
    import android.content.Intent;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.firebase.client.AuthData;
import com.firebase.client.Firebase;
import com.firebase.client.FirebaseError;
import com.google.android.gms.auth.api.Auth;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.auth.api.signin.GoogleSignInResult;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.SignInButton;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthCredential;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.auth.GoogleAuthProvider;

import java.util.Map;

public class SignInActivity extends AppCompatActivity implements GoogleApiClient.OnConnectionFailedListener,
        View.OnClickListener {

    private static final String TAG = "SignInActivity";
    private static final int RC_SIGN_IN = 9001;
    private SignInButton mSignInButton;
    private Button but;
    private EditText email;
    private EditText password;
    private FirebaseAuth mAuth;
    private FirebaseUser mFirebaseUser;

    private GoogleApiClient mGoogleApiClient;
    private FirebaseAuth mFirebaseAuth;
    String user_id="",pass="";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sign_in);
        email=(EditText)findViewById(R.id.emails);

        password=(EditText)findViewById(R.id.passwords);

        but=(Button)findViewById(R.id.create);
        Firebase.setAndroidContext(getBaseContext());

        mAuth = FirebaseAuth.getInstance();

        but.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                user_id= email.getText().toString();
                pass= password.getText().toString();
               Firebase ref = new Firebase("https://final-6b828.firebaseio.com/auth");
                ref.createUser(user_id, pass, new Firebase.ValueResultHandler<Map<String, Object>>() {
                    @Override
                    public void onSuccess(Map<String, Object> result) {
                        System.out.println("Successfully created user account with uid: " + result.get("uid"));
                        String a=  result.get("uid").toString();
                        Log.i("Success",user_id);
                        Log.i("Success",pass);
                        Toast.makeText(getApplicationContext(), "Pass",
                                Toast.LENGTH_LONG).show();
                    }
                    @Override
                    public void onError(FirebaseError firebaseError) {
                        // there was an error
                        System.out.println("Failed to create user account : ");
                        Log.i("Failed","a");
                        Toast.makeText(getApplicationContext(), "Failed",
                                Toast.LENGTH_LONG).show();
                    }

                });

            }
        });

        mSignInButton = (SignInButton) findViewById(R.id.sign_in_button);

        mSignInButton.setOnClickListener(this);

        GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                .requestIdToken(getString(R.string.default_web_client_id))
                .requestEmail()
                .build();
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .enableAutoManage(this /* FragmentActivity */, this /* OnConnectionFailedListener */)
                .addApi(Auth.GOOGLE_SIGN_IN_API, gso)
                .build();

        // Initialize FirebaseAuth
        mFirebaseAuth = FirebaseAuth.getInstance();
    }

    private void handleFirebaseAuthResult(AuthResult authResult) {
        if (authResult != null) {

            FirebaseUser user = authResult.getUser();
            Toast.makeText(this, "Welcome " + user.getEmail(), Toast.LENGTH_SHORT).show();

            startActivity(new Intent(this, MainActivity.class));
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.sign_in_button:
                signIn();

                break;
            default:
                return;
        }
    }

    private void signIn() {
        Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
        startActivityForResult(signInIntent, RC_SIGN_IN);
    }

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

        if (requestCode == RC_SIGN_IN) {
            GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
            if (result.isSuccess()) {

                GoogleSignInAccount account = result.getSignInAccount();
                firebaseAuthWithGoogle(account);
                Log.e(TAG, "Google Sign In Successfull.");
            } else {

                Log.e(TAG, "Google Sign In failed.");
            }
        }
    }

    private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {
        Log.d(TAG, "firebaseAuthWithGooogle:" + acct.getId());
        AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);
        mFirebaseAuth.signInWithCredential(credential)
                .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                        Log.d(TAG, "signInWithCredential:onComplete:" + task.isSuccessful());

                        if (!task.isSuccessful()) {
                            Log.w(TAG, "signInWithCredential", task.getException());
                            Toast.makeText(SignInActivity.this, "Authentication failed.",
                                    Toast.LENGTH_SHORT).show();
                        } else {
                            startActivity(new Intent(SignInActivity.this, MainActivity.class));
                            finish();
                            try {
                                Thread.sleep(5000);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                });
    }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

        Log.d(TAG, "onConnectionFailed:" + connectionResult);
        Toast.makeText(this, "Google Play Services error.", Toast.LENGTH_SHORT).show();
    }

}
}

The code used to create an user is :
but.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            user_id= email.getText().toString();
            pass= password.getText().toString();
           Firebase ref = new Firebase("https://final-6b828.firebaseio.com/auth");
            ref.createUser(user_id, pass, new Firebase.ValueResultHandler<Map<String, Object>>() {
                @Override
                public void onSuccess(Map<String, Object> result) {
                    System.out.println("Successfully created user account with uid: " + result.get("uid"));
                    String a=  result.get("uid").toString();
                    Log.i("Success",user_id);
                    Log.i("Success",pass);
                    Toast.makeText(getApplicationContext(), "Pass",
                            Toast.LENGTH_LONG).show();
                }
                @Override
                public void onError(FirebaseError firebaseError) {
                    // there was an error
                    System.out.println("Failed to create user account : ");
                    Log.i("Failed","a");
                    Toast.makeText(getApplicationContext(), "Failed",
                            Toast.LENGTH_LONG).show();
                }

            });

        }
    });

Comment: hi Devid,thanks for responding.now i got the answer.the code i used to create a user was wrong.i got the correct code from. [link]https://github.com/firebase/quickstart-android/blob/master/auth/app/src/main/java/com/google/firebase/quickstart/auth/EmailPasswordActivity.java#L69-L69.......thanks.
Comment: @SachinVarma If you solved your own question please post an answer with the code(instead of adding it to the question) and accept it so the question will not remain unsolved.
Comment: Hi Sachin, welcome to StackOverflow. Can you please edit your question with the error you get creating a user?
You have posted a lot of code here! Can you please reduce it? :)
Comment: @Luksprog,thanks for the comment,it is edited now.
Answer: The correct code to create a user is..
but.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            user_id= email.getText().toString();
           pass= password.getText().toString();
            createAccount(user_id,pass);
 }
    });

 private void createAccount(String email, String password) {
    Log.d(TAG, "createAccount:" + email);
    if (!validateForm()) {
        return;
    }

   // showProgressDialog();

    // [START create_user_with_email]
    mAuth.createUserWithEmailAndPassword(email, password)
            .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {
                    Log.d(TAG, "createUserWithEmail:onComplete:" + task.isSuccessful());

                    // If sign in fails, display a message to the user. If sign in succeeds
                    // the auth state listener will be notified and logic to handle the
                    // signed in user can be handled in the listener.
                    if (!task.isSuccessful()) {
                        Toast.makeText(SignInActivity.this, "Authentication failed.",
                                Toast.LENGTH_SHORT).show();
                    }

                    // [START_EXCLUDE]
                    //hideProgressDialog();
                    // [END_EXCLUDE]
                }
            });
    // [END create_user_with_email]
}
private boolean validateForm() {
    boolean valid = true;

    String emails = email.getText().toString();
    if (TextUtils.isEmpty(emails)) {
       email.setError("Required.");
        valid = false;
    } else {
       email.setError(null);
    }

    String passwords = password.getText().toString();
    if (TextUtils.isEmpty(passwords)) {
        password.setError("Required.");
        valid = false;
    } else {
       password.setError(null);
    }

    return valid;
}