What is this small line between 2 notes?

Question:
Can someone please let me know what the small vertical line between the 2Es marked 5 and 3 in the treble clef is?
What is the purpose of it? This is in one of my piano music sheets.
Comment: I suspect a typesetting/printing error, but someone with more piano score experience may recognize it.  Might be related to https://music.stackexchange.com/questions/70009/what-is-the-meaning-of-this-small-vertical-line
Comment: Does this line occur only once or multiple times in your sheets?
Answer: It's definitely odd and I haven't seen many of these, but I believe its meaning varies with the each author.
I've seen some use this little vertical line to mark a change of scale/mode from that point onwards, and on others to indicate a break on a repetitive pattern that came before it, usually with note's lengths.
If you can post the score before and after it we can further analyse. Also, try to find another of these vertical lines on the same score so we can rule out a typo.
Comment: I suspect Alphonso's comment is correct:   it's emphasizing the finger-shift that's indicated with the   3 -- 5  notation above the notes.
Answer: The small line between the two Es (and the longer one in bass for that matter) is a tie. The note needs to be one beat (one quarter, one crotchet) long, and since there's a quaver before and after it, it makes it easier to read to lwrite two E quavers and tie them. Play the first, keep the note held until you play the B. In l.h. hold the E for two and a half beats.
OR - the vertical line ( not a well-worded question) means play the same note again - but watch that you change fingers first.
Comment: not the tie, the small line between the two higher Es. Looking at it again, it may indicate the finger shift from 5th to 3rd finger on the same note.
Comment: @CarlWitthoft - there are *four* Es in what purports to be the treble clef, and two more in the bass, and there was no mention of a bee-line. Is a line not a curve? Most of the straight lines I draw are...
Comment: I fear I must object because the tie is not a line - it's a curve.  Signed, Mr. Math_OCD .    And because the question quite specifically says "the 2 Es in the treble clef"
Comment: Well I cant see any clefs at all!
Answer: I have not been able to find anything that explains this marking, but I have two guesses.
The first is that it has something to do with playing harpsichord, perhaps an indication to change register, since Purcell was writing for harpsichord, not piano.
The second is that it is a phrase marking of sorts, an indication of a break. Beat 3 is ending a phrase. The whole measure is a tonic chord, and the two 16th notes are acting as a pick-up into the next measure. In playing this piece, especially on piano, the repeated Es and change in fingering would necessarily mean that the first E would have to be cut off short if the 2nd E were to be played directly on the second half of beat 3. However, because the LH notes on beat 3 are also eighth notes, it is a clear indication that both hands must hold that 8th note for full value and release together. This then means there is a break before the next phrase to allow for the action of playing a repeated note in the RH, and the 2nd half of beat 3 will being "late."


Search for simpler (other) idea to show $(1.001)^{1000}>2$

Question: The below question asked me to solve: (without using logarithm) which one is bigger $$2 \ , \ (1.001)^{1000}$$ I use two Idea to show $(1.001)^{1000}$ is bigger.

First: $$\lim_{n \to \infty}\left(1+\frac 1n\right)^n=e=2.71...\\$$and $1000$ is big enough to say $$(1.001)^{1000} \sim e>2$$
Second: Using binomial expansion $$(1.001)^{1000}=(1+0.001)^{1000}=\\1+1000\times 1^{999} \times (0.001) +\frac {1000\times 999}{2}1^{998}(.001)^2+...=\\1+1+\frac{999}{2000}+...>2$$   Now ,my question is there any simpler or other Idea to show $(1.001)^{1000}>2$
Thanks in advance for any hint.
Comment: I think your binomial expansion approach is pretty simple and natural. You don't even need to evaluate the third term - just see that it is >0.
Comment: Show that $n \mapsto \left( {1 + \frac{1}{n}} \right)^n $ is strictly increasing: by the AM-GM inequality $$\left( {1 + \frac{1}{n}} \right)^n  = \left( {1 + \frac{1}{n}} \right)^n  \cdot 1 < \left[ {\frac{{n\left( {1 + \frac{1}{n}} \right) + 1}}{{n + 1}}} \right]^{n + 1}  = \left( {1 + \frac{1}{{n + 1}}} \right)^{n + 1} .
$$
Comment: "$1000$ is big enough ..." is a bit unconvincing. $(1.001)^x=2$ at around $693$. This is mere luck if you ask me
Comment: @Khosrotash Then $2 = a_1  < a_{1000} $. ($a_n=\left(1+\frac{1}{n}\right)^n$)
Comment: @Gary: Thank you but after that ?
Comment: @Gary: Oh I got it just a moment when I send a comment, anyway  I do appreciate.
Answer: According to Bernoullli's inequality, we have $(1+x)^r\ge1+xr$. for this problem consider $x=0.001$ and $r=1000$.
Note: Here $(1+x)^r=1+xr$ is not the case because $r\neq0$
Comment: I wouldn't say that using only the first two terms in the binomial expansion is 'simpler' than the binomial expansion itself.
Answer: The inequality is equivalent to
$$2^{\frac 1{1000}} <1+\frac 1{1000} $$
But this is true according to GM-AM:
$$2^{\frac 1{1000}} = \sqrt[1000]{1^{999}\cdot 2}\stackrel{GM-AM}{<}\frac{999+2}{1000} = 1+\frac 1{1000}$$
Comment: VERY nice +1. i enjoy....this one is very simple to understand.
Comment: @Khosrotash Thank you for your appreciation :-)
Comment: I do appreciate it,  but as time goes new ideas coming... I want to take tickmark to answer, but let me know if there is more solution.
Answer: By elementary arithmetic:
$$1.001^2=1.002001\ge1.002$$
$$1.001^4=1.004006004001\ge1.004$$
$$\cdots$$
$$1.001^{128}>1.128.$$
$$1.001^{256}>1.256.$$
$$1.001^{512}>1.512.$$
Finally,
$$1.001^{1000}>1.001^{512+256+128}>1.512\cdot1.256\cdot1.128>2.$$
Comment: very nice and easy to understand for a child who never deals with calculus technics.
Comment: @Khosrotash: thanks, that's what I am ;-)
Answer: Let's pretend we know nothing of mathematical induction, so we can't just say $(1+x)^n\ge1+nx$ for all $n\ge1$ (and $x\ge-1$), but let's assume we can do enough algebra to know that
$$(1+x)^2=1+2x+x^2\gt1+2x$$
and
$$(1+x)^5=1+5x+10x^2+10x^3+5x^4+x^5\gt1+5x$$
for all $x\gt0$.  Then we can show
$$(1+x)^{10}\gt(1+5x)^2\gt1+10x$$
from which it follows that
$$(1+x)^{100}\gt(1+10x)^{10}\gt1+100x$$
and, finally,
$$(1+x)^{1000}\gt(1+100x)^{10}\gt1+1000x$$
at which point we can plug in $x=1/1000$ to conclude
$$1.001^{1000}=\left(1+{1\over1000}\right)^{1000}\gt1+{1000\over1000}=2$$
Answer: You can us bernoulli inequality
$(1,001)^{1000}=(\frac{1001}{1000})^{1000}=$
$(1+\frac{1}{1000})^{1000}\geq  1+\frac{1} {1000}×1000$
Answer: $$f(x):=\left(1+\frac1x\right)^x$$ is a strictly growing function of $x$, and $f(1)=2$.

