Can Guacamole work behind NAT?

Question: I am now in the process of searching proper replacement for TeamViewer, i.e. the solution which will allow me to connect to any machine, whether I am in LAN or external network. Hosting bypass server on my own is highly appreciated.
Eventually I ran against Guacamole and read a big bunch of appraisal about it, and not for nothing. Thin clientless HTML5 solution which provide access on any protocol ever used is cool thing, BUT!
The only thing that bothers me is accessibility of the Guacamole behind NAT, or corporate proxy or whatever. I want something Teamviewer-like experience (accessible everywhere) but without TV. I'm kinda a newbie in a networking so easy networking set up is rather critical here.
As I see it from the description, Guacamole consists of Tomcat server installed somewhere and nothing more. I didn't get clearly what should be done on remote machine so that remote machine become accessible over NAT?
Is this possible at all?
Answer: Short answer
Guacamole probably won't help you with NAT..
Long answer
As can be seen on Chapter 1. Implementation and architecture, the actual graphical session client is guacd which runs on the Guacamole server.
So, the simplest answer is:

make your Guacamole server reachable from your web client (presumably, publicly accessible from the Internet, possibly actually in some kind of DMZ).
Then ensure your desktop server is reachable by guacd.

All in all, if the desktop machine you want to reach is in the same network as the Guacamole server, problem already solved.
If it's deeper in your network, then make a rule to allow guacd to reach it and you're done.
If the machine is in another random location, it looks like Guacamole won't help you.  You have to figure out some NAT-traversal scheme from the Guacamole server.
Comment: Thanks for the answer. *ensure your desktop server is reachable by guacd* means that remote machine and `guacd` have to be absolutely reachable by each other and Guacamole doesn't have any built-in tools to solve this problem? Correct?
Comment: Short answer: AFAIK yes, correct. Long answer: I would not be definitive about what it does not have (which might change in the future anyway). TeamViewer-centric expectations suggest guacamole being a RDP/VNC/SSH client in a browser, able to reach other machines running some kind of daemon. Guacamole appears to be shaped very differently: a web front-end to a RDP/VNC/SSH client running on a server. See https://news.ycombinator.com/item?id=8166744 for an example of reaching RDP servers inside the same NAT that contains guacd.
Comment: Why they not swaped connection?  If guacd connects server this will be possible!!

Do you know alternatives to Guacamole?

Can Guacamole work behind NAT?


React JS - ESLint - Rules for ignoring components with UNSAFE_componentWillMount, UNSAFE_componentWillUpdate, and UNSAFE_componentWillReceiveProps

Question: Currently, I'm getting these linting errors:
ESLint: UNSAFE_componentWillUpdate should be placed after someFunction (react/sort-comp)
and
ESLint: Identifier 'UNSAFE_componentWillUpdate' is not in camel case. (camelcase)
Currently, I'm not able to find the correct rules to add to .eslintrc to apply to the prepended UNSAFE_ component lifecycles. I'm trying to make it apply to both react/sort-comp and camelcase rules, any clues/help would be appreciated
Answer: You can add this to your eslint
"camelcase": [
  "error", {
    "ignoreDestructuring": true,
    "allow": [ "^UNSAFE_" ]
  }
],

This basically just allows all the renamed UNSAFE_ lifecycle methods.
Comment: Where is the eslint config file ? Edit:In the project root folder: /.eslintrc  The code needs to be added under the rules: part


SWT Label Drag'n'Drop

Question: I'm surprised to see that this hasn't been done, or at least my research says so.
I have a Canvas with RowLayout and a bunch of Labels.
The title is pretty straight forward: I want to reorder my labels using DND.
Please don't tell me I have to engineer my own algorithm for calculating bounds and sizes and stuff like that.
Later edit:
I'm considering using Zest, but again, I can't find any example where graph nodes are snapped to eachother.
Comment: Did you consider using something like [Zest](http://www.eclipse.org/gef/zest/)?
Comment: Yes, I have. I want that to be my last resort, because I don't want to overengineer my widget.
Answer: I did something like this about a year ago.
My method of solving this problem was to use a data model to hold the label information.  Use the canvas.getChildren() and search for a separator composite between each object or the label that you dropped on top of.  When a drag and drop operation was completed you would search for the item that you dropped on and move the reference to the appropriate position in the model. Then reset the information on each label.  Only requirement to do this is to keep a data structure with the label info and a reference to the canvas.
Comment: I've thought of this myself, but how do I know which control is under my mouse when I execute the drop? Just iterate through the children and check their bounds?
Comment: Something like the following:

public void drop(DropTargetDropEvent dtde) {
    Object src = dtde.getSource();
    List children = canvas.getChildren();
    for (int i = 0; i < children.size(); i++) {
        if (children.get(i).equals(src)) {
            //update
        }
    }
}
Comment: Additionally, if the contents of the labels are unique, you could look at the contents of the label you dropped on and cycle through the model to determine the position that you dropped at.  You would just have to caste the object returned to a control that lets you get access to the text contained in the control; so, at a minimum, caste to composite or label. The method to do this is somewhat similar in that your perform String targetKey = ((Composite/Label)dtde.getSource()).getText();  Then just search the model for the index to insert the transfer source and update as needed.
Comment: I want to implement the widget with `Presentation Objects`: POJOs that hold information on the label and its container. I think my drag data will hold the PO, because it would make my life easier in the `drop event` method (I'll have access to both label and PO).
Comment: You helped me figure out the implementation for what I'm needing. Thank you, thumbs up.
Comment: Did a blog post on this, with source code. http://georgiangrec.wordpress.com/2013/08/11/swt-composite-drag-and-drop/

SWT Label Drag'n'Drop


Apurar direção da rolagem num elemento

Question: O código em baixo visa detetar a direção da rolagem num elemento especifico:
var control = 0,
    lastScrollTop = 0,
    element = document.getElementById('idDoElemento');

element.onscroll = function() {

  var scrollAmt = element.scrollTop;

  if (scrollAmt > lastScrollTop) {
    // baixo
  }
  else if (scrollAmt < lastScrollTop) {
    // cima
  }
  else {
    // parado
  }

  lastScrollTop = scrollAmt;
};

Mediante a direção da rolagem, podemos por exemplo, despoletar uma ação.
Pergunta
Para o que foi descrito, o processo está a decorrer de forma eficiente ou o mesmo pode ser simplificado?

var control = 0,
    lastScrollTop = 0,
    element = document.getElementById('rolagemAqui'),
    feedback = document.getElementById('direcao');

element.onscroll = function() {

  var scrollAmt = element.scrollTop;

  if (scrollAmt > lastScrollTop) {
    feedback.innerHTML = "baixo";
  }
  else if (scrollAmt < lastScrollTop) {
    feedback.innerHTML = "cima";
  }
  else {
    feedback.innerHTML = "parado";
  }

  lastScrollTop = scrollAmt;
};
html,
body {
  width: 100%;
  height: 100%;
  margin: 0;
  padding: 0;
  overflow: hidden;
}
#rolagemAqui {
  overflow: scroll;
  position:absolute;
  top:0;
  left:0;
  right:0;
  bottom:0;
}
#direcao {
  position: absolute;
  z-index:1;
  left: 48%;
  top: 0;
  background-color: pink;
  padding: 6px;
}

