Vertices of a parallelogram inside of a quadrilateral using vectors

Question: Let $E$ and $F$ be the midpoints of the sides $AB$ and $CD$ of a quadrilateral $ABCD$. Prove that the midpoints of segments $AF$, $BF$, $CE$, and $DE$ are vertices of a parallelogram.
This is what I have so far but I don't know if it's right or where to go with it.
Comment: Mention if $AD||BC$.
Comment: Please show your effort. Assume position vectors of the vertices of the quadrilateral are $a, b, c, d$ then you can easily find position vectors of the vertices of $GHIJ$. Then showing that the sides are parallel is just finding direction vectors.
Comment: @RAHUL the problem does not mention that AD is parallel to BC it just says ABCD is a quadrilateral
Comment: I also need to use vectors
Comment: You need at least three vectors to describe the shape of a general quadrilateral.
Answer: Here is another way to approach the problem.  We want to prove that segments GH and JI are parallel and of the same length, likewise, for the other 2 sides. If there were a vector, $v=H-G$ and another vector $v_1=I-J$,  then if they turned out to be the same vector, by algebra, then we could say they were both parallel and of the same length.  That is the game plan.
Define midpoint $$E=\frac{A+B}{2}$$
Define midpoint $$F=\frac{C+D}{2}$$
Define midpoint $$G=\frac{A+F}{2}$$
Define midpoint $$H=\frac{D+E}{2}$$
Now substitute into $v$ and $v_1$
$$v=H-G=\frac{D+E}{2}-\frac{A+F}{2}$$
and continue by substituting for $E$ and $F$
$$v=\frac{D+\frac{A+B}{2}}{2}-\frac{A+\frac{C+D}{2}}{2}$$
Now algebraically untangle this nonsense to get
$$v=-\frac{1}{4}A+\frac{1}{4}B-\frac{1}{4}C+\frac{1}{4}D$$

Next we will define the 2 midpoints that we don't have yet.
Define midpoint $$I=\frac{B+F}{2}$$
Define midpoint $$J=\frac{E+C}{2}$$
Now substitutions for $I$ and $J$
$$v_1=I-J=\frac{B+F}{2}-\frac{E+C}{2}$$
Next more substitutions for $E$ and $F$, defined above:
$$v_1=\frac{B+\frac{C+D}{2}}{2}-\frac{C+\frac{A+B}{2}}{2}$$
Once again do the algebra untangle:
$$v_1=-\frac{1}{4}A+\frac{1}{4}B-\frac{1}{4}C+\frac{1}{4}D$$
See that $v$=$v_1$.
Now you can do the same idea with the other 2 sides and conclude that you have a parallelogram.


Why was Canada's Mens 4x100 relay team DQed in the London Olympics?

Question: http://t.thestar.com/#/article/sports/olympics/2012/08/11/london_2012_canada_disqualified_in_mens_4x100_relay.html  says that Canada was on the podium...

until the judges saw that Connaughton, running the third leg and on the final turn, had taken one step on the lane line, earning the team an automatic disqualification.

I don't know what rule was violated. Can someone explain it?
Answer: Olympic track races are covered by the rules of the IAAF. You can download a PDF from the rules page. That PDF says, on page 159,

Lane Infringement

(a) In all races run in lanes, each athlete shall keep within his
  allocated lane from start to finish. This shall also apply to any
  portion of a race run in lanes.

(b) In all races (or any part of races) not run in lanes, an athlete
  running on a bend, on the outer half of the track as per Rule
  162.10, or on any curved part of the diversion from the track for
  the steeplechase water jump, shall not step or run on or inside the
  kerb or line marking the applicable border (the inside of the
  track, the outer half of the track, or any curved part of the
  diversion from the track for the steeplechase water jump).
Except as stated in Rule 163.4, if the Referee is satisfied, on the report
  of a Judge or Umpire or otherwise, that an athlete has violated this
  Rule, he shall be disqualified.

There is an exception if you're in a straight segment and gained no advantage, but the article says he was on the turn. The rule clearly says "shall not step or run on or inside the kerb or line" so stepping on the line breaks the rule.


How to convert a stdClass object to a SimpleXMLElement object

Question: I have a JSON file from a web service and want to use this data with a Drupal module. However, this module expects XML data. So I have the idea of overwriting the module. To do this, I need to convert the JSON file in XML, and ensure the file changes from JSON to PHP array.
Does any method or library exist to do this or convert .json file to .xml directly?
Now I have an array that is like the following one:
Array(
  [0] => stdClass Object(
    [sponsor] => stdClass Object(
      [created_at] =>
    )
  )
)

I need to convert this array in:
SimpleXMLElement Object(
  [@attributes] => Array(
    [type] => Array(
      [sponsor] => Array(
        [0] => SimpleXMLElement Object(
          [created-at] =>
        )
      )
    )
  )
)

Answer: Using the XML Serializer package, you can use the following code to make the conversion, as reported in this answer on Stack Overflow.
function json_to_xml($json) {
  $serializer = new XML_Serializer();
  $obj = json_decode($json);

  if ($serializer->serialize($obj)) {
    return $serializer->getSerializedData();
  }
  else {
    return NULL;
  }
}

Alternatively, you can use the following code give in this answer for the same question.
require_once 'XML/Serializer.php';

$data = json_decode($json, true)

// An array of serializer options.
$serializer_options = array (
  'addDecl' => TRUE,
  'encoding' => 'ISO-8859-1',
  'indent' => '  ',
  'rootName' => 'json',
  'mode' => 'simplexml'
);

$Serializer = &new XML_Serializer($serializer_options);
$status = $Serializer->serialize($data);

if (PEAR::isError($status)) {
  die($status->getMessage());
}

echo '
';
echo htmlspecialchars($Serializer->getSerializedData());
echo '
';

Answer: I had a similar issue where I wanted to mock away a SoapClient and verify the web service payloads generated by our system. I tried working with SimpleXMLElement to parse prepared XML snippets (requests and response) but had several issues with that and ended up writing my own stuff in the end.
https://github.com/FredrikWendt/php-xml-sax-stdclass
(It doesn't handle XML node attributes at all but turned out useful although SoapClient can't be mocked by Phockito.)


Logistic regression with complete separation AND repeated measures

Question: Consider a typical logistic regression on data with a binary response $Y$, and some predictor variables $X$'s.
I understand that when the event is rare, or in the case of complete separation, one could apply the Firth correction, for example in SAS:
proc logistic data=mydata descending;
class x1;
model y=x1 / firth;
run;

Recently I encountered a situation where repeated measures were made for all subjects ($\text{time}=1,2,3)$. All $X$'s such as race and gender would be considered time-invariant. Only the binary response $Y$ might change over time.
With three rows per participant, I can then fix a mixed model or GEE (with repeated statements in SAS) to account for the repeated measures.
But what can I do in case of a rare event or complete separation now with repeated measures? After some research, it seems that the Firth correction is only available in proc logistic, which I believe does not handle repeated measures.
Answer: In such cases I would personally go with a Bayesian model and an informative prior on the $\beta$'s. Using R, such model could look like this:
library(brms)

# Specify an informative prior to handle separation
prior_info <- c(
  set_prior("normal(0, 1.5)", class = "b", coef = "predictor")
)

# Specify the model using brm
model <- brm(outcome ~ predictor + (1 | subject_id),
             data = mydata,
             family = bernoulli(),
             prior = prior_info
)
# Plot conditional effects
conditional_effects(model)

There's lots of information on priors for logistic regressions. This gets you started: https://discourse.mc-stan.org/t/default-priors-for-logistic-regression-coefficients-in-brms/13742
If you go this route you might need to adjust the prior to make it work on your specific example.
Alternatively, it seems that PROC NLMIXED seems to be able to implement a "Penalized Likelihood Logistic Regression for Sparse Data Using Data Priors".
Or this one from the same author: https://www.lexjansen.com/phuse-us/2020/as/AS14_ppt.pdf
I don't know enough about PROC NLMIXED to further commment on this though.
Comment: Thank you so much for the informative answer. I was pretty surprised that I could not find R or SAS documentation that deals with BOTH complete separation and repeated measures. I found a similar question asked 8 years ago: https://stats.stackexchange.com/questions/178754/using-conditional-logistic-regression-for-repeated-measures-complete-separation
Comment: @RonaldCarlos happy you found it useful!


Given a dataset, how does one know whether there's (statistical) noise on a set of measurements or not?

Question: Just out of curiosity, I'm looking at linear regression and there are of course cases where the measurements of the response variable are not noisy(say in the case of a simulator). But in general how does one know if there's noise on a set measurements or not? Is this just something we assume in the abscence of evidence to the contrary?
Comment: What is "statistical" noise?
Comment: Then what is physical noise? Literal sonic noise like how people occasionally describe music they don't like?
Comment: @Dave used it to specify that I don't mean noise in the physical sense unless said physical noise has resulted in noisy measurements
Answer: Given a dataset (with no other information), you can never prove or know that a set of measurements include "noise" where noise is defined as a random process governed by a probability distribution.  What is perceived as noise could possibly be a signal of an unknown cause.
However, you can check assumptions about a signal that you perceive as noise to determine if it is effectively noise for your analysis.  In simple linear regression, $Y = \beta X + \epsilon$.
$\epsilon$ can be assumed to be noise if it follows a normal distribution $\epsilon \sim N(0, \sigma^2)$ and if the distribution of $\epsilon$ is statistically independent of the regressors.
In cryptography, there are also multiple tests of randomness that get applied to potential random number streams to determine if they are sufficiently random.  I don't normally see this type of thing in statistics / data science though.  See this from NIST.

Given a dataset, how does one know whether there’s (statistical) noise on a set of measurements or not?


Why wrapper object is eligible for garbage collection?

Question: This question is taken from SCJP. We need to find Objects which are eligible for garbage collecrtion. The answer says c3 and short story. I need to know , why its short story eligible for GC. This is actually an instance variable. Does it mean, if i don't use my instance variables they are eligible for Garbage Collection?
Actual Answer as per book is : Only one CardBoard object (c1) is eligible, but it has an associated Short wrapper object that is also eligible. So "two" objects are eligible.
class CardBoard {
    Short story = 200;
    CardBoard go(CardBoard cb) {
      cb = null;
      return cb;
    }
    public static void main(String[] args) {
      CardBoard c1 = new CardBoard();
      CardBoard c2 = new CardBoard();
      CardBoard c3 = c1.go(c2);
      c1 = null;
      // do Stuff
    }
}

Comment: What would you expect to happen to the `Short` instance once the enclosing `CardBoard` instance is GCed?
Comment: Yaa thats what i am thinking what will happen to short if C1 is garbaged?
Answer: It all comes down to what the garbage collector considers "reachable". Basically, it starts at the so called garbage collection roots (the local variables in an executing thread are an example of such roots), and follows all references to other objects. After having visited all objects it can reach by traversing all these references, there are a few left which are no longer reachable, meaning no matter how hard you try, you'll never use these objects again, so they can be safely thrown away (or collected as garbage).
Although c1 references its story object, there is no way to reach either one, so they're both eligible.
c3 never references an object, the example is intended to confuse, but go() always returns the null reference and no object instance is ever created for c3, and it's also not hanging on to either object referenced by c1 or c2 (although the later is irrelevant for this case, since it's still referenced by the c2 variable).
Comment: BUT WHY IT IS SAYING "associated Short wrapper object that is also eligible" ?? WHAT THAT MEAN?
Comment: @user2985842; no need to shout. It means that the object referenced by the variable `c1` is in turn referencing an object of type `Short` (called wrapper object, as it's only wrapping a primitive value and has no other purpose than allow it to be used as an object), and although it is referenced, it is no longer reachable, and thus eligible for garbage collection. If it's the "associated" part that's tripping you up, you need to have another look at objects and classes, each `CardBoard` object instance have (by the class definition) a reference to a `Short` object via the field `story`.
Comment: Sorry 4r shout...I didn't mean that...I got ure answer...thanks
Answer: If nothing refers to c1 then the Short story = 200; field (belonging to the c1 instance) is also eligible for collection.
Answer: The answer doesn't say c3 it says c1 and thus the Short story it contains.  This is due to the line
c1 = null;

At this point the object which was referenced by c1 can be GCed and thus any object it refers to.
Comment: @ElliottFrisch: c3 never was anything but null.
Comment: @ElliottFrisch But there's no object that's becoming unreferenced. Garbage collection happens on instances, not the variables that (no longer) contain them.
Comment: @roe Good catch, you're right. It was never instantiated.
Comment: Technically it is implementation dependent - `story` may be cached in which case `c1.story == c2.story` and only `c1` is eligible! ;-)


