Why does every American sport except Football seem to have a farm league?

Question: Baseball (MLB) has a minor league, Hockey (NHL) has the AHL, Basketball (NBA) has the D-League, and even Soccer (MLS) has the USL and NASL although they may not be farm leagues in the same sense as the other sports.
It could be argued that NCAA college football is a developmental league, but that alone does not explain why there is no professional developmental league for after college since all the other sports listed above have NCAA college leagues and still have a farm league.
Comment: The NFL did have its own farm league! It was called the World League, and it operated between 1991 and 2007. See my answer below.
Answer: There are a few differences between American Football and other sports that lead to this: particularly, the length of playing careers (shortest by far), and the cost of running a team (largest by far).
NFL teams are very large, with 53 players active of whom 46 play on any given Sunday, and every single one is typically utilized except perhaps a backup QB - compared to a baseball team (25, of which 12 or so play most days), hockey team (25), or basketball team (15, of which many teams use single digits in most games).  Assuming a true minor league existed - where the game was played the same as it is at the pro level, which is fairly important for the minor league to have value - you'd need similar roster sizes, certainly at least 40 per squad; that would cost a lot of salary.
Football also is the most dangerous of sports, which means it would have substantially higher expenses for doctors and health insurance; it also probably would need to pay players significantly more (minor league baseball players make very little, so a minor league team is pretty cheap - lots of players who have no shot at the majors, just filling spots, at $30k a year).  If it were a true minor league, with nearly NFL size players (so 280-300 lb offensive and defensive linemen, etc.) you'd need to pay people appropriately.  Semipro football is a thing and people certainly enjoy playing it for very little or no money, but they're not playing at the intensity and with players of the size of NFL players.  You wouldn't be able to get away paying people peanuts.
The current Arena Football League, which is not really a minor league - the size isn't comparable - pays about $15k in salaries per player; but the talent level isn't nearly the NFL level that it would need to be.  The earlier Arena league, which did have close enough to NFL talent that it had some elements of a minor league system (ie, it wasn't uncommon for good Arena players to go to the NFL), paid much more - 31k minimum, 80k average.  They also went bankrupt quickly.  The current one is doing better, but even now isn't entirely financially sound - and that's with a lower quality of player at the lower salary level.  The CFL pays about 80,000 a year, which is probably the only league that can truly claim to be sufficient quality that it could fill in as a minor league system directly.
The NFL does have the practice squad, which serves some of the purposes of a minor league team (ie, some talent that they work with regularly to learn the systems, and can call up to the main team when someone gets hurt).  I imagine the size of that squad (8 players) is well defined by the actual needs of teams - if everyone needed more, they'd increase that size.
All of this is notwithstanding the fact that there have been multiple attempts to sell smaller leagues as NFL minor leagues.  The USFL tried in 2012, now the FXFL is giving it a shot... who knows what will happen, but I suspect the same as in the past: a few years of failure followed by league closure.  College football and NFL football just are too successful right now at chasing viewers to lose out to a new minor league.  The major attraction of minor league baseball is watching professional baseball in your home town - and colleges provide that for football.
Comment: Good answer...though I believe that Football--while slightly higher--does compare to hockey in terms of injury statistics. I'm not sure injury rates are a major reason.
Comment: @Coach-D Practice squad serves a single purpose of a minor league system, which is to provide a readily available source of players you can easily sign to the team who you are allowed to teach your methods and get used to your coaching - so if you need to add someone quickly to fill a LB spot or something, you can do so.  That's similar to AAA in baseball where you have some "AAAA" pitchers there waiting to come up and start if you have an injury.  I don't disagree that it's very different in other ways, but it serves that purpose (more or less).
Comment: Practice squad is hardly a minor league system.  First you are covering 8 out of 24 positions at most.  Second the team really doesn't own the practice squad players.  Any team can get your practice squad player or force you to place them on the roster (which means you have to demote another player that they may claim).  I think the big issues are venues and player ages.  Your answer is solid but you have to think if football players have shorter careers, college is taking 4 out of those years, which differs in the other sports more.
Comment: Injury rates are an element of the total cost of running a team.  They're not the only reason football doesn't have a minor league, but they're one element of the totality.
Comment: I think another reason is the talent pool.  If you look at the sports that have minor leagues, they are international sports.  Baseball has many Latin American, Caribbean, and Asian players.  The NBA has players from all over the globe.  Hockey has players in many parts of Europe as well as Canada and Russia.  Soccer, obviously has players all over the world.  American football is pretty isolated to the US and Canada.
Answer: Money.
If the NFL wants a farm system and there is a good chance they will in the future they will end up footing the bill for a lot of the infrastructure/costs.
I have had offers to play in an older version of arena football and that included a per diem and $250 a game.  I am not sure most current arena league players get paid more than 20-30K a year if that.  So the choice was easy for me, stay at my tech job.  So right away to get a higher quality player the league will have to be able to pay players something more than minimum wage.  Also note that since almost all good players will opt to go to college right now (this could change) for football experience, that your player pool is 22-30 year old.  If I was 19 and was offered an arena league spot I would have taken a pack of gum.  At 24 with a real job there are ramifications to quit your job (to make practices) to make almost nothing.  Baseball and hockey have a lot of teens and very early 20s in their pool.  While football might have these ages too, the best out of this group will play at Alabama or Ohio St.
A small football team (11 on 11) would need at least 35 players to function.  This is usually the case in semi-pro leagues I have been involved in - which are nothing but regional clubs that play each other.  There are several leagues like this in the midwest.  There are "tryouts" but usually anyone is accepted at a practice given they don't get in the way.  Some teams just need warm bodies for a scrimmage.
And then a coaching staff for football is usually a lot bigger than other sports.  You would have at least a head coach, 2 assistants, and trainer on staff.  This is the bare minimum.
The only sport that comes close to football as for equipment costs is hockey.  With the concussion issues I have seen equipment prices go up 3-4 fold for organizations the past few years.  Not only is stuff more expensive but the stuff expires and has to be replaced more.
And then the biggest hurdle is facilities.  Baseball stadiums are multi-use venues, support tons of games (colleges usually share), and are not real expensive.  Hockey arenas are more expensive but offer a great fan experience with the fans sitting on top of players and the arena atmosphere support a lot of concession sales.  The NBA D-league is losing money right now but they are using shared arenas, (I have not heard of an arena being built for the sole reason of a D-league team), hardly any equipment costs, and the players make very little.
So with the costs associated the only thing that compares with football is hockey.  And hockey has three intrinsic advantages.  It has younger player pool, it has a different in-game atmosphere, and a biggie is that Canada and the northern US is hockey crazy with little competition.  (Note a fourth that was brought to my attention is that hockey rinks often are used almost 24/7 in the minors for ice time, adult leagues, ice shows, and so on)
Football will have to find some way to play games in places that fans want to visit.  Indoors would be preferable but fans and the NFL probably are going to want a standard field.  These teams really need to be in cities where there isn't great sports competition and the only venues indoors are mainly in the NFL - a few colleges might be able to help out here.  Also the intimacy of the experience is off putting 10K-15K fans in a stadium that holds 70K.  Same holds true putting the games in a college outdoor stadium.  Just no real answer for the facilities issue that a minor league football system would face and really the reason for so many minor league football failures.
The only answer is for the NFL to step in and build a few stadiums using the same kind of slow build style that has been used for soccer over the past 10 years.  In fact they might be able to use some of the newer soccer stadiums.  It is a given that a football team would start its season in the winter or spring so there is a lot of chance for sharing stadiums but even if they have shared stadiums that have little upfront money, there will be losses for years until there is a fan base to support these events.
Note: That if this happened that the NFL draft would have to have a complete overhaul.  Actually the whole player acquisition process would have to be overhauled too.  So first the draft might have to go 20+ rounds to support a team's ownership of a minor league player.  This would mimic baseball/hockey and would really be a different.
Second NFL teams rely on being able to pick up players when theirs get hurt.  A lot of times the player is on another team's practice squad.  If teams had minor league systems they would own practice squad players.  You could say that well a team should have backups on its minor league team... Well if 4 offensive guards go down, what if a team doesn't have enough?  There could be situations where a team could get a practice squad player from another team at the guard position and he is the best guard not on a roster in the NFL, but if that team had a minor league system their guard might be the 500th best not on a roster... No answer for this but this would have to be greatly changed.
Answer: The NFL used to operate its own developmental league in the USA and Europe between 1991 and 2007. It was initially called the World League of American Football with teams in both the USA (including non-NFL cities like Sacramento and San Antonio) and in Europe. After a few years during which the league was on hiatus, it returned in 1995 as an all-Europe affair. In 1998 the league changed its name to NFL Europe and operated up through 2007. The fact that the NFL currently plays one or two games in London each year is a remnant of NFL Europe.
When the league was operating and playing games in the spring and summer, NFL teams could assign several young players over to develop. While this was a good idea on paper, I remember that the players that did get sent over were generally borderline/fringe players, typically those that are cut after the final preseason game. So basically, the players who are on today's NFL practice squads are those that would have been sent to NFL Europe. The good rookies (like 1st or 2nd round picks) were kept on the NFL teams' rosters.
NFL starting quarterbacks who played in the World League/NFL Europe earlier in their careers include:

Kurt Warner (1998 with Amsterdam; NFL Pro Bowl 1999, 2000, 2001, 2008; NFL MVP 1999, 2001)
Jake Delhomme (1998 with Amsterdam and 1999 with Frankfurt, NFL Pro Bowl 2005)
Brad Johnson (1995 with London, NFL Pro Bowl 1999, 2002)
Jon Kitna (1995 with Barcelona)
Scott Mitchell (1992 with Orlando)
Comment: Also note that there was a major problem that this league faced from an owner perspective and the same one that the D-league is trying to rectify.  Since there wasn't a one-to-one relationship between NFL teams and WL there was a lot of politics and infighting on playing time and roster spots.
Answer: While I cannot elaborate directly towards your question about a farm league for the NFL, there are still many indoor and Semi-Pro leagues out there if you are interested in a side bar to lower level leagues that might interest you or others reading this great post.
Here Wiki has a great list of American Football organizations around the US and Canada that are both professional, Indoor and Semi-pro.
Read up on these leagues now, because who knows maybe the future will change and a couple of them will become farm leagues, or maybe not....
Answer: Of all college sports in the United States, football is the one that most resembles a professional league. In many ways, the NFL relies on colleges to act as their farm teams. The downside of this approach is that the teams cannot train players into their systems like European football academies tied soccer teams do. The upside is that fans pay way more attention to college football than they do baseball, hockey, or basketball's (relatively new) minor league programs. This way many football players are recognizable stars before they are even drafted by an NFL team.


JS Ajax onreadystatechange is not defined although object exists

Question: I am struggling with this for a day now, and going in circles and help would be greatly appreciated :-)
Abstract
Asynchronous ajax calling cgi with resolver and fqdn variables in order to return a dns resolution agains this pair. (returns the output of dig @resolver $fqdn)
Problem
In firebug I can see that get requests are being fired asynchronously and responses to the browser are as expected. However I cannot place the responses in correct divs in doc as onreadystatechange doesn't recognize the objects.
Side note
Apart from the fact that I am iterating through the array of objects It appears that they all are fired instantaneously even when delay between iterations is placed.