parado

  Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut aliquam, velit nec laoreet lacinia, erat risus aliquet sapien, vel maximus dui nunc ut justo. Aliquam dictum mauris non metus sagittis consectetur. Proin molestie sem vel lorem convallis, sed blandit ipsum rhoncus. Phasellus molestie risus nec auctor eleifend. Nulla ultrices eu tortor at euismod. Integer ut facilisis enim. Donec pulvinar laoreet rutrum. Mauris tincidunt, massa vitae molestie efficitur, sem nulla imperdiet justo, in sagittis enim elit consequat ex. Duis imperdiet libero ut maximus ornare. Maecenas vestibulum massa vel suscipit aliquam. Etiam sed orci vestibulum, faucibus orci a, fringilla mi. Etiam sit amet augue eget est luctus consectetur vitae aliquet sem. Donec venenatis porttitor rutrum. Proin hendrerit urna velit, nec scelerisque sem consectetur et. Sed ultricies risus at tortor euismod, id sodales sapien tristique. Ut vel bibendum nisi. Donec et tempus est. Phasellus efficitur imperdiet nibh, quis faucibus sem dapibus quis.
  Pellentesque sed justo ut nulla fringilla consectetur. Nullam sed tempor nisi, quis vehicula turpis. Sed malesuada purus risus, nec pellentesque velit fringilla in. Sed sed risus et quam sagittis tincidunt in at nulla. Pellentesque vitae semper mi, sed bibendum mauris. Maecenas feugiat leo eu ipsum vehicula, at accumsan nisi ultricies. Nulla felis leo, eleifend in elit ut, egestas viverra lorem. Vivamus vel libero vitae lectus blandit porttitor quis a ante. In efficitur iaculis lorem, eget faucibus nulla ornare nec. Maecenas vestibulum, eros non tempus pretium, neque leo facilisis ante, vitae bibendum velit ligula vitae tortor. Donec euismod magna magna, sed iaculis ante fermentum ac. In elementum leo turpis, id viverra est ultrices nec.
  Nam non risus finibus justo ornare porta. Integer bibendum ex in velit placerat, id iaculis leo eleifend. Etiam ornare scelerisque eros eu bibendum. Sed luctus massa et nunc semper gravida. Fusce id ornare velit. Cras porttitor sed risus vitae gravida.
  Nam sit amet odio sed leo tincidunt cursus id et mauris. Vestibulum vitae euismod ex, eu elementum lacus. Nunc non lacus pellentesque, feugiat enim luctus, congue velit. Donec lorem ex, semper in erat ac, sollicitudin pulvinar lorem. Integer quis interdum enim, ut faucibus nisl. Aenean sit amet orci euismod lacus ullamcorper vestibulum. Aenean eu lacus arcu. Praesent bibendum est quis neque sagittis, ac egestas eros mattis. Sed consequat vulputate nulla, nec varius nulla laoreet sed. Sed magna mauris,
  faucibus quis scelerisque ac, volutpat a velit. Etiam eu nibh eget dui malesuada convallis. Aliquam aliquet nisi sed ligula blandit cursus. Etiam quis velit nec orci luctus faucibus. Aliquam hendrerit varius sodales. Nulla a neque lorem. Vestibulum
  non nibh neque. Praesent at arcu ac orci molestie ultrices vel vitae quam. Praesent quis ligula sed magna maximus eleifend. Donec nec enim accumsan, viverra orci dapibus, fermentum metus. Aliquam rhoncus erat ut tortor laoreet congue at in felis. In
  eget erat vel justo ornare dignissim. Nunc tincidunt magna felis, vel maximus nibh pharetra eget. Phasellus tempor interdum arcu ac scelerisque. Mauris semper, magna in ultricies dapibus, neque risus imperdiet lorem, a maximus massa nisl volutpat sem.
  Duis ipsum velit, cursus vel quam eu, tincidunt hendrerit erat. Nulla eleifend, urna nec cursus maximus, lectus diam auctor mi, id posuere metus odio ut dui. Morbi auctor sagittis augue eu dapibus. Aenean eu metus elementum ante ullamcorper malesuada.
  Nunc blandit nec augue eu sollicitudin. Integer vitae scelerisque urna, id gravida sem. Aliquam ultricies dui vitae libero consectetur, quis varius nisl dictum.
  Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut aliquam, velit nec laoreet lacinia, erat risus aliquet sapien, vel maximus dui nunc ut justo. Aliquam dictum mauris non metus sagittis consectetur. Proin molestie sem vel lorem convallis, sed
  blandit ipsum rhoncus. Phasellus molestie risus nec auctor eleifend. Nulla ultrices eu tortor at euismod. Integer ut facilisis enim. Donec pulvinar laoreet rutrum. Mauris tincidunt, massa vitae molestie efficitur, sem nulla imperdiet justo, in sagittis
  enim elit consequat ex. Duis imperdiet libero ut maximus ornare. Maecenas vestibulum massa vel suscipit aliquam. Etiam sed orci vestibulum, faucibus orci a, fringilla mi. Etiam sit amet augue eget est luctus consectetur vitae aliquet sem. Donec venenatis
  porttitor rutrum. Proin hendrerit urna velit, nec scelerisque sem consectetur et. Sed ultricies risus at tortor euismod, id sodales sapien tristique. Ut vel bibendum nisi. Donec et tempus est. Phasellus efficitur imperdiet nibh, quis faucibus sem dapibus
  quis. Pellentesque sed justo ut nulla fringilla consectetur. Nullam sed tempor nisi, quis vehicula turpis. Sed malesuada purus risus, nec pellentesque velit fringilla in. Sed sed risus et quam sagittis tincidunt in at nulla. Pellentesque vitae semper
  mi, sed bibendum mauris. Maecenas feugiat leo eu ipsum vehicula, at accumsan nisi ultricies. Nulla felis leo, eleifend in elit ut, egestas viverra lorem. Vivamus vel libero vitae lectus blandit porttitor quis a ante. In efficitur iaculis lorem, eget
  faucibus nulla ornare nec. Maecenas vestibulum, eros non tempus pretium, neque leo facilisis ante, vitae bibendum velit ligula vitae tortor. Donec euismod magna magna, sed iaculis ante fermentum ac. In elementum leo turpis, id viverra est ultrices nec.
  Nam non risus finibus justo ornare porta. Integer bibendum ex in velit placerat, id iaculis leo eleifend. Etiam ornare scelerisque eros eu bibendum. Sed luctus massa et nunc semper gravida. Fusce id ornare velit. Cras porttitor sed risus vitae gravida.
  Nam sit amet odio sed leo tincidunt cursus id et mauris. Vestibulum vitae euismod ex, eu elementum lacus. Nunc non lacus pellentesque, feugiat enim luctus, congue velit. Donec lorem ex, semper in erat ac, sollicitudin pulvinar lorem. Integer quis interdum
  enim, ut faucibus nisl. Aenean sit amet orci euismod lacus ullamcorper vestibulum. Aenean eu lacus arcu. Praesent bibendum est quis neque sagittis, ac egestas eros mattis. Sed consequat vulputate nulla, nec varius nulla laoreet sed. Sed magna mauris,
  faucibus quis scelerisque ac, volutpat a velit. Etiam eu nibh eget dui malesuada convallis. Aliquam aliquet nisi sed ligula blandit cursus. Etiam quis velit nec orci luctus faucibus. Aliquam hendrerit varius sodales. Nulla a neque lorem. Vestibulum
  non nibh neque. Praesent at arcu ac orci molestie ultrices vel vitae quam. Praesent quis ligula sed magna maximus eleifend. Donec nec enim accumsan, viverra orci dapibus, fermentum metus. Aliquam rhoncus erat ut tortor laoreet congue at in felis. In
  eget erat vel justo ornare dignissim. Nunc tincidunt magna felis, vel maximus nibh pharetra eget. Phasellus tempor interdum arcu ac scelerisque. Mauris semper, magna in ultricies dapibus, neque risus imperdiet lorem, a maximus massa nisl volutpat sem.
  Duis ipsum velit, cursus vel quam eu, tincidunt hendrerit erat. Nulla eleifend, urna nec cursus maximus, lectus diam auctor mi, id posuere metus odio ut dui. Morbi auctor sagittis augue eu dapibus. Aenean eu metus elementum ante ullamcorper malesuada.
  Nunc blandit nec augue eu sollicitudin. Integer vitae scelerisque urna, id gravida sem. Aliquam ultricies dui vitae libero consectetur, quis varius nisl dictum.

Answer: O código funciona bem e não vejo como otimizá-lo se o objetivo for detectar o sentido do rolamento a cada passo (ou seja, em todo evento scroll, que é disparado múltiplas vezes enquanto o conteúdo é rolado).
Mas dá para otimizar se o objetivo for detectar o sentido "resultante" do rolamento – quando o que importa é se no final do rolamento o conteúdo está mais para cima ou para baixo do que no início, ignorando os passos intermediários (pode-se rolar rapidamente várias vezes para cima e para baixo no processo). Nesse caso, é possível usar um timer para fazer throttling:

var lastScrollTop = 0,
    element = document.body,
    timer,
    intervalo = 500;

/**
 * Retorna:
 * -1 para rolamento acima
 * 1 para rolamento abaixo
 * 0 para nenhum rolamento
 */
function sentido() {
  var scrollAmt = element.scrollTop;
  var sinal = 0;
  if (scrollAmt > lastScrollTop) {
    sinal = 1;
  }
  else if (scrollAmt < lastScrollTop) {
    sinal = -1;
  }
  lastScrollTop = scrollAmt;
  return sinal;
}

// Listener
element.onscroll = function() {
  clearTimeout(timer);
  timer = setTimeout(function() {
    document.getElementById('status').innerHTML = 'Sentido do rolamento: ' + sentido();
  }, intervalo);

};
#status {
  position: fixed;
  top: 0;
  width: 100%;
  height: 12px;
  padding: 6px;
  background: #ccc;
}

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque posuere purus vel nisi condimentum efficitur. Donec at velit aliquet, pretium ex eget, ornare dolor. Quisque eu condimentum felis. Nulla facilisi. Cras rutrum nibh id erat vestibulum, vitae ornare tellus rutrum. Nam mauris orci, pulvinar convallis euismod interdum, pretium id purus. Pellentesque nulla felis, auctor ac neque condimentum, scelerisque accumsan ex. Morbi dignissim felis id rutrum dictum. Aliquam metus arcu, euismod at tempor at, dictum a massa. Sed fringilla augue justo, in porttitor magna iaculis nec. Phasellus ornare enim varius arcu molestie, vitae ultrices nunc laoreet. Phasellus hendrerit porttitor diam, at efficitur arcu viverra venenatis. Curabitur congue leo lectus, id mattis lacus aliquet a. Integer efficitur augue quis nibh posuere suscipit. Vestibulum facilisis nulla libero. Proin vitae diam non augue iaculis suscipit id id lorem.

Integer maximus, dui id tempor rutrum, tellus urna gravida lacus, quis eleifend massa leo ac sem. Vivamus congue sagittis lectus eu pellentesque. Duis blandit non odio vitae pharetra. Donec sem massa, tempor vitae mattis vel, accumsan ut ex. Integer consequat, nibh non ultrices dapibus, erat ligula mollis lorem, sit amet placerat lorem tellus quis eros. Duis id justo euismod mauris pharetra condimentum. Aenean a diam sit amet velit fringilla tempus ac in libero. Nulla elementum interdum nisl sit amet convallis. In hac habitasse platea dictumst. Nullam accumsan leo ut nulla varius pretium. Aenean iaculis facilisis ultricies.

Vivamus pharetra mi in dui pulvinar rhoncus. Proin rhoncus purus ac risus egestas hendrerit. Nulla facilisi. Proin leo lacus, rhoncus vitae diam vitae, hendrerit pretium lacus. Nullam dictum porttitor ex, rutrum ornare velit aliquam eu. Nullam sagittis sed lectus nec ultricies. Sed porta, leo sed consectetur dapibus, ligula velit blandit elit, in gravida dolor enim nec sem. Nullam pharetra vel tortor sit amet efficitur. Aliquam erat volutpat.

Sed quis nibh odio. Phasellus cursus ullamcorper lobortis. Aliquam in maximus dolor. Fusce tincidunt ornare lacus in suscipit. Nam id augue tempus, suscipit purus at, rutrum felis. Nam suscipit massa ac interdum sodales. Suspendisse semper arcu et velit iaculis, id gravida lacus rhoncus. Curabitur a diam non nisl lobortis dictum quis eu elit. Nullam lorem risus, viverra at erat nec, mollis scelerisque eros. Nunc malesuada efficitur neque, rhoncus ultrices nisl dapibus ut. In ultricies nec sapien id viverra. Nullam at sem ullamcorper, maximus libero id, imperdiet ante. Donec aliquam, enim nec venenatis pellentesque, nunc erat molestie risus, ac aliquet libero justo eu orci. Integer tincidunt consequat turpis, a pharetra magna condimentum vel. Etiam suscipit magna vel feugiat vestibulum.

Mauris fermentum blandit neque, sit amet dignissim turpis dictum vitae. Curabitur congue augue sit amet felis consectetur maximus. Maecenas sit amet justo vitae urna aliquet tristique. Maecenas in neque facilisis, dapibus turpis at, interdum lectus. Praesent commodo ante eros, lobortis elementum mauris consequat eu. Fusce convallis nunc sed augue malesuada gravida. Sed dignissim velit in nibh porttitor consequat. Proin at tortor porta, pretium nisl at, pellentesque turpis.

Phasellus ornare eget augue in consequat. Ut in rutrum ante. Vivamus interdum mi sapien, ac commodo sapien sollicitudin eget. Suspendisse lacinia, massa vel lacinia vulputate, justo est commodo dolor, vel sodales lacus velit quis tortor. Nulla facilisi. Duis vehicula quis dui at varius. Integer ultrices tempor dolor. Vestibulum nec arcu ut ligula semper fringilla ut ut lorem. Nam et dapibus sapien. Nullam pharetra egestas ante, nec congue risus elementum non. Integer aliquet dolor sit amet metus ultrices, quis eleifend sapien dictum. In euismod, mi et congue ullamcorper, libero mi rhoncus tortor, in laoreet libero tellus dictum dui. Mauris suscipit convallis nibh, et ullamcorper turpis sollicitudin vel. Nullam tincidunt dolor ut mauris fermentum, ac tempus mi lobortis. Vivamus quis justo sagittis, tempor ex nec, volutpat orci. Nullam consectetur volutpat euismod.