Indeed for $x>0$,
$$(\log(f(x))'=\log\left(1+\frac1x\right)-\frac1{x+1}>0$$
because
$$(\log(f(x))''=-\frac1{x(x+1)^2}<0$$ and the first derivative decreases to $0$.


Solving the halting problem for *almost* all machines?

Question: As I understand it, the proof of the halting problem's undecidability is conceptually pretty simple. You postulate a machine $h(m, x)$ which (1) always halts and (2) returns 1 if $m$ halts with input $x$, 0 if not. Using this, you build a machine $g(m)$ that spins forever if $h(m, m) = 1$, and halts if $h(m, m) = 0$. Then, $g(g)$ creates a contradiction: if it halts, then $h(g, g) = 1$ and $g(g)$ must spin forever; and similarly, if spins forever, it must halt.
So my question is: does this say anything about the halting problem for machines other than those that solve the halting problem or use machines that solve it? That is, couldn't you still build a machine $h'(m, x)$ that solves the halting problem for any machine except $h$, $h'$, and any machine that includes $h$ or $h'$? With that restriction, you can't evaluate $g(g)$, and the contradiction goes away. It seems like such a machine would still be extremely powerful.
Or does the math behind my loose understanding of the proof-of-undecidability preclude this? One way I could imagine this happening is if the precise definition of "except any machine…" can be proved to be not-halting, in which case the answer to my question is basically that the existence (or definition?) of $h'$ is not decidable.
I am not super well-versed in this branch of mathematics, so an "explain it like I'm 5"-type answer would be much appreciated!

(Apologies if this is a dup; I searched for other halting problem questions and couldn't find and answer, though I'm not sure what to add to focus the search. This seems similar to, but different from, this question.)
Comment: I recall reading a paper about how for a random Turing machine, halting problem is decidable with probability $1$. Although that's just another way to say that most Turing machines are boring.
Answer: The theorem says that there is no algorithm that solves the halting problem for all Turing machines.  There are certainly algorithms that solve the halting problem for some subclasses of machines.  However your criterion is not well stated.  There are other problems for which it is known that algorithms do not exist, e.g. the word problem for groups, or existence of solutions of diophantine equations. Halting for Turing machines that search for solutions of these is also undecidable.
Comment: Typically an undecidability proof might involve some sort of "encoding" of a problem known to be undecidable into a different form.  Thus the undecidability of Diophantine equations (Hilbert's 10th problem) was proven by showing that all recursively enumerable sets are Diophantine.
Comment: Is the proof of those other problems' undecidability different from the proof of the general halting problem's undecidability? That is, do we just have to take each kind of problem one at a time, determining if a general halting algorithm can be created for it?
Answer: I'm not going to answer the question, because I don't know what the correct answer is. I'm just trying to reformulate it so that it can receive a precise answer from someone. The term 'include' in the original question may lack the required precision for the question to have a definite answer.
The usual proof that the Halting Problem is unsolvable employs a form of diagonalization: we assume the existence of the machine H that solves the problem and then we construct another machine D for which H won't always work; the point is that D is constructed by reference to H itself: D is so defined that H, when fed D's code, would have to behave otherwise than it behaves on that input. D is defined in such way that its computations are logically related to H's.
Suppose we want to restrict ourselves to considering only those computations that are unrelated to H's behavior in the sense that they cannot be defined in terms of H's behavior. For this limited problem the classical proof doesn't go through. So the question arises: can such an H exist, which is successful for all computations in the restricted range even if it doesn't work for all possible computations?
An answer in the affirmative would perhaps imply that computations can be accommodated in a hierarchy of levels such that for any level n, there is a machine some of whose computations are of level greater than n and which solves the Halting Problem for all computations of level n.
I am not sure my own terms ('can be defined in terms of') are any more precise than the original 'include' but perhaps they are.
Answer: It can be shown that neither $h(g,g)$ or $g(g)$ halt. Hence you can solve $g(g)$ by building a second halting machine $h'$ that returns $0$ if input is $(g,g)$ and calls $h$ otherwise. I don't have a proof but my guess is that in general, for any program and any input, you can always construct a machine $M$ that tells whether it halts or not. However, there will always be some program and some input for which $M$ loops. To solve the problem, try to build a different halting machine $M'$. Given a particular program and input, the most challenging part, of course, is to figure out which halting machine is going to solve it. For some cases, it is fairly obvious but most cases remain elusive but not impossible to solve.
Answer: That was the question in my head for some time and here is my answer.
Let's consider a clever version of the miraculous machine h, call it h'. h' first examines its input (m,x) and enters an infinite loop if it somehow detects that m contains h, and then proceeds to solve the halting problem for other inputs. But then problem still remains when m contains a machine equivalent to h', and there are infinitely many such machines.
So let's move further and consider an even more clever machine h'' which first examines its input (m,x) and enters infinite loop if it detects that m contains a machine equivalent to h'', then solves halting problem for other inputs. But then, by Rice's theorem, using h'', we can build a machine which solves the original halting problem, which is impossible.
Rice's theorem makes it clear that this uncomputability phenomenon is not just limited to some small set of problematic inputs.


How to create directories using samba client

Question: I have a java code for samba client that puts a file from my unix machine to a windows machine. I need to check if a directory exits, and if not, create the directory and then put the file in that directory. I am able to put the file in an existing directory. It is the creating a new directory part that seems tricky.
Comment: which lib do you use?
Comment: JCIFS lib. to be specific, jcifs.smb.NtlmPasswordAuthentication, jcifs.smb.SmbException, jcifs.smb.SmbFile, jcifs.smb.SmbFileOutputStream
Answer: if you use JCIFS lib you can create a directory using SmbFile
 SmbFile sFile = new SmbFile(path, authentication);
 sFile.mkdir();

For more information see the documentation
Comment: How do i check if the directory exits? How do i give a name to the directory?
Comment: @RKPoddar `sFile.exists();` with the path you specify the directory name. See the documentation from my answer


Injective map between power series ring

Question: Suppose $k$ is a field and let $n > m$. Does there exist injective homomorphisms
$$ k [[x_1, x_2, \ldots, x_n]] \rightarrow k[[x_1, x_2, \ldots, x_m]]\ ?$$
Comment: Taken from http://mathoverflow.net/a/25231
Comment: no, it is from the "false beliefs" thread at MO.
Answer: This answer is (a revision of) Simon Wadsley's comment posted here with the only goal to remove this question from the unanswered queue.
Let $k$ be a countable field, and take a map $k[[x,y,z]] \to k[[u,v]]$ that sends $x$ to $u$, $y$ to $uv$ and $z$ to $uf(v)$ for some $f∈k[[v]]$. It isn't hard to see that only for countably many choices of $f$ can the kernel  possibly be non-zero.

Injective map between power series ring


How to call an array outside of a function in SketchUp Ruby

Question: I am building a custom Decimal Degrees (DD) to Decimal Minute Seconds (DMS) function to use in SketchUp's Ruby. Below is my script.
arg1 = 45.525123

def DMS(arg1)
    angle = arg1
    deg = angle.truncate()
    dec = (angle - angle.truncate()).round(6)
    totalsecs = (dec * 3600).round(6)
    mins = (totalsecs / 60).truncate()
    secs = (((totalsecs / 60) - (totalsecs / 60).truncate()) * 60).round(2)
    array = [deg, mins, secs]
end

DMS(arg1)

So far so good, if you ran this script in Ruby, you'd probably end up with an array that gives you
[45, 31, 30.44]
I then try to add a line of code which assigns that array under a different name. Here is the new code with the extra line.
arg1 = 45.525123

def DMS(arg1)
    angle = arg1
    deg = angle.truncate()
    dec = (angle - angle.truncate()).round(6)
    totalsecs = (dec * 3600).round(6)
    mins = (totalsecs / 60).truncate()
    secs = (((totalsecs / 60) - (totalsecs / 60).truncate()) * 60).round(2)
    array = [deg, mins, secs]
end

DMS(arg1)
bearingarray = array

If you ran the second block of code however, you would end up with an array of [1, 2, 3].
My expectation was that I would get that exact same values in the array, but under the different name.
What has gone wrong? What should I do to fix it?
Thanks for your help!
Comment: Your code has all sorts of problems that strongly suggest you might want to use a different approach to learning both Ruby and its integration into Sketchup.  Is there possibly a specific Ruby/Sketchup forum or personal coach you might be able to use?
Comment: Again, this is hardy the place for this type of thing, but just as a favor, I'll point out a few things:  You shouldn't use a local variable in your method definition.  It makes no sense.  ```def DMS(arg1)``` should probably be something like ```def DMS(any_arg)``` or ```def DMS(num).  You're not defining a method based on a local variable.  You're defining a method that can be used with ANY valid value.  That's why its useful.  Also, ```truncate``` doesn't need the parentheses if you're not using an argument, and there's no reason to define ```array``` inside your method.
Comment: BTW, I recommend not starting a method name with an upper case letter. It works in your case, because you require a parameter, but say you want to change the definition to make the parameter optional. You can't call a parameterless method, where the name starts with an upper case letter, because the parser would think that it is the name of a constant.
Answer: Your second code block is wrong, if you run it you get <code>undefined local variable or method array for main:Object</code>.
You are probably running the code in an interactive session and you have defined <code>array</code> before, take into account <code>array</code> is local to <code>DMS</code> function.
I would say what you want is to do
<code>arg1 = 45.525123

def DMS(arg1)
  angle = arg1
  deg = angle.truncate()
  dec = (angle - angle.truncate()).round(6)
  totalsecs = (dec * 3600).round(6)
  mins = (totalsecs / 60).truncate()
  secs = (((totalsecs / 60) - (totalsecs / 60).truncate()) * 60).round(2)
  array = [deg, mins, secs]
end

bearingarray = DMS(arg1)
</code>
Assigning the output of <code>DMS</code> to <code>bearingarray</code>
Comment: May I suggest to remove the meaningless assignment to the variable `array` inside the `DMS` method? You just create a local variable and throw it away immediately. Of course this already exists in the OPs original code, but IMO, it does not help the OP to repeat something which is already badly designed from the onset.
Comment: Agree with @user1934428.  In addition, if it were me it would probably be ```def DMS(angle)``` and I would completely delete ```angle = arg1```...and that's just for starters.
Comment: Agree, the code can be improved in many ways, I just copy/pasted the definition so it is clear what needs to be changed in order to answer the original question


Automatically carousel rotation for image blocks

Question: I need to change pics in carousel automatically every 2 sec. Cause i'm not good at JS at all could you help me, where i need to add a timer ?
Here html part

and links for all js files:
http://pastebin.com/AgBGXY4M
http://pastebin.com/4HziWhTw
Answer: you have two options to achieve this:
1) Edit js file at line itemSpeed = 500 to itemSpeed = 2000 (2000 milliseconds = 2 sec)
2) Pass itemSpeed as an option while calling

use whatever works for your best.
Comment: i need to switch it automaticaly every 2 sec. without clicking arrows


"Not" Operator Inside a Handlebars Template

Question: Take the following example which disables a button if a checkbox is not checked and enables it when checked:
Handlebars:
<form {{action "register" on="submit"}}>
  {{input type="checkbox" checked=isAgreed}}
  {{input type="submit" value="Register" class="btn btn-primary" disabled=isNotAgreed}}
</form>

Javascript:
App.ApplicationController = Ember.ObjectController.extend({
  content:{
    isAgreed:false
  },
  isNotAgreed:function(){
    return !this.get('isAgreed');
  }.property('isAgreed'),
  actions:{
    register:function(){
      alert("registered");
    }
  }
});

As demonstrated in this JSBin.
I am wondering if there is a cleaner way of doing this.  For example removing the isNotAgreed observable property and just using something in my handlebars template like {{input type="submit" value="Register" disabled=!isAgreed}}.  Is there a way to do this?
Comment: We can't use operators inside the handlebars template as in the javascript.We can avoid observable property for these kind of requirements.Here is my soln in [jsbin.](http://jsbin.com/uBOXIVu/2/edit)
Answer: In the moment doesn't exist a not operator !, in the binding property, of handlebar template.
You can use the computed property macro not, to have some syntax sugar:
So instead of:
isNotAgreed:function(){
  return !this.get('isAgreed');
}.property('isAgreed')

you can use:
isNotAgreed: Ember.computed.not('isAgreed')

You can see all the avaliable computed macros here
I hope it helps
Comment: Thanks +1, that is a nice thing I didn't know existed in ember.  But I was really hoping to put this very simple logic into the template itself.  Is there anyway to do it even with a handlebars helper or by extending Ember.checkbox?
Answer: Alternatively you can bind a class disabled which will be true when isAgreed is false as follows.
<button type="submit" {{bind-attr class=":btn :btn-primary isAgreed::disabled"}}>Register</button>

Since you are using twitter-bootstrap also, this disabled class will give disabled like behaviour to the button.
Here is a simplified bin of your problem.
Comment: Thank you.  This one is what I was looking for. In my opinion it is the cleanest.


How to print a specific line from file based on UUID defined in variable?

Question: I wanted to print the specific line from <code>/etc/fstab</code> based on UUID defined in a variable. But when I'm trying with below code it is not giving proper results.
Code:
<code>---
- name: check
  hosts: all
  become: true

  tasks:

    - name: set fact for uuid
      set_fact:
        uuid_disk: "{{ item.value.links.uuids }}"
      loop: "{{ ansible_devices | dict2items }}"
      when: ('swap' in (item.value.links.labels))

    - name: print
      debug:
        msg: "{{ uuid_disk | join() }}"

    - name: fstab
      slurp:
        src: /etc/fstab
      register: output

    - name: print
      debug:
        msg: "{{ item | select('match','UUID') | list }}"
      loop: "{{ (output.content | b64decode).splitlines() }}"

    - name: print
      debug:
        msg: "{{ item }}"
      loop: "{{ (output.content | b64decode).splitlines() }}"
      when:  (item | regex_search('^UUID')) in uuid_disk
</code>
Comment: uuid_disk output is : "6e87632e-b052-4ef6-a91b-78f1be1a99c5"
Comment: Do you mean like `when: uuid_disk in item`?
Answer: Q: "Print the line from the file based on the UUID defined in a variable."
A: Fetch the file and select the line. For example, declare the path to store /etc/fstab on the controller
<code>  fstab_path: "/tmp/test/{{ inventory_hostname }}/fstab"
</code>
and fetch the file
<code>    - fetch:
        src: /etc/fstab
        dest: "{{ fstab_path }}"
        flat: true
</code>
Given the variable with the UUID value
<code>  uuid_disk: 01865fce-8bb9-48ad-a9eb-1ff43a8db4a5
</code>
search the line
<code>  uuid_line: "{{ lookup('file', fstab_path).splitlines()|
                 select('search', uuid_disk) }}"
</code>
gives for example,
<code>  uuid_line:
  - UUID=01865fce-8bb9-48ad-a9eb-1ff43a8db4a5 none swap sw 0 0
</code>

Example of a complete playbook for testing
<code>- hosts: all

  vars:

    uuid_disk: 01865fce-8bb9-48ad-a9eb-1ff43a8db4a5

    fstab_path: "/tmp/test/{{ inventory_hostname }}/fstab"
    uuid_line: "{{ lookup('file', fstab_path).splitlines()|
                   select('search', uuid_disk) }}"

  tasks:

    - fetch:
        src: /etc/fstab
        dest: "{{ fstab_path }}"
        flat: true
    - debug:
        var: uuid_line
</code>

The above solution prints the fstab lines of UUID(s) labeled swap. (This is how you get the UUID.) Vice-versa you can print the partitions used as swap in fstab. Let me rephrase the question
Q: "From /etc/fstab get UUID of swap partition(s). Then, display the partition(s)."
A: First gather the facts and create a dictionary UUID/partition. Then, parse /etc/fstab and get the UUID of the swap entries. Get the partition(s) of the UUID(s).

Gather the facts

<code>    - setup:
        gather_subset: devices
</code>
, get the partitions, and create the dictionary uuid
<code>  partitions: "{{ ansible_devices|
                  json_query('*.partitions')|
                  combine }}"
  uuid: "{{ dict(partitions|
                 dict2items|
                 selectattr('value.uuid')|
                 json_query('[].[value.uuid, key]')) }}"
</code>
gives for example,
<code>  uuid:
    01865fce-8bb9-48ad-a9eb-1ff43a8db4a5: sdb4
    04dc9170-bdbc-4a22-abaf-b9e3cf1ba969: sda5
    7074BA0A74B9D2D8: sda2
    9a2199dd-0662-47b4-a957-adbcf5d350f4: sdb5
    EC808480808452CE: sda1
    F86C-A380: sdb2
    c484594d-fd2e-4f57-9c14-74b8e397d8ed: sdb3
</code>

Declare the path to store /etc/fstab on the controller

<code>  fstab_path: "/tmp/test/{{ inventory_hostname }}/fstab"
</code>
and fetch the file
<code>    - fetch:
        src: /etc/fstab
        dest: "{{ fstab_path }}"
        flat: true
</code>
Use the filter community.general.jc to create the list of dictionaries fstab
<code>  fstab: "{{ lookup('file', fstab_path)|
             community.general.jc('fstab') }}"
</code>
gives for example,
<code>  fstab:
  - fs_file: /
    fs_freq: 0
    fs_mntops: errors=remount-ro
    fs_passno: 1
    fs_spec: UUID=c484594d-fd2e-4f57-9c14-74b8e397d8ed
    fs_vfstype: ext4
  - fs_file: /boot/efi
    fs_freq: 0
    fs_mntops: umask=0077
    fs_passno: 1
    fs_spec: UUID=F86C-A380
    fs_vfstype: vfat
  - fs_file: /export
    fs_freq: 0
    fs_mntops: defaults
    fs_passno: 2
    fs_spec: UUID=9a2199dd-0662-47b4-a957-adbcf5d350f4
    fs_vfstype: ext4
  - fs_file: none
    fs_freq: 0
    fs_mntops: sw
    fs_passno: 0
    fs_spec: UUID=01865fce-8bb9-48ad-a9eb-1ff43a8db4a5
    fs_vfstype: swap
  - fs_file: none
    fs_freq: 0
    fs_mntops: sw
    fs_passno: 0
    fs_spec: /usr/swap0
    fs_vfstype: swap
</code>
Get the UUID(s) of the swap entries
<code>  uuid_swap: "{{ fstab|
                 selectattr('fs_vfstype', '==', 'swap')|
                 selectattr('fs_spec', 'match', 'UUID=')|
                 map(attribute='fs_spec')|
                 map('split', '=')|
                 map('last') }}"
</code>
gives
<code>  uuid_swap:
    - 01865fce-8bb9-48ad-a9eb-1ff43a8db4a5
</code>

Get the partition(s) of the UUID(s)

<code>  partition_swap: "{{ uuid_swap|map('extract', uuid) }}"
</code>
gives
<code> partition_swap:
    - sdb4
</code>

Example of a complete playbook for testing
<code>- hosts: all

  vars:

    partitions: "{{ ansible_devices|
                    json_query('*.partitions')|
                    combine }}"
    uuid: "{{ dict(partitions|
                   dict2items|
                   selectattr('value.uuid')|
                   json_query('[].[value.uuid, key]')) }}"

    fstab_path: "/tmp/test/{{ inventory_hostname }}/fstab"
    fstab: "{{ lookup('file', fstab_path)|
               community.general.jc('fstab') }}"
    uuid_swap: "{{ fstab|
                   selectattr('fs_vfstype', '==', 'swap')|
                   selectattr('fs_spec', 'match', 'UUID=')|
                   map(attribute='fs_spec')|
                   map('split', '=')|
                   map('last') }}"
    partition_swap: "{{ uuid_swap|map('extract', uuid) }}"

  tasks:

    - setup:
        gather_subset: devices
    - debug:
        var: uuid

    - fetch:
        src: /etc/fstab
        dest: "{{ fstab_path }}"
        flat: true
    - debug:
        var: fstab

    - debug:
        var: uuid_swap
    - debug:
        var: partition_swap
</code>
Answer: Regarding

How to print the specific line from file based on UUID defined in variable?

you may have a look into the following minimal example playbook
<code>---
- hosts: localhost
  become: false
  gather_facts: false

  vars:

    uuid_disk: 12345678-abcd-efgh-ijkl-123456789012

  tasks:

  - name: fstab
    slurp:
      src: /etc/fstab
    register: output

  - name: Print UUID, if there is any
    debug:
      msg: "{{ item | regex_search('[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}') }}"
    loop: "{{ (output.content | b64decode).splitlines() }}"

  - name: Print line where UUID match
    debug:
      msg: "{{ item }}"
    loop: "{{ (output.content | b64decode).splitlines() }}"
    when: uuid_disk in item
</code>
and Similar Q&A about

Searching for UUIDs in text


Disable cookies until consented

Question: I am trying to disable cookies until the user has provided consent. I dont have a lot of cookies on my website, the only ones that may collect some "personal data" are added by google analytics.
Google analytics has provided with the following scripts to disable their cookies:
window['ga-disable-UA-xxxxxxxx-y'] = true;
But this only removed _ga _gat _gid. I am trying to find a way to remove these as well:
gadwp_wg_default_dimension,
gadwp_wg_default_metric,
gadwp_wg_default_swmetric
Also, some cookies are being set by third party, like like _biz_dfsA, _biz_nA are being set by cloudfare.
Is there a way to disable specific cookie knowing just it's name?
Thanks.
Answer: I'm not sure if you can prevent them from being set but you can check if they are set:
if (document.cookie.split(';').filter(function(item) {
    return item.indexOf('reader=') >= 0
}).length) {
    console.log('The cookie "reader" exists')
}

//ES2016
if (document.cookie.split(';').filter((item) => item.includes('reader=')).length) {
    console.log('The cookie "reader" exists')
}

And delete:
document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";

https://developer.mozilla.org/en-US/docs/Web/API/Document/cookie

Disable cookies until consented


Taking derivative of $\frac{\log x}{\sqrt{x}}$

Question: Is it correct to write
$$
\frac{d}{dx}\frac{\log x}{\sqrt{x}} = \frac{2 - \log x}{2x^{{3/2}}}?
$$ I tried applying the quotient rule,
$$
\left(\frac{u}{v}\right)'=\frac{u'v-uv'}{v^2}
$$
but I'm confused on how to get the numerator equal to $2 - \log x$ and the denominator equal to $2x^{3/2}$.
Comment: That doesn't answer the question, random. Show us exactly what you did, we'll show you exactly where it all went wrong.
Comment: When you tried to apply the quotient rule, what _did_ you get?
Comment: Show us your work in applying the quotient rule.
Comment: random, Show us your workings - *in an edit to your post,* please.  Write your result of $$\frac d{dn}\left(\frac {\log n}{\sqrt n}\right)$$
Comment: I was able to get $n^{3/2}$ but could not understand where the $\frac{2 - logn}{2}$ comes from
Comment: I would but it's taking me a long time because I'm not proficient with latex
Comment: Alternately use the product rule $u'v+uv'$ with $u=\ln(x)$ and $v=x^{-1/2}$, I found it often simpler for not having to deal with fractions over fractions. Can you tell what are $u'$ and $v'$ ? The rest just follows.
Comment: @zwim As the quotient rule is derived from a combination of the product rule and the chain rule, this type of band-aid solution in order to _not have to work with fractions within fractions_ is rather retroactive from an educator's standpoint.  I do not think that OP's issue is with the calculus part of this question, but from the _pre-calc_ required -- that is, simplifying rational expressions.
Comment: @Andrew Chin don't know
Answer: $\frac{d}{dx}\frac{\ln x}{\sqrt{x}}= \frac{\frac 1x×\sqrt{x}-\ln x\frac{1}{2\sqrt{}x}}{x} =\frac{2-\ln x}{2x^{3/2}}$


pytest-mock how to patch nested function

Question: I have the following code:
my_module.py
def my_func(number):
    def nested_func(value):
        '''
        Doing some calculation
        '''
        return result
    output = []
    for i in range(number):
        res = nested_func(i)
        output.append(res)
    return output

I'm using pytest with pytest-mock and mocker as a fixture in test_my_module.py
test_my_module.py
def test_my_module(mocker):
    expected_res = [1, 1, 1]
    mocker.patch('nested_func', return_value=1)

    from my_module import my_func
    assert my_func(3) == expected_res

But when I run in py.test I got an error:
TypeError: Need a valid target to patch. You supplied: 'nested_func'

Is there any way to mocker.patch functions\methods, which are not visible in testing module and located as nested in that functions, I want to test?
Comment: Actually, if you read the answers to the question mentioned by @quamrana, you will find that the local function is created anew each time `my_func` is called - so you cannot patch it, as it doesn't exist at patch time. You can only patch the outer function (e.g. `my_func`).
Comment: Does this answer your question? [How to access a function inside a function?](https://stackoverflow.com/questions/17395338/how-to-access-a-function-inside-a-function)
Comment: I think no, because my main function doesn't return a function. It has only nested function which is used for calculations inside main function
Answer: As a follow up to @MrBean Bremen, I think a work around is to define nested_func outside of my_func and call it within my_func
def nested_func(value):
   result = value + 2
   return result
def my_func(number):
   output = []
   for i in range(number):
       res = nested_func(i)
       output.append(res)
   return output

Your test_my_module
from my_module import my_func
def test_my_module(mocker):
    expected_res = [1, 1, 1]
    mocker.patch('my_module.nested_func', return_value=1)

    assert my_func(3) == expected_res


Integrar Classes da ES2015 com jQuery

Question: Depois de muita leitura eu finalmente consegui fazer a Babel funcionar e, assim, transcompilar os scripts.
Antes de utilizar das, vamos chamar de classes da ES2015, após ler sobre melhores práticas eu tinha algo assim:
( function( Navigation, window, document, $, undefined ) {

    Navigation.menu = function() {

        ( '#menu' ).on( 'click wheel', function( e ) {

            // Do something with DOM

        });
    }

    Navigation.menu();

}( window.Navigation = window.Navigation || {}, window, document, window.jQuery ) );

Então, aos poucos, eu fui tentando fazer a implementação com a ES2015:
class Navigation {

    constructor( data ) {

        this.data = data;

        this.init();
    }
}

class Menu extends Navigation {

    init() {

        $( '#menu' ).on( 'click wheel', function( e ) {

            // Do something with DOM
        });
    }
}

Criei uma classe base com aquilo que é comum à cada tipo de navegação (menu, sidebar...) achando que assim que Objeto Menu fosse instanciado o construtor de Navigation chamaria o método init, inicializando o Evento.
Funciona, mas não como eu imaginei.
Dentro de Navigation.init() (Location na verdade, mas apenas para contextualizar um método abstrato), se eu tentar acessar as propriedades de Navigation:
console.log( this.data );

Funciona perfeitamente como esperado mas dentro de jQuery.on() eu recebo um undefined o.O
Eu imaginei que, talvez, o escopo de thispudesse estar sendo sobrescrito e depurei apenas ele e obtive o nó clicado (uma imagem).
E eu queria saber o porquê, é claro, mas também como consertar isso para integrar adequadamente, se for possível, mas preferivelmente sem ter que, por exemplo, injetar o escopo this em Navigation.init():
class Navigation {

    constructor( data ) {

        this.data = data;

        this.init( this );
    }
}

class Menu extends navigation {

    init( _this ) {

        // _this points to Navigation, inside or inside jQuery.on()
    }
}

Answer: Isso acontece pela forma como o jQuery funciona com os callback de eventos, ele faz com que o this seja o elemento que disparou o evento.
Como você está usando o Babel então fica bem simples resolver esse problema, é só você usar uma Arrow Function, que diferente de uma função, anônima ou não, ela não altera o contexto do this, ficaria assim
init() {
    $( '#menu' ).on( 'click wheel', ( e ) => {
         // agora aqui o this vai continuar sendo a sua classe
    });
}

Repare que tudo que mudou foi a remoção do keyword function e a adição da seta =>.
O Babel vai saber converter isso corretamente, no javascript final ele deve criar uma nova variável temporária automáticamente
O detalhe que fica ai é que uma coisa comum do jQuery é usar $(this) para manipular o elemento que disparou o evento, o que não vai mais funcionar, mas você ainda pode pegar o elemento que disparou o evento neste caso pelo e.target ou e.currentTarget, então poderia também fazer algo como $(e.target) para manipular o elemento com o jQuery.
No caso do e.target pode acontecer de não ser o mesmo elemento do this, isso pode acontecer quando o evento veio de um elemento filho do qual você adicionou o event handler, por exemplo

        teste

Com este HTML se eu adicionar um handler para o click do $("#menu") o e.target vai me retornar o div interno, enquanto o this seria o div externo, neste caso usando o e.currentTarget ele retornaria o mesmo que o this.
A documentação não fala muito sobre a diferença entre o this e o e.currentTarget, mas pesquisando sobre isso encontrei explicações dizendo que no geral seriam os mesmos valores, a menos que fosse usado o $.proxy para alterar o contexto da função.
Inclusive devo acrescentar que o $.proxy também é uma alternativa para corrigir o seu problema, ficaria assim:
init() {
    $( '#menu' ).on( 'click wheel', $.proxy(function( e ) {
         // agora aqui o this vai continuar sendo a sua classe
    }, this));
}

Basicamente você passa a função e seu this atual, que representa a instância de sua classe, porém ainda acontece a mesma coisa que aconteceria usando uma Arrow Function, como o this foi modificado não tem como usar o $(this), seria necessário usar $(e.currentTarget) por exemplo, então acho a primeira forma mais simples, ficando com o código mais limpo.
Em ultimo caso, se você realmente quiser ou por algum motivo precisar usar $(this), então a alternativa é capturar o this em uma variável local
init() {
    let _this = this; //ou var _this = this;
    $( '#menu' ).on( 'click wheel', function( e ) {
         // agora aqui você pode usar o _this para acessar sua classe
         // e ainda pode usar o $(this) para manipular o elemento
    });
}

Comment: E passar a usar `$( e.target )` ao invés de `$( this )` é seguro, sem problemas de compatibilidade?
Comment: @user5613506 eu diria que na maioria dos casos sim, mas a documentação cita que existem casos em que o `this` e o `e.target` podem não ser o mesmo elemento no caso de ter ocorrido a propagação do evento de algum elemento filho, mas olhando a documentação me parece ser possível usar também o `e.currentTarget`, vou incluir mais algumas informações na resposta

Integrar Classes da ES2015 com jQuery


Android Drawable setLevel(); not filling SeekBar appropriately

Question: Okay so I've been able to customize a few SeekBar's to be used as a Bar Graph type of image, but since I need to be able to switch between a Green or Red Image (depending on certain values) which you can see below. The problem is that regardless of what value I use in the setLevel for the Drawable it doesn't fill appropriately (you can see the image below for an example since the green bar should be closer to the right based on the two values)

Below is the code for the section that setups this entire MTD Commission bar section, I don't know how much of the code you would need to see so I just decided to post all of this section.
void setupMTDBarSection() {
    //Get Current Date and Number of Days in Current Month
    Calendar cal = Calendar.getInstance();
    int numberOfDays = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
    SimpleDateFormat today = new SimpleDateFormat("dd");
    String currentDate = today.format(new Date());

    //Get MTD Goal value from Preferences
    String goalString = preferences.getString("keyMonthlyGoal", "0");
    float mtdGoalFloat = Float.valueOf(goalString);
    Integer mtdGoal = (int)mtdGoalFloat;
    MTDGoalValue.setText(NumberFormat.getCurrencyInstance().format(mtdGoalFloat));

    //Get Current MTD Value
    String mtdString = preferences.getString("keyMTDValue", "0");
    float mtdValueFloat = Float.valueOf(mtdString);
    Integer mtdValue = (int)mtdValueFloat;
    MTDCurrentProgress.setText(NumberFormat.getCurrencyInstance().format(mtdValueFloat));

    //Do some math to determine if the Rep is below/above the daily goal
    Integer dailyGoal = mtdGoal/numberOfDays;
    Integer currentDayGoal = dailyGoal * Integer.valueOf(currentDate);

    if (mtdValue >= currentDayGoal) {
        MTDGreenTrack.setLevel(mtdValue);
        MTDProgressBar.setProgressDrawable(MTDGreenTrack);
        MTDProgressBar.setMax(mtdGoal);
        MTDProgressBar.setProgress(mtdValue);
    }
    else {
        MTDRedTrack.setLevel(mtdValue);
        MTDProgressBar.setProgressDrawable(MTDRedTrack);
        MTDProgressBar.setMax(mtdGoal);
        MTDProgressBar.setProgress(mtdValue);
    }

    //Add Percentage to MTD Text
    NumberFormat percentFormat = NumberFormat.getPercentInstance();
    float percent = mtdValueFloat/mtdGoalFloat;
    String percentage = percentFormat.format(percent);
    MTDPercentText.setText("(" + percentage + ")");

    //Setup MTD Indicator
    MTDIndicator.setMax(numberOfDays);
    MTDIndicator.setProgress(Integer.valueOf(currentDate));
    MTDIndicator.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View view, MotionEvent motionEvent) {
            return true;
        }
    });

}

Comment: It's hard to tell because we don't have your actual values, but my hunch is that you're not setting the maximum value right. If the minimum is 5000 and the max is 6000, then the "max" should be 1000. But like i said, it's hard to tell.
Comment: If you mean the values for the Progress Bar max and progress, those are the values that are displayed on the left and right. So in the pictured example, the max value is 6000 and the current progress value is 5000. I don't have a minimum value set, but I can set it to 0 if that would make a difference.
Answer: I believe I found the issue. Apparently when you call setProgressDrawable more than once then you need to re-draw the image that is used since it looses the format that was previously there. Also, don't really need to set the level each time of the drawable as well, it matches up with the progress value of the Seekbar. Below is the code that works for me so far
Rect bounds = MTDProgressBar.getProgressDrawable().getBounds();
        MTDProgressBar.setProgressDrawable(MTDGreenTrack);
        MTDProgressBar.getProgressDrawable().setBounds(bounds);
        MTDProgressBar.setProgress(mtdValue);
        MTDProgressBar.setMax(mtdGoal);


"Bottomless" Collection View (Load more images)

Question: I'm using the SDWebImage library to download and cache images for use in a UICollectionView grid view. Everything works great with the initial load of 24 images (3 across, 8 down) but I'd like to add another 24 images when the user hits the bottom of the screen. Does anyone know how I trigger this?
Answer: UICollectionView is a subclass of UIScrollView so you can detect the when you have reached the current "bottom" the same way by implementing UIScrollViewDelegate methods. Check this post out on how to do it:
UIScrollView, reaching the bottom of the scroll view


Sequences formed by integer evaluations of polynomials modulo $ p^{k} $, where $ p $ is a prime number and $ k \in \Bbb{N} $.

Question: I have the following question.

Let $ p $ be a prime number and $ k $ a positive integer. Let $ (a_{n})_{n \in \Bbb{Z}} $ be a two-way sequence in $ \Bbb{Z} / p^{k} \Bbb{Z} $. Then is it true that $ (a_{n})_{n \in \Bbb{Z}} $ is periodic with period $ p^{l} $ for some $ l \in \Bbb{N}_{0} $ if and only if there exists a numerical polynomial $ f $ such that $ (a_{n})_{n \in \Bbb{Z}} = \left( f(n) + p^{k} \Bbb{Z} \right)_{n \in \Bbb{Z}} $?

Note: We say that $ f $ is a numerical polynomial if and only if $ f \in \Bbb{Q}[X] $ and $ f(n) \in \Bbb{Z} $ for all $ n \in \Bbb{Z} $. For example, $ \dfrac{1}{2} X^{2} + \dfrac{1}{2} X = \dfrac{1}{2} X (X + 1) $ is a numerical polynomial, so a numerical polynomial is not necessarily an element of $ \Bbb{Z}[X] $.
Using the method of finite differences, one can prove that the answer is 'yes' for any prime number $ p $ and $ k = 1 $, but that is as far as I have gone.
Thanks!
Answer: One direction is easy:
Let the sequence be given by a numeric polynomial $f$. Then $mp^rf\in\mathbb Z[X]$ for some $r\ge 0$ and $m$ coprime to $p$. Hence $mp^rf(X+p^l)\equiv mp^r f(X)\pmod {p^l}$. With $l\ge k+r$ this gives us $f(x+p^l)\equiv f(x)\pmod{p^k}$ for all $x\in\mathbb Z$, i.e., the sequence is periodic.
For the other direction we can use the method of finite differences. All we need is that after finitely many steps, the difference sequence becomes constant zero. For this note that the influence of an original entry in the $n$th differrence row is given by someting like $(-1)^i{n\choose i}$. In row $n=p^l$, the outer binomial coefficients $\pm1$ cancel by periodicity and all others are multiples of $p^l$. Hence difference row $p^l$ is divisble by $p^l$ (and again periodic). Repeating the proces, we sooner or later end up with a row divisible by $p^k$, as desired


glmer.nb with weights and nested random effects - Convergence Error

Question: I have a dataset of behavioural observations in an experiment on free ranging breeding birds. I'd like to calculate GLMMs.
The dataset has the following parameters:

Behaviour (count data)
Behaviour during Baseline (count data)
Nest
Individual
Treatment Condition
Sex of Individual
Amount of time an individual was seen during experiment

I would like to use the time an individual was seen as a model weight, as I want cases in which the individual in question is seen more to have higher influence in the model than cases in which they are only seen very rarely.
When checking my response variable (the counts of the behaviour) it most likely fits a negative binomial distibution:

When looking at the data the it has a very high count of zeros (133 out of 240 to be exact)

quantile(Data$ACTW)
  0%    25%    50%    75%   100%
0.00   0.00   0.00  44.75 909.00

The problem I face now is that when I want to fit a negative binomial model with nested random effects with lme4, I come across a convergence error.
This is my Model:
ACTW_Model_CP <- glmer.nb(ACTW ~ Condition + Parent + (1|Nest/Individual) + (1|ACTW_BL),
                          weights = Seen, data = Data, verbose = TRUE)

ACTW is the Behaviour in question
Condition is the treatment condition
Parent is the sex
Nest is the specific nest/the location
Individual is the identifier for the individual
ACTW_BL is the behaviour recorded during baseline observations
Seen is the amount of time the individual was seen (Zero to one)

Running the model resulted in:
> ACTW_Model_CP <- glmer.nb(ACTW ~ Condition + Parent + (1|Nest/Individual) + (1|ACTW_BL),
+ data = Data, weights = Seen, verbose = TRUE)
theta.ml: iter 0 'theta = 0.830397'
theta.ml: iter1 theta =-0.687164
theta.ml: iter2 theta =-0.0026382
theta.ml: iter3 theta =0.00521452
theta.ml: iter4 theta =0.0102195
theta.ml: iter5 theta =0.0197524
theta.ml: iter6 theta =0.0373503
theta.ml: iter7 theta =0.0683011
theta.ml: iter8 theta =0.118839
theta.ml: iter9 theta =0.192281
theta.ml: iter10 theta =0.280215
theta.ml: iter11 theta =0.354639
theta.ml: iter12 theta =0.387487
theta.ml: iter13 theta =0.391826
theta.ml: iter14 theta =0.39189
th := est_theta(glmer(..)) = 0.3918897
Error in eval(expr, envir, enclos) :
  pwrssUpdate did not converge in (maxit) iterations
In addition: Warning message:
In checkConv(attr(opt, "derivs"), opt$par, ctrl = control$checkConv,  :
  Model failed to converge with max|grad| = 0.017808 (tol = 0.001, component 1)

I have tried to simplify the model, yet I did not manage to get any models calculated. I also tried both optimisers included in lme4.
My question is as follows:
Is there a way to model my data in a way that accounts for the amount of time an individual was seen during the experiment?
I'm running lme4 version 1.1-12 in R 3.2.1 under Windows 7 (x86_64-w64-mingw32).
Comment: But treating it as a random effect would not do that ! Unless I understood the description incorrectly, `ACTW_BL` is a baseline measurement of your outcome variable. I don't see any rationale for treating it as a grouping variable.To be a random effect it should be 1) a factor (ie. not something measured), 2) a sample from a larger population.  By treating it as random you are saying that your measurements are clustered within each level of it.
Comment: Without a reproducible example, we can only speculate, so I would ask you what happened when you increased `maxit`?
Comment: I increased the maxit to `control=glmerControl(optCtrl=list(maxfun=2000000))` but it still did not reach convergence in the `pwrssUpdate (...)` The `In addition:(...)`-Warning did go away though
Comment: Why do you treat `ACTW_BL` as a random effect ?
Comment: I treat `ACTW_BL` as a random effect as because I want to correct for the effect that the presence of humans had on the birds' behaviour.
Comment: you probably want to use offsets to account for variable amount of time observed ...
Comment: @RobertLong's comments are (IMO) correct. I don't think it's worth proceeding further with this question until that issue is corrected, or at least clarified.  I *could* make up a reproducible example myself to show how this messes things up, but I probably won't get to it ...
Answer: It is hardly surprising that it fails to converge. As you have shown, the response variable is highly zero-inflated. Even if it did converge, I would treat the results with great suspicion.
You need to use a package which allows for a zero-inflated negative binomial or zero-inflated overdispersed Poisson response, such as glmmADMB, glmmTMB and MCMCglmm.
Comment: I don't think `MCMCglmm` allows for negative binomial responses, but it does allow for (and in fact require) observation-level random effects in a Poisson model, leading to a marginal logNormal-Poisson distribution which is very similar to NB. I would consider trying `glmmADMB` or `glmmTMB` (https://github.com/glmmTMB/glmmTMB) ...
Comment: @BenBolker I was thinking of the overdispersed poisson model that is similar to NB (which I was you are talking about I think ?). Anyway I have updated the answer. Thanks.


Get a parent class jquery

Question: I want to get the ancetor of the li that have active class to target his son (the button) class an make a collapse by area-expanded= true in it.
This is the html:

 <button class="nav-link" type="button" data-toggle="collapse" data-target="#nav-collapse-2" aria-controls="nav-collapse-2" aria-expanded="true">Typographies</button>

          Les familles

         Hiérarchisation

this is some js :
var get_url = function (){
    $(".navbar-nav--left .nav-link, .nav-submenu .nav-submenu-link").each(function(){
        var $this = $(this);
        if($this.attr('href') == window.location.href.substr(window.location.href.lastIndexOf('/') + 1)){
            // var regex = /\/\/.*\/(.*)\//g;
            // var match = regex.exec(window.location.href);
            // console.log("eeeeeee : ",match )
            $this.addClass('active');
            // var collapsed = $(".nav-item *");

            collapsed = $(this).closest(".nav-item")[0];

        }
    });
};

I'm stuck in this piece of code :(
Comment: Are you using bootstrap? If you're using bootstrap, the right way to toggle a collapse event should look like [this](https://getbootstrap.com/docs/4.0/components/collapse/#collapseshow)
Comment: Bit confusing as it looks like you've provided some code that sets the active class, but not the code that you've asked for: `$(".active").closest(".nav-item").find("button.nav-link")`
Answer: I didn't understand well your question, but in order to get the parentElement of an element with a class .active here is how:
let myElement = document.getElementByClassName("active")[0];
let brotherButton = myElement.parentNode.querySelectorAll("a")[0];

Above we've got myElement which has the class .active, then thru his parent we selected his brother anchor tag.
Hope this help.

Get a parent class jquery


Partition into subgroups

Question: In a class of 7 boys and 8 girls, how many ways are there to partition the class into 4 mutually disjoint unlabelled subgroups such that each of the subgroup has at least one girl and that the girls A and B will not belong to the same group?
Answer: First lets see how to partition the girls. They need to be in four sets since each set must have at least one girl.
We seperate into three cases:
Case 1 is when girl $A$ is not the only girl in her group. In this case we first seperate all girls except $A$ in $7 \brace 4$  ways(stirling coefficient of the second kind). This is because $A$ is not the only girl in her group, so every group must contain at least one of the $7$ girls that are not $A$. After doing this there will be four groups into which $A$ can be put. However one of those groups has $B$, so we can't pick that one. But there are three options. Therefore there are $3  {{7} \brace 4}$ ways to do it.
Case 2: girl $A$ is alone. Then we seperate the remaining girls in $7 \brace 3$ ways.
Therefore there are $3  {{7} \brace 4}+ {7\brace 3}$ ways to seperate the girls into $4$ subgroups.
After the girls have been seperate we proceed to seperate the boys, but this is easy because now the subgroups are "labelled" since the girls that are allready in them distinguish them. So there are $4^7$ ways to assign the boys.
Thus the final answer is $4^7(3  {{7} \brace 4}+ {7\brace 3})=(16384)(3(350)+301)=22,134,784$
Comment: I was unfamiliar with this Stirling Coefficient of the Second Kind.  So, any time you are asked how many ways can you divide up $n$ unique objects into $k$ nonempty subgroups, the answer is $n \choose k$?
Comment: yeah, but in this case there where special restrictions, but yes. that is what the Stirling coefficient counts. They are not very easy to compute. There is a recursion and a formula for $n\brace k$ which has $k$ terms.
Comment: Remember not to mistake $n \brace k$ with $\binom{n}{k}$. The latter is for binomial coefficients.
Comment: Ah.  I had made that mistake. Thanks.
Comment: Hi! Thanks for the clear explanation, I totally get how to arrange the girls now, however, I am still unclear why the number of ways to assign the boys is $4^7$
Comment: If the girls have already been assigned to the four subgroups these subgroups are now different between each other. So at this point of the construction they are different. Then there are $4$ options to assign boy $1$. There are $4$ options to assign boy $2$, there are $4$ options to assign bou $3$..... Since these decisitions are independent we get there are $\underbrace{4\times 4 \times 4 \dots \times 4}_{\text{7 times}}$ ways to assign the boys.
Comment: oh it makes sense now, thank you!

Partition into subgroups


Using a ForeignCollection

Question: My entity contains the following private ForeignCollection attribute:
@ForeignCollectionField
private ForeignCollection<Order> orderCollection;

private List<Order> orderList;

What is the best way or usual way to avoid a having a caller use a ForeignCollection?  Is there any neat way to return the Collections data to a caller?
How does the following method look?  It allows a caller to access the data via a List. Would you recommend doing it this way?
public List<Order> getOrders() {
    if (orderList == null) {
        orderList = new ArrayList<Order>();
        for (Order order : orderCollection) {
            orderList.add(order);
        }
    }
    return orderList;
}

Answer: If it's ok to change the signature to Collection rather than List, you could try using Collections.unmodifiableCollection().
public Collection<Order> getOrders()
{
    return Collections.unmodifiableCollection(orderCollection);
}

Otherwise, your approach of using a lazy member variable is fine (provided you don't need synchronization). Also, note that you can just use the constructor of ArrayList to copy the values from the source collection:
orderList = new ArrayList<Order>(orderCollection);

Comment: accepted this answer but hoping a better solution comes along.

Using a ForeignCollection


Is there a way to temporarily disable multilanguage selector links when a page doesn't have a translation?

Question: Currently when a basic page doesn't have a translation and you click on a different language in the multilanguage switcher it shows you the page in the same language. This causes a lot of duplicate content on the website which is bad for SEO.
How can I make sure the multilanguage switcher link to a different language shows up when the article is actually translated and disable the link when it isn't? Is there a way to configure this?
Answer: You could implement hook_preprocess_block in your theme.
Hope this helps you.
<code>/**
 * Implements hook_preprocess_HOOK() for block.html.twig.
 */
function bartik_preprocess_block(&$variables) {

  if ($variables['plugin_id'] == 'language_block:language_interface') {
    // Gets current node object from the current path.
    $node = \Drupal::routeMatch()->getParameter('node');

    // Gets all the translation languages, returns an array.
    $languages = $node->getTranslationLanguages();
    // Gets the number of languages.
    $number_of_languages = count($languages);

    if ($number_of_languages == 1) {
      // Basically, clears out the content render array.
     $variables['content'] = array();
    }
  }
}
</code>


Independence of random vectors implies independence

Question: Suppose we have some sequence of random variables $X_t$ with $t\in\mathbb{Z}$. Now suppose that we have that the vectors $(\ldots,X_{t-1},X_t)$ and $(X_{t+1},X_{t+2},\ldots)$ are independent for all $t$. How can I prove that the sequence $X_t$ is actually itself independent? Thanks for any hints or help.
Answer: If $Y=(Y_1,\ldots,y_m)$ and $Z=(Z_1,\ldots,Z_n)$ are independent vectors and $g,h$ measurable functions, then also $g(Y)$ and $h(Z)$ are independent. Choosing $$g(y_1,\ldots,y_m) := y_j \qquad \text{and} \qquad h(z_1,\ldots,z_n) := z_k,$$ we find that $Y_j$ and $Z_k$ are independent for any $j \in \{1,\ldots,m\}$ and $k \in \{1,\ldots,n\}$.
Now, since by assumption $(\ldots,X_{t-1},X_t)$ and $(X_{t+1},X_{t+2},\ldots)$ are independent, we get that $X_t$ and $X_s$, $s \geq t+1$, are independent. Similarly, the independence of $(\ldots,X_{t-2},X_{t-1})$ and $(X_t,X_{t+1},\ldots)$ implies the independence of $X_t$ and $X_s$ for any $s \leq t-1$. This shows that $X_s$ and $X_t$ are independent.
Using an induction one can show that $X_{t_1},\ldots,X_{t_n}$ are independent for any $t_1,\ldots,t_n \in \mathbb{Z}$.


Having a hard time writing a midi melody in my DAW

Question: I have a problem. I am writing a midi melody in a part of a song in Reaper.
I'm having a hard time writing it because several notes sound out of beat and I have no reference (bar lines) so, being a repetitive melody, when I start a new bar I might unintentionally place a note a little bit before or after and the melody loses its rhythm.
Is there anything I can do to help me in this situation? My knowledge of harmony is very basic, the signature time of the song is 4/4 and I think that in this case I am putting about 11 notes per bar.
Comment: This seems like one of those questions we'd need to be looking over your shoulder to see what's going on. As we can't see that far, we *really* need a better explanation. How are you 'writing' it? Clicking notes in, playing it live…" If you have no reference, what is driving your tempo? [Plus the 11 notes in a bar bit, which feels more like a quantity than a quality].
Comment: Can you turn a metronome on?
Comment: There should be grid lines in the piano roll view. Also there is probably a snap function and/or quantize to help you get notes right on the beat.
Comment: Do you intend to put 11 notes in a bar, or something more like 8 or 12?
Answer: There are technology issues and music theory issues to solve here. I'm unfamiliar with Reaper, so let's address the music theory ones first. You say you have "about 11 notes per bar"; are these notes all the same length? That would be surprising—but not unheard of—since 4/4 could divide evenly into 12 notes, but 11 would not line up with the beats that are inside the bar. If you're not sure, hum your melody carefully to yourself and think: are any of the notes longer or shorter than others? How do they line up with beats? If you tap your foot (or turn on a metronome) to mark the beat, which notes start at the same moment that a beat starts? If it turns out that the notes are of different lengths, you might have to figure out how to represent their different lengths in notation.
But how are you interacting with the DAW? Looking at the Reaper user guide, around page 222 talks about editing MIDI items. You can see a "piano roll" view that doesn't even require you to know the difference between quarter notes and eighth notes in music notation; instead, the notes are represented as rectangles of varying widths on a grid-like timeline. This grid does tell you where your beats and bars are, and you can arrange the notes among them. You can probably even "quantize" the notes (p. 168?) to be certain exact lengths (though I'm not sure it can handle 11/12ths). If these beats and bars don't seem to have anything to do with what you want, you might need to set the project's tempo ("bpm") to the speed you want; see p. 165.


Best way to make hovering over one  element affect another?

Question: Code:
My Code:
 - This is the image
Text here - This is the text that should change color
if above image is hovered.

If either of the two structures are hovered over, I want them to have the same color.  For the image, the image changes when it's hovered and the color of that image is red. I need the text to be red as well.
Question:
How do I change the color of the text if the image is hovered?
Edit:
The html document cannot be edited.
Comment: is it possible to wrap both `a` under the same container?
Comment: I can't.  The site's current stucture is in that way and nobody wants to change it.  Can't I do something with CSS3? I am googling stuff right now.
Comment: The colour of what text if what image is hovered? Show the *actual* HTML, don't describe it at us. Also, with reference to your question's title: *what `div` elements*?
Comment: it has to be pure CSS or you can use jQuery?
Comment: @agustinmeriles I am open to both but prefer less jquery.
Comment: Well - the additional detail changes your question somewhat significantly. As @david-thomas said - please show us the *actual* HTML, rather than describing it to us - or we can't give you a valid solution.
Answer: Several approaches:

IF you have control over the HTML, and can add a wrapper element, you can put them both in a single containing element, and use CSS.

  Text here

Then for CSS:
.hoverable:hover > .text_with_it { color: red; }
/* Or replace *red* with whatever color you want */

This works by making the text change color based on the parent being hovered - which will be true when the mouse is over either the image a OR the text a.
IF your text a will always come immediately after your image a, and the only changes you need to make on-hover are changes to the text:

Text here

Then for CSS:
.text_with_it:hover,
.image_is_displayed_using_this:hover + .text_with_it { color: red; }

This will make it so that whenever you mouse over the image OR the text, the text's color will change. Note that it is a bit more brittle, though - because it relies on your HTML being laid out in a specific manner.
Use an IMG tag - that's what they exist for.

   Text here

Then for CSS:
a.text_with_it:hover { color: red; }

Lastly - if you need to do it with jQuery, try this:
var selector = '.image_is_displayed_using_this, .text_with_it';
$(selector).hover(function (ev) {
    $(this).siblings(selector).add(this).addClass('hovered');
}).mouseout(function (ev) {
    $(this).siblings(selector).add(this).removeClass('hovered');
});

Then for CSS:
a.hovered { color: red; }

Here's a jsFiddle showing it working (very simplistic).
Comment: You can't nest interactive elements, such as `a`, or `button`, elements. Certainly Chromium [un-nests nested `a` elements](http://jsfiddle.net/davidThomas/g8MGB/).
Comment: @troyalford thanks.  As a new guy learning this it's really helpful.  How can i do the same but reverse? Hover the text to change the image.
Comment: Unfortunately, @starbucks, that is one of those edge conditions. The `+` CSS selector works on elements immediately *pro*ceding an element. However, there is no pure-CSS way to target an element immediately *pre*ceding an element - which makes it tough. In that case, you may need to go to the jQuery solution - or - try to target the two elements' parent. I can help more with that if you update to the actual HTML.
Comment: I can't suggest HTML changes until you actually show me what your HTML currently looks like. If you have the option, though, to make changes at all, try to alter your HTML to match my 1st solution above. That's the *right* way to do it.
Comment: Good point, @DavidThomas - I went ahead and removed that example, and added a jQuery version.
Comment: Thanks @troyalford, what HTML changes would you recommend.  I will try and convince them to change it if it makes sense.
Answer: I would wrap them both in an element like
text
 then set the css .hoverable:hover { color: yellow; }
Comment: @starbucks said that can't modify the document
Comment: @AgustinMeriles Good catch. Javascript will have to do if he really can't edit the html portions. I recommended an edit of original question to make this more clear for others. Limitations like that are important to note.
Answer: Use CSS? to change the text red on hover
a :hover { color: # }

Should work when you hover over the image too, as they are both "a" elements
Comment: I'm not voting this down, because frankly there's no information in the question to enable any answers, but I suspect that the OP wants to hover over *one* element and affect another.
Answer: based solely on your description, it's easiest in jquery:
$('a.image_is_displayed_using_this').hover( function() {
    $('a.text_with_it').css('background-color','gray');
}, function() {
    $('a.text_with_it').css('background-color','white');
});

Answer: If you can use jQuery, you can do something like this
$(document).ready(function(){
    $("a.image_is_displayed_using_this").mouseout(function(){
        $("a.text_with_it").css("color", "black");
    }).mouseover(function(){
        $("a.text_with_it").css("color", "red");
    });
});


Given $x=x(t)$, $\ddot x = f(x)$ can you find $\dot x(x)$?

Question: Given $x=x(t)$,  $\ddot x = f(x)$ can you find $\dot x(x)$?
In this particular problem I have $\ddot x=-\frac 1{x^{2}}$ and I want to find $\dot x (x)$, is this possible? How about the general case (the one above)?
Answer: Let $\dot x=p$. Then
$$
\ddot x=\frac{dp}{dt}=\frac{dp}{dx}\,p.
$$
The equation becomes
$$
p\,\frac{dp}{dx}=-\frac{1}{x^2}\implies p\,dp=-\frac{dx}{x^2}.
$$
Integrating we get
$$
\frac12\,p^2=\frac1x+C\implies\dot x=\pm\sqrt{\frac2x+C\,}\,.
$$
Comment: Thanks, very helpful. Just curious: If I wanted to do this with definite integrals, what would be the limits of integrations after the $p\,dp=-\frac {dx}{x^2}$ part?
Comment: If $p(x_0)=p_0$, it would be $\int_{p_0}^pp\,dp=-\int_{x_0}^x\dfrac{dx}{x^2}$.
Comment: Wouldn't I have to put the same limits in both sides? As in $\int _{x_0}^x p\, dp = - \int_{x_0}^x \frac {dx}{x^2}$?
Comment: @user14141414 In the above comment, the LHS is with respect to $p$. So as the RHS ranges from $x_0$ to $x$, the LHS ranges from $p_0=p(x_0)$ to $p=p(x)$.
Answer: Julian beat me to it, but here's an answer for your particular $\ddot{x}$. Rewrite the differential equation in terms of $\dot{x}$.
$$\ddot{x} = \frac{d\dot{x}}{dt} = -\frac{1}{x^2}$$
Now divide both sides by $\dot{x}$.
$$\frac{1}{\dot{x}}\frac{d\dot{x}}{dt}=-\frac{1}{x^2} \frac{1}{\dot{x}}$$
This simplifies to a nice, separable equation:
$$\frac{d\dot{x}}{dx}=-\frac{1}{x^2} \frac{1}{\dot{x}}$$
$$\int\dot{x}\ d\dot{x}=-\int\frac{1}{x^2} dx$$
$$\frac12\dot{x}^2=\frac{1}{x} +C$$
$$\dot{x}^2=\sqrt{\frac{2}{x} +C}$$


Resilient Propagation: How to choose between RPROP+, RPROP-, iRPROP+, and iPROP-

Question: I am using ENCOG to implement a Perceptron network.  One of the easiest back-propagation (gradient descent) algorithms to use is the Resilient Propagation algorithm.
There are four variants for this algorithm:

RPROP+
RPROP-
iRPROP+
iRPROP-

My question is, how would one choose between these variants, and what exactly is the difference between these calculation methods?
I understand that Resilient Propagation keeps a map of weight differences which the Resilient Back Propagation algorithm uses to calculate the weight changes on the next iteration (instead of updating all the weights with the same value), but I would like to know how these different variants differ in updating these weights, and any advice (anecdotal or with backup research) that one would use to choose between these variants.
Answer: According to the 2003 paper Empirical Evaluation of the Improved Rprop
Learning Algorithms, iRPROP+ has the best performance.


Java Swing - Show multiple panels

Question: I'm using the Java Swing UI Designer in IntelliJ :( I designed something in the designer using multiple panels and spacers with 1 parent panel. When I add the main panel, the first one inside it shows, but the others don't.
Frame structure:

Panel1

GradientPanel

Panel
Spacers

What I designed

What I get

import keeptoo.KGradientPanel;

import javax.swing.*;

public class LogIn extends JFrame{
private KGradientPanel KGradientPanel1; //Automatically added by the designer
private JPanel panel1; //Automatically added by the designer

public static void main(String[] args) {
    JFrame frame = new JFrame();
    frame.setTitle("CarbonTec Dashboard");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setResizable(false);
    frame.setSize(1800,1000);
    frame.setContentPane(new LogIn().panel1);
    frame.setVisible(true);

    ImageIcon imageIcon = new ImageIcon("Icon.png");
    frame.setIconImage(imageIcon.getImage());
}
}

Comment: Sidenote: Setting the `JFrame` visible via `setVisible(true)` should be done as the last step after you added all your components and set up your GUI. Also, don't `extends JFrame` if you don't actually want to change the frame functionality.
Comment: (1-) @Tom6468 *The invention Java Swing is the worst thing* - don't blame the tool, blame the carpenter. Swing is very easy to use. The code you posted tells us nothing. It doesn't even show you adding the gradient panel to the frame or the child panels to the gradient panel.  Also, using the UI designer is not recommended. You spend your time learning the designer and not learning Swing.
Answer: First you need to know that your class is a JFrame, but in the main method you create a new JFrame.
Better would be to have a class Program that has the main method. In this main method you make a new instance of LogIn.
The Program class can look like this:
public class MainProgram {

  public static void main(String[] args) {
    LogIn logIn = new LogIn();
  }
}

The LogIn class should then look like this:
    import keeptoo.KGradientPanel;
    import javax.swing.*;

    public class LogIn extends JFrame{
    private KGradientPanel KGradientPanel1 = new KGradientPanel(); //Automatically added by the designer
    private JPanel panel1 = new JPanel(); //Automatically added by the designer

    // This is the constructor.
    public LogIn {

        setTitle("CarbonTec Dashboard");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setResizable(false);
        setSize(1800,1000);
        setContentPane(panel1);

        ImageIcon imageIcon = new ImageIcon("Icon.png");
        setIconImage(imageIcon.getImage());

        // Here you can add the gradient panel to panel1.
        panel1.add(KGradientPanel1); // The name should be written in lower case.

        setVisible(true);
    }

But I don't know why you need the panel1, you could add the KGradientPanel directly.
Comment: I did all that, but now it's just all white. IntelliJ says that the JPanel and KGradientPanel are overwritten by generated code, probably the built-in designer. When I remove that part, it's back to where it was before
Comment: Then it looks like your login is the whole window. Then to add a panel to this frame you have to use the method `getContentPane().add(Component c)`. I don't know which panel is the one on the right (black).
Comment: This is the structure in the designer: https://imgur.com/a/F396YY1
The gray panel is inside the gradientpanel. The thing is that it doesn't show up in the java class
Comment: Ok, then it looks like your panel1 is your main panel. So you have to give this panel a layout to be able to position elements on it.  If you don't specify a layout, then it's the FlowLayout, which is how the elements are lined up. Thus, the white/black panel is next to the GradientPanel.

Either replace the panel1 with the GradientPanel so that it is in the background. Then you have to give the GradientPanel a layout to place the white/black on it.

If you can't replace the panel1, you need to give the GradientPanel a layout and then add the white/black panel on top of it.
Comment: Thanks for your help, it just doesn't work. The invention Java Swing is the worst thing that happened to this world. Im going to uninstall it, otherwhise I might punch my monitor.
Comment: A hint from me, do not use a designer but try to program it yourself. It is much more relaxed, then you are completely variable.
Comment: And please vote this answer.

Java Swing - Show multiple panels


winsock error code 10060 exchange 2013

Question: I just setup an exchange 2013 server, and have an intenret send connector using my mx records, no smarthost, i have cu9 installed, but am getting an error in my exchange quque
error encountered while communicating with primary target ip address: "failed to connect, Winsock error code, 10061, win32 error code 10061"
I have installed ad and dns on this server too, i have read some other posts, and people said they recreated their sent connector, i tried that but mail is still stuck
Im not sure on what more information is needed but happy to share it
Answer: I figured it out, this was spam coming in, email was flowing fine.

winsock error code 10060 exchange 2013


Error Passing Extra Parameter to Custom Form

Question: I have a simple custom form that works until I try to add a custom parameter for my module called "forms_admin".
These are the contents of my forms_admin.routing.yml
forms_admin.settings:
  path: 'admin/config/system/forms/{arg1}'
  defaults:
    _form: '\Drupal\forms_admin\Form\FormSettings'
    _title: 'Forms Settings'
  requirements:
    _permission: 'access content'

This is a relevant part of my FormSettings.php file (Currently do not have any custom Validation or Submit actions)
public function buildForm(array $form, FormStateInterface $form_state, $arg1 = NULL) {
    $form['title'] = array(
      '#type' => 'textfield',
      '#title' => t('Title'),
      '#required' => TRUE,
    );

    $form['submit'] = array(
      '#type' => 'submit',
      '#value' => t('Submit'),
    );

return $form;
}

And my third file is: forms_admin.links.menu.yml
forms_admin.config:
  title: Forms
  route_name: forms_admin.settings
  parent: system.admin_config_system
  description: 'Forms settings'
  weight: 0

The moment that I add {arg1} to my forms_admin.routing.yml and , $arg1 = NULL to my FormSettings.php file, I am unable to acces the website.

I receive a white page with the error that states:

The website encountered an unexpected error. Please try again later.

After removing arg1 from my two files and going to the Recent Log messages, this is the error I receive:

Symfony\Component\Routing\Exception\MissingMandatoryParametersException: Some mandatory parameters are missing ("arg1") to generate a URL for route "forms_admin.settings". in Drupal\Core\Routing\UrlGenerator->doGenerate() (line 182 of /var/www/test_site/docroot/core/lib/Drupal/Core/Routing/UrlGenerator.php).

I have tried changing arg1 to other names, not making $arg1 = NULL, etc. and I receive an error every time.
What am I missing?
Comment: It looks good to me - the parameter is named the same and is optional. The error indicates something's trying to generate a URL from the route without a parameter (which obviously can't work). I'm not sure the error's coming directly from a mistake in the code you've posted (it just manifests when you have a required parameter). If you have for example a menu link tied to the route you should provide a default parameter so it can generate the URL IIUC. See [optional parameters from the routing docs](https://www.drupal.org/docs/8/api/routing-system/using-parameters-in-routes).
Comment: @Andy The menu link was the issue! Thank you for catching that! How do I modify it to provide a default parameter?
Comment: It's not the link itself that you need to modify, it's the route: see the link in my previous comment and look under _optional parameters_. For example in [`ban.routing.yml`](https://api.drupal.org/api/drupal/core%21modules%21ban%21ban.routing.yml/8.5.x) there are two routes with parameters, but only `ban.admin_page` specifies a default for its parameter.
Answer: The problem is that your FormSettings class is not the controller in this case. It's the controller method which is where the routing system expects $arg_1.
I think you need to define your own controller which accepts the request and passes the argument to the form. Extending the core Drupal\Core\Controller\FormController class is probably the simplest way forward.
Comment: Is there a reference to "forms_admin.settings" anywhere else? Seems like it's the default (without arg) that's being objected to. Maybe try adding a default entry for it in routing.yml?
Comment: I don't think you need a custom controller to pass on arguments. See eg. `ban.delete` in [ban.routing.yml](https://api.drupal.org/api/drupal/core%21modules%21ban%21ban.routing.yml/8.5.x) and [`Drupal\ban\Form\BanDelete::buildForm()`](https://api.drupal.org/api/drupal/core%21modules%21ban%21src%21Form%21BanDelete.php/function/BanDelete%3A%3AbuildForm/8.5.x).
Comment: I stand corrected. How odd that your code doesn't work, then.
Comment: Just posted the same, didn't notice your reply - that's my guess, yeah.
Comment: Thank you for all of your comments and thoughts! The issue ended up being in my .links.menu.yml file.


Problema na hora de fazer push no GitHub

Question: Opa, estou tentando enviar meus arquivos para um repositorio no github mas tá dando erro.
Fiz da seguinte forma:
git init
git add .
git commit -m "xxx"
git remote add origin https://github.com/rodriguesJeff/classes_dbv/
git push origin master

Mas tá dando o seguinte erro:

Daí eu dou o git pull e dá isso:
 * branch            master     -> FETCH_HEAD

Ajuda aí pls
Comment: Evite postar mensagem de erro como imagem.
Answer: Isso ocorre quando a sua versão local (na sua máquina) está "atrasada" em relação a sua versão remota (no seu caso, que está no GitHub). Imagina o seguinte cenário:

Você cria um arquivo teste.html com o conteúdo abaixo e faz o commit e push para salvar no GitHub

    <title>Helo World</title>

Helo World

Seu colega de trabalho que não tem nada pra fazer (ou até você mesmo em outra máquina) olha esse arquivo e muda os textos, traduzindo para português. Novamente é salvo no GitHub
No outro dia você quer fazer um teste de animação com o título na página, você commita mas quando tentar salvar no GitHub, da esse erro

A solução é fazer o pull primeiro para sincronizar o local com o remoto e então salvar, mas tome cuidado, dependendo da situação pode ser que alguma alteração de conflito, se estiver usando uma IDE boa ela irá lhe alertar
Em algumas situações talvez você queira escrever o código local em cima do remoto, eu faço bastante isso, as vezes eu esqueço de commitar algum arquivo e volto para o commit anterior, recommito (dessa vez com o arquivo que faltou) e fasso push usando a opção --force
Answer: Só rodar os seguintes comandos e depois dar o push de novo
git fetch
git reset --hard origin/master

Comment: Obrigado cara, funcionou


Convert Json to List with .NET

Question: After days to try to convert Json to List of objects, I'm  here.
I have a REST API that return the Json string:
{
   GetItemsListResult:"[
      {
         "code":"VOL00056",
         "clsID":223108653,
         "type":2,
         "status":1,
         "free":0.0,
         "total":671088640.0,
         "perc":99,
         "descr":"no mailing",
         "dt":20160926,
         "tm":112456,
         "full":1
      },
      {
         "code":"VOL00055",
         "clsID":111760419,
         "type":2,
         "status":1,
         "free":0.0,
         "total":671088640.0,
         "perc":99,
         "descr":"Email",
         "dt":20160817,
         "tm":222411,
         "full":1
      }
   ]"
}

I know that this string comes from a DataTable:
String JSONresult = JsonConvert.SerializeObject(ds.Tables[0]);

I created two class: one that describe the object model and another that get the collection. But when trying to
VolumeCollection volumes = Newtonsoft.Json.JsonConvert.DeserializeObject<VolumeCollection>(listVolumes);

I obtain
    Could not cast or convert from System.String to System.Collections.Generic.List`1[Volume].
What is wrong?
Volume Class:
public class Volume
    {
        public String code  { get; set; }
        public Int32 classId  { get; set; }
        public Byte volumeType  { get; set; }
        public Byte status  { get; set; }
        public float freeSpace  { get; set; }
        public float totalSpace { get; set; }
        public Int16 fillPercentage { get; set; }
        public String classDescription { get; set; }
        public Int32 closeDate { get; set; }
        public Int32 closeTime { get; set; }
        public Boolean isFull { get; set; }
}

The json string received is:
"\"
[{\\"FreeSpace\\":0.0,\\"TotalSpace\\":671088640.0,\\"FillPercentage\\":99,\\"ClassDescription\\":\\"Email esterne\\",\\"CloseDate\\":20161001,\\"CloseTime\\":212512,\\"IsFull\\":true,\\"VolumeType\\":2,\\"ClassId\\":111760419,\\"Code\\":\\"VOL00057\\",\\"Status\\":1},
{\\"FreeSpace\\":0.0,\\"TotalSpace\\":671088640.0,\\"FillPercentage\\":99,\\"ClassDescription\\":\\"Corrispondenza no mailing\\",\\"CloseDate\\":20160926,\\"CloseTime\\":112456,\\"IsFull\\":true,\\"VolumeType\\":2,\\"ClassId\\":223108653,\\"Code\\":\\"VOL00056\\",\\"Status\\":1}
]\""
It seems to be a not valid json...
Comment: Can you share your `VolumeCollection` class?
Comment: you have invalid json string
Comment: Your JSON string is invalid. That's why it can't deserialize. Can you post the controller generating that JSON? Something is wrong with that part.
Comment: public class VolumeCollection
        {
            public List GetItemsListResult { get; set; }
        }
Comment: Could you share the `Volume` class too? Preferably add it to your question. As well as the `VolumeCollection` class.
Answer: Given that your json is not valid and given that the following is:
{
    "GetItemsListResult": [{
        "code": "VOL00056",
        "clsID": 223108653,
        "type": 2,
        "status": 1,
        "free": 0.0,
        "total": 671088640.0,
        "perc": 99,
        "descr": "no mailing",
        "dt": 20160926,
        "tm": 112456,
        "full": 1
    }, {
        "code": "VOL00055",
        "clsID": 111760419,
        "type": 2,
        "status": 1,
        "free": 0.0,
        "total": 671088640.0,
        "perc": 99,
        "descr": "Email",
        "dt": 20160817,
        "tm": 222411,
        "full": 1
    }]
}

using the following classes that I generated, this works:
    public class GetItemsListResult
    {
        public string code { get; set; }
        public int clsID { get; set; }
        public int type { get; set; }
        public int status { get; set; }
        public double free { get; set; }
        public double total { get; set; }
        public int perc { get; set; }
        public string descr { get; set; }
        public int dt { get; set; }
        public int tm { get; set; }
        public int full { get; set; }
    }

    public class RootObject
    {
        public List<GetItemsListResult> GetItemsListResult { get; set; }
    }

var res = JsonConvert.DeserializeObject<RootObject>(json);
N.B: this site generated the classes from the JSON: json2csharp
Comment: Ok, given that the json comes from a DataTable, can I change it? Can I rename GetItemsListResult with a name significative?
Comment: Not sure I follow you, are you saying that you don't control how the json is created?
Comment: More or less... I can "convice" who prepare the json :-) The data comes from a database table. How can I change the preparation of data?
Comment: Instead of just using a DataTable in the first place, create objects from each row of the table, then serialize that into `json` instead, it's much more maintainable.
Comment: Ok, instead of a DataTable, loop with a DataReader and create the list of object. Right?
Comment: Yeah, that'll do the trick. Or, still load into a DataTable then read each row. DataReader will be faster though.
Comment: No worries, it all comes down to how you want to implement it, either way will work.
Comment: After changed the code to convert datatable to a list of object and then serialize to json, I obtain same result. I figured out who put the GetItemsListResult string. The API Rest comes from WCF service

[OperationContract]
        [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped, UriTemplate = "itemslist/{id}")]
        string GetItemsList(string id);

How can avoid to put it?
Answer: Your GetItemsListResult is a string, not an array.  Notice the double quotes:
GetItemsListResult: "[

So, ideally you want to fix your json to be a real array.
If you don't have control over the json, then as a poor alternative you could recursively parse the strings to extract the array.
Answer:
you have invalid json string:

1.1 valid json like this:
{
"GetItemsListResult":[
{"code":"VOL00056","clsID":223108653,"type":2,"status":1,"free":0.0,"total":671088640.0,"perc":99,"descr":"no mailing","dt":20160926,"tm":112456,"full":1},
{"code":"VOL00055","clsID":111760419,"type":2,"status":1,"free":0.0,"total":671088640.0,"perc":99,"descr":"Email","dt":20160817,"tm":222411,"full":1}
]
}

With http://json2csharp.com/ build data model

2.1 like this:
public class GetItemsListResult
{
    public string code { get; set; }
    public int clsID { get; set; }
    public int type { get; set; }
    public int status { get; set; }
    public double free { get; set; }
    public double total { get; set; }
    public int perc { get; set; }
    public string descr { get; set; }
    public int dt { get; set; }
    public int tm { get; set; }
    public int full { get; set; }
}

public class RootObject
{
    public List<GetItemsListResult> GetItemsListResult { get; set; }
}

with http://www.newtonsoft.com/json help parse you json

3.1 like this:
var jsonObj = JsonConvert.DeserializeObject<RootObject>(jsonString);

Convert Json to List with .NET


How to achieve a similar "vibe" to this song?

Question: I want to write a song similar to "dumb dumb" by mazie. I want to achieve a similar feel of weird, dreamy nostalgia the song has. I know a lot of this feeling comes from dissonance between descending chromatics and diatonic tones, but is there any other things I need to keep in mind when writing a song like this? Thank you for your help!
Answer: This is my first attempt at contributing to the Music Theory Forum so please forgive if I completely screw it up!  Anyhow, I've taken the liberty of transcribing the beginning of the song:

The thing that stands out for me in this the chromaticism is bars two and four which lean on the D augmented chord.  This lends the song its characteristically "whimsical" element that you often see in showtunes (for lack of a better term) and the like.   Reduced to its most basic form it frequently appears in Broadway (often as a vamp) as such:

Or, in a slightly more "jaunty" form:

Also adding to the style is the minor chord in bar 8 that again uses the raised sixth/flat seventh degree of D major for chromatic coloration, this time resolving downwards.
Other things that create this slightly surreal/dreamy/nostalgic effect are  the colorful instrument timbres/effects, the generally light texture and the slightly understated singing in the, for lack of a better term, Lily Allen style.


Eclipse Internal Browser doesn't apply HTML tags

Question: I've created a simple servlet in Java and showing its HTML output in Eclipse internal browser.
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        PrintWriter writer = response.getWriter();
        writer.println("
 Hello World
");
    }

But the output is like this :

Why doesn't apply
 tag ?
Answer: Need to set response content type:
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException,ServletException
{
     response.setContentType("text/html");

     PrintWriter writer = response.getWriter();

     writer.println("
 Hello World
");

}


How to split a Single Column with multiple entries into multiple columns

Question: I have a csv file with entries of multiple columns in a single column with multiple quotes. When I load it in R using data.table(fread) it appears as a table with quotes. I have tried using quote=FALSE, but it is not working.
Here's how it looks like
I also tried reading it using read.csv it appears as a single column with multiple entries.
I also tried using print.data.frame using quote=FALSE. But it is not working either.
So I have two problems:

How to split this single column into multiple and
How to remove these quotes

I will be grateful for your help.
Comment: Screenshots are not helpful for sharing data. Please add data using `dput` so that it is easier to help you. Please read the info about [how to ask a good question](http://stackoverflow.com/help/how-to-ask) and how to give a [reproducible example](http://stackoverflow.com/questions/5963269)
Answer: It's difficult to answer your question without having reproducible data, but here is an example which may help you:
You need to use the data.table and assuming your Bev is a data.frame, you process each column with quotes with the gsub function like below.
d <- data.frame(site = c('"hello"','"vietnam"'),value= c(1,2))
d
#       site value
#1   "hello"     1
#2 "vietnam"     2
d$site <- gsub('"', '', d$site)
d
#     site value
#1   hello     1
#2 vietnam     2

Consider renaming your colnames, it will be easier later on to work with this dataset.
Answer: I'm sure the quote marks are a result of how you read-in the data. Try to read-in your data as .txt. That is, copy-and-paste the data from the csv-file to a txt-file and use read.table as well as these arguments:
data <-read.table("[Your path]/[File name].txt", header=T, quote="", sep="\t", fill=F, comment.char="")


Does a factorial design work for factors that have discrete levels, but can't be classified as "high" or "low"?

Question: I have eight factors, four with 2 levels and four with 3 levels. These levels are not "high" and "low" in the sense that they can be turned off and on—but are instead things like "voiced" and "unvoiced", "male" and "female", or "front", "middle", and "closed."
Is it appropriate to arbitrarily choose which factor represents high and which represents low? Can I say when x = voiced = high = 1 and when x = unvoiced = low = -1, go through runs determined by a factorial design, and still get results that make sense? Are there any things I have to look out for when doing this?
My instinct is "yes, this is perfectly fine," but this type of analysis is fairly new to me, and I'd like to be certain.
Answer: If by "factorial design" you mean ANOVA then yes, you can do ANOVA with variables that do not have an order. You don't need the "high" and "low" and, indeed, shouldn't have them.  E.g you can have a variable "voiced" and code it "unvoiced" and "voiced".
Comment: I suppose this is what I mean, yes. Thanks for your answer. Do you, by chance, have any suggestions for relatively quick reading material that would get me somewhat up to speed on ANOVA? I unfortunately don't have the time to read through a whole textbook, but am well versed in mathematics, so somewhat dense literature is ok.
Comment: I don't have any particular links.  There's a bunch of things to beware of in ANOVA (and in regression, which is the same model).
Comment: Ah, bummer. Thank you, though, for the answer! That is one step forward. I'll accept it when the 5-min. limit is up.


Disabling Browse to Library in Media Upload Field

Question: I'm on Drupal 7.2 with the included Media Module. I'm also using WYSIWYG if that matters at all.
I'm seeing that when a user clicks the image upload field, they have a choice of either 'web' or 'library'.  The Library option shows all files that other users have uploaded to be included in other nodes. How do I disable that so that they don't see all the other files?
I don't use galleries- just upload/attach images to nodes that the users themselves create. Guests and Registered Users BOTH can see the nodes and image files- but I don't want them to have access to all the images that have been uploaded previously.
I think this has something to do with Private/Public, but I can't figure it out. Any input?
Comment: This is a current feature request in the media module issue queue and there appears to be a patch being tested. [Issue #992978: Add 'View media browser library' permissions](http://drupal.org/node/992978)
Answer: On Drupal 8+ go to: <code>/admin/config/media/browser</code>

Set the "Enabled browser plugins" to only "upload" and save the page.
Now when people click on the button in the WYSIWYG to add something, they should only get the upload option and not see the library.
Comment: The question said they were on Drupal 7.2
Answer: This can be accomplished with a module, and this hook:
<code>/**
 * Implements hook_media_browser_plugins_alter().
 */
function my_module_media_browser_plugins_alter(&$plugins) {
  // Hide the "Library" tab on the WYSIWYG media upload widget.
  unset($plugins['library']);
}
</code>