Below is a code with my comments
As resolver is an array I created an array of xmlhttprequest objects.
<code>function resolve() {
     var numofres = 6;
     var arr = new Array;
     arr[0] = "192.168.1.11";
     arr[1] = "184.108.40.206";
     arr[2] = "126.96.36.199";
     arr[3] = "184.108.40.206";
     arr[4] = "188.8.131.52";
     var len = arr.length;
     var ax  = new Array(); //creating ax as an array
     for (var i=0; i<=len; i++) {  //iterating through the length of resolvers array
         ax[i] = new XMLHttpRequest(); //assigning to each item in array new object
         //alert(ax[i]); // shows that object exists
         ax[i].onreadystatechange = function(){
              /*===
              problem is above - firebug will show:
              **Uncaught TypeError: Cannot read property 'readyState' of undefined**
              **ax.(anonymous function).onreadystatechangehello.cgi:30**
              oddly it will still populate divs inner html  with 'loading +1 '
              albeit regardless of readystate code (can be 4 or anything else )
              It perplexes me why i is thought as a function?
              =====*/
              // alert(i);  //if this is enabled I will see readyState==4 populated correctly
              if (ax[i].readyState != 4) {
                   document.getElementById('return_table_'+i).innerHTML="loading "+i;
              }
              if(ax[i].readyState == 4){
                  // get data from the server response
                  var response_ready=ax[i].responseText;
                  document.getElementById('return_table_'+i).innerHTML = response_ready;
              }
         }
         ax[i].open("GET","av.pl?resolver=" + arr[i] +"&fqdn=google.com",true); //works
         ax[i].send(null); //works
      }

 }
</code>
Answer: Your problem is an extremely common one. In JavaScript, variables are scoped at the function level, not at the block statement level.  Thus, as you iterate through that loop with the variable "i", each function you create in the loop shares the same "i".  Thus when the functions are actually called, the value of "i" will be what it is at the end of the loop — and that's a point beyond the end of the array!
To avoid the problem, you need to create those functions in another function.  A clean way to do that is to have a separate local function:
<code> function makeReadyStateHandler(i) {
     return function() {
          if (ax[i].readyState != 4) {
               document.getElementById('return_table_'+i).innerHTML="loading "+i;
          }
          if(ax[i].readyState == 4){
              // get data from the server response
              var response_ready=ax[i].responseText;
              document.getElementById('return_table_'+i).innerHTML = response_ready;
          }
     };
 }
</code>
Then just call that function from the loop:
<code>      ax[i].onreadystatechange = makeReadyStateHandler(i);
</code>
By using a separate function like that, you assure that each handler function will have its own copy of "i" that's frozen at the correct point in the loop. The function will return a newly-created function as its result, which you'll use as the event handler.
Comment: my good Sir! I thank you very much for this detailed and complete answer to my problem. The circle of doubt is broken, function works now as expected making me a happier and wiser person :-)


Post preview description eliminates BR tags in wordpress

Question: using WP, when I type in paragraph and then press "Shift Enter" it goes to new line (if we see html code, it places ). But when I see in the homepage recent posts preview short description, it shows plain text without br effect. How to tackle this issue?
Post Editor View Screenshot:
View Image 1
Preview on Homepage:
View Image 2
Answer: Add
 to your text to break text line. Learn more
Comment: i added  and many of them to test, but on homepage post description, it ommits all 's.
Comment: Are you using text editor? You could also follow [this instructions](https://blog.templatetoaster.com/wordpress-line-break-not-working/) for the problem.


How do I insert an image instead of fillOval?

Question: public void paint(Graphics g) {
    g.setColor(Color.green);
    g.fillOval(ballPosX, ballPosY, 20, 20);
}

I want to insert an image here, i.e. "ball.png" image inside a "res" folder in Java project.
How can I do this keeping all of the ball functions, like ball position and size. Just need to paste an image instead of automatically drawn circle
Comment: Use the `drawImage(...)` method of the Graphics object. It allows you to specify the location and even scale the image if required. Also for custom painting you should override the `paintComponent()` method of your JPanel or JComponent.
Comment: [2D Graphics Trail](https://docs.oracle.com/javase/tutorial/2d/index.html#:~:text=This%20trail%20introduces%20you%20to,for%20beginners%20in%20computer%20graphics.); [Painting in AWT and Swing](https://www.oracle.com/java/technologies/painting.html); [Performing Custom Painting](https://docs.oracle.com/javase/tutorial/uiswing/painting/index.html)
Answer: Try using g.drawImage() method.
Example
public void paintComponent(Graphics g) {
   g.drawImage(...);
}

You can adjust the arguments in the g.drawImage() to adjust the image drawn.
Comment: (1-) 1) that suggestion was already given an hour ago. There is no need to repeat the same advice 2) you should NOT override paint(). Again that suggestion was also given and can also be found in the tutorial links provided. Please read the tutorials.


Como incluir uma ação no botão de cadastrar com HTML5?

Question: Estou com o seguinte código:
<form action="paginas/login.php">

Usuário:
 <input id="cmpG" type="text" name="usuario"/>

Senha:
 <input id="cmpG" type="password" name="senha" size=8 maxlength=8/>

A senha deve conter 08 caracteres (alfanumerico)

        <input id="bnt" type="submit" value="Login"/>
        <input id="bnt" type="reset" value="Limpar"/>
        <BUTTON >Cadastrar</BUTTON>

</form>

Bom, não sei como fazer o botão de cadastrar, tentei com input e do tipo submit, mas ele vai para a página login.php também, como fazer com que ele vá para outra página?
Comment: E você esperava que ele fizesse o que? Ele não vai para outra página magicamente. Ou tem que estar em outro `form` ou tem que criar uma ação personalizada para ele.
Comment: Fosse para uma página `cadastro.php` mas não sei se isso é possível, estou apenas tentando fazer rs, sem referência nem nada.. A ideia seria ter duas páginas como destino para o form, se o usuário apertar o botão X ele ir para página X e se apertar Y ir para página Y, ambos passando parâmetros.
Answer: Tens duas opções:

mudar o action com JavaScript e fazer submit via JavaScript
mudar o action com o formaction adicionado no HTML5 (IE9+)

De qualquer das maneiras podes ter dois botões submit:

    <input class="bnt" name="" type="submit" value="login"/>
    <input class="bnt" type="submit" value="cadastrar"/>
    <input class="bnt" type="reset" value="Limpar"/>

Repara que mudei também id para class pois IDs têm de ser únicas.
usando JavaScript:
var form = document.querySelector('form');
var inputDiv = document.getElementById('barra');
var urls = {
    cadastrar: 'paginas/cadastro.php',
    login: 'paginas/login.php'
};
function verificarDestino(e){
    e.preventDefault();
    console.log(e.target);
    var tipo = e.target.value;
    var url = urls[tipo];
    form.action = url;
    alert(url); // só para verificar
    form.submit();
}
inputDiv.addEventListener('click', verificarDestino);

jsFiddle: http://jsfiddle.net/4zveq0y4/
usando HTML5

    <input class="bnt" type="submit" value ="Login" formaction="paginas/login.php"/>
    <input class="bnt" type="submit" value ="Cadastrar" formaction="paginas/cadastro.php"/>
    <input class="bnt" type="reset" value="Limpar"/>

jsFiddle: http://jsfiddle.net/4zveq0y4/2/
Deste modo o próprio elemento input re-escreve o action do form.
Nota:
Na minha resposta uso input mas se quiseres usar button a lógica é a mesma e o formaction usa-se da mesma maneira também.
Answer: Ou você tem que fazer:
<form action="paginas/login.php">

Usuário:
 <input id="cmpG" type="text" name="usuario"/>

Senha:
 <input id="cmpG" type="password" name="senha" size=8 maxlength=8/>

A senha deve conter 08 caracteres (alfanumerico)

        <input id="bnt" type="submit" value="Login"/>
        <input id="bnt" type="reset" value="Limpar"/>

</form>
<form action="paginas/cadastrar.php">
    <BUTTON >Cadastrar</BUTTON>
</form>

Ou usa um evento onclick para dar uma ação personalizada nele. Aproveitando seu próprio código seria algo assim:
<BUTTON onclick="window.location.href='paginas/cadastrar.php'">Cadastrar</BUTTON>

Coloquei no GitHub para referência futura.
Talvez você queira fazer de outra forma mas te dei um exemplo de forma simplificada.
Comment: Ok, entendo melhor a tua lógica. Nesse caso ele podia ter simplesmente uma âncora para a página cadastrar. Juntei à minha resposta info sobre `button` que é igual, bem visto, obrigado.
Comment: Se tiveres 2 forms ele não vai enviar os dados da outra, no segundo caso envia o form vazio.
Comment: @Sergio sim, claro, mas o que ele quer é chamar uma página de cadastro que não é o mesmo formulário mesmo. No fundo é até o mais correto. Ter um botão dentro de um `form` mas não usar os dados dele está semanticamente errado, apesar de funcionar. E o meu entendimento é este, Se ele quer enviar os dados, de fato a solução de envio baseado no `click` é a adequado, por isso eu coloquei as duas. A sua resposta, apesar de correta e mais completa, não usa o `` que é o que ele quer usar.
Comment: Concordo, mas usei o que ele queria.


Objective-C ARC block __strong __weak

Question: With ARC
test1:
@interface test01ViewController ()

@property (strong) void(^myBlock)(id obj, NSUInteger idx, BOOL stop);

@end

@implementation test01ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.navigationItem.title = @"test01";

    [self setMyBlock:^(id obj, NSUInteger idx, BOOL stop) {
        [self doSomethingWithObj:obj];
    }];
}

object (self) has an explicit strong reference to the block. And the block has an implicit strong reference to self. That's a cycle, and now neither object will be deallocated properly.
so test1 dealloc not calling.
test2:
@interface test03ViewController ()

@property (strong) void(^myBlock)(id obj, NSUInteger idx, BOOL stop);

@end

@implementation test03ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.

    self.navigationItem.title = @"test03";

    __weak test03ViewController *weakSelf = self;
    [self setMyBlock:^(id obj, NSUInteger idx, BOOL stop) {
        __strong test03ViewController *strongSelf = weakSelf;
        [strongSelf doSomethingWithObj:obj];
    }];
}

__weakSelf - > __strongSelf, I think it not difference with test1 , but test2 can calling dealloc.
Why?
Comment: in test 2: while myBlock will not be executed it will not retain self
Answer: Have a look at this answer: https://stackoverflow.com/a/28475562/543224

Anyway regarding this pattern, capturing a strong reference there doesn't do anything for the case of self getting deallocated before the block runs, that can still happen. It does ensure self doesn't get deallocated while executing the block. This matters if the block does async operations itself giving a window for that to happen.
Answer: In the first case, the block captures the variable self, which is a strong reference (i.e. it has type test01ViewController * __strong).
In the second case, the block captures the variable weakSelf, which is a weak reference (i.e. it has type test03ViewController * __weak).

Objective-C ARC block __strong __weak


Is it possible to pass the value of an Angular-generated input without an ID into a function?