Aliquam et ipsum non eros mollis dapibus nec sit amet sapien. Pellentesque eleifend et nisi non interdum. Maecenas aliquet dolor vel malesuada egestas. Pellentesque at purus mauris. Quisque nulla tellus, egestas in iaculis at, sollicitudin nec est. Donec turpis enim, condimentum nec tincidunt eu, ultrices ac tellus. Aliquam massa urna, ultrices ut pulvinar nec, iaculis vel purus. Maecenas blandit elit mi, eget posuere odio faucibus et. Integer sit amet lacus tortor. Suspendisse et quam tempor, rhoncus diam eget, tincidunt nisl. Morbi pharetra gravida tellus, ut facilisis sem aliquam a.

Aenean eu vehicula erat. Donec sed sagittis lacus. Sed ac mi felis. Proin elit lorem, laoreet a fringilla sit amet, pulvinar vitae ligula. Nullam et mi quis magna lacinia maximus eget vitae purus. Duis semper fringilla sapien ornare bibendum. In ultricies dignissim dui vitae porta. Maecenas a erat ante. Phasellus viverra orci a metus sagittis accumsan. Curabitur condimentum purus eget congue molestie. Mauris quis mattis lectus. Quisque non volutpat orci. Sed eget lacus vehicula, mattis ante id, porttitor odio.

Nullam id posuere est, nec vestibulum sapien. Nunc consequat lacus at mi pharetra, quis vehicula quam ornare. Vivamus a odio enim. Mauris vitae mauris quis quam volutpat consequat ullamcorper vel elit. Morbi consectetur egestas justo. Curabitur odio leo, ultrices a semper ac, interdum nec enim. Nullam pellentesque viverra sagittis. Nunc vel orci viverra, luctus turpis vitae, condimentum libero.

Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Pellentesque commodo eget sapien sit amet imperdiet. Ut ultricies risus a augue suscipit, non semper mauris convallis. Aenean consectetur convallis ligula, facilisis tempor lorem iaculis at. Integer et velit facilisis, faucibus dolor ut, posuere magna. Maecenas tristique ornare ante, sit amet commodo sem lobortis sit amet. Mauris convallis varius felis, at tempor massa tempor a. Cras fringilla laoreet sem eget ullamcorper. Ut feugiat justo tincidunt, dictum elit sit amet, blandit sapien. Aenean sed viverra tortor. Ut at nisl et urna imperdiet maximus eu nec nisl. Cras dapibus dui ut fringilla semper. Aenean cursus metus placerat diam congue, semper vestibulum eros egestas. Suspendisse eget tortor a dui luctus elementum et sed est. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Nunc nec lacus eu nunc sodales rutrum.

Vestibulum ullamcorper, ex pharetra auctor convallis, quam quam pellentesque dolor, condimentum suscipit mauris nulla vitae nunc. Suspendisse auctor dolor eget justo tempus, vel blandit purus accumsan. Aliquam metus lacus, fermentum vel faucibus non, rutrum pretium velit. Mauris sit amet consectetur justo. Nunc accumsan suscipit mi, sed maximus diam posuere sit amet. Donec ultrices tristique neque, sed consequat lorem convallis eu. Aenean viverra eu ex non tempor. Nullam in luctus eros. Curabitur eget arcu efficitur, convallis leo quis, sollicitudin velit. Pellentesque vulputate augue ac diam posuere fringilla. Nulla cursus eros at purus mollis porttitor. Quisque tincidunt nisi ut aliquet pretium.

Fusce in metus erat. Mauris tincidunt urna lacus. Suspendisse vehicula, nunc in malesuada malesuada, felis augue gravida ex, sed gravida elit arcu ac neque. Pellentesque in fringilla tellus. Donec hendrerit vitae quam at suscipit. Pellentesque fermentum, velit eget pretium lobortis, sem lacus vehicula tortor, ut finibus felis ante sed justo. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Donec laoreet libero ac lacinia eleifend. Pellentesque non metus accumsan, lobortis enim eu, vestibulum nisl. Pellentesque a eros augue. Curabitur sed consequat leo. Mauris ac lectus augue. Duis ultricies risus quis venenatis egestas. Quisque non fringilla justo.

Nulla urna purus, elementum et justo in, rutrum mollis lacus. Donec aliquam tempor ligula vel elementum. Sed finibus mattis velit a bibendum. Donec nec urna sodales, consequat odio a, vestibulum dolor. Phasellus sollicitudin viverra pulvinar. Fusce pellentesque mattis viverra. Phasellus augue ante, tincidunt vitae commodo eu, egestas sit amet tortor. Pellentesque vel magna eu elit blandit iaculis. Aliquam consequat condimentum sapien, et accumsan ligula mattis sed. Vivamus dignissim turpis tellus. Aliquam interdum accumsan sapien, eget euismod tortor volutpat nec. Maecenas luctus sollicitudin lacinia.

In ligula ipsum, interdum id quam non, dapibus bibendum est. Proin vel tincidunt purus, non pulvinar nibh. Nam congue libero ac eros fringilla, sed interdum risus viverra. Quisque id nisi ac lectus dapibus mattis nec imperdiet arcu. Vivamus quis interdum elit. Cras pellentesque, dui at mollis tincidunt, tortor nulla convallis nisl, in mattis purus sem eu nibh. Aenean congue arcu feugiat lectus mattis commodo. Vivamus tincidunt leo vel bibendum volutpat. Pellentesque eget mauris eget lacus blandit lobortis. Curabitur egestas urna nec mollis pretium. Etiam ac purus vel augue scelerisque posuere ut eu nibh. Ut tempor non nunc facilisis iaculis. Nullam dictum felis imperdiet, placerat magna eleifend, convallis mi. Praesent sit amet accumsan dui.

In at ipsum turpis. Aliquam non elit pulvinar, luctus eros a, tristique lorem. Praesent vitae elit neque. Vivamus molestie diam libero, id pellentesque dui feugiat at. Donec risus massa, fermentum ac ultricies quis, pulvinar et mi. Morbi fermentum velit vitae purus dignissim tempus. Sed eget ipsum interdum, venenatis dui a, convallis leo. Etiam accumsan libero nec ultrices ultricies. Curabitur vel sem neque. Nunc accumsan porta vestibulum. Nunc varius felis nec sodales bibendum. In eget arcu nec magna sagittis ultrices. Nam interdum lacinia sagittis. Donec blandit mauris nibh, a tincidunt libero suscipit ut.

Donec sed lacus efficitur, rhoncus dolor a, varius turpis. Maecenas efficitur vel justo nec hendrerit. Morbi quis mauris tristique enim tincidunt consequat. Morbi ut felis neque. Quisque eu sapien hendrerit, maximus turpis id, sollicitudin erat. Pellentesque a egestas sem, nec cursus mauris. Proin augue turpis, semper vel pulvinar in, luctus eget arcu. Mauris ullamcorper ultricies sollicitudin. Duis quis placerat odio. Pellentesque nec ullamcorper massa. Aenean sed euismod justo. Suspendisse potenti.

Praesent urna nisl, semper nec laoreet vitae, sodales sagittis nulla. Nam cursus purus eu sodales convallis. Praesent quis vulputate nulla, a vehicula nisi. Pellentesque consequat turpis eget imperdiet porta. Aenean est orci, tincidunt vel nibh vel, tempus iaculis ipsum. Donec vehicula tellus purus, et laoreet tellus pulvinar quis. Suspendisse potenti. Nullam tempus arcu vel luctus ultrices. Nulla semper, eros vitae placerat aliquam, metus arcu finibus tortor, at vulputate sapien augue sed nunc. Donec pulvinar, justo vel viverra porttitor, nisl magna mattis tortor, id venenatis dolor ex et diam.

Nunc dignissim posuere neque ut accumsan. Pellentesque laoreet sem eget accumsan lacinia. Pellentesque vel nisi tincidunt, venenatis odio ac, feugiat nulla. Praesent maximus dui quis odio eleifend, eget elementum est tincidunt. Vestibulum at tempus sem, vel cursus lacus. Sed facilisis efficitur odio, in ultrices purus vehicula ut. Praesent commodo pretium congue. Curabitur non magna in turpis interdum mattis. Pellentesque porttitor, lacus venenatis egestas iaculis, turpis est condimentum dolor, eget maximus est ligula sed velit. Aenean neque velit, malesuada sed dictum sed, auctor facilisis nunc. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Donec ac leo nunc. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras eget ullamcorper ipsum. Etiam dapibus nisl ac malesuada pellentesque.

Nota: removi a variável control do código, que não estava sendo utilizada.
Answer: Se não precisas de saber se está parado então podes optimizar removendo o ultimo else e deixar somente:
  if (scrollAmt > lastScrollTop) {
    // baixo
  }
  else if (scrollAmt < lastScrollTop) {
    // cima
  }