Posting a List of Unique Users with Their Correct Number of Replies in jQuery Code

Question: I'm trying to show a list of top users and their number of replies, but there are two problems:

it's showing the wrong number of replies for a user (it's doubling it for some reason), and
sometimes a user is showing up multiple times in the list of top users

I need a list of all unique users with their correct number of replies, like this:

Jane Doe 8
Jack Smith 7
Andrea Johnson 5
Fred Jackson 4
Etc.

I think the part that needs editing is this:
    {
        var htmlToAdd = '';
        people.sort(compareTotals);

    people.remove(0);

        var peopleLimit = people.length;
        if (peopleLimit > 10)
            peopleLimit = 10;
        for (var i = 0; i < peopleLimit; i++)
        {
            htmlToAdd = htmlToAdd + '
' + people[i][3] + ' has posted ' + people[i][0] + ' replies.
';
        }
        jQuery('#peopleList').html(htmlToAdd);
    }

Any ideas of what I need to change?
In case this helps, here is the full code:
     if (jQuery("div.community_topic_box").size() > 0)  // Only true for the front page
    {
        jQuery("#postersFrame").insertAfter(".community_stats");
    }
    else
    {
        jQuery("#postersFrame").hide();
    }
});

var people = new Array();
var peopleFinished = 0;
var repliesHandled = 0;
var count = 0;

// Generic JSON functions
function JSONscriptRequest(fullUrl) {
    this.fullUrl = fullUrl;
    this.headLoc = document.getElementsByTagName("head").item(0);
    this.scriptId = 'YJscriptId' + JSONscriptRequest.scriptCounter++;
}
JSONscriptRequest.scriptCounter = 1;
JSONscriptRequest.prototype.buildScriptTag = function () {
    this.scriptObj = document.createElement("script");
    this.scriptObj.setAttribute("type", "text/javascript");
    this.scriptObj.setAttribute("src", this.fullUrl);
    this.scriptObj.setAttribute("id", this.scriptId);
}
JSONscriptRequest.prototype.removeScriptTag = function () {
    this.headLoc.removeChild(this.scriptObj);
}
JSONscriptRequest.prototype.addScriptTag = function () {
    this.headLoc.appendChild(this.scriptObj);
}

function handlerTopics(results) {
    var obj;
    if ( results.total > 0)
    {
        count = results.total / 30;
        var htmlToAdd = '';
        if (results.total > 30)
        {
          var iterations = results.total / 30;
      for (var j=0; j < iterations; j++)
      {
        obj=new JSONscriptRequest('https://api.getsatisfaction.com/companies/' + companyName + '/topics.json?sort=recently_active&active_since=' + timeStamp + '&limit=30&page=' + j +'&callback=handlerEachTopics');
        obj.buildScriptTag(); // Build the script tag
        obj.addScriptTag(); // Execute (add) the script tag
      }
        }
    else{
       obj=new JSONscriptRequest('https://api.getsatisfaction.com/companies/' + companyName + '/topics.json?sort=recently_active&limit=30&active_since=' + timeStamp + '&callback=handlerEachTopics');
           obj.buildScriptTag(); // Build the script tag
       obj.addScriptTag(); // Execute (add) the script tag
    }
    }
    jQuery('#peopleList').html('Loading member details...')
}

function handlerEachTopics(results) {
    if ( results.data.length > 0)
    {
      for(var i=0; i<results.data.length; i++)
      {
    if (results.data[i].active_replies > 0)
    {
       obj=new JSONscriptRequest( results.data[i].url + '/replies.json?callback=handlerEachTopicReplies');
           obj.buildScriptTag(); // Build the script tag
       obj.addScriptTag(); // Execute (add) the script tag
       repliesHandled++;
    }
      }
    }
    peopleFinished++;
}

function handlerEachTopicReplies(results) {
    if ( results.data.length > 0)
    {
      for(var i=0; i<results.data.length; i++)
      {
        if ((!results.data[i].author.employee) &&(!isInArrayYet(results.data[i].author.canonical_name) > 0))
        {
            people[people.length] = [1, results.data[i].author.canonical_name, results.data[i].author.at_sfn, results.data[i].author.name];
        }
      }
    }
    repliesHandled--;
    if ((peopleFinished >= count - 1) && (repliesHandled <= 0 ))
    {
        var htmlToAdd = '';
        people.sort(compareTotals);

    people.remove(0);

        var peopleLimit = people.length;
        if (peopleLimit > 10)
            peopleLimit = 10;
        for (var i = 0; i < peopleLimit; i++)
        {
            htmlToAdd = htmlToAdd + '
' + people[i][3] + ' has posted ' + people[i][0] + ' replies.
';
        }
        jQuery('#peopleList').html(htmlToAdd);
    }
}

function isInArrayYet(name)
{
  for(var i=0; i< people.length; i++)
  {
    if (people[i][1] == name)
    {
      people[i][0]++;
      return true;
    }
  }
  return false;
}

function compareTotals(a, b) {
    return b[0] - a[0];
}

Array.prototype.remove = function(from, to) {
  var rest = this.slice((to || from) + 1 || this.length);
  this.length = from < 0 ? this.length + from : from;
  return this.push.apply(this, rest);
};

  </script>

How do I make each item in the list of users and their replies appear only once, and how do I make the number of replies stop multiplying? Thank you for your help.
Comment: What are the contents of the `people` variable? Do a `console.log(people)`. And show, if possible, how it being generated the array
Answer: If you are having an issue with the number of posts, you would better at the
htmlToAdd + '
' + people[i][3] + ' has posted ' + people[i][0] + ' replies.
';
and make sure that it's correct. You might want to recheck the  people array and the data in that array.
Other part of the code is fine for me. If you can post the full code I would be able to help you out.


Handling multiple http requests and subscribe at the end Angular 4

Question: I have a Angular 4 Issue that I cannot resolve.
I make several http calls to get data. the number of calls I make is determine by a prior response with a list of Items to address. I need proccess
 ( concat responses ) all the items in order before write the file object to file. The problem is that the write occurs before the calls complete.