Question: I'm trying to make the values of the cells in a column on a table editable. The problem is, since the table is dynamically generated using MatTableDataSource in Angular with values from an API, the cell elements can't have unique IDs. How can I make it so that on a blur (after editing and changing the value in a cell), it passes that value to a function that can then write that new value into a request to the API to update it?
Here's the HTML of the column of cells in question:

    <ng-container matColumnDef="maxInstalls">
       Max Installs

       <input type="number" min="0" value="{{profile.maximumInstalls}}">

      </ng-container>

Answer: What about
<input type="number" min="0" value="{{profile.maximumInstalls}}" (blur)="onBlu(profile)">

if you want the value of the input you need to create a reference to input and use it like below
<input #valueInput type="number" min="0" value="{{profile.maximumInstalls}}" (blur)="onBlur(valueInput.value)">

see the working example here
Comment: That only returns the object taken from the API, not the value of the input box itself. I need to know the value the user typed in before blurring their focus.
Comment: That reference made it work. Now I just have to figure out why it's sometimes marking it as an unused variable even though I use it in a function. But thanks! That answers this question.


Making up datasets with matching or distinct summary statistics

Question: 4)  Make up three data sets with 6 numbers each that have:
a)  The same mean but different standard deviations.
b)  The same mean but different medians.
c)  The same median but different means.
Can anyone tell me the procedure of finding the data sets which match the above mentioned criteria.
Comment: Is this [tag:self-study]? Please read its description in the link and add the tag if it fits. Also read the recommendations if that's the case. Otherwise ignore.
Comment: Also, your question is currently too simply worded, I'd recommend you to add more details to bring some attention to the actual issues you're facing with the question.
Comment: @Firebug thanks for the reply, let me change it a bit.
Answer: For a), an example could be
$$D_1 = (1,2,3,4,5,6)$$ $$D_2= (0,1,2,5,6,7)$$ $$D_3=(-1,0,1,3,6,12)$$
the mean is 3.5 for all three but the standard deviations differ. Can you figure out the rest?
Comment: How did you find them, I mean is there a formula or some procedure?
Comment: Just made them up! You could go by trail and error, or you could just set a mean e.g. 3.5 and set it equal to a sum of 5 numbers of your choice divided by 6 and then solve for the 6th number in the sum. In $D_1$ for example, you would have
$3.5 = \frac{1+2+3+4+5+x}{6}$. Solving for $x$ completes the dataset. Repeat two times, being careful that the numbers are 1) differently heterogeneous (different sd) 2) contain 3.5, the mean.


Right censoring in survival analysis

Question: I work with data at an union. If you are member while studying your monthly fee is 0 or a small amount depending on the type of membership. When you end your studies the fee increases significantly since you become a 'normal' member.
I'm currently doing EDA (e.g. Kaplan Meier Survival Curves) trying to figure out whether there is a relationship between e.g. age, type of membership under the studies (the free or the almost free), gender etc and the survival time af becoming a 'normal' member.
The problem is, that for many of the students they continue their study after a while hence returning to the free or low-fee membership. That of course gives extremely high survival rates (since they return to the free or low-fee membership) and make it difficult to find a significant relationship.
I have three ideas for how to deal with this, but don't know which one to those.

combining the periods if the break between studies is e.g. under 6 months

censoring them when they return to their studies

only use the last of the periods they study

What is pros and cons for each approach? I want to get it right from the start to avoid any p-hacking. Any thoughts or reference to good resources is appreciated.
Comment: If you can move back from the 'dead' state to the 'alive'  one, survival analysis is not a suitable tool.
Answer: As @Glen_b noted in a comment, a simple survival model isn't appropriate for this type of data, in which the state of an individual can switch back and forth over time.
There are, however, extensions of simple survival models to multi-state models that can handle your data. This vignette of the R survival package provides a useful introduction. Those tools allow you to model transitions between "student" and "normal" membership in both directions, along with transitions out of the union completely as a terminal event.

Right censoring in survival analysis


How can I do a global Model afterSave() on Cake?

Question: How can I do a global Model afterSave() on Cake? I want to do some things right after a save is done.
Thanks,
Gino
Answer: Put it in your AppModel (and extend your models from that). Check out the CookBook on models


Elisp - Avoid prompt in interactive function

Question: I'm trying to call the following org-mode function to insert the current timestamp in the buffer. The function is called by a script.
(org-time-stamp-inactive)