e a minha resposta termina aqui.
Se precisas da funcionalidade de "parado" continua a ler :)
A funcionalidade de "parado" não funciona quando escutas o evento scroll pois o evento não é disparado mais a partir do momento que o scroll chegou ao fim. Sugiro acrescentar escuta a eventos que geram scroll. Fiz um exemplo com o mouse wheel que mostra o estado "parado" quando o scroll chegou ao fim. Até podias usar a direção do mousewheel para saber a direção, mas calcular a diferença de scroll parece-me bem.
Para saber qual o evento da roda do mouse escutar podes usar este feature detect:
evento = 'onwheel' in document ? 'wheel' : 'onmousewheel' in document ? 'mousewheel' : 'DOMMouseScroll';`

O código ficaria assim:
var control = 0,
    lastScrollTop = 0,
    element = document.getElementById('rolagemAqui'),
    feedback = document.getElementById('direcao'),
    evento = 'onwheel' in document ? 'wheel' : 'onmousewheel' in document ? 'mousewheel' : 'DOMMouseScroll';

function tratarScroll() {
    var scrollAmt = element.scrollTop;
    if (scrollAmt > lastScrollTop) {
        feedback.innerHTML = "baixo";
    } else if (scrollAmt < lastScrollTop) {
        feedback.innerHTML = "cima";
    } else {
        feedback.innerHTML = "parado";
    }

    lastScrollTop = scrollAmt;
};

element.addEventListener(evento, tratarScroll);
element.addEventListener('scroll', tratarScroll);

jsFiddle: https://jsfiddle.net/vdfyxyrw/
Podes juntar a isso a funcionalidade de saber se o scroll nativo da barra chegou ao fim. Para isso tens de fazer uma barra de scroll artificial pois a barra nativa não dispara eventos para saber se estás a fazer drag no mesmo sítio.
Neste caso podias juntar mais umas linhas que funcionariam também para quando o scroll é iniciado por uma seleção de texto que força um scroll. Um exemplo disso (sem a custom scrollbar) seria assim.

Apurar direção da rolagem num elemento


Using Make's file function

Question: I'm trying to dump the value of make variables to a file for further processing.
So far, I've been able to print the values to the command line using the following rule:
print-%:
    @echo '$*=$($*)'

Which you call with the command line
make print-VAR

I really don't want it on stdout, but printed to a file.  The GNU Make "file" function seems like the thing I should be using:
http://www.gnu.org/software/make/manual/html_node/File-Function.html#File-Function
The page jumps into a complex example right away though, so I've implemented the following but can't seem to get it to work: it prints the @echo to stdout, but when I look in my directory there is no output.txt file.
printf-%:
    @echo '$*=$($*)'
    $(file > output.txt,$($*))

What am I missing?
EDIT: Well, looks like I can just use
@echo '$($*)' > output.txt

to do what I want, but that still doesn't explain why my file call wasn't working.
Comment: Why are you not simply redirecting `echo` to a file?
Comment: What version of make are you using? I believe the file function is very new.
Comment: Just checked the version, and it's 3.82 which doesn't have the file function!
Comment: Crap.. good point.  I grabbed the line @echo from another site and thought it was a make built-in and couldn't be redirected, but

    \@echo '$($*' > output.txt

works.
Comment: Please consider posting your edit as an answer and accept it.  This way, it will not appear as "unanswered" any more (which why I came over here...)
Answer: Two Responses from comments section:
1) To get the functionality desired, just redirect the "@echo" statement to a file
printf-%:
    @echo '$*=$($*)' > output.txt

2) The reason the file function did not work is that it is a feature of Make v4.0 and newer, not 3.8, which was the version I was using.
Comment: Ga-a-a! Why wouldn't earlier version error out on $(file...)? This no-op behavior was puzzling me too for quite some time!
Answer: You can print out variables before make gets to running anything in the shell. This gives you all of them (well, apart from the ones with a space in their name)
$(foreach _,${.VARIABLES},$(info $_ is $(flavor $_) with value [$(value $_)] which expands to [$_]))

giving
$ make
GNUMAKEFLAGS comes from the [environment] and is simple with value [] which expands to []
<D comes from the [automatic] and is recursive with value [$(patsubst %/,%,$(dir $<))] which expands to []
?F comes from the [automatic] and is recursive with value [$(notdir $?)] which expands to []
⋮

This is often essential as variables can change as makefiles are parsed.

Using Make's file function


How to 'tilt' a regression line

Question: I would like to know how I would go about essentially tilting a regression line. Say I have a regression line with a slope of exactly 1. I would like to instead, tilt the entire regression line clockwise so that it maintains the same distribution, but looks more like a flat line with no slope.
Comment: What does "maintains the same distribution" mean? What is this "tilting" intended to represent?  What relationship is the resulting line supposed to have with the original data (or bivariate distribution) with which the regression was performed?
Comment: Can *tilting the regression line* be formulated as *shrinking the regression coefficient towards zero*? Then you could think about shrinkage methods like LASSO or ridge regression. However, I am not sure how that would affect the distribution of errors.
Comment: @RichardHardy: weal, for one it will make the sum of squared errors larger;)
Answer: Do you mean to change the data so it has a regression line that's close to flat?
If so, just subtract some multiple of the predictor (IV, x-variable) from each data point. The slope changes by that multiple. e.g. if you say $y^*=y-2x$ then the slope of a regression of $y^*$ on $x$ will be 2 smaller than a regression of the original $y$ on $x$.
If you want it exactly flat, just take the residuals from the least squares fit as your 'tilted' $y$.

How to 'tilt' a regression line


minimum criteria for datasets used with TraMineR

Question: I posted this to the TraMineR user list and it was suggested that it would be appropriate to post it here as well.
Any suggestions as to how to determine the minimum dataset size and missingness characteristics to which TraMineR may be applied sensibly would be helpful. I looked for information in documentation but did not see anything that I could use as a heuristic.
I am using TraMineR to analyze 5 years of BMI observations, coded as a four-level ordinal categorical variable for 5046 elementary school children (grades K-5).  Only 414 of these have 5 observations ( ~ 56% of the K, 1 students measured at time 1 who could have had been measured in years 1 to 5).  Here are have two related, if not well-stated, questions:

Is it legitimate to focus only on complete cases since I only have 5 data points and high cumulative natural attrition? Testing the complete cases against all cases reveals no substantive difference in values of predictors. The analyses from complete cases are informative, while including all cases, regardless of imputation choice, just makes things noisy. I tried admitting only sequences of 4 or 5, but results were still noisy.
Is five too short a sequence object to use with TraMineR, given the imputation  patterns required by the full dataset, regardless of whether they are due  to planned missingness or MAR?
Below is the number of cases with from 1 to 5 observations.
      1    2    3   4   5
      1846 1287 869 630 414

TraMineR is a great tool. I want to make sure I am using it appropriately.
Answer: There are two aspects in that question, namely

What is the minimal dataset size for a sensible sequence analysis?
What is the maximum number (or proportion) of unknown elements that we can admit in each sequence?

And the answer depends largely on what you want to do.
Let us first discuss the dataset size.
The size of categorical sequence datasets includes three dimensions, namely

the number $n$ of sequences
sequence lengths $\ell$
the size $a$ of the alphabet

TraMineR is basically an exploratory tool and as such is useful as soon as it can help discovering or highlighting non trivial characteristics of the observed sequences.
Longitudinal characteristics (number of transitions, longitudinal distribution, longitudinal entropy, complexity index, turbulence, ...) make sense for $n=1$, but will only be useful for sequences of some length, say $\ell=4$ or 5. Longitudinal measures may have limited interest when the alphabet contains only 2 elements.
For cross-sectional characteristics (modal state, entropy, ...) size conditions are similar to those required to give sense to the distribution of a categorical variable. Again, interest increases with the size of the alphabet.
Regarding dissimilarity-based analysis, the clustering of sequences is not different from the clustering of any other kind of data. It becomes very useful when $n$ exceeds say 100 or 150.
Likewise, representative sequences prove useful when $n$ exceeds say 50 or 100, even though they can be computed and make sense for smaller sizes $n$. Discrepancy analysis is different. It is inferential and relies on statistical significance. It may be hard to find significant group distinction when $n$ is small.
If the sequences are analyzed with an inferential perspective, then the question becomes for which $n$ can we extend the characteristics of the observed sequences to the whole population. Assuming the (possibly weighted) sequences are representative of the population, the minimal required $n$ will depend on the variability of the sequences. The higher the variability across sequences, the larger the required $n$. With TraMineR, you can compute (with dissvar) a pseudo variance or pseudo deviance $s$ given the dissimilarity measure. For a given precision $r$ (maximal dissimilarity we may tolerate between two patterns to consider them as similar), a very rough solution could be $n> 2(r/s)^2$.
Regarding the number of unknown elements (missing values)
Plots (i-plot, d-plot, ...) can be useful just to highlight the presence and distribution of the unknown elements in the sequences.
Then, if the aim is to study trajectories, sequences with too many unknown elements would not carry any useful information. On the other hand, considering only complete sequences we may lose too many cases and even worth lose representativeness. A solution I have often adopted is to retain only sequences with at most a given percentage, say 30% of missing states.
An alternative that could be useful for the situation described in the question, would be to successively run a separate analysis by considering only sequences up to length 3, 4, 5, and interpret the results conditionally for sequences of at lest that length.
Answer: It depends on what you want to do with the sequences.  You can generate index plots and sequence statistics using any of the samples and missing data.  Clustering to define groups will work as well.
Perhaps a more important question is what are you trying to learn from sequences that cannot be done using the BMI percentiles as longitudinal numeric data?  You lose information when categorizing the BMI percentiles.  I also considered sequence analysis with my BMI data from kids and decided against categorical data analysis for this reason.
Comment: The motivation for categorical analysis is twofold:


Searching for files containing text (not string) in bash

Question: How do I find files containing some particular text containing newlines and plenty of other charachters all sorts of quotes and backslashes using terminal?
Comment: may be you should take a look at man pages of `egrep` to search with regular expression. As I do not know what exactly you're searching for, I can tell you this `find /dir -type f | xargs egrep '---'
Replace `'---'` with actual regex
Comment: The problem is the search pattern is way too big for this. Specifically it's a piece of html code. Tried grep -F, but the passage contains non-unique lines, so the output is messy.
Answer: grep is somewhat line-based, so matching across line boundaries might be problematic with it. If you've the memory to spare, match against the whole file with e.g. perl:
$ (echo fish; echo cat; echo dog; echo frog) \
  | perl -0777 -nE 'say $1 if m/(cat.dog)/s'

The "all sorts of quotes and backslashes" bit will likely mostly be avoiding shell interpolation rules, e.g. via '\'' type tricks or see ascii(7) and then in perl use an appropriate \047 or \x52 or whatever as necessary. Lacking the memory to load the file, strings(1) might first be used to reduce the amount of data to search.


How can I add pagination to the comments of advanced forum in drupal 7?

Question: I use Drupal 7 but don't see any pagination on the comment pages, how can I add a pager there please?
Answer: I think that this can help you.
Let me know if this is working.
Comment: hi mixerowsky, thanks a lot for your quick answer. unfortenutaly this did not worked on my side. i can see a page ron the topic list but found no solution even the link you have sent me to get the pagination on the comments working. may i missing to put a special render code to display the pager? thanks!
Comment: Whilst this may theoretically answer the question, [it would be preferable](http://meta.stackoverflow.com/q/8259) to include the essential parts of the answer here, and provide the link for reference.


Django ManyToMany relationship with abstract base - not possible, but is there a better way?

Question: Given the following models:
class BaseMachine(models.Model)
    fqdn = models.CharField(max_length=150)
    cpus = models.IntegerField()
    memory = models.IntegerField()

    class Meta:
        abstract = True

class PhysicalMachine(BaseMachine)
    location = models.CharField(max_length=150)

class VirtualMachine(BaseMachine)
    hypervisor = models.CharField(max_length=5)

class Sysadmin(models.Model):
    name = models.CharField(max_length=100)
    admin_of = models.ManyToManyField...

In this example I would like to relate 1 sysadmin to many machines - be them either an instance or PhysicalMachine or VirtualMachine. I know I can't have a ManyToMany with an abstract base, but I was wondering if there was a better way of achieving this than just having a separate ManyToMany field on sysadmin for each of the models? In this small example that could be tolerable, but if you have more than 2 subclasses, or if there are other models which you need to relate with the 'base' class, it becomes something more to manage.
Thanks :)
Answer: EDIT: I have updated the soultion, so one admin can have many machines and one machine can have many admins:
class Sysadmin(models.Model):
    name = models.CharField(max_length=100)

class BaseMachine(models.Model):
    fqdn = models.CharField(max_length=150)
    cpus = models.IntegerField()
    memory = models.IntegerField()
    admins = models.ManyToManyField(Sysadmin)

    class Meta:
        abstract = True

class PhysicalMachine(BaseMachine):
    location = models.CharField(max_length=150)

class VirtualMachine(BaseMachine):
    hypervisor = models.CharField(max_length=5)

In [1]: s1 = Sysadmin(name='mike')

In [2]: s1.save()

In [3]: m1 = PhysicalMachine(fqdn='test', cpus=1, memory=20, location='test')

In [4]: m1.save()

In [5]: m1.admins.add(s1)

In [6]: m1.save()

In [7]: m2 = VirtualMachine(fqdn='test', cpus=1, memory=20, hypervisor='test')