ComponentA.ts:
   this.service.getlist(parm1, parm2, parm3)
      .finally( () => this.listComplete()
      .map( lst => this.writeToFile(lst) )
      .subscribe (res => { console.log("Done!"); } );

writeToFile(obj)
{
  console.log("File Downloaded");
}

service.ts:
 var response = this.http.post( this.sourceURL, options)
     .map( res => { this.consumeList( res.json(), Objname ))
     .finally( () => console.log(" I'm Done ")
     .catch( (ex) => Observable.throw(this.reportError(ex)));

consumeList(obj : any, Objname)
{
     obj.forEach( element => {
          this.getChunk(obj);
       }
     )
}

getChunk(obj) {

   this.http.get(obj,options)
      .map(res => ths.getData(res, _name)
      .catch( (ex) => Observable(this.logException(ex,_name)))
      ***.finally( () => this.clientWrite() )***
      .subscribe();
}

getData(obj, name)
{
   this._blob.push(obj);
}

clientWrite()
{

     SaveAs([this._blob], _name);

}

The Write is occuring after the first object is read.
Comment: Have you looked at using `forkJoin` ?
Comment: I've added a Observable using forkjoin with no success.. With my still being new to Anguar I may be wrong but I'm thinking the issue may also be related to scope and subscriptions
Comment: You might be right but the code you've posted is incomplete and difficult to understand ... for instance.  where is `this.service.getList` called (ngOnInit, constructor)? Where is the `getList` method in your service. Please update your post with relevant code.
Comment: I will add actual code. I typed the above since source is on another computer
Comment: Source:  download.ts
Comment: import { Component, OnInit } from '@angular/core';

import { AppLinkService } from '../app-link.service';
import { Globals} from '../myGlobals';
  fileDownload(ev)
  {

    this.applinkservice.downloadSuccess = false;
    this.applinkservice. downloadedFile =""; . . .
    return this.applinkservice.fileDownload(this.globals.user,this.globals.password,target)
    .finally( () => this.downloadComplete())
    .map(fl => this.writeToFile(fl))
    .subscribe (res => { this.FileDownloaded(res)} , () => this.downloadComplete2());
  }
Comment: fileDownload(ev)
  {

    this.applinkservice.downloadSuccess = false;
    this.applinkservice. downloadedFile ="";
Answer: Because I don't see all of the functions that you use I show you a example how to use Observable.forkJoin. forkJoin is the best option to execute several http queries simultaneously
Service
getChunk(obj) {
   //with help of this object you will inform Observable that everything has been done
   let subject: Subject<any> = new Subject();

   this.http.get(obj,options)
      .map(res => ths.getData(res, _name)
      .subscribe((element: any) => {
            //if everything goes well
            subject.next(element)
            subject.complete();

        }, (error: HttpErrorResponse) => {
            //if you get error
            subject.error(error);
            subject.complete();
        })
   //remember to return this object
   return subject;
}

In component you use getlist but you do not have this function in service
getlist(objArray)
{
   let obsArray = [];
   objArray.forEach(element => {
       //create Observable object and add them to array which you will return
       obsArray.push(Observable.from(this.getChunk(element))
   }
   return obsArray;
}

In component use
Observable.forkJoin(this.service.getlist([obj1, obj2, obj3]))
   .subscribe(tArray => {
       //tArray is array with response from all request
       console.log("Done!");
   }, error => {
   })

remember to import in service
import { Observable, Subject } from 'rxjs';

and in component
import { Observable } from 'rxjs';

EDIT - RESPONSE TO A COMMENT
Without seeing the whole code, it's hard to evaluate what the server returns and what some variables contain.
MyService.ts
import { HttpErrorResponse, HttpClient } from '@angular/common/http';
import { Observable, Subject } from 'rxjs';
.... //others imports

@Injectable()
export class MyService {
  private sourceURL: string = "http://youAPIAdress.com";
  private _blob;

  constructor(
    private http: HttpClient
  ) {}

  getChunkList(options: any, callback: (objURL: string[]) => void, errorCallback: (errorResponse: HttpErrorResponse) => void): void {
    this.http.post( this.sourceURL, options)
      .subscribe((objURL: any[]) => {
        //if you use HttpClient don't have to do res.json()
        //if objURL is not an array, make an array of received data
        callback(objURL);
      }, (error: HttpErrorResponse) => {
        errorCallback(error)
      })
  }

  getChunkElement(objURL) {
    let subject: Subject<any> = new Subject();
    this.http.get( objURL)
      .subscribe((responseObj: any) => {
        subject.next(responseObj)
        subject.complete();
      }, (error: HttpErrorResponse) => {
        subject.error(error);
        subject.complete();
      })
    return Observable.from(subject);
  }

  setData(chankElements: any[]): void {
    //do somthing with recived part of the data
    // this._blob.push(obj); - it will not work. I suggest using some library to work with blob object
    //try this
    this._blob = new Blob(chankElements, { type : 'image/jpeg' });
  }

  clientWrite(_name) {
    //save data to local
    SaveAs([this._blob], _name);
  }

}

Component
  options: any;
  constructor(
    private myService: MyService,
    ) {
    //set options
    this.myService.getChunkList(this.options, response => {
      //if response is adresses array
      let obsArray = [];
      response.forEach(urlAdress => {
          obsArray.push(Observable.from(this.myService.getChunkElement(urlAdress))
      })
      Observable.forkJoin(obsArray)
        .subscribe((chankElements: any[]) => {
         //chankElements is array with response from all request
         this.myService.setData(chankElements);
         this.myService.clientWrite();
         console.log("Done!");
      }, error => {
        //TODO somthing with error
      })

    }, error => {
      //TODO somthing with error
    })
  }

Comment: I've implemented your example above. The problem now is that the list is returned out of order.  Any idea how to solve this?
Comment: I like you answer . but perhaps I should better explain my goal.  Here the problem.   (1) I make a HTTP request to download a file.  (2) The file is huge so the response returns a list of file names of each chunk ( the server splits the file and stores in a known location on remote server).  (3) I need to make multiple request to get each chunk and reassemble the chunks in the correct order before writing the  assembled data to the local hard-drive.    I could really use a answer ASAP.
Comment: If you built a plunker with an example, it would be easier to find a solution.
I have edited the answer - better matching to your description.
Comment: If you are looking to execute multiple http requests synchronously have a look here https://stackoverflow.com/questions/38875375/how-to-make-synchronous-http-calls-in-angular-2


What is a "hot spare" on FreeNAS?

Question: What is a "hot spare" with regard to ZFS RAIDZ on FreeNAS?
I'm hoping that it means an extra, attached disk that can automatically take over for a failed disk in the RAID ... ?
If so, how do I set that up?
Answer: Yes, that is exactly what a hot spare is. The hot spare drive would occupy a drive bay and could be assigned to one or more data pools (global spare), and would automatically start a rebuilding process in the event of a failed disk.
This is in contrast to a cold spare drive, that would sit outside of the server/enclosure in order to be swapped manually when there's a failure.
Comment: What exactly do I need to do to set it up to take over?
Comment: I used `zpool add raid-5x3 spare ada0`, and now `zpool status` lists ada0 as a spare. But is that it? No need to format, create a volume, etc?
Comment: Nope. Not much else to do. I also saw the note about spares not working properly in FreeNAS. I would check on that just to make sure... However, spares have always functioned well in my Solaris and Nexenta ZFS environments.
Answer: the FreeNAS docs are the best place to get this information.  Take a look: http://doc.freenas.org/index.php/Volumes
Comment: I don't trust those docs, because so much is out of date. There are many references to obsolete errors & procedures. One thing it says there is: "Use this option with caution as there is a known bug in the current FreeBSD implementation. This will be fixed by zfsd which will be implemented once it is committed to FreeBSD." Is that still the case?

What is a "hot spare" on FreeNAS?


How to show, that a potential has no local maxima between its isopotential lines

Question: I have a potential field $\phi$, given by a charged surface $\Gamma$ in the domain $\Omega$ with the constraint, that the potential is constant at the surface. This means my potential function reads
$$
\phi(x) := \int_\Gamma \frac{\sigma(y)}{\|x-y\|} \text{dy}
$$
with the surface charge density $\sigma$, which is defined by the constraint that the potential is constant at $\Gamma$:
$$
\phi(x) = \phi(\hat{x}) \ \forall x, \hat{x} \in \Gamma
$$
Now I want to show that
$$
\phi(x) \le \phi(\hat{x}) \ \forall x \in \Omega, \tilde{x} \in \Gamma
$$
As $\phi(x)\equiv \text{const} \ \forall x \in \Gamma$ I know that $\Gamma$ is an isopotential surface of the potential field, which tells me that the gradient $\nabla \phi(x) \ \forall x \in \Gamma$ is orthogonal to $\Gamma$.
That the potential field decreases for potentials far from all charges is easy to see, but I do not see how to show that
$$\phi(\tilde{x}) = \phi(x+\alpha(\hat{x}-x)) < \phi(x)\ \forall \alpha \in(0,1), x, \hat{x} \in \Gamma, \tilde{x} \in \Omega\setminus \Gamma$$
I guess somehow there should be a contradiction that charges which create a potential $\phi(\tilde{x}) > \phi(x)$ cannot exist because then $\Gamma$ cannot have an isopotential, but I do not see how to prove that.
Comment: The restriction $\Omega$ seems not relevant to the definition of $\phi$; only the surface $\Gamma$ matters. So thinking $\phi$ as a function on $\mathbb{R}^3$, it is harmonic on $\tilde{\Omega} = \mathbb{R}^3 \setminus \Gamma$ and vanishes at infinity. So assuming that $\Gamma$ is positively charged, the maximum of $\phi$ is achieved at $\partial \tilde{\Omega} = \Gamma$ by the maximum principle.
Comment: You're right, $\Omega$ does not matter. But i fail to see why $\phi$ is harmonic on $\tilde{\Omega}$. When I have a sphere surface as $\Gamma$ I would expect a local minimum at the sphere center and the maximum on $\Gamma$ while the function vanishes at infinity.
Comment: An intuitive reason is that $\phi$ is obtained by a "linear combination" of harmonic functions $x \mapsto \| x - y\|^{-1}$. Also, if $\Gamma$ is a closed surface so that it enclosed some finite volume $\mathcal{V}$, then by your assumption on the constant value of $\phi$ along $\Gamma = \partial\mathcal{V}$, the potential $\phi$ must be also constant in $\mathcal{V}$. (This is again a consequence of the maximum principle.)
Comment: Thank you. Do you want to make it an answer, so I can accept it?
Answer: I add the comments from @sangchul-lee as a self-answer here, as he did not make them into an answer up to now.
When having a charged surface $\Gamma$ in $\mathbb{R^3}$, the potential field $\phi$ is harmonic in $\mathbb{R}^3 \setminus \Gamma$. By the maximum principle it cannot have true local maxima.
When by definition of the problem all charges are located at $\Gamma$ and $\phi(x)=\phi(y)=\phi_\Gamma\ \forall x,y \in \Gamma$, the function $\phi$ assumes its global maximum at $\Gamma$ and vanishes at infinity.
The interior of any solid which is bounded by a subset of $\Gamma$ has constant potential $\phi_Gamma$, as $\phi$ has no local maxima or minima and the potential at the boundary is $\phi_\Gamma$
The domain $\Omega$ does not matter as the previous is true in all $\mathbb{R}^3$.


Naïve Bayes vs Bayes classifier

Question: While studying the naive Bayes classifier, two questions came to mind:

When (if this can happen) is the naive Bayes classifier equivalent to the Bayes classifier?
Why do I usually read in textbooks that naive Bayes is popular? What makes it so "popular"?
Comment: The "naive" independence of features assumption makes the calculations multiples (or sums in log space) which is convenient to calculate. It is relatively easy to get class probabilities and provides a sort of baseline for model comparison. The popularity is because it would the model to "beat".
Answer: I would try not to conflate naive Bayes and the concept of a Bayes classifier.  The former is a specific kind of classification model, whereas the latter should really just be viewed as an "optimal" classifier in a given setting (it could be any type of model, so long as it's the "true" model).
The reason we call the optimal classifier a Bayes classifier is because the best classifier needs to use Bayesian updating when making predictions, by which we mean that we follow Bayes theorem (it is a theorem after all) when updating our expectations based on evidence.
To say that a naive Bayes classifier is the Bayes classifier would just mean that no classifier can perform better in terms of misclassification rate (that is, it "knows" all the marginal distributions of the predictors for each class and correctly assumes they're all independent).
To your second question, I believe naive Bayes gained popularity because it's easy to implement and historically (despite it's generally false assumptions) it often performed well at certain tasks, particularly text classification.

Naïve Bayes vs Bayes classifier


How do I make asp menu extend to the end of the page when scrolling?

Question: I have a horizontal asp menu in a div. The div is set set to width:100% which fills the width of the page, however when the page can be horizontally scrolled the div doesn't extend to the end of the page. I have tried setting min-width%:100%; in the CSS of the div, however this doesn't make a difference. Can anyone help me to solve this problem by telling me how to make the div fill out the width of the page when the page can be horizontal scrolled. I am using CSS 2.1 and ASP.NET 2.0
The code for the div is:
<code>            <div class="clear hideSkiplink">
            <asp:Menu ID="NavigationMenu" runat="server" CssClass="menu"     EnableViewState="false" Orientation="Horizontal">
                <staticmenuitemstyle  ItemSpacing="30"/>
                           <StaticHoverStyle BackColor="DarkGray" BorderColor="Black"     BorderStyle="Solid" BorderWidth="1"></StaticHoverStyle>
                <Items>
                    <asp:MenuItem NavigateUrl="~/Home.aspx" Text="Home"/>
                    <asp:MenuItem NavigateUrl="~/Report.aspx" Text="Report an   Operational Risk"/>
                    <asp:MenuItem NavigateUrl="~/View.aspx" Text="View Reported Operational Risks"/>
                    <asp:MenuItem NavigateUrl="~/UpdateClose.aspx" Text="Update/Close a    Case"/>
                </Items>
            </asp:Menu>
        </div>
</code>
The CSS for the div and menu  is:
<code>.hideSkiplink
{
background-color:#FF9900;
width:100%;
float:left;
}

.menu
{
padding: 4px 0px 4px 12px;
}

.menu ul
{
list-style: none;
margin: 0px;
padding: 0px;
width: auto;
}

.menu ul li a, div.menu ul li a:visited
{
background-color: #FF9900;
color: #000000;
font-weight: bold;
font-size:14px;
display: block;
line-height: 1.35em;
padding: 4px 20px;
text-decoration: none;
white-space: nowrap;
}

.menu ul li a:hover
{
background-color: #bfcbd6;
color: #465c71;
text-decoration: none;
}

.menu ul li a:active
{
background-color: #465c71;
color: #cfdbe6;
text-decoration: none;
}
</code>
Comment: Have you tried adding "float:left" to the div?
Comment: Yeah I just tried that now and there was no difference. What was that supposed to do?
Comment: Well with this basic fiddle http://jsfiddle.net/ffMLs/, I can get it to span 2000px just by setting float:left. Is there some other option in your HTML layout that is limiting the size of the div?
Comment: @MightyLampshade I don't think so. I have posted all the code that I believe affects the menu in the original post
Comment: Ah, in the CSS class "clear" are you specifying clear:both? That will stop the `float:left` property working.
Comment: @MightyLampshade Yeah I did have clear:both in the css class 'Clear' so I took it out but it still doesn't work. Even if i do floaat:right it has no efect. It seems as if float isn't working, im using CSS 2.1 ann asp.net 2.0
Comment: Try wrapping it like this. I think I messed up that fiddle before, sorry :(

http://jsfiddle.net/ffMLs/2/
Comment: @MightyLampshade Okay I will try this on Tuesday, I would like you to know that I do not have a fixed width, the width always changes so I will not enter a fixed width like you did. Im not sure if it will still work
Comment: @MightyLampshade I still couldn't get this to work. I think this is because I do not have a fixed width
Comment: Hmm a fixed width should not matter when you are using `float:left` with a width of 100%. Is your page dynamically increasing it's size horizontally? Are you adding objects during runtime that extends the page? Also, have you checked whether your `html` and `body` CSS have a width of 100%? You could also try specifying `float:left` on the `html` or `body` elements.
Comment: Yes the page is creating its size based on a gridview which dynamically changes. The body is 100% but html is not defined in the CSS. Thanks for the help you have given so far, it is appreciated.
Answer: I put the gridview in a scrollable div so that the page has a fixed width.


Java Stack class / Palindrome class

Question: Question: Develop a Stack class (NEEDS TO HAVE (at least) push, pop, and isEmpty methods) (The ONLY data structure you could use/have in your Stack class SHOULD be a CHAR ARRAY)
Second, develop a second Java class named Palindrome that in its main method, receives a string as a command-line argument, and then uses a Stack object to check whether the given string is a palindrome or not.
The Palindrome class would be the ONLY one with the main() method which receives a command-line argument (JUST ONE STRING WITH NO WHITESPACES) and checks whether it's a palindrome or not. It does so by creating an object of class Stack and calling its methods in some parts of your algorithm.
Answer:
public class Stack {

    private int position, capacity;
    private char[] stack;

    public Stack(int n) {
        capacity = n;
        position = -1;
        stack = new char[capacity];
    }

    public void push(char obj) {
        // stack is not full
        position++;
        stack[position] = obj;
    }

    public char pop() {
        // stack is not empty
        char temp = stack[position];
        position--;
        return temp;
    }

    public boolean isEmpty() {
        return position == -1;
    }

    public char peek() {
        return stack[position];
    }

    public boolean isFull() {
        return position == capacity - 1;
    }

}

public class Palindrome {

    public boolean same(char ch1, char ch2) {
        return (ch1 == ch2) ? true : false;
    }

    public boolean palindrom(String s) {
        int len = s.length();
        char token = 0;
        Stack stack = new Stack(len);

        for (int i = 0; i < len; i++) {
            token = s.charAt(i);
            if (token != ' ')
                stack.push(new Character(token));

        }

        for (int j = 0; j < len; j++) {
            token = s.charAt(j);
            if (token != ' ')
                if (!same((Character) (stack.pop()), s.charAt(j)))
                    return false;
        }

        return (stack.isEmpty()) ? true : false;
    }

    public String reverse(String original) {
        String reverse = "";
        int length = original.length();

        for (int i = length - 1; i >= 0; i--)
            reverse = reverse + original.charAt(i);

        return reverse;
    }

    public static void main(String[] a) {
        Palindrome s = new Palindrome();
        System.out.println( s.palindrom(a[0]) ? "Palindrome" : "Not Palindrome");
    }
}

Error:  Exception in thread "main"
  java.lang.ArrayIndexOutOfBoundsException: 0   at
  Palindrome.main(Palindrome.java:41)
Comment: [How to debug small programs](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/)
Comment: Do you understand what `ArrayIndexOutOfBoundsException` indicates?
Answer: System.out.println( s.palindrom(a[0]) ? "Palindrome" : "Not Palindrome");

You probably are not running this program from the command line hence the array a is empty.
How to run Java program from the command line with arguments

Java Stack class / Palindrome class


How do I include a React app?

Question: We are moving towards a hybrid-headless model with Drupal 7. All our data is exposed through RESTful and I have successfully built React app using the data.
How can pull that app in as a block? I put the code in a block and the app loses much of its styling and 1 third of the data is hidden. The basic functionality still works, but that's not enough.
Is there some trick to getting the a the full app to run correctly in a block?
Thank you
Answer: I solved this as follows:

install react-app-rewired:  npm i --D react-app-rewired --
this is important so you don't try to load react more than once
change package.json so build executes react-app-rewired build -- full instructions here: https://github.com/timarney/react-app-rewired
Pick a spot in your Drupal install for your react app  -- I chose sites/all/react, it seemed right to me
load react into your template using the CDN links https://reactjs.org/docs/cdn-links.html
update package.json with homepage for your app to reflect where you are saving it for example: "homepage": "/sites/all/libraries/myapp/",
build your react app and copy the contents of the build folder to the location you chose for storing your app
build a simple module to load your app as a block (code below)
add the block to your page however you see fit

/* Adds the block to the block menu */
function my_app_block_info() {
  $blocks['my_react_app'] = array( //a new array for each new app
    'info' => t('My React App'),
    'cache' => DRUPAL_NO_CACHE,
  );

  return $blocks;
}

/* set the content for the block */

function my_app_block_view($delta = '') {
  $block = array();
  switch ($delta) {
    case 'my_react_app': //a new case for each new app
        $block['content'] = file_get_contents(libraries_get_path('appfolder').'/index.html');

        break;
     }
  return $block;
}

<code> /*
   file_get_contents loads the index.html page that loads
   the react app don't use libraries_get_path if you saved your app
   somewhere else
 */
</code>
Comment: Did you try [PDB](https://www.drupal.org/project/pdb) @daniel-lefebvre
Comment: Nice module, thanks :) But I am working with D7 so, there are a number of nice headless options that I don't have access to.

How do I include a React app?


Establish relationship between two text fields

Question: I am stuck in a strange issue. I have two content types twilio  and call recordings. Both content types have caller phone number in common

Recording

Twilio

Now I would like to generate a report using views which can select field between two content types based on phone number.
In non Drupal terms I want inner join based on two text fields.
How can I achieve this?
Comment: based on a quick look at the images you attached, you don't have common field in both content-type, make 1 field first, then add an existing field to the second content-type, so you can have common fields!
Comment: The fields are not common, but the purpose is common. I want to implement this without altering any structure
Comment: I can smell of a custom module for that, I don't see any way out.
Answer: Both content types have to share a field, in the same way a both the database tables used in a INNER JOIN have to share a common field for the join to work.
In Drupal, this is easy as you can reuse fields between your content types and in this wway joining the content types will be super simple with Views.
Current setup:

Recording: field_called_phone, field_caller_phone
Twilio: field_phone_number

Suggested setup:

Recording: field_called_phone, field_phone_number
Twilio: field_phone_number


Add a new column with the names of columns where the row is True or some other specific value

Question: I have this data frame:
Name    Pr  VP  Tr  Me  Sa  Ar
Alicia  1   0   0   0   1   0
Bonnie  0   1   1   0   0   0
Cathy   1   1   1   1   1   1
Daphne  1   0   0   0   0   1
Elena   0   0   0   1   1   1
Faye    0   0   0   0   0   1

And I want to make this dataframe, which adds a column with the name of every column which is 1 in each row:
Name    Pr  VP  Tr  Me  Sa  Ar  Nominations
Alicia  1   0   0   0   1   0   Pr, Ar
Bonnie  0   1   1   0   0   0   VP, Tr
Cathy   1   1   1   1   1   1   Pr, VP, Tr, Me, Sa, Ar
Daphne  1   0   0   0   0   1   Pr, Ar
Elena   0   0   0   1   1   1   Me, Sa, Ar
Faye    0   0   0   0   0   1   Ar

I'd prefer tidyverse but base R would be useful to know too.
Answer: We can loop over the rows with apply and MARGIN = 1 and paste the 'names' where the 'x' is 1
df1$Nominations <- apply(df1[-1], 1, function(x) toString(names(x)[x == 1]))
df1$Nominations
#[1] "Pr, Sa"                 "VP, Tr"                 "Pr, VP, Tr, Me, Sa, Ar" "Pr, Ar"
#[5] "Me, Sa, Ar"             "Ar"

Or using tidyverse, reshape to 'long' format with pivot_longer, grouped by 'Name' summarise by pasteing the 'name' where the 'value' is 1 and join with the original dataset
library(dplyr)
library(tidyr)
df1 %>%
   pivot_longer(cols = -Name) %>%
   group_by(Name) %>%
   summarise(Nominations = toString(name[as.logical(value)])) %>%
   right_join(df1) %>%
   select(names(df1), everything())
# A tibble: 6 x 8
#  Name      Pr    VP    Tr    Me    Sa    Ar Nominations
#  <chr>  <int> <int> <int> <int> <int> <int> <chr>
#1 Alicia     1     0     0     0     1     0 Pr, Sa
#2 Bonnie     0     1     1     0     0     0 VP, Tr
#3 Cathy      1     1     1     1     1     1 Pr, VP, Tr, Me, Sa, Ar
#4 Daphne     1     0     0     0     0     1 Pr, Ar
#5 Elena      0     0     0     1     1     1 Me, Sa, Ar
#6 Faye       0     0     0     0     0     1 Ar

data
df1 <- structure(list(Name = c("Alicia", "Bonnie", "Cathy", "Daphne",
"Elena", "Faye"), Pr = c(1L, 0L, 1L, 1L, 0L, 0L), VP = c(0L,
1L, 1L, 0L, 0L, 0L), Tr = c(0L, 1L, 1L, 0L, 0L, 0L), Me = c(0L,
0L, 1L, 0L, 1L, 0L), Sa = c(1L, 0L, 1L, 0L, 1L, 0L), Ar = c(0L,
0L, 1L, 1L, 1L, 1L)), class = "data.frame", row.names = c(NA,
-6L))

Answer: Making my own data for the example, and using the data.table package:
library(data.table)
dt1 <- data.table(
  "name" = LETTERS[1:5],
  "V1" = c(1,0,0,1,0),
  "V2" = c(1,0,1,0,1))

dt1[melt(dt1, id.vars = "name")[value == 1, .(.(variable)), keyby = name], on = "name"]

Using data from Akrun
df1[melt(df1, id.vars = "Name")[value == 1, .(.(variable)), keyby = Name], on = "Name"]

Giving
     Name Pr VP Tr Me Sa Ar                V1
1: Alicia  1  0  0  0  1  0             Pr,Sa
2: Bonnie  0  1  1  0  0  0             VP,Tr
3:  Cathy  1  1  1  1  1  1 Pr,VP,Tr,Me,Sa,Ar
4: Daphne  1  0  0  0  0  1             Pr,Ar
5:  Elena  0  0  0  1  1  1          Me,Sa,Ar
6:   Faye  0  0  0  0  0  1                Ar

It's making a long data.table using name as the id, subsetting to those where there is a 1, and listing values that were the original column names (variable), then joining back to the original.


Why is printing an instance of my object throwing it in a an infinite loop, and crashing with the error EXC_BAD_ACCESS?

Question: I am making a Swift framework to handle large (256-bit) numbers so I created a struct called UInt256. I tried conforming it to FixedWidthInteger, UnsignedInteger, and BinaryInteger so that it can be used as a regular Swift integer type. My problem is printing it. Whenever I create a UInt256 with a certain value, it works just fine. When I try to print it, it calls the UInt256.init(integerLiteral:) for some reason, and that seems to throw it in an infinite loop, which ends up in the EXC_BAD_ACCESS error.
First, I went back to before I conformed it to all the integer protocols and it worked fine. I want to know why I can't successfully conform it without this error.
I have analyzed the thread when it crashes, and whenever it tries to print the object, it calls the UInt256.init(integerLiteral:) command with a value of 0.
One interesting thing I noticed was that the error has to do with arrays and array buffers. In that init function, I tried creating a useless array and it always crashes on the first line that includes an array initializer. Is this possibly because after the repeated loop, it runs out of space for the array buffer?
I tried adding a print statement in the suspect init function and tried printing the value passed to it. Sure enough, the test printed '0' like 100 times and then crashed.
Here is all code needed to paste it into a Playground:
import Foundation

/// Adds a character and a string
///
/// - Parameters:
///     - left: String
///     - right: Character
///
/// - Returns: The string with the appended character
public func +(left: String, right: Character) -> String {
    var newString = left
    newString.append(right)
    return newString
}

/// Adds a character to a given string, and assigns the new string to the original
///
/// - Parameters:
///     - left: inout String
///     - right: Character
///
/// - Returns: The string with the appended character
@discardableResult public func +=(left: inout String, right: Character) -> String {
    left = left + right
    return left
}

extension String {
    // MARK: Subscripts

    /// References the ith character of a string
    subscript (i: Int) -> Character {
        return self[index(startIndex, offsetBy: i)]
    }
}

/// The size of the big number
public let BN_SIZE = 4

/// Size of BN in Bytes
public let BN_SIZE_IN_BYTES = MemoryLayout<UInt64>.size * BN_SIZE

/// Size of a BN String
public let BN_STR_SIZE = (2 * BN_SIZE_IN_BYTES + 1)

/// An unsigned 256-bit integer, sometimes denoted as just 'BN', or a BigNumber
public struct UInt256: CustomDebugStringConvertible, FixedWidthInteger, UnsignedInteger {

    // MARK: Static properties

    /// It's just 0, expressed as a UInt256
    public static let zero = BigNumber()

    // MARK: Properties

    /// The BN as a hex string
    public var hexString: String {
        var string = ""
        let bnSizeCountdown = Array(1...BN_SIZE).reversed()
        for i in bnSizeCountdown {
            let uint64IndexCountdown = Array(1...16).reversed()
            for j in uint64IndexCountdown {
                string += toChar(self[i - 1] >> ((j - 1) * 4))
            }
        }

        return string
    }

    /// The hex representation of the BN, used for debugging
    public var debugDescription: String {
        return hexString
    }

    /// The array of UInt64's representing the BN. This is a fixed size of BN_SIZE
    public var array: [UInt64]

    // MARK: Initializers

    public init(integerLiteral value: UInt) {
        self.array = [UInt64](repeating: 0, count: BN_SIZE) // THIS is the line that gives me the error: EXC_BAD_ACCESS (code=2, address=0x7ffeef3ffff8)
        self[0] = UInt64(value)
    }

    public init(_truncatingBits bits: UInt) {
        self.array = UInt256.from(int: bits).array
    }

    /// Creates a BN from an array of UInt64's
    ///
    /// - Parameters:
    ///     - array: An array of UInt64's
    ///
    /// - Returns: Nil if the array size is incorrect, but otherwise returns the corresponding BN
    public init?(array: [UInt64]) {
        if array.count != BN_SIZE { return nil }
        self.array = array
    }

    /// Creates a BN from a hex string
    ///
    /// - Parameters:
    ///     - hex: A hex string to be converted to BN
    ///
    /// - Returns: Returns nil if hex string is invalid
    public init?(hexString hex: String) {

        self.array = [UInt64](repeating: 0, count: BN_SIZE)

        for i in 0..<hex.count {
            if toNibble(hex[i]) == 16 { return nil }

            let reversedSequence = (1..<BN_SIZE).reversed()

            for j in reversedSequence {
                self[j] <<= 4
                self[j] |= (self[j - 1] >> 60) & 0x0f
            }

            self[0] <<= 4
            self[0] |= UInt64(toNibble(hex[i]) & 0x0f)
        }
    }

    /// Creates a BN of value 0
    public init() {
        self.array = [UInt64](repeating: 0, count: BN_SIZE)
    }

    // MARK: Static Functions

    /// Converts an Integer to a BigNumber
    ///
    /// - Parameters:
    ///     - int: An UnsignedInteger to convert to a BigNumber
    ///
    /// - Returns: A BigNumber
    public static func from<T: UnsignedInteger>(int: T) -> BigNumber {
        var bn = BigNumber()
        bn[0] = UInt64(int)
        return bn
    }

    // MARK: Enumerations

    // MARK: Subscripts

    /// Gets or sets a value for the given index in the BN array representation
    public subscript(i: Int) -> UInt64 {
        get {
            return array[i]
        } set(newValue) {
            array[i] = newValue
        }
    }

    // MARK: Conformance Requirements

    public static var bitWidth: Int {
        return BN_SIZE_IN_BYTES * 8
    }

    public typealias Words = UInt64.Words

    public typealias IntegerLiteralType = UInt

    public func addingReportingOverflow(_ rhs: UInt256) -> (partialValue: UInt256, overflow: Bool) {
        return (self + rhs, (self > (self + rhs) ? false : true))
    }

    public func subtractingReportingOverflow(_ rhs: UInt256) -> (partialValue: UInt256, overflow: Bool) {
        return (self + rhs, (self < (self - rhs) ? false : true))
    }

    public func multipliedReportingOverflow(by rhs: UInt256) -> (partialValue: UInt256, overflow: Bool) {
        return (self * rhs, (self > (self * rhs) ? false : true))
    }

    public func dividedReportingOverflow(by rhs: UInt256) -> (partialValue: UInt256, overflow: Bool) {
        // don't trust this, I don't even know what this does
        return (self / rhs, (self > (self / rhs) ? false : true))
    }

    public func remainderReportingOverflow(dividingBy rhs: UInt256) -> (partialValue: UInt256, overflow: Bool) {
        // I don't know how this would result in an overflow, but whatever
        return (self % rhs, false)
    }

    public func multipliedFullWidth(by other: UInt256) -> (high: UInt256, low: UInt256) {
        // what does this even mean? Seriously, if someone else would like to write this part, that'd be great
        return (self, self)
    }

    public func dividingFullWidth(_ dividend: (high: UInt256, low: UInt256)) -> (quotient: UInt256, remainder: UInt256) {
        // what does this even mean? Seriously, if someone else would like to write this part, that'd be great
        return (self, self)
    }

    public var nonzeroBitCount: Int {
        var nonzeros: Int = 0
        for i in 0..<BN_SIZE {
            nonzeros += self[i].nonzeroBitCount
        }
        return nonzeros
    }

    public var leadingZeroBitCount: Int {
        var leadingZeros: Int = self[3].leadingZeroBitCount
        for i in (0..<(BN_SIZE-1)).reversed() {
            if self[i+1].nonzeroBitCount > 0 {
                break
            }
            leadingZeros += self[i].leadingZeroBitCount
        }
        return leadingZeros
    }

    public var byteSwapped: UInt256 {
        let reversedArray = self.array.reversed()
        return UInt256(array: reversedArray.map { $0.byteSwapped })!
    }

    public var words: UInt64.Words {
        // I have no idea what this variable is supposed to be.
        // someone else please do this
        return UInt64.Words(8)
    }

    public var trailingZeroBitCount: Int {
        // I couldn't be bothered to write this right now.
        // I'm in the car after a long day and I am tired
        // I just want this project to build so I can say I had a good day and go to sleep
        return 0
    }

    // MARK: Private Methods

    /// Converts an ascii hex character to a nibble
    func toNibble(_ char: Character) -> UInt8 {
        let n = UInt64(char.asciiValue!)
        return  ((n >= 0x30) && (n <= 0x39)) ? UInt8(n - 0x30):
            ((n >= 0x41) && (n <= 0x46)) ? UInt8(n - 0x37):
            ((n >= 0x61) && (n <= 0x66)) ? UInt8(n - 0x57):
        0x10
    }

    /// Converts a nibble to a hex character
    func toChar(_ nibble: UInt64) -> Character {
        var c: Character
        let n = 0x0f&nibble

        if 0 <= n && n < 10 {
            c = String(n)[0]
        } else {
            switch n {
            case 10:
                c = "A"
            case 11:
                c = "B"
            case 12:
                c = "C"
            case 13:
                c = "D"
            case 14:
                c = "E"
            case 15:
                c = "F"
            case 255:
                c = "F"
            case 16:
                c = "0"
            default:
                c = "X"
            }
        }

        return c
    }

    // MARK: Comparisons

    /// Checks if two BNs are equal
    ///
    /// - Parameters:
    ///     - a: A BN
    ///     - b: Another BN
    ///
    /// - Returns: True if they are equal, false if not
    public static func == (a: BN, b: BN) -> Bool {
        for i in 0..<BN_SIZE {
            if a[i] != b[i] {
                return false
            }
        }
        return true
    }

    /// Checks if two BNs are unequal
    ///
    /// - Parameters:
    ///     - a: A BN
    ///     - b: Another BN
    ///
    /// - Returns: True if they are unequal, false if not
    public static func != (a: BN, b: BN) -> Bool {
        return !(a == b)
    }

    /// Checks if a BN is smaller than another BN
    ///
    /// - Parameters:
    ///     - a: The number that is checked to be smaller
    ///     - b: The number that is checked to be larger
    ///
    /// - Returns: True if a < b, false if otherwise
    public static func < (a: BN, b: BN) -> Bool {
        if a == b { return false }
        for i in 0..<BN_SIZE {
            if a[3-i] > b[3-i] { return false }
        }
        return true
    }

    /// Checks if a BN is larger than another BN
    ///
    /// - Parameters:
    ///     - a: The number that is checked to be larger
    ///     - b: The number that is checked to be smaller
    ///
    /// - Returns: True if a  (a: BN, b: BN) -> Bool {
        if a == b { return false }
        for i in 0..<BN_SIZE {
            if a[3-i] = b, false if otherwise
    public static func >= (a: BN, b: BN) -> Bool {
        return a == b || a > b
    }

    /// Less than OR equal to
    ///
    /// - Parameters:
    ///     - a: A BN
    ///     - b: Another BN
    ///
    /// - Returns: TRUE if a <= b, false if otherwise
    public static func <= (a: BN, b: BN) -> Bool {
        return a == b || a  BigNumber {

        var r = BigNumber()
        var carry_out: UInt64 = 0
        var carry_in: UInt64 = 0

        for i in 0..<BN_SIZE {
            r[i] = a[i] &+ b[i]
            if (r[i] < a[i]) {
                carry_out = 1
            }
            if (carry_in != 0) {
                r[i] &+= 1
                if ( 0 == r[i]) {
                    carry_out = 1
                }
            }
            carry_in = carry_out
            carry_out = 0
        }

        return r
    }

    /// Subtracts BigNumber b from BigNumber a
    ///
    /// If the subtraction will result in a negative number, there will be an overflow error
    ///
    /// This uses Two's Complement subtraction
    ///
    /// - Parameters:
    ///     - a: Left BigNumber
    ///     - b: Right BigNumber
    ///
    /// - Returns: Difference of parameters
    public static func - (a: BigNumber, b: BigNumber) -> BigNumber {

        // First, calculate two's complement of B

        var b_t = b

        for i in 0..<b_t.array.count {
            b_t.array[i] = ~b_t.array[i]
        }

        b_t = b_t + UInt256.from(int: UInt(1))

        return a + b_t
    }

    /// Multiplies two BNs
    ///
    /// - Parameters:
    ///     - a: A BN Factor
    ///     - b: Another BN Factor
    ///
    /// - Returns: The product
    public static func * (a: BigNumber, b: BigNumber) -> BigNumber {
        var p = BN()

        let multiplier = a = b ? a : b

        var index = multiplier
        let zero  = BN()
        while index != zero {
            p = p + adder
            index = index - UInt256.from(int: UInt(1))
        }

        return p
    }

    /// Divides BN a by BN b, and returns the quotient
    ///
    /// - Parameters:
    ///     - a: Dividend
    ///     - b: Divisor
    ///
    /// - Returns: The quotient
    public static func / (a: BN, b: BN) -> BN {
        if b == BN.zero { fatalError("Dude you can't divide by zero in OUR universe") }
        var q = BN.zero
        var dividend = a
        while (dividend >= b) {
            q = q + UInt256.from(int: UInt(1))
            dividend = dividend - b
        }
        return q
    }

    /// Modulo operator
    ///
    /// - Parameters:
    ///     - a: Dividend
    ///     - b: Divisor
    ///
    /// - Returns: The remainder as a BN after division
    public static func % (a: BN, b: BN) -> BN {
        if b == BN.zero { fatalError("Dividing by zero is not possible, sorry!") }
        var dividend = a
        while (dividend >= b) {
            dividend = dividend - b
        }
        return dividend
    }

    // MARK: Bitwise operators

    /// Bitwise AND operator
    ///
    /// - Parameters:
    ///     - a: A UInt256
    ///     - b: Another UInt256
    ///
    /// - Returns: The bitwise AND of the two values
    public static func & (a: UInt256, b: UInt256) -> UInt256 {
        var ANDarray: [UInt64] = a.array
        for i in 0..<ANDarray.count {
            ANDarray[i] &= b[i]
        }
        return UInt256(array: ANDarray)!
    }

    /// Bitwise OR operator
    ///
    /// - Parameters:
    ///     - a: A UInt256
    ///     - b: Another UInt256
    ///
    /// - Returns: The bitwise OR of the two values
    public static func | (a: UInt256, b: UInt256) -> UInt256 {
        var ANDarray: [UInt64] = a.array
        for i in 0..<ANDarray.count {
            ANDarray[i] |= b[i]
        }
        return UInt256(array: ANDarray)!
    }

    /// Bitwise XOR operator
    ///
    /// - Parameters:
    ///     - a: A UInt256
    ///     - b: Another UInt256
    ///
    /// - Returns: The bitwise XOR of the two values
    public static func ^ (a: UInt256, b: UInt256) -> UInt256 {
        var ANDarray: [UInt64] = a.array
        for i in 0..<ANDarray.count {
            ANDarray[i] ^= b[i]
        }
        return UInt256(array: ANDarray)!
    }

    // MARK: Assignment operators

    public static func *= (lhs: inout UInt256, rhs: UInt256) {
        lhs = lhs * rhs
    }

    public static func += (lhs: inout UInt256, rhs: UInt256) {
        lhs = lhs + rhs
    }

    public static func -= (lhs: inout UInt256, rhs: UInt256) {
        lhs = lhs - rhs
    }

    public static func /= (lhs: inout UInt256, rhs: UInt256) {
        lhs = lhs / rhs
    }

    public static func %= (lhs: inout UInt256, rhs: UInt256) {
        lhs = lhs % rhs
    }

    public static func &= (lhs: inout UInt256, rhs: UInt256) {
        lhs = lhs & rhs
    }

    public static func |= (lhs: inout UInt256, rhs: UInt256) {
        lhs = lhs | rhs
    }

    public static func ^= (lhs: inout UInt256, rhs: UInt256) {
        lhs = lhs ^ rhs
    }

    public func hash(into hasher: inout Hasher) {
        for uint64 in array {
            hasher.combine(uint64)
        }
    }

}

/// For convenience, a UInt256 can be known as a BN
public typealias BN = UInt256

/// For convenience, a UInt256 can be known as a BigNumber
public typealias BigNumber = UInt256

Here is the test code:
let a: UInt256 = 42

print(a)

Any additional code you want to see can be found at the GitHub page
The expected result from the tests should be a "2A" (42 in hex) proceeded by a bunch of 0's. Instead, it just crashes.
This error has been giving me a headache because I have absolutely no idea where to begin. Any help would be much appreciated.
Comment: What is `BN_SIZE`? What is `from(int:)`? Please post just enough code that someone can copy and paste into a playground and reproduce your issue.
Comment: @rmaddy Sorry about that! I added the code. BN_SIZE is the amount of UInt64's in a UInt256 (so 4) and from(int:) is just a function that creates a UInt256 from an unsigned integer. Sorry I didn't include those earlier.
Comment: Again, post just the right amount of code such that it can be copied and pasted into a playground and tested as-is. Your code, as posted, has lots of errors.
Comment: @rmaddy All needed code is in there. I pasted all that into a Playground on my end as well to make sure that's all the code that's needed. Thanks for pointing that out.
Comment: Last time. Post just enough code. There is no way that much code is needed to demonstrate the issue. Make it easy for people to help you.
Comment: @rmaddy You said there were a lot of errors when you put it in a Playground. A lot of those errors were there because when I left out a lot of code, it no longer conformed to the protocols I was trying to conform it to. Removing all that code would certainly make the code simpler, but would it would not work in a Playground as you wanted. I'm not quite sure how else to post the code.
Answer: Change print(a) to debugPrint(a). You have a coherent implementation of debugDescription so calling debugPrint will work.
Comment: I don't know that. You've hooked things up in some way that causes recursion. The point is that you have implemented `debugDescription` but you are not calling it. Call it. You have not told your types how to respond to `print` but you have told them how to respond to `debugPrint`. So do that.
Comment: Avoid `print` until you figure out where the recursion is coming from.
Comment: I'll try that, but why is it that print(a) won't work?
Comment: Also I would like to point out that you are reinventing the wheel, as big-number libraries for Swift already exist.
Comment: Duly noted. Also I'm more making the big number library for experience so I can learn more.


Dynamically Fix/Repair Invalid HTML in Javascript

Question: I am currently writing a program that works very similar to a rich text editor, the way my HTML code is outputted is invalid and similar to this:
This is a test title

Google Chrome renders that invalid HTML as valid HTML which looks like this
This is a test title

I want to find the way Google Chrome (or a parser that outputs the same results) converts the broken HTML into that valid HTML so I can render this valid HTML instead of letting each browser use their own "HTML repairing techniques" which could cause compatability problems. I've seen programs such as HTMLAgilityPack but that seems to be for .NET and I'm using Javascript.
Honestly, I understand I should post my own code to do this but I really have no idea where to even start at dynamically correcting/repairing the invalid HTML and assume there's some sort of correction standard or library (My example was only based on two layers too, it could go much deeper) but I haven't been able to find anything.
Any assistance would be greatly appreciated.
Answer: Albeit this doesn't fix any cross-compatibility of HTML repairing due to each browser having their own implementation, I found I could use the DOMParser API to access the corrected HTML.
const dom = new DOMParser().parseFromString(
  'This is a test title',
  'text/html'
)

This allowed me to then query the DOMParser and get the corrected HTML with
const html = dom.querySelector("body").innerHTML


What is the best fingering for these 3 jumpy octave bars?

Question: I'm not sure how to do the fingering for this? The first 4 notes per bar are especially challenging.
I've tried 5,5,1,51 and 5,1,5,51 but none of it feels really good :( I'm learning on my own so I hope someone more experienced could help!
thank you
Answer: I have been playing piano for several years and have won first place at many competitions and performed at major venues such as Carnegie Hall.
At first glance, I would suggest you use both hands to navigate this tricky 3-octave jump. However, if you are already playing things in your right hand, I suggest you use the fingering 5, 1, 2, 25, 1. When you get to play the third note with your index finger, don't press that note by repositioning your hand. Play that note by almost flipping your hand from the last note. This fingering is especially helpful because it creates momentum with your whole hand almost turning to eventually hit that middle C.
Take the fingering very slow until you can do it with your eyes closed (literally!. This will help with accuracy later). Then slowly speed up the tempo and you should be able to execute it flawlessly.
I hope that helped! Let me know if you are still having trouble.


Replace list of value in a text file

Question: I have the following problem:
I have a huge file and i have to replace some value (more than one).
Ad example, I have to replace:
DOG with RED
CAT with BLUE
FISH with GREEN
...

...
n    with N

Do you know some software that is able (putting in input a list value) to replace all the value of the list in one hit in the text?
EDIT:
My text file is something really big as a book or similar.
In this book i have many words that i have to replace with other words
Comment: What tools do you have to hand? What counts as "one pass"?
Answer: You can use sed to substitute matching expressions, for example
sed -e 's/DOG/RED/g;s/CAT/BLUE/g' < inputFile > outputFile

You haven't specified if you wan this changed in place or not. You could clearly delete the old version afterwards if you were happy with the results.
.....
If you are on Windows some other answers will give you an equivalent or suggest tools such as cygwin: e.g. here
Comment: That's where I was going with "What tools do you have?" cygwin would provide.

Replace list of value in a text file


Importing multiple csv files into pandas and merge them into one DataFrame

Question: I have multiple csv files (Each file contains N number of Rows (e.g., 1000 rows) and 43 Columns).
I would like to read several csv files from a folder into pandas and merge them into one DataFrame.
I have not been able to figure it out though.
The problem is that, the final output of the DataFrame (i.e., frame = pd.concat(li, axis=0, ignore_index=True) ) merge all columns (i.e., 43 columns) into one column (see the attached image)
Screenshot of the code
an example of selected rows and columns (file one)
               Client_ID    Client_Name  Pointer_of_Bins   Date        Weight
                C0000001       POLYGONE      TI006093     12/03/2019   0.5
                C0000001       POLYGONE      TI006093     12/03/2019   0.6
                C0000001       POLYGONE      TI006093     12/03/2019   1.4
                C0000001       POLYGONE      TI006897     14/03/2019   2.9

an example of selected rows and columns (file two)
                   Client_ID    Client_Name  Pointer_of_Bins   Date        Weight
                    C0000001       POLYGONE   TI006093      22/04/2019   1.5
                    C0000001       ALDI       TI006098      22/04/2019   0.7
                    C0000001       ALDI       TI006098      22/04/2019   2.4
                    C0000001       ALDI       TI006898      24/04/2019   1.9
The expected outputs would look like this (merge of multiple files that might contains thousands of rows and several columns, as the attached data is just an example, while the actual csv files might contain thousands of rows and more than 45 columns in each file)
               Client_ID    Client_Name  Pointer_of_Bins   Date        Weight
                C0000001       POLYGONE      TI006093     12/03/2019   0.5
                C0000001       POLYGONE      TI006093     12/03/2019   0.6
                C0000001       POLYGONE      TI006093     12/03/2019   1.4
                C0000001       POLYGONE      TI006897     14/03/2019   2.9
                C0000001       POLYGONE      TI006093     22/04/2019   1.5
                C0000001       ALDI          TI006098     22/04/2019   0.7
                C0000001       ALDI          TI006098     22/04/2019   2.4
                C0000001       ALDI          TI006898     24/04/2019   1.9

TO Download the two CSV files, click here (dummy data
Here is what I have done so far:
import pandas as pd
import glob
path = r'C:\Users\alnaffakh\Desktop\doc\Data\data2\Test'
all_files = glob.glob(path + "/*.csv")
li = []
for filename in all_files:
    df = pd.read_csv(filename, sep='delimiter', index_col=None, header=0)
  # df = pd.read_csv(filename, sep='\t', index_col=None, header=0)
    li.append(df)
frame = pd.concat(li, axis=0, ignore_index=True)

Comment: @QuangHoang, Thanks for your reply, but if i remove it, i get this error                (                                              UnicodeDecodeError: 'utf-8' codec can't decode byte 0xc7 in position 8: invalid continuation byte)
Comment: get rid of `sep='delimeter'`. The code as it is now, read **all** dataframes as one columns.
Comment: Please share some dummy data. I support what @QuangHoang mentioned: you need to either get rid of `sep='delimiter'` or use an **actual delimiter** which has been used in the file. This is why I suggest you share some dummy data (may be 4 lines with only 5 columns) so we could test against that.
Comment: You might consider to use dask.
Answer: Solution
You could use pandas.concat to recursively concatenate the .csv file contents.
In fact, I see that you used it and your application of concat seems fine to me. Try investigating the individual dataframes that you read. The only way your columns could merge into a single column is if you did not mention the correct delimiter.
import pandas as pd

dfs = list()
for filename in filesnames:
    df = pd.read_csv(filename)
    dfs.append(df)
frame = pd.concat(dfs, axis=0, ignore_index=True)
df.head()

Example with Dummy Data
Since the dummy data available is not in text format yet, I am using just some dummy data I made.
import pandas as pd
from io import StringIO # needed for string to dataframe conversion

file1 = """
Col1    Col2    Col3    Col4    Col5
1   ABCDE   AE10    CD11    BC101F
2   GHJKL   GL20    JK22    HJ202M
3   MNPKU   MU30    PK33    NP303V
4   OPGHD   OD40    GH44    PG404E
5   BHZKL   BL50    ZK55    HZ505M
"""

file2 = """
Col1    Col2    Col3    Col4    Col5
1   AZYDE   AE10    CD11    BC100F
2   GUFKL   GL24    JK22    HJ207M
3   MHPRU   MU77    PK39    NP309V
4   OPGBB   OE90    GH41    PG405N
5   BHTGK   BL70    ZK53    HZ508Z
"""

Load data as individual dataframes and then concatenate them.
df1 = pd.read_csv(StringIO(file1), sep='\t')
df2 = pd.read_csv(StringIO(file2), sep='\t')
print(pd.concat([df1, df2], ignore_index=True))

Output:
   Col1   Col2  Col3  Col4    Col5
0     1  ABCDE  AE10  CD11  BC101F
1     2  GHJKL  GL20  JK22  HJ202M
2     3  MNPKU  MU30  PK33  NP303V
3     4  OPGHD  OD40  GH44  PG404E
4     5  BHZKL  BL50  ZK55  HZ505M
5     1  AZYDE  AE10  CD11  BC100F
6     2  GUFKL  GL24  JK22  HJ207M
7     3  MHPRU  MU77  PK39  NP309V
8     4  OPGBB  OE90  GH41  PG405N
9     5  BHTGK  BL70  ZK53  HZ508Z

Comment: @Meet Yes, you can use multi-index with a file-source identifier. But I would advise against using filenames as part of the multi index. Filenames could be long and when they are named you may not have any control over their nomenclature logic. Rather, if you want to track just the source of the data, I would suggest you add another column "Source" and fill in the file name there. You can always conditionally extract file-specific data this way. But consider keeping your index singular as long as you can, unless it is absolutely necessary.
Comment: @Wisamhasan Thank you for making the data available. However, please paste the first 5 columns and 4 rows of each of the two csv files into your problem statement as your sample data from csv files. And then also provide what you will expect. You data needs to be minimal and reproducible. It's best not to share data files.
Comment: @Wisamhasan Thank you for the rows and columns. However, I asked for the data to be pasted into your problem description as text. This makes your problem easily replicable. Please make a code block and paste your data-columns (subset) from file-1 and file-2 into that code block.
Comment: thanks but again the attached code doesnt solve the proplem.
Comment: The code is to answer the problem you mentioned. I left another comment about checking the actual delimiter used. It looks like that your problem exists in the data. Please check what delimiter has been used and then use that.
Comment: What delimiter are you using?
Comment: @Wisamhasan Could you please consider **`accepting`** and **`voting up`** the answer?
Comment: This works. Thanks. Is it possible to index the new dataframe with the imported file name? Just to identify which data is from which file? May be a multi-index?
Comment: @CypherX Thanks for pointing that out. Will keep a note of that. For my specific case, the files that I will be merging in the dataframe are generated by my own program from other system and the file names are just years - 2012.csv, 2013.csv like that. So, i'd work for me. But sure, it is a better approach to store file name or path as a column and get necessary data (say year in my case) from that to convert as index. I need that index yes.


Sensible distribution for modelling counts per population

Question: I have some crime data where the crime rate for a given year in a given town is reported as number of police reports per thousands of people in this town, eg $5/6$ for five reported crimes in a town of 6000 people. In the nature of things there will be some high-variance measurements from small towns and some less-variable measurements from larger towns.
If it was only the number of police reports it would be count data, and I'd figure that the sensible choice would be a Poisson distribution. Is there a similar sort of theoretically founded choice for this count-per-something situation?
Below is a histogram of the rates and the log of these rates; from these it's kind of tempting to call the data log-normal but I have no theoretical basis for saying so. Further below is a very long string you can copy to get a vector of these rates in R.

<code>rates <- c(15.4, 11.6, 10.9, 10.9, 10.5, 10, 9.8, 9.8, 9.5, 9, 9, 8.9, 8.8, 8.8, 8.7, 8.4, 8.2, 8.2, 8.2, 8, 7.9, 7.9, 7.8, 7.7, 7.6, 7.6, 7.6, 7.5, 7.5, 7.4, 7.4, 7.3, 7, 7, 6.9, 6.9, 6.8, 6.8, 6.8, 6.8, 6.7, 6.7, 6.6, 6.6, 6.5, 6.5, 6.5, 6.4, 6.4, 6.4, 6.3, 6.3, 6.3, 6.3, 6.2, 6.2, 6.2, 6.1, 6.1, 6.1, 6.1, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 5.9, 5.9, 5.9, 5.9, 5.9, 5.8, 5.8, 5.8, 5.8, 5.8, 5.7, 5.7, 5.7, 5.6, 5.6, 5.6, 5.5, 5.5, 5.5, 5.5, 5.5, 5.4, 5.4, 5.4, 5.4, 5.4, 5.4, 5.4, 5.4, 5.3, 5.3, 5.3, 5.3, 5.3, 5.3, 5.2, 5.2, 5.2, 5.2, 5.2, 5.2, 5.1, 5.1, 5.1, 5, 5, 5, 5, 4.9, 4.9, 4.9, 4.9, 4.9, 4.8, 4.8, 4.7, 4.7, 4.7, 4.6, 4.6, 4.6, 4.6, 4.5, 4.5, 4.5, 4.5, 4.5, 4.4, 4.4, 4.4, 4.4, 4.3, 4.3, 4.3, 4.3, 4.3, 4.3, 4.3, 4.3, 4.2, 4.2, 4.2, 4.2, 4.2, 4.2, 4.2, 4.2, 4.2, 4.2, 4.1, 4.1, 4.1, 4.1, 4, 4, 4, 4, 4, 4, 4, 4, 3.9, 3.9, 3.9, 3.9, 3.9, 3.9, 3.9, 3.9, 3.8, 3.8, 3.8, 3.8, 3.8, 3.8, 3.7, 3.7, 3.7, 3.7, 3.7, 3.7, 3.7, 3.7, 3.7, 3.6, 3.6, 3.6, 3.6, 3.6, 3.6, 3.6, 3.6, 3.5, 3.5, 3.5, 3.5, 3.5, 3.5, 3.5, 3.5, 3.5, 3.4, 3.4, 3.4, 3.4, 3.4, 3.4, 3.4, 3.4, 3.3, 3.3, 3.3, 3.3, 3.3, 3.2, 3.2, 3.2, 3.2, 3.2, 3.2, 3.2, 3.2, 3.2, 3.2, 3.1, 3.1, 3.1, 3.1, 3.1, 3.1, 3.1, 3.1, 3.1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 2.9, 2.9, 2.9, 2.9, 2.9, 2.9, 2.9, 2.9, 2.9, 2.9, 2.9, 2.9, 2.9, 2.8, 2.8, 2.8, 2.8, 2.8, 2.8, 2.8, 2.8, 2.8, 2.8, 2.8, 2.7, 2.7, 2.7, 2.7, 2.7, 2.7, 2.7, 2.7, 2.7, 2.7, 2.7, 2.6, 2.6, 2.6, 2.6, 2.6, 2.6, 2.6, 2.6, 2.6, 2.6, 2.6, 2.6, 2.5, 2.5, 2.5, 2.5, 2.5, 2.5, 2.5, 2.4, 2.4, 2.4, 2.4, 2.4, 2.3, 2.3, 2.3, 2.3, 2.3, 2.3, 2.3, 2.3, 2.3, 2.3, 2.3, 2.2, 2.2, 2.2, 2.2, 2.2, 2.2, 2.2, 2.2, 2.1, 2.1, 2, 2, 2, 2, 2, 2, 2, 1.8, 1.8, 1.6, 1.5, 1.5, 1.4, 1.4)
</code>
Comment: Modelling the log of the crime rate is common. When there are zeroes, a popular alternative is to use a Poisson model predicting the counts, but use the population as an offset term.
Comment: This is relevant:  http://stats.stackexchange.com/questions/142338/goodness-of-fit-and-which-model-to-choose-linear-regression-or-poisson/142353#142353
Comment: Pretty much all statistical software allows you to include an *exposure* term for Poisson models (which is equivalent to an offset). Depending on the software, this will either be the population counts, or the log of the population counts. [See this discussion](http://spssx-discussion.1045642.n5.nabble.com/genlin-poisson-regression-with-offset-td5725663.html#a5725664) for how an offset term in a Poisson regression can help you interpret the model as rates.
Comment: @AndyW That's interesting what you say about the offset Poisson, how would I do it that practice?
Answer: Sometimes the negative binomial is used too.
The most interesting option is, however, the Hurdle Models!
They work as a Poisson, but the probability of getting a 0 has its own parameter.


Is there a way to control the YouTube HTML5 Player volume manually (JavaScript/Inspect Element)?

Question: I am looking for a way to control the YouTube HTML5 player volume with JavaScript or by editing something in the element inspector in Firefox. Currently, I'm using Bootcamp on a Mac and it jacks up the volume a TON, so if I go above 25% on the HTML5 player, it blasts my ears out. I do have my System volume almost at 0 as well.
I am looking for a way to get the HTML5 player to go to 4% volume or 3% volume. With my mouse, I can only be precise enough to change it by 4% at a time.
I've looked everywhere I can think in the HTML5 properties, but I can't find anything that holds data for audio level.
Can someone help me out with that?
Thanks!
Comment: @AlexeiDarmin I looked at that, but it doesn't seem to want to work. I'm getting the error that setVolume is not a function. Could this stuff be for the old YouTube player and not the HTML5 one?
Comment: Googling "Youtube volume javascript" Gives you the solution https://developers.google.com/youtube/js_api_reference?hl=en

`player.setVolume(volume:Number):Void
Sets the volume. Accepts an integer between 0 and 100.`
Answer: Assuming the video player HTML element has a class name of 'video-stream html5-main-video', you would accomplish this as follows;
<code>var video = document.getElementsByClassName('video-stream html5-main-video')[0]
var newVolume = video.volume

//increasing our volume
newVolume += .75

 //value of volume should be between 0 and 1
if (newVolume >= 0 && newVolume <= 1) {
    // if valid value, use it
    video.volume = newVolume;
} else {
    // otherwise substitute a 0 or 1
    video.volume = (newVolume < 0) ? 0 : 1;
}
</code>


Toggle bool with checkbox and playerprefs in Unity C#

Question: I'm trying to make a checkbox in Unity UI that returns a bool endless game as 'true', and 'false' if it's a timed game. I want to do this with PlayerPrefs. I understand that PP only supports int, float and strings. I created a function that true to 1.
I have a Game Manager that handles the overall state of the game, this gameobject is the only one in my game that doesn't get destroyed on load.
So far the Game Manager has a bool 'endless' that is initialized as
endless = PlayerPrefs.GetInt("Endless", 1) == 0;

in the start function.
Now I have an options menu that houses the checkbox, in this script is the following:
public void OnToggleEndless()
{
    if (endLessToggle.isOn)
    {
        PlayerPrefs.SetInt("Endless", manager.endless ? 1 : 0);

        print("Endless Button ticked");
    }
    else
    {
        PlayerPrefs.SetInt("Endless", manager.endless ? 0 : 0);
        print("Endless Button unticked");
    }

}

But when I hook it up, play the game and go to the options menu and tick 'Endless Game', nothing happens. I tried to put the OnToggleEndless(); method in Update, but that just gives me endless lines of the print("Endless Button ticked"); message, the PlayerPrefs aren't saved. I'm wondering if the checkbox is even hooked up properly. I cannot figure this one out!
Comment: " But when I hook it up, play the game and go to the options menu and tick 'Endless Game', nothing happens" Are you sure that you attached this "OnToggleEndless()
" function to ToggleButton event handler?
Answer:
The PlayerPrefs aren't saved

The saving of the PlayerPrefs seems faulty are you sure you want to actually check for manager.endless instead of endLessToggle.isOn.
Because the state of endLessToggle.isOn changes depending if you enabled or disabled the checkbox. But the state of manager.endless never changes and is set to either true/false at the start of the game.
This results in you not actually changing the PlayerPrefs variable when you toggle the checkbox.
Example:
private void Start() {
    // Check if we enabled or disabled the endlessToggle Checkbox last time we played
    // and set the checkbox accordingly.
    endLessToggle.isOn = (PlayerPrefs.GetInt("Endless", 1) == 0);
}

// Call when we toggle the Checkbox.
public void OnToggleEndless() {
    // Get the current state of our toggle button.
    int enable = endLessToggle.isOn ? 1 : 0;
    // Log result into console to test it.
    Debug.Log("We set Endless to: " + enable);
    // Set the PlayerPrefs equal to our current state.
    PlayerPrefs.SetInt("Endless", enable);
}

I don't think you need to use a a global variable from your GameManager anyway, because you already have the PlayerPrefs which does the same thing for you.
Additionally you need to set the state of the CheckBox equal to the PlayerPrefs when you start the Game.
Comment: Thanks Mathew! I forgot to save the playerprefs! Also my options menu was screwed up somehow and I had to reassign the script to it. It works great now! Thanks again for taking the time to read and respond to my question!


Rule to redirect to registration page after adding new product to cart

Question: Rule to redirect to registration page after adding new product to cart. I am using ubercart module for this and working with drupal 7
Comment: It is present in store/cart configuration setting.
Answer: Yes, the options is given by default in ubercart. Go to admin->store->configuration->cart
Please check the attached image for more clarification.


Check whether if paraboloid of revolution reflect all the rays that strike it in one direction

Question: In [part 5 Physical Applications of the Derivative as Slope of Chapter 4]  of Calculus: An Intuitive and Physical Approach(Second Edition), discussed the question about What shape should a surface of revolution have in order to reflect in one direction all the rays that strike it?
In [this part] , the book concluded that

I am trying to seek the relation of $x$ and $y$ of the curve which could reflect all the rays that strike it in one direction according to the above conclusion, that is ∠1=∠2 and $\tan\angle 2 = \frac{1}{f^{'}\left( x \right)}$ where $f^{'}\left( x \right)$ is the slope of the tangent at P(x,y) of the curve , while $\tan\angle 1 = \frac{f^{'}\left( x \right) - k_{\text{FP}}}{1 + f^{'}\left( x \right)k_{\text{FP}}}$ where $k_{\text{FP}}$ is the slope of FP, ∠1=∠2 leads to $\tan\angle 1 = \tan\angle 2$.
I want to check if $\tan\angle 1 = \tan\angle 2$ holds in the [parabola case] , where $\tan\angle 2 = \frac{1}{f^{'}\left( x \right)} = \frac{1}{\frac{x}{2p}} = \frac{2p}{x}$ and $\tan\angle 1 = \frac{f^{'}\left( x \right) - k_{\text{FP}}}{1 + f^{'}\left( x \right)k_{\text{FP}}} = \frac{\frac{x}{2p} - \frac{\frac{x^{2}}{4p} - p}{x}}{1 + \frac{x}{2p} \cdot \frac{\frac{x^{2}}{4p} - p}{x}}$,however , I cannot simply $\tan\angle 1$ to equal to $\tan\angle 2$, that's the problem , so what's wrong ?
Answer: It seems to me that you're most of the way there. I don't see why you can't simply equate the two tangents at this point in your proof. The angles are clearly measured in compatible directions, as you can see if you extend the ray $\overline{FP}$ and examine the opposite angle to $\angle1$. The horrible expression that you have for $\tan{\angle1}$ eventually simplifies to $\frac x{2p}$ as required.
Another way to verify the equality of the angles without quite as much messy algebraic manipulation is to show that the tangent at $P$ bisects the angle between $FP$ and $FD$. This is quite straightforward to do using vectors. For $x\gt0$ a direction vector of $FP$ is $\mathbf v = \left(x,{x^2\over4p}-p\right)$ and the direction of $FD$ is simply $\mathbf w = (0,1)$. Their angle bisector is $$\|\mathbf w\|\mathbf v - \|\mathbf v\|\mathbf w = \left(x,{x^2\over4p}-p+\sqrt{x^2+\left({x^2\over4p}-p\right)^2}\right) = \left(x,{x^2\over2p}\right) = x\left(1,{x\over2p}\right).\tag{*}$$ The direction vector of the tangent at $P$ is $(1,f')=\left(1,{x\over2p}\right)$. By symmetry, this bisector relationship also holds for $x\lt0$.
Comment: I sloved it myself . The trick is not rush to substitute $y$ in $\tan\angle 1 = \frac{f^{'}\left( x \right) - k_{\text{FP}}}{1 + f^{'}\left( x \right)k_{\text{FP}}}$ where $k_{FP}=(y-p)/x$ with ${\frac{x^{2}}{4p}}$ at first, and ${x^{2}}=4py$ , this could simplify the algebraic manipulation  a bit. Thanks anyway !


How to fix out TF53001 issue in TFS2015?

Question: Working with TFS2015 Upade2 and VS2015 Update2. Everything works well until one of the project collection can't add, rename, delete files. Will prompt an error Message:

TF53001: The database operation was canceled by an Administrator.

This issue can  be reproduced by everyone in my team even with team project collection administrator. How to fix out the issue? Any help would be appreciate!
Thanks Tomhans.
Answer: In order to resolve this error, you might want to start by checking the version of your SQL instance hosting the TFS databases.
To find the version of the SQL instance run the query <code>'select @@version'</code>. The version list for SQL can be found here.
If your SQL version is lesser than SQL 2014 CU4 then update it to CU4 or a higher update. And then try it again. More details please refer this blog from MSDN.
Comment: Took me a while to convince the DBA to patch SQL with CU4, but when it was done - everything worked again. What is confusing is that this error does not seem to be caused by changes like updates, patches etc. At least that was the case in our instance.
Comment: Thanks! But I'm using SQL2014 update2. I think this is not the root cause.
Comment: The error resolved when I change the service back to the original  service account (which was NT Service/MSSQLSERVER) from Domain user and restarted the SQL Server service. You gave me a   a  correctly directiondirection. Thank you for your time any way.


Integration Antiderivative vertical bar

Question:
Possible Duplicate:
What is the name of the vertical bar?

When taking a definite integral, the first step is finding the anti-derivative. Once you have gone through all the steps to complete that, you need to evaluate the anti-derivative. This is often written with the formula for the anti-derivative then a vertical bar after that formula with the upper and lower bounds, much like the integration symbol. What is this vertical bar called? Does it have a name? For that matter, does the integration symbol have a name?
This isn't for homework, but neither is it just out of curiosity. I have a reason for wanting to know this, but it would take a while to explain.
Answer: Integral Symbol (Wikipedia)

The ∫ symbol $\int$ is used to denote the integral in mathematics. The notation was introduced by the German mathematician Gottfried Wilhelm Leibniz towards the end of the 17th century. The symbol was based on the ſ (long s) character, and was chosen because Leibniz thought of the integral as an infinite sum of infinitesimal summands. See long s for more details on the history of ſ.
The long s survives in elongated form, and with an italic-style curled descender, as the integral symbol ∫ used in calculus; Gottfried Wilhelm von Leibniz based the character on the Latin word summa ("sum"), which he wrote ſumma.

As for the vertical bar denoting the bounds of evaluating an antiderivative:
You might as well call it the "evaluation bar." E.g., it's used here: Evaluation Bar Notation.

Integration Antiderivative vertical bar


Dedekind and Bois-Reymond criterion

Question: 1)Dedekind criterion
If $\lim a_n=0$, $\sum_{n=1}^{\infty} (a_n-a_{n-1})$ converges absolutely and the partial sums of $\sum_{n=1}^{\infty}  z_n$ are bounded, then $\sum_{n=1}^{\infty} a_nz_n$ converges.
2)Bois-Reymond criterion
If $\sum_{n=1}^{\infty} (a_n-a_{n-1})$ converges absolutely and $\sum_{n=1}^{\infty}  z_n$ converges, then $\sum_{n=1}^{\infty} a_nz_n$ converges.
I am trying to prove these two theorems but I don't know how to, I would appreciate any hints or suggestions.
For 1): Let $Z_N=z_1+...+z_N$, one can express $$\sum_{n=1}^N a_nz_n=a_NZ_N-\sum_{n=0}^{N-1} Z_n(a_{n+1}-a_n)=a_NZ_N+\sum_{n=0}^{N-1} Z_n(a_n-a_{n+1})$$
From the inequality $0\leq |a_NZ_N|\leq |a_N|M$, one can deduce that $a_NZ_N \to 0$ when $N \to \infty$,
With respect to $\sum_{n=0}^{N-1} Z_n(a_n-a_{n+1})$:  $$|  \sum_{n=0}^{N-1} Z_n(a_n-a_{n+1})|\leq \sum_{n=0}^{N-1} |Z_n||(a_n-a_{n+1})|\leq M\sum_{n=0}^{N-1} |(a_n-a_{n+1})|$$, letting $N \to \infty$, the right member of the inequality converges.
Comment: I believe that the technique you are looking for is summation by parts. Take a look at http://en.wikipedia.org/wiki/Summation_by_parts.
Comment: Your work for Dedekind's criterion looks fine. Have you found an angle of attack for du Bois-Reymond?
Comment: Not yet, I'm thinking
Comment: Do you want to think for yourself some more, or a big hint now?
Comment: I'll go for the big hint, thanks!
Comment: $$R_n = \sum_{k=n}^\infty z_k$$
Comment: $R_n \to 0$, I'll try to use it, thanks again.
Answer: Your proof of the Dedekind criterion is correct. The proof for the du Bois-Reymond criterion must look different, since the proof of the Dedekind criterion depends on the assumption that $a_n \to 0$, which is not part of the hypotheses of the du Bois-Reymond criterion. Instead, we have the assumption that $\sum z_n$ converges, not only that it has bounded partial sums.
In such a case, instead of writing
$$z_n = \left(\sum_{k=1}^n z_k\right) - \left(\sum_{k=1}^{n-1} z_k\right),$$
one can also write
$$z_n = \left(\sum_{k=n}^\infty z_k\right) - \left(\sum_{k=n+1}^\infty z_k\right),$$
where now
$$R_n := \sum_{k=n}^\infty z_k \xrightarrow{n\to\infty} 0$$
can be used to make the solitary term(s) in a summation by parts small.
We find
$$\begin{align}
\sum_{k=1}^N a_k z_k &= \sum_{k=1}^N a_k(R_k - R_{k+1})\\
&= \sum_{k=1}^N a_k R_k - \sum_{k=2}^{N+1} a_{k-1}R_k\\
&= a_1R_1 + \sum_{k=2}^N (a_k - a_{k-1})R_k - a_NR_{N+1},
\end{align}$$
where the first term is constant, the sum is a partial sum of an absolutely convergent series (since the $R_k$ are bounded), and the final term converges to $0$, since $a_N$ is bounded and $R_{N+1} \to 0$. Together, the (conditional) convergence of
$$\sum_{k=1}^\infty a_k z_k$$
follows.

Dedekind and Bois-Reymond criterion


Atributo required do input não funciona depois de utilizar jquery

Question: Olá,
Ao utilizar jquery para desabilitar o botão submit após ser enviado uma vez o atríbuto required no input não funciona mais.
HTML
<form id="ajax" action="#teste" method="POST">

Nome

        <input type="text" name="nome" required>

E-mail

        <input type="email" name="email" required>

Assunto

        <input type="text" name="assunto" required>

Mensagem

        <textarea name="mensagem" name="mensagem"></textarea>
        <input type="submit" value="Enviar" class="btn-submit" >

        </form>

JS
 $(function(){
     $(".btn-submit").click(function () {
       $(".btn-submit").attr("disabled", true);
       $('#ajax').submit();
     });
   });

Exemplo no CodePen: http://codepen.io/flashpremium/pen/gpZZRv
Answer: Você pode usar o evento submit no lugar do click para enviar o formulário, exemplo:
$(function(){
    $("#ajax").on('submit', function() {
        $(".btn-submit").attr("disabled", true);
    });
});

Ao adicionar um listener no evento de submit do seu formulário, você assegura que as validações dentro dele sejam todas disparadas, afinal, elas rodam antes deste evento. Agora quando você usa click no botão do formulário, seria como se você estivesse falando: "Ei, escute apenas quando este botão for clicado, não interessando se o formulário foi enviado ou não". Logo, o evento dispara apenas com o botão, antes de qualquer evento do próprio formulário, o que atrapalha a validação do mesmo.
Inclusive, utilizando o submit para disparar seu formulário AJAX permite usar a funcionalidade padrão dos browsers de enviar um formulário pressionando a tecla Enter.
Obs.: Note que eu removi a linha $("#ajax").submit() visto que como agora estamos tratando o próprio evento de submit, ele já será enviado de qualquer forma.
Comment: Isso resolve o problema, obrigado Kazzkiq!