This, as expected, brings up a prompt asking for the date to use for the timestamp. But I want to skip the prompt and insert the timestamp directly. Is that possible at all? Haven't found anything that could help me.
Comment: FWIW, the Org code here does not look wonderful. It should be possible (easy) to use such a function non-interactively. And the doc is also not up to par. The doc for such commands should say clearly that it prompts the user. And it should of course *describe each parameter*. If I were an Org user I would submit a bug report...
Comment: Check the documentation, and see if it takes the timestamp as an argument. Then pass the argument: `(org-time-stamp-inactive your-time-stamp)`
Comment: It looks like it doesn't, so I guess it's a dead end.
Answer: org-time-stamp unconditionally¹ calls org-read-date to prompt the user for a date. You can't pass a date. But you can locally bind org-read-date to a function that returns the date that you want to use.
(require 'cl)
(flet ((org-read-date (org-with-time &rest args)
         (format-time-string (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d")
                             (current-time))))
  (org-time-stamp-inactive with-time))

¹  Except sometimes when there is already a time stamp, but that's no help.
Comment: Interesting approach. But flet isn't defined on my emacs for some reason :/
Comment: @fullmontis Oh, yes. `flet` is part of the `cl` library which you need to load explicitly. It's bundled with Emacs.
Comment: @fullmontis `with-time` comes from the part of your script that you haven't shown. It's whatever you're passing as the argument to `org-time-stamp-inactive`.
Comment: Note that `cl` and thus `flet` are obsolete, and superseded by `cl-lib`.  Modern Emacs Lisp code should use `cl-lib` with [Generalized Variables](https://www.gnu.org/software/emacs/manual/html_node/elisp/Generalized-Variables.html) to make temporary function overrides, i.e. bind the `symbol-function` cell with `cl-letf` ([example](https://github.com/rejeep/shut-up.el/blob/bafd5be3a6edb20fa9022b496a42f06f3d85748b/shut-up.el#L114)).
Comment: @lunaryorn Emacs 23 (which doesn't have `cl-lib`) is far from obsolete.
Comment: @Gilles I'd consider Emacs 23 as obsolete, but YMMV obviously.  In any case, I was obviously talking about the state of affairs in the latest stable release and upcoming Emacs 24.4.  Code for older Emacs versions is not exactly "modern", is it?
Comment: @lunaryorn There's a difference between modern and obsolete. Unless the question calls for it, I normally write answers that are useful to people out there right now. Many existing systems still run Emacs 23, for example Debian stable, RHEL/CentOS, and I think OSX if not using an external package source. Ubuntu LTS switched last month. It takes years for a software version to become obsolete — most users don't upgrade often. Given that `cl` still works in Emacs 24 and that its sole defect is the imperfect compatibility with Common Lisp, there's no urgency to stop using it.
Answer: This should insert the current inactive time stamp:
(org-insert-time-stamp nil nil t)

Comment: Thank you, this works. I've used the following to insert a timestamp with the current time too.
    (org-insert-time-stamp nil t t)
Answer: I ended up creating the timestamp from scratch with the following call:
  (insert (format-time-string "[%Y-%m-%d %a]"))

Comment: Exactly what I was looking for, thanks!
Answer: You can find the answer in documentation for similar function (org-time-stamp)

[...] With two universal prefix arguments, insert an active timestamp
  with the current time without prompting the user. [...]

So.. all you need to do is press C-u C-u before you invoke the function (for example C-u C-u M-x org-time-stamp-inactive RET)
Comment: I know that :) But I don't know how to do this when calling the function from a script. And I also wanted to know if it is possible more in general to avoid prompts in interactive functions.
Comment: Oh, OK. I'm not sure if there's a more general way of doing it, but there's a quic hack if you want to avoid having to insert universal argument: `(defun my-org-time-stamp ()
  (interactive)
  (let ((current-prefix-arg '(16)))
    (call-interactively 'org-time-stamp)))` This would also work in a script.
Comment: To insert inactive timestamp the last call in that function should be `(call-interactively 'org-time-stamp-inactive)`
Comment: no dice, still inserts the timestamp as active. I guess it's a bug. Oh well, thanks anyway :)
Comment: IIRC that bug was fixed a few weeks ago. At least I reported a very similar one. Anyway, using `(org-time-stamp-inactive '(16))` should be (almost) equivalent to the let form above.


Q: Ngrok configure file not found

Question: I want to open 2 ports by ngrok. first I started ngrok HTTP 80 worked ok. but when I try to open another ngrok TCP 443 the result
Tunnel session failed:

Your account 'USERNAME' is limited to 1 simultaneous ngrok client
  session. Active ngrok client sessions in region 'us':
    - 806d84d5e153ff13136eddee04de8157 (x.x.x.x)
ERR_NGROK_108

I found one solution but I don't know to configure ngrok.yml for the tunnel .
I couldn't find the file ...help me please
Answer: In GUI Files:

Open Home Folder
Press Ctl + H
In search box type "ngrok"
directory will apear in first place
double click on .ngrok2

In Ternminal:

cd home
cd user
ls -a
cd .ngrok2
emacs ngrok.yml
Answer: It would help to confirm that you have created an account first. Once you have an account you would be given an authtoken running this command
./ngrok authtoken <your-auth-toke>

or
ngrok authtoken <your-auth-toke>

would create both the .ngrock2 folder and the config file.
This is what worked for me.
Answer:
An ngrok account is limited in how many agents it can simultaneously run. This limit is listed for each plan as "online ngrok processes" on the pricing page. This error indicates you've exceeded that limit.
https://ngrok.com/docs/errors/err_ngrok_108

You may need to upgrade your plan, or email email@example.com.

I had a simmilar problem, and:
ngrok config upgrade

Worked for me

Q: Ngrok configure file not found


É possível adicionar o Expo à um projeto existente?

Question: Gostaria de saber se é possível adicionar o Expo à um projeto React Native que já existe.
Na documentação do Expo só encontrei para criar um projeto do zero.
Answer: Infelizmente não é possível, pois o Expo te oferece todo um workflow em um ambiente de desenvolvimento um pouco diferente que o react-native-cli. Tanto é que uma vez que o projeto for ejetado do Expo (expo eject) você terá de criar um novo projeto com Expo (expo init) para desenvolver.


Trabalhando com array com X camadas em JS

Question: Estou com um grande problema, já pesquisei em diversos lugares e não achei a solução espero que vocês possam me ajudar...
Meu objetivo é criar uma função em JS que vai pegar um array como base, que aqui vou chamar de "A" a estrutura dele é essa:
var A = {
        a1: {
            c1: 50,
            c2: 50,
        },
        b1: {
            d1: 0,
            d2: [1 => "hello"],
            d3: [2 => "world"],
        }
    };

A função vai receber outro array, que vou chamar de "B", segue a estrutura dele:
var B = {
        a1: {
            c1: 1,
            c2: 125,
        },
    };

Após o array "B" passar pela função ele deve "sair" com a estrutura idêntica ao do "A" e com os valores que faltava no "B" idênticos ao do "A", ou seja:
Array "B" após passar pela função:
var B = {
        a1: { /* índice que já existia no array "B" */
            c1: 1, /* índice e valor que já existia no array "B" */
            c2: 125, /* índice e valor que já existia no array "B" */
        },
        b1: { /* índice que NÂO existia no array "B" e como o array "A" é a base foi criado esse índice no array "B" */
            d1: 0, /* índice e valor que não existia no array "B", é a mesma história do b1 aqui em cima */
            d2: [1 => "hello"], /* mesmo caso dos outros dois acima */
            d3: [2 => "world"], /* mesmo caso dos outros três acima */
        }
    };

Digamos que até ai tudo bem, minha grande questão é, eu tenho o array "A" como base, quando eu querer modificar a estrutura do "A" digamos adicionar mais um nível nele como no exemplo:
var A2 = {
        a1: {
            c1: 50,
            c2: 50,
        },
        b1: {
            d1: 0,
            d2: [e1 => "hello"],
            d3: [
                   f2 => "world",
                   f3 => [
                            g1 => "nova",
                            g2 => "camada"
                         ]
                ],
        }
    };

Do jeito que eu imaginei até agora esse script iria dar erro se eu fizesse isso e é óbvio que eu não quero que isso aconteça, o que eu realmente quero é que o array "B" ao passar pela função, também receba a nova camada...
Já comecei a fazer esse código porém não consigo terminar por causa dessa maldita dúvida.
Código que já desenvolvi http://jsfiddle.net/mateusfmello/mja8ffs2/7/
Comment: Olá Mateus! Acho que estás a chamar aray a objetos. Esta sintax `d2: [e1 => "hello"],` não é de JavaScript. Queres dizer `d2: {e1: "hello"},`?
Comment: Exatamente, vou corrigir... Obrigado pela observação... Você sabe como eu posso resolver essa questão?
Comment: Agora me veio outra questão, o que usar? arrays ou objetos? o que vc sugere?
Comment: Para o exemplo que tens parece-me que objetos é melhor. Vou então dar uma olhada e já comento. Uma pergunta: esses objetos têm só strings e numeros dentro deles? ou elementos do DOM e outros?
Comment: Pode ter números, strings e objetos... A grande questão é o objetos... Você chegou a dar uma olhada no código que esta no jsfiddle?
Comment: Sim, ví o jsFiddle. Já vou responder (se ninguém fôr mais rápido que eu) mas queria saber mais informação para dar a resposta certa.
Comment: Ultima pergunta: dizes "Pode ter números, strings e objetos" eu queria saber se esses objetos têm algo do DOM?
Comment: Não vai conter, porém vai resultar gráficos em canvas... os dados que vai ser passado para a função é os dados do canvas...
Answer: Uma parte importante é usares uma função que tenha um interface claro. Ou seja essa função deve ter como função/ordem comparar o que lhe é dado e mais nada.
Assim sugiro algo assim:
function completarObjetos(original, aCompletar) {
    function dup(o) {
        return JSON.parse(JSON.stringify(o));
    };

    for (var key in original) {
        var obj = original[key];
        var aC = aCompletar[key];
        if (aC) {
            if (dup(aC) == dup(obj)) continue;
            else aCompletar[key] = completarObjetos(obj, aC);
        } else {
            aCompletar[key] = dup(obj);
        }
    }
    return aCompletar;
}

Usando a lógica da função dup() podes clonar partes internas do objeto original e também comparar objetos via sua representação string poupando mais iterações nos sub-objetos de cada um quando isso não é necessário.
jsFiddle: http://jsfiddle.net/m4jqcvx0/1/
Comment: @falsarella eu estava a pensar em objetos que no caso passariam por referência. Mas podem ser strings... bem visto, obrigado. Corrigi.
Comment: Cara é isso ai mesmo, vlw, funcionou certinho... eu sou novo por aqui, e minha reputação é baixa, mas assim que tiver mais de 15 eu volto e dou um voto na tua resposta...
Comment: Sergio, `aC = completarObjetos(obj, aC);` não deveria ser `aCompletar[key] = completarObjetos(obj, aC);`?
Comment: @MateusFernandesdeMello ótimo que ajudou. Bemvindo! Se quiseres podes marcar a resposta como aceite. Independentemente da reputação.
Comment: Blz, já marquei...
Answer: Em determinadas estruturas dos objetos a função entrava em loop infinito, devido isso fiz uma pequena alteração e venho compartilhar com vocês
Em
 else aC = completarObjetos(obj, aC);

eu adicionei a seguinte verificação else if (typeof obj == "object") aC = comple... dessa forma não ocorre mais o loop infinito.
Como ocorria o loop infinito? Quando o for (var key in original) { terminava de percorrer toda estrutura assim chegando no último valor, a variável key virava uma string com o valor 0 (zero) e com isso toda vez que passava na verificação if (dup(aC) == dup(obj)) dava como false, pois aC retornava M, pois var aC = aCompletar[0]; sendo assim pegava a primeira letra do nome Mateus e obj retornava w, pois var obj = original[0]; sendo assim pegava a primeira letra do nome world, lembrando que isso ocorria no último loop, estando em
 d3: {
     2: "world"
 },

e como a verificação if (dup(aC) == dup(obj)) retornava false o código executado era o else aCompletar[key] = completarObjetos(obj, aC); assim chamando milhares de vezes a mesma função e ocorrendo a mesma coisa sempre.
Códigos: http://jsfiddle.net/mateusfmello/m4jqcvx0/4/
Remova if (typeof obj == "object") da linha 44 e agora adicione
console.log(key);
console.log(typeof key);

na linha 38, abra o console do seu browser (F12), execute o código clicando em "Run" e observe o erro...
Answer: acabei de achar o que eu queria, $.extend(true, param1, param2);, porém depende do jQuery.
Funciona da seguinte forma, o true informa que queremos adicionar os dados do param2 no param1 de forma recursiva, como já podemos observar parece que param2 tem todos os dados e em param1 que poderia estar faltando, mas não é bem assim,  o param1 seria o objeto que você tem todos os dados seria no caso o default, por tanto, o param2 é o parâmetro que ira passar novos dados, ou então personalizar os dados do param1.
Espero que gostem :D
Documentação: http://api.jquery.com/jquery.extend/


Making Panel-Col-last the first

Question: I have a 2-column panel (Regular, not stacked). I've made it responsive and it appears allright in mobile view @media screen and (max-width: 519px) {width: 100%;}.
The only problem is that my site is a Right to left one, and therefore, What you guys call "Panel-col-first" appears last in mobile view and it's seems Illogical... What is the way to change it, specifically for that particular panel?
Btw, CSS games (Float) didn't help one bit, so I'm looking for a another way, may it be customization of other files.
Comment: No one knows how to solve it?
Comment: check this jsfiddle, found on stackoverflow: http://jsfiddle.net/brettdewoody/3s3uc/

Link to answer: http://stackoverflow.com/a/21841999/594897
Comment: Trust me, I need a way to change how the module itself works... I just don't have the needed knowledge in PHP to do so and I'm looking for more of a "recipe" Of what to change, So I'll shell mark it up for next occasions...
Answer: The control over the Panel-col's (Panel columns) can be maid manually via the relevant TPL file (each one of the natural Panels' layouts has it's own TPL).
The TPL files are stored at sites\all\modules\panels\plugins\layouts. Check there for the layout you use for your panel.
At my case, I've edited the layout "twocol". It's TPL is inside it's directory (also named "twocol").
There I've changed:

<?php print $content['left']; ?>

<?php print $content['right']; ?>

To:

<?php print $content['right']; ?>

<?php print $content['left']; ?>

After I did this flip, I still haven't seen the change in responsive mode... This is because a change had to be made in the CSS file also... The CSS change is basically comprised of a float: change, and a media screen and () change. Inspect each Panel-pane to get more info on the float and width and then make these, and any other needed changes, in the CSS file.
This manual editing seems to me to be the only way for RTLization\flipping the layouts. I hope the developers of the module would make a more "friendly" option for RTLization.
Note: Better make a backup of the edited versions of your files and store them outside the sites\all\modules\Panels folder - This could save time in case a Panels update would delete them; Even though this action is relatively short.

Making Panel-Col-last the first


Send and Receive json data from api

Question: I need to send some json data to a url and receive its json response. I am not so good at json, and i searched and found the following code
<code><?php
$json_data = array(
'partnerid' => '123',
'outletid' => '321',
'mobile' => '0123456789',
'secret' => 'qwert',
'amount' => '100',
);

$json = json_encode($json_data, true);

$req_url = "https://myapiprovider.com/api/requestdata";

//send json request
//Initiate cURL.
$ch = curl_init($req_url);
//Tell cURL that we want to send a POST request.
curl_setopt($ch, CURLOPT_POST, 1);
//Attach our encoded JSON string to the POST fields.
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
//Set the content type to application/json
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
//Execute the request
$result = curl_exec($ch);

//receive json response
$content = file_get_contents($req_url);
//Make sure that it is a POST request.
if(strcasecmp($_SERVER['REQUEST_METHOD'], 'POST') != 0){
throw new Exception('Request method must be POST!');
}

//Make sure that the content type of the POST request has been set to application/json
$contentType = isset($_SERVER["CONTENT_TYPE"]) ? trim($_SERVER["CONTENT_TYPE"]) : '';
if(strcasecmp($contentType, 'application/json') != 0){
throw new Exception('Content type must be: application/json');
}
//Receive the RAW post data.
$content = trim(file_get_contents("php://input"));
//Attempt to decode the incoming RAW post data from JSON.
$decoded = json_decode($content, true);
//If json_decode failed, the JSON is invalid.
if(!is_array($decoded)){
throw new Exception('Received content contained invalid JSON!');
}
//Process the JSON.
?>
</code>
I get the following exception 'Content type must be: application/json'. Why? I have set the content type to application/json. right? Please help immidiate.
Comment: What is response content type ? value of `$contentType` ?
Comment: $contentType is application/x-www-form-urlencoded
Comment: Instead of reading from php input. You can try to get from `$_POST`.
`curl_setopt($ch, CURLOPT_POSTFIELDS,array('json'=>$json));`
And you can get result in `$_POST['json']`
Answer: <code>$json_data = array(
'partnerid' => '123',
'outletid' => '321',
'mobile' => '0123456789',
'secret' => 'qwert',
'amount' => '100',
);

$json = json_encode($json_data, true);
$req_url = "https://myapiprovider.com/api/requestdata";

$curl = curl_init();
curl_setopt ($curl, CURLOPT_URL, $req_url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, count($json));
curl_setopt($curl, CURLOPT_HTTPHEADER, array("Content-Type: application/json"));
curl_setopt($curl,CURLOPT_POSTFIELDS, $json);
$result = curl_exec($curl);
curl_close($curl);
$result = json_decode($result);
</code>
Comment: Please provide your api url

Send and Receive json data from api


Como determinar o número de arestas do radarchart?

Question: Estou usando RadarChart do Chart.js.
Tenho esse Fiddle funcionando.

Vejam que neste exemplo o gráfico é montado dinamicamente de acordo com os dados inseridos.

Bem, mas eu gostaria de determinar a quantidade de arestas geradas, independente dos valores, ou seja, ao invés das 4 arestas que foram geradas no Fiddle, eu gostaria de 10 arestas. O resultado ficaria como na imagem:

Além das arestas, existe alguma forma de acrescentar legenda tanto para as linhas quanto para os itens no gráfico?

Apesar da documentação e outras configurações disponíveis, infelizmente não sou tão bom em inglês, e mesmo usando o Translate e fazendo tentativa e erro não consegui obter o resultado tão requerido.
 Salve Stackoverflow em Português!
 Alguém poderia me ajudar?
Answer: Consegui tudo nesse Fiddle. Tentativa e erro.

Segue o código completo:

var radarChartData = {
  labels: ["Eating", "Drinking", "Sleeping", "Designing"],
    datasets: [
   {
    label: "My First dataset",
    fillColor: "rgba(220,220,220,0)",
    strokeColor: "rgba(220,220,220,1)",
    pointColor: "rgba(220,220,220,1)",
    pointStrokeColor: "#fff",
    pointHighlightFill: "#fff",
    pointHighlightStroke: "rgba(220,220,220,1)",
    data: [2,2,2,2]
   },
   {
    label: "My Second dataset",
    fillColor: "rgba(151,187,205,0)",
    strokeColor: "rgba(151,187,205,1)",
    pointColor: "rgba(151,187,205,1)",
    pointStrokeColor: "#fff",
    pointHighlightFill: "#fff",
    pointHighlightStroke: "rgba(151,187,205,1)",
    data: [8,8,8,8]
   }
  ]
 };

 window.myRadar = new Chart(document.getElementById("canvas").getContext("2d")).Radar(radarChartData, {
            responsive: true,
        //scaleShowLabels : true,
        animationSteps: 80,
        animationEasing: "easeOutQuart",
        scaleOverride: true,
        scaleSteps: 10,
        scaleStepWidth: 1,
        scaleStartValue: 0,
        angleShowLineOut : false,
        scaleLineColor: "rgba(0, 0, 0, 1)",

        legendTemplate : '<% for (var i=0; i<datasets.length; i++) { %>'
                    +'<h3 style=\"color:<%=datasets[i].strokeColor%>\">.'
                    +'<% if (datasets[i].label) { %><%= datasets[i].label %><% }%>'
                +'<% } %>
'
        });

document.getElementById("legendDiv").innerHTML = window.myRadar.generateLegend();
#canvas-container {
        width: 100%;
        text-align: center;
    }

    canvas {
        display: inline;
    }

            <canvas id="canvas"></canvas>

Para a maioria das opções, usei as configurações globais.

Na questão de uma escala estática, basta mudar a opção scaleOverride que por padrão vem false para true, e isso te obrigará a especificar alguns outros valores, como scaleSteps (Até onde vai a sua escala? no meu caso 10, então scaleSteps = 10), scaleStepWidth (de quanto em quanto será incrementado, no meu caso 1 em 1), e por ultimo scaleStartValue que determina o valor de partida.

Para a legenda, me baseei nessa resposta, onde apenas alterei no legendTemplate lineColor para strokeColor, pois o link em questão resolve o problema para outro tipo de gráfico.


Want to insert XML elements at particular position in XML file

Question: I have a XML file like this
<RoadPart>
    <Vehicles>
                <ConfigurationSummaryListPosition>
                  <ConfigurationSummary>Test name</ConfigurationSummary>
                </ConfigurationSummaryListPosition>
    </Vehicles>
    <Vehicles>
                <ConfigurationSummaryListPosition>
                  <ConfigurationSummary>Test name</ConfigurationSummary>
                </ConfigurationSummaryListPosition>
    </Vehicles>
    <Vehicles>
                <ConfigurationSummaryListPosition>
                  <ConfigurationSummary>Test name</ConfigurationSummary>
                </ConfigurationSummaryListPosition>
    </Vehicles>
</RoadPart>

I want to insert below part at a position i wish in above XML.
<Vehicles>
            <ConfigurationSummaryListPositionTest>
              <ConfigurationSummary>Test name</ConfigurationSummary>
            </ConfigurationSummaryListPositionTest>
</Vehicles>

Suppose i want to insert Vehicles element at 2nd position then result will be as follows:
<RoadPart>
    <Vehicles>
                <ConfigurationSummaryListPosition>
                  <ConfigurationSummary>Test name</ConfigurationSummary>
                </ConfigurationSummaryListPosition>
    </Vehicles>
    <Vehicles> // My inserted data
                <ConfigurationSummaryListPositionTest> // My inserted data
                  <ConfigurationSummary>Test name</ConfigurationSummary> // My inserted data
                </ConfigurationSummaryListPositionTest> // My inserted data
    </Vehicles> // My inserted data
    <Vehicles>
                <ConfigurationSummaryListPosition>
                  <ConfigurationSummary>Test name</ConfigurationSummary>
                </ConfigurationSummaryListPosition>
    </Vehicles>
    <Vehicles>
                <ConfigurationSummaryListPosition>
                  <ConfigurationSummary>Test name</ConfigurationSummary>
                </ConfigurationSummaryListPosition>
    </Vehicles>
</RoadPart>

How to insert vehicle element part at specific position help me.
Comment: Do you use XDocument or XmlDocument?
Comment: I am using XDocument
Comment: Possible duplicate of [Inserting XML node at specific position](http://stackoverflow.com/questions/10578983/inserting-xml-node-at-specific-position)
Answer: If you know the element after what you want to place a new one than use XDocument.AddAfterSelf Method (MSDN). Or XDocument.AddBeforeSelf to place before the given element.
Answer: Try this:
XElement root = XElement.Parse(@"
    <RoadPart>
        <Vehicles>
            <ConfigurationSummaryListPosition>
                <ConfigurationSummary>Test name</ConfigurationSummary>
            </ConfigurationSummaryListPosition>
        </Vehicles>
        <Vehicles>
            <ConfigurationSummaryListPosition>
                <ConfigurationSummary>Test name</ConfigurationSummary>
            </ConfigurationSummaryListPosition>
        </Vehicles>
        <Vehicles>
            <ConfigurationSummaryListPosition>
                <ConfigurationSummary>Test name</ConfigurationSummary>
            </ConfigurationSummaryListPosition>
        </Vehicles>
    </RoadPart>
");
XElement toAdd = XElement.Parse(@"
    <Vehicles>
        <ConfigurationSummaryListPositionTest>
            <ConfigurationSummary>Test name</ConfigurationSummary>
        </ConfigurationSummaryListPositionTest>
    </Vehicles>
");
root.Elements().Skip(1).First().AddBeforeSelf(toAdd);

//Alternatively
root.Elements().Take(1).Last().AddAfterSelf(toAdd);

To insert multiple elements, each one with its own index:
(As you haven't shown how your indexes map to the elements to insert, I'll assume a Dictionary<int,XElement>.)
var dict = new Dictionary<int, XElement>() {
    {3, XElement.Parse("<Inserted id=\"1\" />")},
    {1, XElement.Parse("<Inserted id=\"2\" />")}
};

//We need parse the elements to insert in descending order, or else the indexes
//will be affected by previous insertions
foreach (var kvp in dict.OrderByDescending(kvp => kvp.Key)) {
    if (kvp.Key == 0) {
        root.AddFirst(kvp.Value);
    } else {
        root.Elements().Take(kvp.Key).Last().AddAfterSelf(kvp.Value);
    }
}

Note: this will crash on a non-existent index.
Comment: If i have a list that contains index where to insert vehicle elements in XML file then how i do this dynamically.
Comment: @TejasThakor The list you are using should be part of your question.
Comment: @TejasThakor Do you want to insert the same element multiple times, or different elements each time? If different elements, how are the indexes mapped to the appropriate elements?
Comment: I want to insert different element every time, every time i have to insert element at some index position in XML.For example if i want to insert element in between then?


Will pyspark inner join keep duplicates in the first dataset in the following example?

Question: So, I have the following two dataframes:
DF1 looks like following:
+---------+-----------+
|  Name   |   Money   |
+---------+-----------+
|    A    |   50.3    |
|    B    |   26.9    |
|    C    |   11.4    |
|    A    |   35.8    |
|    B    |   59.2    |
|    A    |   90.8    |
|    C    |   23.5    |
|    D    |   23.5    |
|    D    |   54.6    |
|    E    |   78.0    |
|    A    |   12.3    |
|    F    |   20.3    |
|    A    |   57.1    |
+---------+-----------+

DF2 looks like following (list of unique names):
+---------+
|  Name   |
+---------+
|    A    |
|    C    |
|    D    |
+---------+

What kind of join will give me the following (only keeping A, C and D that appear in DF2):
+---------+-----------+
|  Name   |   Money   |
+---------+-----------+
|    A    |   50.3    |
|    C    |   11.4    |
|    A    |   35.8    |
|    A    |   90.8    |
|    C    |   23.5    |
|    D    |   23.5    |
|    D    |   54.6    |
|    A    |   12.3    |
|    A    |   57.1    |
+---------+-----------+

Answer: A simple inner join should solve your problem. Since you want only the values that are matched in both dfs, inner join will keep only the matched keys between the DF's.
df = df1.alias("t0").join(
        df2.alias("t1"),
        on=f.col("t0.Name") == f.col("t1.Name"),
        how='inner'
    ).select(
        f.col("t0.Name"),
        f.col("t0.Money")
    )

Comment: Your answer could be improved by adding more information on what the code does and how it helps the OP.
Answer: imo simple inner join will be ok here, it is going to filter records from df1 with names which do not exists in df2 which is what you expect

df1.join(df2,d1("name") ===  d2("name"),"inner")

In the title you asked about duplicates, duplicated record are going to stay there after inner join, if you want to remove them you can use distinct
you can find sample inner join below (inner is default type of join in Spark and that's why i just could skip 3rd parameter here)
Answer: What you need is a LEFT SEMI join, which is really the equivalent of doing the SELECT * FROM df1 WHERE df1.Name IS IN df2.Name - in PySpark code, it will look like this:
df1 = spark.createDataFrame([("A", 50.3), ("B", 26.9), ("C", 11.4), ("A", 35.8), ("B", 59.2), ("A", 90.8), ("C", 23.5), ("D", 23.5), ("D", 54.6), ("E", 78.0), ("A", 12.3), ("F", 20.3), ("A", 57.1)], "Name: string, Money: double")
df2 = spark.createDataFrame([("A",), ("C",), ("D",)], "Name: string")

df1.join(df2, "Name", how="left_semi").show()
+----+-----+
|Name|Money|
+----+-----+
|   A| 50.3|
|   A| 35.8|
|   A| 90.8|
|   A| 12.3|
|   A| 57.1|
|   C| 11.4|
|   C| 23.5|
|   D| 23.5|
|   D| 54.6|
+----+-----+

You can read more in PySpark Docs


Pass Bash flags and commands

Question: I'd like to be able to run flags and commands something like:
bash script.sh -c flag1 -b flag2 command1 command2

Some more real examples:
e.g.1 bash oneScript.sh -p password -u user list images
e.g.2 bash oneScript.sh -u user list images (ask for password while running the script) ...
e.g.3 bash oneScript.sh -p password delete files (ask for user while running the script) ... another command, not listing but deleting)

How can I do something like this in bash scripts?
I'd like to be able to add some extra flags (or not) if the user wants but after the flags I'd like to add some commands that can be read in the script
Any idea please?
Regards,
Comment: Have you looked into the `getopts` builtin?
Comment: Yes ... but this is not enough
Answer: I think I founded an answer:
While I'll have flags like:
# Way to force the branch version
seed="true" # set default to true
while getopts 'bc:hp:o:s:t:u:v:' flag; do
    case "${flag}" in
        b) backup="true" ;;
        c) configFile="${OPTARG}" ;;
        h) export helpMenu="true" ;;
        p) rootPassword="${OPTARG}" ;;
        s) seed="${OPTARG}" ;;
        t) restoreTag="${OPTARG}" ;;
        u) upgradeTo="${OPTARG}" ;;
        v) versionNumber="${OPTARG}" ;;
        *) echo "blabla" ;;
    esac
done

I can also have something like this:
args=("$@")
ELEMENTS=${#args[@]}
_option=""
_command=""
for (( i=0;i<$ELEMENTS;i++)); do
    if [[ "${args[${i}]}" == "restore" || "${args[${i}]}" == "list" || "${args[${i}]}" == "backup" ]]; then
        _option="${args[${i}]}"
        value=$((i+1))
        _command=${args[${value}]}
    fi
done

So ... now I should be able to do:
bash script.sh -p password -t 0 list images

Comment: I think you could use the `$OPTIND` parameter to shift your flags away after you've processed them instead of re-building your non-option arguments array, see [this example](https://mywiki.wooledge.org/BashFAQ/035#getopts).
Comment: Good stuff, seems like you have solved your own problem! Be sure to accept your answer (unless someone posts something better). You have to wait ~48 hrs to accept. BUT ... if you're testing `"${args[${i}]}"` each time in the mile-wide `if ` test, you already know about `case`, it seems that it the easier to read solution. But maybe there is something there I'm missing. You know your problem better than I do ;-) Good luck.

Pass Bash flags and commands


Python 3: List inside dictionary, list index out of range

Question: I have created a dictionary where the entries are lists like this:
new_dict
{0: ['p1', 'R', 'p2', 'S'], 1: ['p3', 'R', 'p4', 'P'], 2: ['p5', 'R', 'p6', 'S'], 3:   ['p7', 'R', 'p8', 'R'], 4: ['p9', 'P', 'p10', 'S'], 5: ['p11', 'R', 'p12', 'S'], 6: ['p13', 'S', 'p14', 'S']}

From here I am trying to check that the elements inside the lists are in my list below Moves. For example, in new_dict[0], I want to check that the 1st element and the third element in Moves, if not, raise the class exception. (This is a snippet of the code.)
class NoStrategyError(Exception): pass

j=0
while j < len(new_dict):
    i = 0
    while i < 4:
        # Write the code for the NoSuchStratgyError
        Moves = ['R', 'S', 'P', 'r', 's', 'p']
        if new_dict[j][1+4*i] not in Moves or new_dict[j][3+4*i] not in Moves:
            raise NoStrategyError("No such strategy exists!")
        i+=1
    j+=1

Now here is the problem, when I run this, I get the following error:
if new_dict[j][1+4*i] not in Moves or new_dict[j][3+4*i] not in Moves:
IndexError: list index out of range
What does this mean?
Is there a better way to write the inner while loop? And change it instead to a for loop? Something like, for elem in new_dict[j]?
Comment: May be helpful: http://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized-chunks-in-python
Comment: Your lists have a maximum of 4 elements, but `1 + 4 * i` goes from 1 to 13.
Comment: I just realized it. I don't need that inner `while loop`. Phew!
Comment: Also, why are you using a dictionary with consecutive integer keys instead of a list?
Comment: The keys represent the n-th game played. But really, it was also because I had to regroup a flattened list by fours. I didn't know how to do that without using a dictionary.
Answer: Notice that in the first interation of your nested loop, we see the following values that are both in Moves:
>>>new_dict[0][1], new_dict[0][3]
('R', 'S')

However, on your second iteration in the nested loop, you are trying to evaluate terms that are not included in the dictionary:
>>>new_dict[1][5], new_dict[1][7]
IndexError: list index out of range

Notice that new_dict[1] only has 4 elements:
>>>new_dict[1]
['p3', 'R', 'p4', 'P']

So you can only reference new_dict[1][0],new_dict[1][1],new_dict[1][2],new_dict[1][3]:
>>>new_dict[1][0],new_dict[1][1],new_dict[1][2],new_dict[1][3]
('p3', 'R', 'p4', 'P')


"Quantize" when rounding numbers Python 3.2

Question: I'm trying to find a way to snap or quantize numbers to specific values after a math operation and don't really know the best way to approach the problem.
A specific example:
I have a list of numbers that I want to be my master numbers - 5, 10, 30, 60, 120, 180
I have a list of numbers that are currently inputted - 10, 20, 60, 120
Now I want to multiply all the inputted numbers by 2, and have them snap (or quantize/get rounded to) the nearest of my master numbers.
So a number like 10, once multiplied by two, I'd like to have it snap to 30. I dont think it's a big problem for the top or bottom because I think I can use math.ceil and math.floor to contain the ends. Similarly I'd like 20 to be rounded to 30 as well (20*2=40, rounded down as 30 is closer than 60).
I saw a similar question in regards to rounding to 10s, 100s, etc, but can't really figure out how to apply the answer there, as I'm still relatively new! : )
Comment: No really, for `10` both 10 and 30 are possible - `10*2` = 20. `abs(20 - 10)` = 10. `abs(20-30)` = 10. Which one do you want?
Comment: Would be a fun exercise for a modified binary search ..
Comment: for `10` as input both 10 and 30 are possible?
Comment: Sorry if that was confusing. To elaborate on the example, the user would input 10, and it would be passed through the program as 10, unless the user activates the "Multiplication" button in this case, in which it multiplies all incoming values by 2. But the problem is that the program can only run with certain values given (the master numbers), and 20 wouldn't be one of them, so I'd like to round it to 30, which would be the closest.
Answer: Use the bisect module to quickly pinpoint the desired quantity:
import bisect