In [8]: m2.save()

In [9]: m2.admins.add(s1)

In [10]: m2.save()

In [11]: m1.admins.all()
Out[11]: [<Sysadmin: Sysadmin object>]

In [12]: m2.admins.all()
Out[12]: [<Sysadmin: Sysadmin object>]

Comment: But could I attach many *machine's to 1 sysadmin instance? Using ContentType I would have to create multiple sysadmin instances for each *machine?
Comment: I have updated the solution, so one admin can have many machines and one machine can have many admins.
Comment: Reversing the relationship will work for my use case, thanks guys.
Comment: If you find my answer useful, please mark it as correct with green mark. Thank you.
Answer: Have you considered a generic relationship using the contenttypes framework?


Nonparametric expected value estimation of sample from unknown distribution

Question: I have a data sample (in this case an EEG data sample, but my question refers to any type of data samples of prior unknown distributions).
I would like to do a nonparametric estimate of the expected value for my sample. I did some research, from what I understood I can do this using bootstrap sampling. I found a pdf here giving a formula for bootstrap expected value, hopefully it's correct.
In case it's not, can someone please let me know how to do it once I have generated the samples by bootstrapping?
Another possibility seems to be MCMC, but I would need to know the distribution from what I understood. I could do a kernel density estimation probably, but I think using bootstrapping might be less complex?
I can use python, Matlab or R, in case you do this kind of thing often and have code at hand to share, I'd really appreciate it.
Any other methods/suggestions are more than welcome.
Answer: It is quite simple; you make a subsample by sampling with replacement:
sample(x,replace=T)

calculate the statistic you want on it:
mean(sample(x,replace=T))

finally average it over many repetitions:
mean(replicate(1000,mean(sample(x,replace=T)))


Multiple inheritance with Django

Question: I'm using Django for a project, and I want to use a couple of apps that extend the admin by subclassing the admin class.
How can I have them both sublass the admin class?
from django.contrib import admin
from testing.models import *
from reversion.admin import VersionAdmin
from moderation.admin import ModerationAdmin

class ItemAdmin(VersionAdmin):
    pass

admin.site.register(Item, ItemAdmin)

Comment: You can't subclass a module. Subclassing is... erm... for classes. Is `class ItemAdmin(VersionAdmin, ModerationAdmin)` what you want? (I doubt it.) If so, why doesn't it work?
Answer: Both VersionAdmin and ModerationAdmin appear to use the "cooperative super" feature of Python. So I'd try to just use multiple inheritance:
class ItemAdmin(VersionAdmin, ModerationAdmin):
    pass

If this fails, you can see whether it works better with the reverse order. If this still fails, you need to study the specific issue, and find out why the cooperative super doesn't work.

Multiple inheritance with Django


Ksh and if statements

Question: I have done very little programming in C++, and I am not really understanding how to use code in KornShell (ksh) on the Knoppix OS. The resources given to us by the professor has been little, so it is hard to work out. The two text books we have for class talks mostly about commands in variations of UNIX, though little to do with ksh.
Write a shell script that accepts exactly one argument which must be a positive integer. (My second one has two)
Ksh Code:
NUMBER=$1
read -p NUMBER
# Test that one argument was input.
if [[ $# -ne 1 ]];then
  echo "Please enter an integer as an argument"
  exit 1
elif [[ $NUMBER -le 0 ]];then # Test value of argument is less than or equal to zero
    echo "Please enter a number > 0"
    exit 1
fi

while [["$NUMBER" -ne 1]];do
    printf $NUMBER
if [[$NUMBER -gt 1]];then
        printf ","
    fi
NUMBER=$(($NUMBER-1))
done
printf $NUMBER

When I run this from the shell I keep getting "Please enter an integer as an argument" as an output, though the entry was 3, or something like that.
I noticed that there was not anything for user input, so I tried to enter this myself with
read -p NUMBER

before the if statement.
What am I missing from the code to continue on with the rest of the script to be run?
Comment: I've rolled back this question.  You can say thanks by upvoting the answers and comments that helped you and *accept* the one that helped you most.
Answer: You should double quote your variables in [ ... ] conditions, or use the extended [[ ... ]] conditions (yes, a third type of condition). For numeric operations, (( .. )) are usually used (oh my, fourth type!).
See man bash or Advanced Bash Scripting Guide.
Comment: @user3193284: Try asking the professor. When I was teaching, I encouraged my students to ask questions.
Comment: The OP script is not at all using `csh` syntax. `elif` is definitely supported by `bash`, `ksh` and any POSIX compliant shell and is not a `csh` keyword. Another comment, the question is about `ksh` but you suggest `bash` documentation. Despite being both mostly POSIX shell and sharing a lot of extensions, each one have specificities so the bash scripting guide might confuse the OP.
Comment: @jlliagre: You are correct about `elif`. Nevertheless, I had responded to the original question, that had been heavily edited and retagged. In the beginning, it was tagged `bash` and contained the work in the title.
Comment: Ok removing my -1 then. You should remove your first sentence though.
Answer: The first passed argument should be acquired by using
NUMBER=$1

don't know what you mean by $X..
Note: $0 is the command executed, for example in ./myscript.sh foo
the $0 = ./myscript.sh and $1 = foo
After you set it to you variable NUMBER you can check if it's a positive integer:
if [[ $NUMBER =~ ^[0-9]+$ ]]; then
    echo "It's ok!"
else
    echo "BAD :("
fi

Comment: `NUMBER = $1` is a syntax error in shell - get rid of the spaces around the `=`. You can do that in C or C++ or Python or Perl or ..., but not in bash/ksh/sh (don't remember if that's acceptable in csh, but that's ok, really).
Comment: Thanks.  I found out, with help, that it is very picky on what it accepts as syntax. Must be a space after [[ and before ]].
Answer: To accept just one argument you should check the number of arguments passed to the script (which is what I think your teacher is asking):
if [[ $# -ne 1 ]]

$# gives you the number of arguments passed to your script, so it is easy to check the number of argumets that are being passed to it.
Now you only need to check if it is an integer and the sign. I don't know what exactly is what your teacher want you to know, but you can use awk's functions to check wether the parameter is a number, an integer and its sign (the sign is also easy with ksh).
Comment: I guess not, if your teacher asked for a script that accept exactly 1 parameter $# is the answer. You only need to test $1 once you have checked that only one parameter is passed to the script.
Comment: I mean, remove the "" and add a space after [[ and another space before ]] ----> while [[ $NUMBER -ne 1 ]];do
Answer: You should remove the read -p NUMBER instruction which defeat the previous one.
You shoud then fix that line:
elif [[ $NUMBER -le 0 ]];then

to
elif [ "$NUMBER" -le 0 ];then

The last part is using the wrong tests and is missing an ending new line:
while [["$NUMBER" -ne 1]];do
    printf $NUMBER
if [[$NUMBER -gt 1]];then
        printf ","
    fi
NUMBER=$(($NUMBER-1))
done
printf $NUMBER

should be
while [ $NUMBER -ne 1 ];do
    printf $NUMBER
    if [ $NUMBER -gt 1 ];then
        printf ","
    fi
    NUMBER=$((NUMBER-1))
done
printf "%s\n" $NUMBER

Ksh and if statements


Need help identifying a distribution by its histogram

Question: I have the sample population of a certain signal's registered amplitude maxima. Population is about 15 million samples. I produced a histogram of the population, but cannot guess the distribution with such a histogram.
EDIT1: File with raw sample values is here: raw data
Can anyone help estimate the distribution with the following histogram:
Comment: The real interest in these data lies in the dozen or more spikes: the amount of data is large enough that those are *real*, in the sense that they are evidence of actual local modes.  There seems to be a rich set of data here with a wealth of information that would be overlooked were a simple parametric formula used to summarize their distribution.
Comment: not that it matters dramatically but when using histograms it usually helps to have the relative frequency instead of absolute frequency on the y-axis.
Comment: @mbaitoff, I'm not sure it would quite fit your application, but in related application areas, magnitudes of waves that undergo (many) random reflections between source and receiver are modeled by a Rayleigh distribution or one of its generalizations, e.g., Rice or Nakagami-$m$ distributions.
Comment: @whuber♦: You're right, those spikes are not random outliers, they seem to represent groups of outliers with some seriously deviant properties. Since the background of the raw data acquisition is indeed group-based, this makes sense. However, raw data represents the maximums of the registered wavelets, and anomalous spikes in wavelets can distort the distribution. I'm now calculating some more robust statistics of the wavelets.
Comment: that is, to provide 120000/15000000=0.008 instead 120000 on vertical axis?
Comment: @mbaitoff: Your comments to the answer of schenectady indicate, that you are less interested in getting the name of the distribution but in finding out WHY the values are distributed this way. Is this correct ?
Comment: @mbaitoff - one problem with the way you have presented this question is that we have to guess at what the values are.  If you could supply some actual data points that would be helpful
Comment: @steffen: Actually, both questions are of much importance. I expect that to derive the physical background from guessed distribution is easier than to derive the distribution from the physical background, since the measured process is specific (an amplitude measurements of inducted seismic waves).
Comment: @Ralph Winters: I have edited the post to provide a link to file with raw data values.
Answer: Use fitdistrplus:
Here's the CRAN link to fitdistrplus.
Here's the old vignette link for fitdistrplus.
If the vignette link doesn't work, do a search for "Use of the library fitdistrplus to specify a distribution from data".
The vignette does a good job of explaining how to use the package.   You can look at how various distributions fit in a short period of time.   It also produces a Cullen/Frey Diagram.
#Example from the vignette
library(fitdistrplus)
x1 <- c(6.4, 13.3, 4.1, 1.3, 14.1, 10.6, 9.9, 9.6, 15.3, 22.1,
        13.4, 13.2, 8.4, 6.3, 8.9, 5.2, 10.9, 14.4)
plotdist(x1)
descdist(x1)

f1g <- fitdist(x1, "gamma")
plot(f1g)
summary(f1g)

Comment: @juanpablo - The statement `f1g <- fitdist(x1, "gamma")` fits a gamma distribution to the original data `x1` and stores it in `f1g`.   The upper left graph in `plot(f1g)` shows a histogram for the original data `x1` as the bars, and the fitted gamma density plot from `f1g` as the continuous line.  The density plot (continuous line) is drawn over the histogram as an indication of how well the "fit" represents the data.
Comment: @juanpablo - Try `descdist()`. I updated the above post to include some code and a link to the old vignette.  I could't get the above vignette link to work. So, Google the following: "Use of the library fitdistrplus to specify a distribution from data". It is a .pdf file.
Comment: (+1( did not know that was called a Cullen/Frey diagram. I had to come up with that myself at one point.
Comment: the second image is with `plotdist` comamnd? How I can get the Cullen/Frey Diagram?
Comment: thanks @bill_080, in the top-left image of `plot(f1g)`, what is the interpretation of that chart ? the bars is a representation of the histogram ? why the density curve over the histogram ?
Comment: @bill_080 many thanks, but the histogram and density have different "scales", how can they be compared ?
Comment: @juanpablo - You'll have to dig into the package to verify the exact histogram scaling calculation (probably peak histogram value scaled to match the peak density value), but it's the similarity in shape that is important.   That applies to all four of those images.   It each case, the empirical plot is being compared to the "theoretical" (or "fit") plot.
Answer:
Population is about 15 million samples.

Then you will very likely be able to reject any particular distribution of a simple, closed form.
Even that tiny bump at the left of the graph is likely to be enough to cause us to say 'clearly not such and such'.
On the other hand, it's probably pretty well approximated by a number of common distributions; obvious candidates are things like lognormal and gamma, but there are a host of others. It you look at the log of the x-variable, you can probably decide whether the lognormal is okay on sight (after taking logs, the histogram should look symmetric).
If the log is left skew, consider whether Gamma is okay, if it's right skew, consider whether inverse Gamma or (even more skew) inverse Gaussian is okay. But this exercise is more one of finding a distribution that's close enough to live with; none of these suggestions actually have all the features that appear to be present there.
If you have any theory at all to support a choice, toss out all this discussion and use that.
Comment: Wow, what kind of intuitiion that about the matter; nice! :)
Answer: I am not sure why you would want to classify a sample to a specific distribution with such a large sample size; parsimony, comparing it to another sample, looking for physical interpretation of the paramters?
Most statistical packages(R, SAS, Minitab) allow one to plot data on a graph that yields a straight line if the data come from a particular distribution. I have seen graphs that yield a straight line if the data is normal(log normal-after a log transformation), Weibull, and chi-squared come to mine immediately. This technique will allow you to see outliers and give you the possiblity to assign reasons for why data points are outliers.
In R, the normal probability plot is called qqnorm.
Comment: Good idea suggesting the qqplot. However, I think that your explanation of the technique is a little vague/hard to understand. Can you provide some exemplary R-code ? This would increase the value of the answer drastically.
Comment: I expect that somebody encountered the picture like mine and investigated the underlying distribution, because the values have physical basis.
Comment: I am investigating the physical background of the sample distribution - how it is distributed and why.


missing missing values in range mysql

Question: I have already asked a similar question, but I still don't seem to be able to get my head around it. I have a column device_create_date on my sql database
2015-07-14 12:35:19
2015-07-15 12:45:37
2015-07-15 12:45:37
2015-07-16 12:35:37
2015-08-14 10:35:21
2015-08-14 12:15:36

I am aggregating these date values in weeks, but there are missing values in between the weeks, where I want these values to just equal 0 so that I can compere them with other metrics in an excel sheet. I created a dummy table "date" to join the values with, so that the select returns 0 for the weeks there are no values for.
Here is the query I used,
select date.year, week(device.device_create_date), count(*)
from device
join date
on date.week_of_year=week(device.device_create_date)
where device.id_customer = 1
group by device.year, date.WEEK_OF_YEAR
order by device.year, date.week_of_year;

Here is what I got back,
2010    26  7252
2010    31  3108
2010    45  7203
2010    1   9324
2010    2   7252
2010    3   2072

Here is what I want it to give me back;
2010 1  9324
2010 2  7252
2010 3  2072
2010 4  0
2010 5  0
2010 6  0
etc

btw these values don't seem to be matching the count on the database either, so I kinda know I'm doing something completely wrong but I am not great at this so any help and direction would be greatly appreciated.
Thank you in advance!!
Comment: We need structure of `device`  ..
Comment: use right join in this case, not inner join. Plus if you have multiple year's data, then you need to use year and week in the date table and join on both.
Answer: Since you always want values from the date table (to get all possible dates) and the the matching rows from device you'll want to use date as the source and use a left join with the device table since an inner join would only return data that matches in both tables.
Try this instead:
select date.year, date.week_of_year, count(device.device_create_date)
from date
left join device on date.week_of_year = week(device.device_create_date)
                and device.id_customer = 1
group by date.year, date.week_of_year
order by date.year, date.week_of_year;

If your tables contain data from more than one year you should add a condition for the year to the join so you don't mix data from multiple years.
Comment: That worked wonders, thank you very much jpw its much appreciated, I spotted the mistake as well after your comment, instead of count(*), count the device create date. I'm under 15 rep so I can't vote up your comment but it was perfect!
Comment: @NickKo If you have data for upcoming years in the `date` table you need to add a filter to only get the year you want: `where date.year = 2015` for instance. You should probably add `and date.year = year(device.device_create_date)` to the join too.
Comment: I read the last comment in answer a bit late hah, yeah it's all working fine now, thank you. #thumbsup

missing missing values in range mysql


Motion question on escape velocity

Question: Assume that the magnitude and direction due to gravity at a point outside Earth at distance $x$ from the Earth's centre is equal to $-\frac{k}{x^2}$, where $k$ is a constant.
i) Neglecting atmospheric resistance, prove that is an object is projected from the Earth's surface with speed $u$, it's speed $v$ in any position is given by $v^2=u^2-2gR^2(\frac1R-\frac1x)$ where $R$ is the Earth's radius and $g$ is the magnitude of acceleration due to Earth's gravity at the Earth's surface.
ii) Show that the greatest height $H$ above the Earth's surface is given by $H=\frac{u^2R}{2gR-u^2}$
iii) Hence if the radius of the Earth is $6400$km and the acceleration due to gravity is $9.8ms^{-1}$ find the speed required by the object to escape Earth's gravitational influence.
I've done part i) and iii), I'm struggling with part ii)
For Part ii) I've let $v=0$ but I get $x=\frac{2gR^2}{2gR-u^2}$
Comment: Since this isn't a physics a forum, you might want to include the fact that $g=\frac{k}{R^2}$.
Comment: I think the maths department at our school expects us to be able to work that out organically because I had to work that out for myself in part i)
Comment: For part 3 you would use the condition in part ii and set $\lim_{H\to\infty}$. I am also stuck on part ii. I don't think it is possible to solve the differential equation from part i. Could we use the fact that the maximum height will be attained when the velocity is $0$? I'm not sure if this statement is necessarily true in all differential equations, however.
Comment: @AlanAbraham in another question on this site https://math.stackexchange.com/questions/1645277/differential-equations-v-fracdvdx-g-fraca2x2?rq=1 someone has asked to show the same thing but the answer stops at where I cannot continue so I assume that is the correct condition.
Comment: @AlanAbraham also for part iii) am I supposed to get 11,200m/s after applying the limit?
Comment: Yes, you should get Earth's actual escape velocity, which is indeed $11200$ m/s
Comment: What is $x$ in part (i)?
Comment: @K.defaoite $x$ is it's distance from the centre of the earth
Answer: I'm pretty sure you made this mistake: Substituting $H=x$ instead of $R+H=x$. With $x=R+H$, and with $v=0$, we have $u^2=2gR^2\left(\dfrac{1}{R}-\dfrac{1}{R+H}\right)=\dfrac{2gRH}{R+H} \implies H=\dfrac{u^2R}{2gR-u^2}$. Hope it helps!

Motion question on escape velocity


How should I check an existing system value with Ansible?

Question: I have an Ansible task where I set the version of Ruby used globally on my system.
- name: Set Ruby global version
  shell: /usr/local/bin/rbenv global 2.2.1

The problem is that this task always has the status of changed. I want it to show changed only if it actually has changed, otherwise ok. This is the best solution I could come up with:
- name: Get current global version Ruby
  shell: /usr/local/bin/rbenv global"
  register: current_ruby_version
  changed_when: False

- name: Set Ruby global version
  shell: /usr/local/bin/rbenv global 2.2.1
  changed_when: current_ruby_version.stdout != 2.2.1

This is going to be a pattern that I'm going to use a lot (check existing value, set value, see if it changed) so this is a bit onerous.
Is there a better way to do this?
Answer: You could combine it into one task:
- name: Set global version Ruby
  shell: /usr/local/bin/rbenv global; /usr/local/bin/rbenv global 2.2.1
  register: old_ruby_version
  changed_when: old_ruby_version.stdout != 2.2.1


How to get users accounts (pages) description using one Facebook API call?

Question: When I want to users description of the pages in facebook:

First of all using graphPath: me/accounts (It returns only IDs of pages)
Second by using page API call getting description field.

In this scenario I need to execute several API call to for getting description of the page.
My question is here a way to get pages description with one Facebook API request?
Answer: This would be the API call: <code>/me/accounts?fields=id,name,description</code>
Example: https://developers.facebook.com/tools/explorer/?method=GET&path=me%2Faccounts%3Ffields%3Did%2Cname%2Cdescription&version=v2.11
Comment: Thanks. Do you know how would be possible to get email address of me/accounts?
Comment: /me/accounts?fields=id,name,description,emails


What should one keep in mind when writing the Neapolitan 6th chord in a chord progression?

Question: So I have just started reading about the Neapolitan 6th, & I'm new to this topic. I know that it is generally used in its first inversion, & is often followed by chord V. Thus it is used in the bII - V - i chord progression (with bII being in first inversion).
A website mentioned about writing this chord in a cadence. It said:

Double the third of the Neapolitan 6th chord. The lowered second scale degree always moves down to the leading tone.

Is this what is generally done while writing the Neapolitan chord? Do you need to double only the 3rd of the chord, or is it possible to double the root of the chord?
Comment: The answer in https://music.stackexchange.com/questions/76416 may interest you. It has a Schubert example showing a Neapolitan in both perfect and half cadences.
Comment: Related: https://music.stackexchange.com/questions/85955/ii6-i-cadence-plagal-or-authentic
Answer: Yes, you generally double the 3rd of the chord. It's the chord note that is easier to resolve. Let's take this example in C major, a simple I bii V I:

You can see that both the neapolitan chord and V use the note D (flat in the first chord, natural in the second one). This is usually considered a bad harmonic relationship (in two chords played next to each other), but with the neapolitan chord, it works. But if you were to double the root (Db), this would be trickier to resolve. Doubling the 3rd is the "safest" way to go.

The lowered second scale degree always moves down to the leading tone.

That is true. Look at the top voice of my example: C->Db->B->C. Db is indeed moving to the leading tone (B) and then to C at the end of my melody.
The progression you posted is one of the most common ones, but you can follow the chord with the I as well:

Or have the I in second inversion, which in turn is followed by the V

Also, it's quite common to find this chord after the iv (or IV in a major scale), because they have the same bass note:

Despite the fact that this is an out-of-scale chord, it sounds quite pleasant to the ears and is a widely accepted chord in the theory/harmony tests.


Creating new template for new page

Question: In drupal 7, I created a content type called page and set the url to /about. If I check the source code I see
<link rel="canonical" href="/website/about">

and
<link rel="shortlink" href="/website/node/7" />