def quantize(num, quant):
    mids = [(quant[i] + quant[i + 1]) / 2.0
            for i in xrange(len(quant) - 1)]
    ind = bisect.bisect_right(mids, num)
    return quant[ind]

quantnum = [5, 10, 30, 60, 120, 180]

inputnum = [10, 20, 60, 120]

for n in inputnum:
    print quantize(2 * n, quantnum)

# Output:
#30
#30
#120
#180

Midpoints are rounded to the larger quantity; change bisect_right to bisect_left to round to the smaller one instead.
For simplicity, this implementation recreates the mids list each time it is called. An efficient implementation would reuse the midpoints, and would run with O(log n) worst-case complexity.
Comment: Awesome. Thanks so much, was simple enough for me to tweak and implement quickly into my program! Cheers!
Comment: @ElburzSorkhabi: The `bisect` module is written in pure python. Go ahead and take a look at it if you want to see how the code works.
Comment: Thanks for the tip, I'll definitely be reading more about it shortly, seems extremely useful.
Answer: For element x of input find the absolute difference of x*2 with each element of master and x*2, and then the minimum of that new list will be the rounded number.
for ex. for  for 20 from the input list, the list of absolute differences is going to be:
[abs(5-40),abs(10-40),abs(30-40),abs(60-40),abs(120-40),abs(180-40)]
which results in [35,30,10,20,80,140], and the minimum difference came for 3rd element ,i.e 30 of master list
In [14]: inp=[10, 20, 60, 120,17,27,50]

In [15]: master=[5, 10, 30, 60, 120, 180]

In [16]: [min(master,key=lambda y:abs(y-x*2)) for x in inp]
Out[16]: [10, 30, 120, 180, 30, 60, 120]

Comment: Sorry, would you be able to explain this slightly? Im having trouble following along 100%. Thanks!
Comment: @ElburzSorkhabi added some explanation.
Comment: Thanks for the speedy answer, I'm still a little green and can't follow your solution to the point of being able to quickly implement it. I really appreciate the help though! Cheers!


Prove that there are no primes in the following infinite sequence of numbers: $1001, 1001001, 1001001001, 1001001001001, ...$

Question:
Prove that there are no primes in the following infinite sequence of
  numbers: $$1001, 1001001, 1001001001, 1001001001001, ...$$

The sequence can be expressed as follows: $$ f: \mathbb{N}-\{0\} \to \mathbb{R} \\ k \to \frac{1-1000^{k+1}}{1-1000}$$
I thought for a moment to use the recurrence relation $a_0=1$ and $a_k = 1000 a_{k-1} + 1$, but it looks like it led nowhere.
Is it possible to use the explicit function? I don't know how to continue. Will someone be able to give me advice? Please, I ask you not to give me the answer. I would like to do exercise myself.
Comment: Basic divisibility rules for $3$ and $11$ show that it's never prime for $k\equiv1,2,3,5$ modulo $6$.
Comment: BTW It would work with $a_0 = 1$ and the resulting series as well.
Comment: @alex.jordan Could you explain your argument? It seems to be interesting, but I don't know how to use it.
Comment: If $k$ is $2$ or $5$ mod $6$, then your numbers are like $100010001$ in that they have a number of $1$s that is divisible by $3$. The test for divisibility by $3$ is to sum digits and see if the result is divisible by $3$. So all these numbers are divisible by $3$. If $k$ is $1$, $3$, or $5$, then the test for divisibility by $11$ applies in the same way. Here, you sum digits but alternate their sign. So for example $1001$ is divisible by $11$ because $-1+0-0+1$ is divisible by $11$.
Answer: Hint : Look at the polynomial $p_n(x)= 1 + x +\dots+ x^n$ for $n= 1, 2,\cdots$ And notice the numbers in the sequence are precisely $p_n(10^3)$. Now by the formula you wrote, we have:
$(10^3 -1) p_n(10^3)= (10^{3(n+1)}-1)$.
Now I think a divisibility argument should work. Let me know if anything is unclear.
Comment: For the second term  we get "lucky." But past that the factorization $(10^{n+1}-1)(10^{2n+2}+10^{n+1}+1)$ does it.
Comment: If $p_n(10^3)$ were prime then it divides the RHS, which factors into $(10^{n+1}-1) (10^{2(n+1)}+ 10^{n+1}+1)$, but $p_n(10^3)$ can't divide $(10^{n+1} - 1)$, can we see a contradiction from here?
Comment: yeah  we have to check first two cases manually i guess
Comment: @AranyaLahiri Where do you know this method?
Comment: I am not really sure about that, i did this problem/ learnt the trick sometimes back. But I am not sure whether this is a general method, and I don't recall any other particular problems using especially this technique
Answer: This is the complement answer of Aranya Lahiri.
We have $(10^3 -1) f(k)= (10^{3(k+1)}-1) =  (10^{k+1}-1)(10^{2k+2}+10^{k+1}+1) $.
If $f(k)$ is prime, so $f(k) \mid (10^{k+1}-1) $ or $f(k) \mid (10^{2k+2}+10^{k+1}+1)$.
Each element $a_k$ of the sequence can be written as $a_k = 1000a_{k-1} + 1$ for a certain $k$, where $a_0=0$.
But $a_k \equiv 1 \pmod 4$ and $(10^{k+1}-1) \equiv -1 \equiv 3 \pmod 4$, thus $f(k) \nmid (10^{k+1}-1) $.
If $f(k) \mid (10^{2k+2}+10^{k+1}+1)$ $\implies$ there exists $t \in \mathbb{Z}$ such that $\frac{1-10^{3(k+1)}}{1-10^3}t = 10^{2k+2}+10^{k+1}+1$. But $t$ is simply a multiple of $\frac{1-10^3}{1-10^{k+1}}$ as we have already seen. The only case where $\frac{1-10^3}{1-10^{k+1}}$ is an integer is when $f(k=2)$, but this number is also divible by $3$. Consequently, $f(k) \nmid (10^{2k+2}+10^{k+1}+1)$. (Contradiction)
Are there any corrections to this answer?
Answer: Let the sequence be $a_n$. Obviously,  $a_1=7\times 11 \times 13$ and $a_2= 3\times 333667$ are not primes. Now let's consider $a_n$ for $n\geq 3$.
$$\displaystyle \begin{aligned}a_n & =1+10^3+10^6+\ldots+10^{3n} \\& =\frac{\left(10^3\right)^{n+1}-1}{10^3-1} \\&=\frac{\left(10^{n+1}\right)^3-1^3}{999}\\&=\frac{\left(10^{n+1}-1\right)\left(10^{2 (n+1)}+10^{n+1}+1\right)}{999} \end{aligned}\tag*{} $$
For any $n\geq 3$, both $10^{n+1}-1$ and $10^{2 (n+1)}+10^{n+1}+1$ are greater than $999$. So $a_n$ can be factorised as a product of two integers greater than $1$ and hence $a_n$'s are never prime numbers.