So if I create a new template called page--node--7.tpl.php then it works.
But if I create a new template called page--about.tpl.php it wont get picked up.
What am I doing wrong here?
Thanks!
Answer: I think you have issue with hook_suggestions that we need to configure correctly for a template to work.
Its already answered here
drupal 7 template suggestions based on path alias
Hope it will help!
Comment: Worked like a charm, thanks for pointing me to it!
Comment: @Jean if this is **the answer** to your question, you used it and it worked, consider marking it as accepted. It is in no way obligatory, but it tells other users with the same problem "this is what I did, and it worked for me" - pretty useful piece of information, right? :)
Answer: You aren't doing anything wrong per se Jean.
I am assuming that you created the content type page and then created a node of the type page. To create a template for just the page you just created and not all of the instances of the content type page, using the node ID is a fairly standard solution. If you want to have that template for all instances of the content type page then you would use page--Content_Type_MACHINE_NAME.tpl.php
You also need to add a preprocess function for that to function:
function THEME_preprocess_page(&$vars, $hook) {
  if (isset($vars['node']->type)) {
    // If the content type's machine name is "my_machine_name" the file
    // name will be "page--my-machine-name.tpl.php".
    $vars['theme_hook_suggestions'][] = 'page__' . $vars['node']->type;
  }
}

I am curious about naming your new content type page since Drupal has a Basic Page content type with the machine name of page already. What is the machine name of your new content type?
If you absolutely must have the template based on the URL then it looks like you need a different preprocess function. I'd think twice about approaching it this way since it is so easy to change the path/alias. You will need to install the path module for this preprocess function to work:
<?php
/**
 * implements theme_preprocess_page() function
 */
// drupal7 code
function yourthemename_preprocess_page(&$vars) {
  // create template based on url aliases if path module is enabled
  if (module_exists('path')) {
    $alias = drupal_get_path_alias(str_replace('/edit','',$_GET['q']));
    if ($alias != $_GET['q']) {
      $template_filename = 'page';
      foreach (explode('/', $alias) as $path_part) {
          // d7 contains two underscore _ after page.
         // During creating tpl file underscore (_) is converted to dash (-)   i.e page--gallery.tpl.php
        $template_filename = $template_filename . '__' . $path_part;        $vars['theme_hook_suggestions'][] = $template_filename; // drupal 7
      }
    }
  }
}
?>

Comment: I do have the path module installed. I set the machine name to "about", I used the code from the comment above and it worked nicely. But from what I gather you suggest to just keep it at page--node--7 etc.
Comment: I do. Only because the page template will not be applied if the alias is changed. Probably not a big issue with your About page.

Creating new template for new page


how to add additional token request (resource) to crm dynamics api integration in spring boot

Question: Need to integrate CRM API in spring boot. I am facing challenge as to how to configure/add additional token request(resource: xyz-dynamics.com), key-value , sent in request body to generate token.
Comment: Found answer to the above :
https://stackoverflow.com/questions/72362533/oauth2-client-with-extra-parameters-in-body-audience
Answer: Depending on what your trying to do, you will want to review one of these flows: https://learn.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-client-creds-grant-flow
if your connecting to PowerPlatform (Dataverse API - some folk still call it CRMAPI), one of the key things that trips folks up most of the time is setting the resource correctly.
The resource / scope you use must be set to the org URL including trailing /.
The Online system will tell you what to use for this if you ask it by querying the API endpoint without authentication.  the response will include a www-authenticate header that includes the Resource name and Authority you need to contact to get a token for that environment.
You can see a code example of this in the Dataverse ServiceClient (.net Client Lib provided by Microsoft) here: https://github.com/microsoft/PowerPlatform-DataverseServiceClient/blob/90998e3ffbf7e6bc25cd0ff82a15c0f0dbcff049/src/GeneralTools/DataverseClient/Client/Auth/AuthorityResolver.cs#L67C74-L67C74


Checkboxes in Webform Custom Composite Table

Question: I've been testing Drupal 9 and Webform 6.2.0-beta2. After researching a few hours, my understanding is that the current Webform doesn't support checkboxes in custom composite fields tables. Is that correct?
For instance, a field type "checkbox" with multiple options like "red, yellow, blue, and black". Once the form processes, these options don't appear on the page.
Answer: @see Issue #3216923: Radios or Checkboxes inside Composite not saved


How steep a hill does a low seeded (tennis) player have to climb?

Question: It was shocking, but a low seeded player ousted Number 2 seeded Li Na in the first (women's) round of the French Open.
My understanding is that the seeding is designed to prevent this from happening so early. For instance, in a field of 128, the top seed is matched against the 128th seed in the first round, the number 2 against the 127th, etc. The idea in the first round is to eliminate the bottom 64 players, and most of the "survivors" will be seeded 1-64.
Given that Kristina Mladenovic eliminated Li Na, it's unlikely that she's really "only" 127. And she gets Li Na's (number 2) spot for the second round of 64, and is likely to be paired against say, the 63rd seeded player.
Would it be a reasonable guess that Mladenovic's true talent level is probably at least 50th to 100th, so that she's probably not an underdog against the number 63rd seed in the second round? Or does history show that these early round eliminations are "flukes" and the "eliminator" gets eliminated soon after?
Comment: One thing to note is that a player's ranking is determined from results over a period of time. *Assuming all things equal*, this would mean Li Na has a better ranking than Kristina Mladenovic because she has had better results over a period of time (in response to "it's unlikely that she's really 'only' 127" - she is ranked as such because her body of work indicates so). Ranking is an indicator of "talent level" (or they wouldn't be ranked as high), but the overall body of *objective* work (ie, results) has to be considered as well.
Answer: Let's clear up a couple of things first...
Only 32 players are seeded in the women's singles draw at the French Open this year. The rest of the field are not seeded, qualifiers, or wild-card entries.
Also - a players "talent level" does not necessarily correspond to their position in the draw or even their seeding. Kristina Mladenovic was in the main draw only because her world ranking 2 weeks prior to the French Open was high enough to warrant her being there. She's currently ranked 103 and has been ranked as high as 36 in her career. It was random that she faced Li Na in the first round - not because she's seeded/ranked #127.
Lastly - don't forget about the "bad day at the office" factor in tennis. As we saw with both Li Na and Serena Williams at the French Open this year - if you have one bad match where you're not playing your best - and your opponent is - you're out. That's the harsh reality of tennis and single elimination tournament competition.
Now, to answer your question...
It sounds like the seeding method you are thinking of is how the Men's NCAA D1 basketball tournament brackets are drawn up (with the #1 seed playing the #16, #2 playing #15 and so on) - but that's not really how tennis does their tournament draws.
In tennis - the seeded players are each put into their own area (usually a quarter) of the draw (how many seeds there are depends on the tournament and the size of the draw). For example, the #1 seed will be in the first/top position of the draw, and the #2 seed will be in the last/bottom position of the draw. This is done so that the #1 and #2 seeds can't possibly face each other until the final match of the tournament.
Once you go past the #1 and #2 seeds, it starts becoming more random about where the seeds fall into the draw rather than a specific formula being applied.
All that is guaranteed after #1 and #2 placement is that the following 6 seeds (#3-#8) end up evenly placed into the 4 quarters of the draw - so again, for the French Open, which is a draw of 128 players for the Women's Singles - two of the top 8 seeds will be within positions 1-32, 33-64, 65-96 and 97-128. Usually those two seeded players go into the first and last positions within those numbers (so they only face each other at the latest possible round).
After that, where the seeded players fall in the draw becomes more random (names drawn from a hat) - and where non-seeded, qualifier and wild-card players fall is also random. The fact that Li Na faced Kristina Mladenovic in the first round had nothing really to do with anything like seeding or ranking - it was just the luck of the draw. I'm guessing that 8 or 9 times out of 10, Li Na wins against a player like Kristina Mladenovic - it just happened to not be her day during that match.
To further show how the draw is more random for non-seeded players, Kristina Mladenovic played Alison Riske in the second round - who's currently ranked #45 in the world - and she also won that match. From what I've seen of lower-ranked players in grand slam events that beat a very high ranked player - the lower-ranked players usually "flame out" in the next round because of their emotional high coming off the "fluke" victory the previous round. Many examples of that come to mind - Stakhovsky beating Federer at Wimbledon and losing in the next round, Lukas Rosol beating Nadal at Wimbledon and then losing in the next round, etc. It's pretty common to see.
Comment: Keep in mind that "true talent level" can change day to day in Tennis. Would you say that because Li Na lost to her that Li Na's "true talent level" is 104? I think not. In Tennis - most of the top 100 or 200 in the world can all compete with each other. Your seeding or ranking matters very little - it has more to do with how well you play on any given day.
Comment: OK, Mladenovic was ranked 103, but given that she beat number 45 in the second round, she made it into the top 32, so her true talent level is at least 30th-40th. That's still "long odds" against number 2, but not as long as 103rd. Whether or not she goes further depends on how she "stacks up" against the survivors.
Comment: When I referred to "true talent level," I meant on a given day, and also on a given court (clay versus grass, versus other courts). I also believe that Li Na regressed, and on that day, she might have been 10 to 20th, instead of "top 5."
Comment: Keep in mind too that Tennis is a very mental and emotional sport and momentum and confidence can play a big role in the outcome of a match. I'm sure once Mladenovic won a set, her confidence was soaring and the momentum in the match shifted her way. From then, she probably felt less pressure and was willing to play a little riskier tennis since she was playing with the lead, rather than playing more conservative  perhaps if she was playing from behind.
Answer: This was too long for a comment, so I am posting it as a CW-answer.
From Wikipedia (here is link to current revision, just in case the article changes in the future):

One version of seeding is where brackets are set up so that the quarterfinal pairings (barring any upsets) would be the 1 seed vs. the 8 seed, 2 vs. 7, 3 vs. 6 and 4 vs. 5; however, this is not the procedure that is followed in most tennis tournaments, where the 1 and 2 seeds are placed in separate brackets, but then the 3 and 4 seeds are assigned to their brackets randomly, and so too are seeds 5 through 8, and so on.
  ...
  While this may seem unfair to a casual observer, it should be
  pointed out that rankings of tennis players are generated by
  computers, and players tend to change ranking positions very
  gradually, so that a more equitable method of determining the pairings
  might result in many of the same head-to-head matchups being repeated
  over and over again in successive tournaments.


Como colocar mais de um pickerView em apenas uma ViewController

Question: Estou tentando montar uma View que pegue os dados do usuário, como altura, peso e idade, usando PickerViews.
Não está me retornando nenhum erro, porém quando executo, as pickerViews ficam apenas com uma interrogação, conforme a foto.
No print, está me retornando o número correto da [row], porém na tela não.
Segue abaixo parte do código:
class IMCViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource
{

    let arrayAnos : [Int] = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18]
    let arrayAltura: [Int] = [50, 51,52,53,54,55,56,57,58,59,60]
    let arrayPeso: [Int] = [30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52]