Sortable table: secondary sort

Question: I have a view (Drupal 6 / Views 2, but I think this may apply to other versions as well) displayed as a sortable table. I can add fixed sort criteria as you can with all views, but once the table is sorted by the visitor on a certain table, those sort criteria are ignored.
In the style options there is a box called "Override normal sorting if click sorting is used", which doesn't make sense to me. It seems to effectively disable click sorting, leaving the end user with a clickable but not working table headers.
Is there a way to keep the fixed sort criteria and use them as secondary criteria?
Answer: The initial sorting that you have specified in views is only used on the first page view. When you click on the header to change the sort the query is altered to use the drupal table sort routines instead. Unfortunately there is no support in the built in table sort code to allow multiple column sort, nor the ability to define a default of descending instead of ascending column. An alternative if your table is displaying all results is to add some Javascript that performs table sorts on the HTML and not provide sorting on the columns in Views. A google.com search for "javascript table sort" will give many results, this one looks to be quite robust: http://tablesorter.com/docs/
Comment: and there is Views integration with Tablesorter: http://drupal.org/project/views_tablesorter
Comment: Thanks, I hadn't considered a javascript-based solution yet. I'd rather do this with php/sql, but I'll take a look.
Comment: The only other easy solution is to create sort criteria in Views, then expose the ones you want people to be able to sort by. The table header sorting issue will still exist, but at least with the exposed sorts they will be able to choose multiple sort options. In this case Views should obey the exposed sorts in the order that they are defined.
Comment: For D7 as well: https://www.drupal.org/project/tablesorter
Answer: As others said before

there is no support in the built in table sort code to allow multiple
  column sort, nor the ability to define a default of descending instead
  of ascending column

But you should have a look at the following approach with Tablesorter.
For D7:
1.Download and enable Tablesorter Module
2.Download and extract Tablesorter jQuery Plugin into sites/all/libraries/tablesorter
3.Add a CSS class tablesorter and an unique id to your Views tables in template.php
/**
 * Preprocess variables for Views tables.
 */
function YOUR_THEME_preprocess_views_view_table(&$vars) {
  $view = $vars['view'];
  $vars['classes_array'][] = 'tablesorter';
  $vars['attributes_array']['id'] = $view->name . '-' . $view->current_display;
}

4.Clear cache a few times. Now Tablesorter should already start to work. You'll see it when the styling changed.
5.For secondary sort you need to add a small custom JavaScript. In template.php:
/**
 * Override or insert variables for the page templates.
 */
function YOUR_THEME_preprocess_page(&$vars) {
    // you might define some conditions around here
    drupal_add_js(drupal_get_path('theme', 'YOUR_THEME') . '/scripts/custom_tablesort.js');
}

6.In that script write the following to tell Tablesorter to sort the first six collumns of certain tables in ascending alphabetical order. To tell Tablesorter to sort only the second and third column in ascending order write sortList: [[1,0], [2,0]] instead.
(function ($) {
  Drupal.behaviors.tableSorting = {
    attach: function (context, settings) {

      $("#your_view_name-display_name").tablesorter({
        sortList: [[0,0],[1,0],[2,0],[3,0],[4,0],[5,0]]
      });

    }
  }
}) (jQuery);

If you want to let Tablesorter secondary sort all your tables you don't need to define a CSS id when preprocessing and simply tell Tablesorter: $("table").tablesorter({ sortList: [[0,0],[1,0],[2,0],[3,0],[4,0],[5,0]] });
After a little testing I'ld say you leave any custom Tablesorter option out (finish with step 4) and simply explain your users that while holding down shift when clicking multiple headers, secondary sorting works on every desired column they want.
Comment: Thanks, I'll definitely try this if I ever need it again.
Answer: Remove the "Default Sort" from the Table settings and use the "Sort Criteria" for the first and second order
Answer: From the question what I get is that you want a table sorter function in Views; if it is so, you can follow the following steps:

Edit the view you want to add the column sorting to.
Under "Basic Settings", look for "Style: Table" and click on the picture of a cog next to it.
Scroll down to see the table settings.
There is a list of the fields, and a tickbox for each labelled "sortable"; tick the boxes for any columns you want users to be able to change the sort order on.
Comment: Thanks, but that's not what I'm looking for. I know how the default table sorting works. What I want is a default sort option that becomes the secondary sort order when the user clicks a table header. For instance, a table is sorted alphabetically by default, but when a user clicks the author column, the table is sorted by author first, while rows with the same author are still sorted alphabetically.
Answer: (D8)
After lots of debugging I ended up with similar D7 approach D7 hook_views_query_alter
It boils down to using triggering the table style plugins clickSort method.

Create a sub folder named multisort in modules.
Safe the code below as multisort.module into folder created above.

<?php

use Drupal\views\Plugin\views\query\QueryPluginBase;
use Drupal\views\ViewExecutable;

/**
 * Implements hook_views_query_alter().
 */
function multisort_views_query_alter(ViewExecutable $view, QueryPluginBase $query) {

  $views_to_alter = [
    // view name
    'sort_test' => [
      [
        'table' => 'node__field_col_a',
        'field' => 'field_col_a',
        'column' => 'field_col_a_value',
        'order' => 'desc',
      ],
    ]
  ];

  if (isset($views_to_alter[$view->id()])) {
    //dpm($query->orderby, 'by config or url');

    $fields_used = [];
    foreach($query->orderby as $field) {
      $fields_used[$field['field']] = 1;
    }

    $fields = $views_to_alter[$view->id()];

    foreach($fields as $field) {
      // Skip fields already clicked
      if (isset($fields_used[$field])) {
        continue;
      }

      $alias = $field['table'] . '.' . $field['column'];
      if (isset($fields_used[$alias])) {
        continue;
      }

      // @see \Drupal\views\Plugin\views\style\Table::buildSortPost
      $view->field[$field['field']]->clickSort($field['order']);
    }

    //dpm($query->orderby, 'altered');

  }
}

Save text below into multisort.info.yml

name: Multisort
type: module
description: Sort on more then one field
core: 8.x
package: Views

Answer: This is my solution in D7/Views 3. It adds a last order_by clause to the query if its not already present. I believe you could look at the $view parameter and add the order by columns from there if you dont want to do it statically like I did.
function MODULENAME_views_query_alter(&$view, &$query) {
  if ($view->name == 'the_name_of_the_view_to_alter') {
    //First check that we don't already sort by the "the_field_alias" column
    if(array_search('the_field_alias', array_column($query->orderby, 'field')) === FALSE) {
      //Add the "the_field_alias" column last in the orderby array
      $query->orderby[] = [
        'field' => 'the_field_alias',
        'direction' => 'ASC',
      ];
    }
  }
}

Comment: Verified, this works well for Drupal 7, thank you!
Answer: Edit the views and go to Table settings there you can see sorting checkbox... you can checked and apply..

Sortable table: secondary sort


Update statement: Error: Target table must be part of an equijoin predicate

Question: I get this error when I try to update a column of Table 1 that is like a column of Table 2.
Target table must be part of an equijoin predicate.
update test
   set category = t1.category
from category_type t1, test t2
where t2.link ilike '%' || t1.type || '%'
and t2.link ilike '%.nike.com/%';

Category_Type Table shown below:
type       category
sandals     shoes
boots       shoes
t-shirts    apparel
-pants      apparel

Answer: I don't know Redshift, but in Postgres you must not repeat the target table in the FROM clause of an UPDATE statement:
update test t2
   set category = t1.category
from category_type t1  --<< do NOT repeat the target table here
where t2.link ilike '%' || t1.type || '%'
  and t2.link ilike '%.nike.com/%';

Answer: You should be able to join with a subquery like this:
update test set category = t1.category
from (
    select c.category, t.link
    from category_type c, test t
    where t.link ilike '%' || c.type || '%'
        and t.link ilike '%.nike.com/%';
) t1
where test.link = t1.link

The AWS docs have join examples further down the page. The last example shows the benefit of the subquery.
The basic form of this query is:
update target set val=t2.val
from (
    select t.id, o.val
    from target t
    join other o on o.id=t.id
) t2
where target.id = t2.id

Comment: Tried that. But I still get an error: relation "t1" does not exist.
update temp set category = t1.category
from (
    select c.category, t.link
    from category_type c, temp t
    where t.link ilike '%' || c.type || '%'
        and t1.link ilike '%.nike.com/%'
) t1
where temp.link = t1.link;
Comment: I'll try and come up with an example I can run on my cluster.
Comment: Looks like my example has an error in the where clause of the sub-select...I can't reference t1 from there. Will fix.
Comment: Thanks! Unable to reference t1 outside the window
Comment: If you run just the inner select does it give you a list of categories and links like you'd expect?
Comment: Yes, it does..!
Answer: This kind of issue Target table must be part of an equijoin predicate only comes when you are updating a table and join condition is also there in update.
To come out from this kind of issue you need to put join inside the () and use where clause outside of parenthesis with primary Key.
I was also facing the same issue then I have taken primary key column of target table where we are updating.
Initial Query:

Final Query:
Answer: The following example returns an error because the FROM clause does not support outer joins to the target table:
update category set catid=100
from event left join category cat
on event.catid=cat.catid
where cat.catgroup='Concerts';

Below is the error:

ERROR:  Target table must be part of an equijoin predicate

If the outer join is required for the UPDATE statement, you can move the outer join syntax into a subquery:
update category set catid=100
from
(
   select event.catid
   from event left join category cat
   on event.catid=cat.catid
) eventcat
where category.catid=eventcat.catid and catgroup='Concerts';

Reference: https://docs.aws.amazon.com/redshift/latest/dg/c_Examples_of_UPDATE_statements.html
Answer: ERROR: Target table must be part of an equijoin predicate

Amazon Redshift SQL does not support Left, right, and full outer joins in the FROM clause of an UPDATE statement; so in that case the query return this error.
OR If you do not specify the table being updated in the join i.e the where clause must have the updated table as part of a predicate.


More options for page--node--edit.html.twig for content type

Question: Using my Theme debug I'm getting the following themplate suggestions
page--node--blogpost.html.twig

page--node--edit.html.twig

When I tried to use different template to edit a blogpost template only like
page--node--edit--blogpost.html.twig

the template was ignored. How to add more template suggestion for Drupal?
Answer: What you are looking for is called theme suggestions you can implement your own or alter existing ones. In this case since the theme hook is provided by another module (core) you need to alter the provided suggestions and add your own.
Check this post with useful examples. Also core's always have excelent examples (Bartik theme example).
/**
 * Implements hook_theme_suggestions_HOOK_alter() for form templates.
 */
function bartik_theme_suggestions_form_alter(array &$suggestions, array $variables) {
  if ($variables['element']['#form_id'] == 'search_block_form') {
    $suggestions[] = 'form__search_block_form';
  }
}


Multivariate Logistic Regression in R or SAS

Question: I was wondering whether there is a specific procedure in either R or SAS which can handle binary correlated data (multivariate logistic regression). More specifically I have a sample of 400 individuals who have selected their food likes among a variety of available options (binary). Also the participants indicated their age, whether they are active or not and their gender. The food options were: pizza, salad, cheese cake and juices. I wanted to know whether there is a procedure in either R or SAS which can explore the correlations between the food options among different demographics for prediction modeling purposes (e.g. younger males who are active and like salad tend to like juices as well).
Answer: Since the OP has not been here since three years before I registered, I find it unlikely that we will get clarification on what is meant by a multivariate logistic regression or binary correlated data. I see two possibilities:

A regression to find the probability that someone selects an item from mutually exclusive choices

A regression to find the probability of someone selecting each item when all or perhaps none can be chosen.

The typical model for problem 1 would be multinomial logistic regression, which models the probabilities of mutually exclusive events. However, the OP makes it sound like someone can choose both juice and salad, so "mutually exclusive" does not seem to fit this problem. In that case, this is a multi-label problem.
R seems to have a package called "mlr" that does this sort of regression.
The theory behind such a model is that there are multiple binomial variables being modeled at once. While considering possible correlations between binomial variables, the regression models several binomial variables at once. Consequently, the regression could predict high probabilities for all four categories (e.g., $99\%$ for all four is possible…maybe someone is really hungry), and the regression could predict low probabilities for all four categories (e.g., $1\%$ for all four of the person is not hungry). The point is that the four predicted probabilities do not have to add up to one, unlike in a multinomial problem with mutually exclusive categories (which might omit one of the categories and leave the probability of that one as whatever probability is left over after the probabilities are calculated for the other categories).
I have a question posted on here about multi-label problems.
What is the statistical model for a multi-label problem?
Multivariate probit regression would be the typical model for a basic model of multiple labels, as the Gaussian-based link function makes it easier to handle correlations between the categories than a logistic link function. If you want something the linked "mlr" package does not provide, perhaps this would be a good place to start your search.
More advanced methods for doing multi-label problems exist, too, including deep learning approaches that I suspect are supported by the TensorFlow implementation in R.
Answer: Both R and SAS can handle your situation:
For R you can check http://www.ats.ucla.edu/stat/r/dae/melogit.htm. It is called Mixed Effects Logistic Regression. I think it is another name for "Multivariate Logistic Regression" note it is not "Multiple Logistic Regression"
To use SAS you can either use  proc Genmod (GEE) http://www.math.unm.edu/~bedrick/glm/examples1.pdf or  Proc GLIMMIX procedure to conduct a mixed effect logistic regression http://www.lexjansen.com/wuss/2006/analytics/ANL-Dai.pdf
Comment: "Mixed Effects Logistic Regression" is *not* another name for "Multivariate Logistic Regression".
Comment: Thanks, after reading this paper several days ago http://galton.uchicago.edu/~pmcc/pubs/paper25.pdf I think they are the same thing. But I might be wrong.
Comment: Yes, I think so.  you can think this way, one person can choose either of each food (yes=1, no=0) and those choices are nested in a person. Sometimes people also call this as multilevel model, i.e. choice as first level and person and second level, or hierarchical linear model, random effect model, mixed model, ..., they are all the same thing, I think.
Comment: Going by the use of `glmer` in that paper, they are discussing Hierarchical/Multilevel Generalized Linear Models.  The confusion is quite understandable, as the terminology in the literature is extremely inconsistent and confusing.
Comment: Thank you for your comments. After reading them all I was not sure whether we have a specific procedure in R which can handle the Multivariate Logistic Regression. I appreciate if you can please comment.
Comment: R, SAS or other statistic software all have specific procedures to handle multivariate logistic regression.
Comment: So can we use the Mixed Effects Logistic Regression (in R) for this purpose as mentioned above? Thanks.
Comment: @MatthewDrury "Mixed effects logistic regression" = "multivariate logistic regression" when one realizes that "multivariate" can be thought of as a representation of a repeated measures design (e.g., each individual is responds to several questions which become multiple dependent variables) where each time of observation is nested within each individual and corresponds to a separate measure, just as Deep North describes.
Comment: Three years ago me regrets starting a debate over terminology : (  At the same time, I think mixed effects regression should involve some term in the likelihood for the dispersal of a random effect around the effect's mean.
Answer: Correction: If the participants were allowed to choose more than one option, Multinomial Logit will not work. (as Deep North noted)
Because you have four different options (pizza, salad, cheese cake and juices) for food choices, this fits into the framework of Multinomial Logit.
You can also consider a nested multinomial logit model. For example cheese cake and pizza can fall into one nest.
http://www.mea.mpisoc.mpg.de/uploads/user_mea_discussionpapers/dp16.pdf
Comment: Multinational logit might not work since choice of pizza, salad, cheese cake and juices may not mutually exclusive. So you can not assume Multinomial  distribution for your choice.
Comment: @ Deep north: If the participants were allowed to choose more than one option, then you are absolutely correct.


Calculate the limit $ \lim_{x\to\infty} \int_{0}^{1} g(xz) dz$.

Question: let $g(x)$ be a continuous function s.t. for each $x \ge 0$, $\lim_{x\to\infty} g(x)=L \ne 0$.
calculate the limit :
$$ \lim_{x\to\infty} \int_{0}^{1} g(xz) dz$$
SOLUTION ATTEMPT: I'm thinking about using the integration term by term Theorem, I know that because $g(x)$ is continuous in every closed interval $[0,b]$ it is integrable there. especially in $[0,1]$. so I can write:
$ \lim_{x\to\infty} \int_{0}^{1} g(xz) dz$=$\int_{0}^{1}  \lim_{x\to\infty} g(xz) dz$
but didn't know how to continue from here. how do I integrate the right side?
any kind of help would be appreciated.
Comment: I don't see any justification for you switching over the integral and the limit...
Answer: Change variables $xz=t$ in the integral which becomes
$$
\lim_{x\to\infty}\frac{1}{x}\int_0^x dt\ g(t)
$$
and then by L'Hopital and using the fundamental theorem of calculus, the limit is equal to $L$.


Is there a way to update the first document in a MongoDB collection given a query and a sort option using the "update" function?

Question: I would like to use the update function in MongoDB to update the first document in a collection given a query and a sort (or orderBy) configuration.
I know the solution with findAndModify:
db.col.findAndModify(query, sort, updates)

Can you do the same using the update function?
Comment: Why wouldn't you use the `findAndModify`?
Comment: @Michael9 because I want to find out if the same can be achieved with `update` :) And of course I use it since I know no alternative.
Answer: No you cannot use sort with update but if you do not specify multi option in your update only the first document that meet the query criteria will be updated.
There is no guarantee for the ordering of documents on disk unless your are using Capped collections.
Comment: What does "first" mean?
Comment: But is there any implicit order? (place on disc, main index `_id`). For me it is important to update the first based on `_id`. And that is why I ask if I can rely on update for that. My practical experience shows me that also the default `_id` index is not considered for normal `update`
Answer: According to the documentation of UpdateOne Specify an empty document { } as filter to update the first document returned in the collection.


using (deep) neural networks for a severely imbalanced image dataset when some classes have <10 images

Question: Taking a long shot here. So I have a a small dataset of ~500 images with discrete labels from 1 to 9. My task is to detect the per-class and overall accuracy of this classification method using a (deep) neural network.
I get an accuracy of 56% using multinomial logistic regression using train/test split method. I used transfer learning in PyTorch for some of the categories that have >25 images (2, 3, 5, 7, and 9). However, I do not know how to use this tutorial and report test accuracy when I only have like 3 or 11 images in a category.
https://pytorch.org/tutorials/beginner/transfer_learning_tutorial.html
Here is the number of images per category:
<code>category 1: 3
category 2: 66
category 3: 175
category 4: 18
category 5: 54
category 6: 12
category 7: 91
category 8: 11
category 9: 38
</code>
What (deep) neural network method (hopefully with a link to tutorial, would you suggest that could work with a dataset like mine that has severe data imbalance and also some categories are having <10 images?
I have provided further discussion of the problem I am dealing with as well here: https://discuss.pytorch.org/t/leave-one-out-cross-validation-for-images-with-labels-and-discrete-confidence-levels-for-labels/29227
Here is the confusion matrix I get from multinomial logistic regression:
Comment: Have you considered the option of "blowing up" your training set by applying transforms to some of the images to create a bigger training set?
Comment: Data augmentation seems like a good idea indeed (+1 to mroman). Comment: with 3 and 11 instances (as in categories 1 and 8) most "within-class" accuracy metrics are you know... *a bit irrelevant*? What will be it be their standard error like? 50%?
Comment: @usεr11852 can you please explain what you mean by 'a bit irrelevant? What will be it be their standard error like? 50%?'
Comment: @mroman I have used 'data augmentation' in the past such as rotation/adding noise/etc as given by DL frameworks. However, just having 3 or 11 sample images to start with is really low, isn't it?
Comment: @usεr11852 also, you say within-class accuracy is a bit irrelevant. Do you mean "per-class accuracy" such as reported in confusion matrix is irrelevant? what accuracy metric do you suggest?
Comment: @MonaJalal: Yes, 0/1 or 1/1 (so 0% or 100% accuracy) is irrelevant as it does not offer any insight on the generalisation of the classifiers performance. We might got unlucky (or lucky) and end-up with 0 (or 100%) accuracy. When looking at  imbalanced datasets we should look at either probabilities or ideally cost-sensitive learning.
Answer: There are several methods to counter imbalanced datasets. Yet, with so few samples in several of the classes I'm not sure if you will ever get a satisfactory classification. I'm not sure if you can learn class features from only 3 samples as in class 1. In any case, this might lead to extreme overfitting or at least not a good generalization.
Nevertheless, you can try the following methods:

Upsampling, i.e. simply doubling items from the minority classes
Data augmentation (as mentioned in the comments), i.e. rotating, scaling, cropping, flipping,... the images (you have to decide which modifications make sense with your application)
Penalizing / cost sensitive learning / class weights, i.e. penalizing the miss-classification of a minority class item more severely than that of a majority class

Disclaimer: I'm not that familiar with Pytorch as I myself work with Keras and Tensorflow most of the time. Maybe someone else can provide some Pytorch specific examples or tutorials. In any way, the keywords should at least guide you into the right direction.