override func viewDidLoad() {
        super.viewDidLoad()

        self.pickerViewPeso.delegate = self
        self.pickerViewPeso.dataSource = self

        self.pickerViewAltura.delegate = self
        self.pickerViewAltura.dataSource = self

        self.pickerViewIdade.delegate = self
        self.pickerViewIdade.dataSource = self

  // MARK: - Métodos de UIPickerViewDataSource

    // Método que define a quantidade de components (colunas) do pickerView
    func numberOfComponents(in pickerView: UIPickerView) -> Int {

        if pickerView == pickerViewAltura {
      //      return arrayAltura.count
        return 1
        }
        else if pickerView == pickerViewPeso {
        return 1

        } else {
        return 1
        }
    }

    // Método que define a quantidade de linhas para cada component
    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {

        if pickerView == pickerViewAltura
        {
            return self.arrayAltura.count
        }
        else if pickerView == pickerViewPeso
        {
            return self.arrayPeso.count
        }
        else
        {
            return self.arrayAnos.count
        }
    }

    // MARK: - Métodos de UIPickerViewDelegate

   func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> Int! {
                if pickerView == pickerViewPeso {
                return self.arrayPeso[row]
            }
                if pickerView == pickerViewAltura {
                return self.arrayAltura[row]
            }
                else{

                return self.arrayAnos[row]
            }
            }

    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {

        if pickerView == pickerViewPeso {
        print("Peso Selecionada: \(row)")
           pesoUsuario = arrayPeso[row]
           print ("O peso do usuário é: \(pesoUsuario)")
        }
        else if pickerView == pickerViewAltura {
        print("Altura Selecionada: \(row)")
        alturaUsuario = arrayAltura[row]
            print ("Altura do usuário: \(alturaUsuario)")
        }
        else{
        print("Idade Selecionada: \(row.description)")
            idadeUsuario = arrayAnos[row]
            print ("Idade do usuário:\(idadeUsuario)")
        }
    }
    }

Podem me ajudar?
Desde já mto obrigado!
Answer: Eu sou novo nesse negocio de swift...E também estou apanhando para
montar um pickerview. Peguei o seu código e rodei...
Realmente aconteceu o que você demonstrou.
Então eu mudei os arrays para String
let arrayAnos : [String] = ["1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17","18"]
let arrayAltura: [String] = ["50", "51","52","53","54","55","56","57","58","59","60"]
let arrayPeso: [String] = ["30","31","32","33","34","35","36","37","38","39","40","41","42","43","44","45","46","47","48","49","50","51","52"]

e mudei o retorno da função
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> Int!

para
 func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String?

Ai tudo funcionou perfeitamente.
Answer: Valeu Ricardo!
Realmente desse jeito funcionou também!
Porém consegui de uma outra forma rs
Eu apenas converti o resultado, pq estava retornando um Inteiro no método, porém a função titleForRow retorna apenas Strings e mantive meu array com inteiros, pois facilitaria em alguns cálculos que preciso fazer com os dados, então apenas converti o resultado para String conforme abaixo:
Muito obrigado, infelizmente sou novo no StackOverflow e não consigo contabilizar meu voto em sua resposta :/
//Função que atribui os títulos para cada row do pickerView
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
            if pickerView == pickerViewPeso {

                return String("\(arrayPeso[row]) Kg")
        }
                if pickerView == pickerViewAltura {
                return String("\(arrayAltura[row]) Cm")

                }else{
                if pickerView == pickerViewIdade && arrayAnos[row] == 1 {
                    return String ("\(arrayAnos[row]) ano")
                }else{
                    return String("\(arrayAnos[row]) anos")

                    }
                }

Answer: Você pode usar a propriedade tag e usar switch ou if e else para distinguir eles.
PickerView.tag = 1

E não tem necessidade de você usar String para converter.


Check my work on permutations of letters

Question:
In how many arrangements can the word "CORONA" be arranged in only 4 letters with no restriction?

I divided into 2 cases:
Case 1: No doubles, hence we have 1 C, 1 O, 1 R, 1 N and 1 A to arrange into 4 spaces, so 5P4, in other words 5!.
Case 2: one double, we have a double O, to arrange into 4 spaces with repetition, so $\frac{4P2}{2!}$ and the rest of the letters C, R, N and A, to be arranged in the 2 remaining spaces, hence $\frac{4P2}{2!}\cdot 4P2$
So the final answer will be adding both: $\frac{4P2}{2!}\cdot 4P2+5!=192$
Is this correct?
Answer:
In how many arrangements can the word "CORONA" be arranged in only 4 letters with no restriction?

Yes your work is both accurate and valid.  However, I found it a bit confusing.
I would have worded it this way.
$\underline{\text{case 1: 0 O's}}$
4! ways to permute the C, R, N, A.
4!
$\underline{\text{case 2: 1 O}}$
$\binom{4}{3} = 4$ ways to choose the other three letters.
Then, 4! ways to permute the O with the other 3 letters.
$4 \times 4!$
$\underline{\text{case 3: 2 O's}}$
$\binom{4}{2} = 6$ ways to choose the other two letters.
Then, $4 \times 3 = 12$ ways to place the other two letters.
$6 \times 12$
Final answer:
$$(4!) + (4 \times 4!) + (6 \times 12).$$


Introductory data trend analysis with R

Question: I am new to the data analysis world and am struggling to find relevant articles / examples related to what I'm trying to do. I have a data set that is like this, for example how many apples are sold at the store each day (where T0 is closing) (stored in a CSV):
Day,T0,T-1,T-2,T-3,...,T-10
2015-04-18,500,400,300,200,...,0
2014-04-17,800,700,200,100,...,0
...

So far I have been able to read the file in and plot a simple line graph for a single day.  Now I want to do more,

Plot all days on a single line graph against each other
Trend analysis (e.g., whats the average sale count in the last hour)
Prediction work (e.g., based on morning sales, whats expected in the last few hours)

I am not looking for specific help with this specific example, but rather examples or case studies online to help guide me to the functionality I need in R.
Answer:
Plotting in R is very convinient using the ggplot2 package.
Have a look at ?ggplot2::geom_line and http://docs.ggplot2.org/current/geom_line.html to see some examples

For trend analysis there are lors of functions. You can use the base R functions. In your example (assuming your data is called df) mean(df$T0) will give you the avg. sales count in the last hour.
There are lots of predition methods implemented in R.
Easy to understand are linear models see ?lm and maybe use the forecast package.

Hope this helps you with your very broad question.
Comment: Thanks, I will look into ggplot2, it sounds like what I am after!

Introductory data trend analysis with R


Insert element with LXML and set attribute and text

Question: I want to insert elements with the same tag multiple times, with different contents and attribute each time with LXML. While it's easy to insert the element, how do I fetch the newly created element to set its text and attributes?
text = ['First', 'Second', 'Third']

for i, t in enumerate(text):
    parent.insert(i, etree.Element('tspan')
    # Now, what object should I use to set text and attrib?

Answer: Using ElementTree (no external library is required)
import xml.etree.ElementTree as ET

xml = '''<root></root>'''
text = ['First', 'Second', 'Third']

root = ET.fromstring(xml)
for txt in text:
    sub = ET.SubElement(root,'tspan')
    sub.text = txt
ET.dump(root)

output
<?xml version="1.0" encoding="UTF-8"?>
<root>
   <tspan>First</tspan>
   <tspan>Second</tspan>
   <tspan>Third</tspan>
</root>

Comment: Thanks, that seems to work with LXML too. I didn't know about the `SubElement` method which returns the newly created element, contrary to `insert`.


Where should I implement my url redirect block?

Question: I have hundreds of url redirects to implement and I am not quite certain where the best, most efficient place to implement the redirect block is:
on the Varnish server or on the Nginx server. The architecture is illustrated below:

I am inclined to implement it on the varnish server as it is the first port of call after the CDN.
Please advise on weaknesses or potential issues with this. Thanks.
Answer: Actually I think you should implement the redirects in nginx. Here is why:
Varnish can indeed create synthetic redirects, but it has to go through a lengthy chain of if comparisons for each request, which gets slower the more redirects you add. It's O(n).
In nginx, you would create a map of old and new URLs as shown below. Because the map is stored in hash tables, lookup is much faster, about O(log n). The difference is not important with only a few redirects, but after hundreds it may get noticeable. After 57,000, it would be very slow in varnish.
In addition, varnish can now cache the redirects, instead of having to synthetically recreate them each request.
The setup in nginx looks like this: You create the map of old and new URLs, for example:
map $uri $new_uri {
    /sofa.html /living/sofas/
    /beds.html /bedroom/beds/
}

Then in the server block which will do the redirections, you simply add a test to see if one of the URLs matched and redirect if it did:
if ($new_uri) {
   return 301 $new_uri;
}


Como calcular a diferença em horas entre duas datas PHP

Question: Tenho duas datas no formato yyyy-mm-dd HH:ii:ss
A data de entrada "$dataE" e
a data de saída "$dataS", tem o objetivo de guardar a data de entrada de um funcionário e a data de saída. Até aqui está tudo bem, agora falta ir buscar esses dois valores "$dataE" e "$dataS" e fazer a diferença para saber as horas totais de trabalho.
Answer: <code>    $start  = new \DateTime( '2017-01-9 10:00:00' );
    $end    = new \DateTime( '2018-02-10 11:39:37' );

    $interval = $start->diff( $end );

    echo implode(",", [
        $interval->y . " anos",
        $interval->m . " meses",
        $interval->d . " dias",
        $interval->h . " horas",
        $interval->i . " minutos",
        $interval->s . " segundos",
    ]);

    echo "Diferença em Horas é : " . ($interval->h + ($interval->days * 24));
</code>
Irá exibir:
<code>    1 anos,1 meses,1 dias,1 horas,39 minutos,37 segundos
    Diferença em Horas é : 9529
</code>
Comment: A minha dificuldade está na parte de ir buscar uma data já inserida, ou seja a parte "$start  = new \DateTime( '2017-01-9 10:00:00' );" não estou a conseguir ir buscar a data que foi inserida no form para substituir a parte "2017-01-9 10:00:00", mas está a guardar a data de saida e de entrada na base de dados


Página em paisagem, e não a figura

Question: Estou criando um arquivo no latex, e precisa que uma das páginas fique em paisagem, pois tem várias figuras. Entretanto, apenas as figuras estão ficando em paisagem, e não a página em si.
Estou fazendo dessa forma:
\begin{landscape}
\begin{figure}[H]
\caption{\label{fig:sub_2018_OSPO-OSISAF_media}OSISAF E OSTIA}
\centering
\includegraphics[width=6cm,height=4cm]{Figuras_resultado/fig_sub_mes_estacao/sub_201801_OSPO-OSISAF_media.jpg}
 ... várias figuras
\end{figure}
\end{landscape}

Como está ficando:

Como quero que fique:

Alguém sabe como fazer isso?
Obrigada pela atenção.
Answer: pdflscape
Se você está utilizando um editor LaTeX PDF, utilize o pdflscape, que adiciona suporte PDF ao pacote lscape. Conforme o código de exemplo a seguir:
\usepackage{pdflscape}
...
\begin{landscape}
...
\end{landscape}

Um exemplo pode ser visto no Overleaf.
lscape
Ou o pacote lscape
\usepackage{lscape}
...
\begin{landscape}
...
\end{landscape}

Comment: Olá. Deu certo! Obrigada!

Página em paisagem, e não a figura