Using razor to build a popup tooltip menu

Question: I am having a problem with dynamically generating this dropdown menu. This works if I'm not making it dynamically.
The @t.Id is working and is different every time in the loop. I'm pretty sure its the first line that's wrong as I have used the id="" before this way.
tagged

        hhhh

            nnnn
            @for( int i = 0; i < t.tTags.Count; i++ ) {
                @Html.ActionLink( t.tTags[i], "TagDetail", "Forums", new { tag = t.tTags[i], page = 0 }, null )
            }

Comment: thought I would add the popup works but doesnt contain the div
Comment: What's not working? I fired this up with some sample data and it renders a list of a links, and inserts IDs where you would expect.
Comment: This should work. Where are you getting error ?what error message you are getting ?
Comment: strange guys, the popup shows but it doesnt include the div, if I load it up eg this, '#tagsdiv') then make the div just tagsdiv it will work fine. no error just isnt loading the div once add it inside a loop with @(t.Id)
Comment: also if i make it (this, 'some text') it will show the some text in the div, so deffo a linking error
Comment: I listed out some possibilities for you. It would help to see the rendered HTML.
Answer: Tips to debug Razor (or any server-side code rendering markup) more effectively:

View the rendered HTML! is it correct?
Remove styles/scripts until you are sure the server is rendering the values you want.
Add a breakpoint to your controller to make sure you are passing data to the view. Your rendering logic may be fine.

That said, your code appears to work fine. I dummied up some data:
@{ var t = new { Id = 1234, tTags = new List<string> { "foo", "bar", "baz" } }; }

tagged

                @for( int i = 0; i < t.tTags.Count; i++ ) {
                    @Html.ActionLink( t.tTags[i], "TagDetail", "Forums", new { tag = t.tTags[i], page = 0 }, null )
                }

This yields:
tagged

            foo
            bar
            baz

One thing that really looks wrong here is '#tagsdiv1234'. Are you sure your tooltip needs an ID including the CSS/jQuery ID selector ("#")?
Another thing that stands out is your tooltip container is wrapped with an outer div set to display:none. The ID'd element will always be hidden because its parent is hidden, even if the tooltip code tries to show it.
Another possibility is that your ID contains a character illegal in an element identifier.
Comment: cheers tim havnt thought about debbugging in that way. Either way this is rather odd. The T.Id is just a number (a topic id) which im also using to create a actionlink button for each topic which works fine. Ive tried deleting each part of the css attached to it. Very odd, can only really be a javascript problem then? and thats way too big to post here :)
Comment: but saying that if i can make it 'some text' and it shows but then instead add this div to it and it wont that means its not a javascript problem? confused as hell lol
Comment: Based on what you described, yes, it could be a JS or CSS problem. What if you remove the "display:none"?
Comment: removed the display none and it changed nothing. Got it to work by removing the span inside the div which is rather odd as I have used this exact layout in another page. very odd, cheers for the help. +1 on the debugging tip


A counter-example to disprove that not every adjacency matrix can be made block-diagonal?

Question: I have a bunch of clusters of proteins (a disconnected graph) and wanted to present this data as an adjacency matrix for various reasons and have been looking for a way to make these adjacency matrices block-diagonal to make the relationships more apparent, but had no luck. I have tried SciPy's reverse Cuthill-McKee, svd, somebody has recommended Dulmage-Mendehlson and a bunch of other decompositions but to no avail. By this point, somebody told me that this might not even be possible in every case.
Would somebody happen to have an example or a concrete formulation of why exactly? I can't quite convince myself that's it's not possible from just looking at my data which looks like this by the way... Clearly, the structures which I'm trying to present are there (the large and small ribosomal subunits) and would probably become more apparent when I pour more data in there, but I would've so loved to also differentiate the clusters within the two subunits because I know they are there. Should I just use a covariance matrix?

Here is what breadth-first search yields by the way. Still I am not sure what that means, but I can definitely see now that permuting out of this state of band-minimization breaks structure rather than builds it, so maybe that's as far as I get today.
Comment: Possibly useful [MathOverflow post](https://mathoverflow.net/questions/68041/showing-block-diagonal-structure-of-matrix-by-reordering).
Comment: There are apparently two clusters between indices $[0, 30]$ and $[60, 80]$ in your original matrix, this is quite visible. However, there are also two entries on row 30 / columns 70 and 80. I think that these entries may connect the two clusters.
Indeed, the result of your BFS (which is just a permutation of the rows and columns) shows a connected graph.
Answer: You always can permute the rows and columns of the adjacency matrix so that each block corresponds to a connected component.  Just find the connected components and then reorder with all nodes from component 1 first, component 2 next, and so on.
Comment: Breadth-first search, depth-first search, union-find are three choices to find the connected components.
Comment: Any idea which algorithm I can use to do that or what's the trick if I were to do it manually? Maybe i'm missing something very basic, but let's say if I run another 10 molecules through my code and it turns out that the clusters( interior to the subunits ) are arranged a bit differently than what it is here, do i permute the namespace(rows and columns = protein names) again?
Answer: Some questions:

What do the colors in your plots represent?
How can you be sure your graph is disconnected if you haven't block-diagonalized its adjacency matrix?  Is there something in the nature of the data that guarantees this?

Now some comments:
If your graph really does have $n$ disconnected components, than its adjacency matrix certainly can be written in block diagonal form with $n$ blocks, regardless of what anybody says.
Something like the following should work.  Let A be an m by m adjacency matrix.  Create an array componentIdentifier of length m, with every element initialized to 0.  Also create an array permutation of length m.
numberComponents = 0
numberVerticesPermuted = 0
for i from 1 to m:
   if componentIdentifier[i] == 0:
      /* vertex i is in a new component */
      numberComponents = numberComponents + 1
      componentIdentifier[i] = numberComponents
      numberVerticesPermuted = numberVerticesPermuted + 1
      permutation[numberVerticesPermuted] = i

      /* find all vertices connected to i */
      k = numberVerticesPermuted
      while k <= numberVerticesPermuted:
         r = permutation[k]
         for c from 1 to m:
            if A[r,c] == 1 and componentIdentifier[c] == 0:
               componentIdentifier[c] = numberComponents
               numberVerticesPermuted = numberVerticesPermuted + 1
               permutation[numberVerticesPermuted] = c
         k = k + 1

When this concludes, numberComponents will hold the number of disconnected components and permutation will hold the permutation of indices needed to put the adjacency matrix in block-diagonal form.
Comment: Thank you, Will! I will try this right away...
The colors in these plots I provided are actually multiple adjacency matrices summed element-wise and then divided by the number of matrices. ( To emulate the "mean of
a population graphs", i realize there are more sophisticated methods out there.) So the brightest spots are the proteins that co-occur in space in multiple molecules.
I think i can guarantee disconnectedness because of how i defined my clusters: any neighbor of $n$'th neighbor belongs to the same cluster. Maybe a spanning forest is a technical term. And I actually have the graph


Doubt in the definition of the Fourier transform in $L^{2}(\mathbb R^n)$

Question: I am trying to understand the definition of the Fourier transform in $L^{2}(\mathbb R^n)$ .
I am understand of this manner :
Let $f \in L^{2}(\mathbb R^n)$ and $n$ a natural number. Define $f_n = f {\chi}_{B(0,n)}$. The Fourier transform of $f$ is the function $\hat{f}$ given by
$$ \hat{f} = \lim_n \hat{f_n}  \ \  \text{(the limit is in $L^2{(\mathbb R^n)}$)}$$
and the  Fourier transfom of $f$ in a point $\xi$ is given by
$$ \hat{f}(\xi) = \lim_{n} \int_{B(0,n)} f_n(x)e^{-2 \pi i \langle x,\xi\rangle} \ dx$$
I am right?
Thanks in advance
Answer: This is correct.
The reason you had to do all these stuff is the fact that $L^2$-function on $\mathbb R^n$ are not necessarily integrable (i.e. $L^1$), but they can be approximated in the $L^2$-norm by functions which are in $L^1\cap L^2$, and this is precisely what you are doing.


Certificate Authority for multiple keys

Question: I have a single server hosting an existing self-signed CA with keys for OpenVPN.
Can I used the same CA and generate keys for freeradius?
Thanks
Answer: Essentially yes, but you'll have to make sure the certificates (not keys) you generate contain the data freeradius will look for. What that is depends on how freeradius is set up, what you use it for.
If you use easy-rsa (supplied with OpenVPN), you'll probably need to edit the openssl.cnf file it uses to generate certificates that are also suitable for your freeradius use-case.
Dealing with X.509 certificates is not fun; documentation is ambiguous and dense, many standards are old and weren't written with the Internet in mind, and in many cases they're also vague. Prepare to have to blaze your own trail.

Certificate Authority for multiple keys


Searching for a certain local ring

Question:
I am searching for a local ring $R$ such that $R/\mathrm{Soc}(R_R)$ is not isomorphic to the two-element ring $\mathbb Z_2$.

Here, by $\mathrm{Soc}(R_R)$ I mean the socle of the right $R$-module $R$.
Thanks for any help!
Answer: If you take $K$ to be any field other than $\mathbb{Z}_2$, then the ring $R=K[X]/(X^2)$ satisfies your requirements, since it is local and $R/\mathrm{Soc}(R_R) \cong K$.
Comment: @karparvar The ideal you mention is also the only non-trivial proper ideal of $R$.  Hence it is simple as an $R$-module, and since the socle of $R_R$ is the sum of all its simple submodules, you get that $(X)/(X^2)$ is the socle.
Comment: Thanks for the answer. I know that the only maximal ideal of $R$ is $(X)/(X^2)$, but what is its socle? And Why? Thanks!
Answer: For $p$ a prime and $n>2$, the only minimal ideal of $\mathbb{Z}/p^n\mathbb{Z}$ is $p^{n-1}\mathbb{Z}/p^n\mathbb{Z}$ and the quotient ring modulo the socle is $\mathbb{Z}/p^{n-1}\mathbb{Z}$: it is a uniserial ring, that is, its ideals are linearly ordered.
For $p\ne2$ the example $\mathbb{Z}/p^2\mathbb{Z}$ is even simpler, because the socle is the same as the maximal ideal.

Searching for a certain local ring


Ivar showing null although it's strongly referenced and initialized and allocated

Question: I have class called A with a public ivar called lines of type NSMutableArray. I allocate and initialize the ivar in the init method. On the other hand I have another class called B which has a strong reference to an ivar of type class A. I allocate and initialize the class A in the init method of class B. What I would expect:
The public ivar of the class A should not be null after the the class B has allocated and initialized the class A as its instance variable. What I get:
When I do the following I find the lines variable of the class A variable to be null:
   myClassAVariable=[[ClassA alloc]init ];
   NSLog(@"The lines object is %@",[myClassAVariable lines]);

Note: I'm using cocos2d.
EDIT:
Here's the part of the ClassA.h file;
@interface ClassA : CCLayer
{
    NSMutableArray *lines;
}
@property(strong,nonatomic)NSMutableArray *lines;

Here's the part of the init method of the ClassA:
if( (self=[super init]) ) {
   lines=[[NSMutableArray alloc] init];
}
return self;

Here's the part of the interface of the ClassB:
 @interface ClassB : CCLayer
 {
       DrawLayer *draw;
 }
 @property(strong,nonatomic)DrawLayer* draw;

And finally, here's the init of the ClassB:
if( (self=[super init]) ) {
   draw=[[DrawLayer alloc] init];
        CCLOG(@"Lines object is %@",[draw lines]);//Shows "Lines object is (null)"
}
return self;

Comment: Can you show us the init of ClassA
Comment: `myClassAVariable=[[ClassA alloc]]init ]` is invalid syntax, could you post the actual code?
Comment: Ho do you know it's strongly referenced? can you paste the definition of `ClassA` ?
Comment: Have a look at my answer below, you need to invoke the setter by `self.lines`
Answer: if lines is just an ivar, that would not invoke its setter when calling [[ClassA alloc]init ];. I would suggest making it a strong property:
ClassA.h:
@property(nonatomic,strong) NSMutableArray *lines;

in ClassA init method:
//initiliaze lines:
self.lines = [[NSMutableArray alloc]init];

Comment: It did actually work, man. I had forgotten just another little nuance. I forgot that I had to call self.draw.lines instead of [self.draw lines]. :) So thanks for reminding.


NextJS SyntaxError: Unexpected token 'export'

Question: I have a library that works flawless on a app using react-create-app. Now, I want to use this library with NextJS (using npx create-next-app --ts) but I got this error:
error - /home/ubuntu/workspace/uikit-showcase-next/node_modules/@orgname/uikit/index.js:1
export * from './components/atom';
^^^^^^

SyntaxError: Unexpected token 'export'
    at wrapSafe (internal/modules/cjs/loader.js:988:16)
    at Module._compile (internal/modules/cjs/loader.js:1036:27)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1101:10)
    at Module.load (internal/modules/cjs/loader.js:937:32)
    at Function.Module._load (internal/modules/cjs/loader.js:778:12)
    at Module.require (internal/modules/cjs/loader.js:961:19)
    at require (internal/modules/cjs/helpers.js:92:18)
    at Object.@orgname/uikit (/home/ubuntu/workspace/uikit-showcase-next/.next/server/pages/index.js:87:18)
    at __webpack_require__ (/home/ubuntu/workspace/uikit-showcase-next/.next/server/webpack-runtime.js:25:42)
    at Object../pages/index.tsx (/home/ubuntu/workspace/uikit-showcase-next/.next/server/pages/index.js:20:75) {
  page: '/'
}```

Comment: Please Make sure You have the latest version of node and than run npx create-next-app --ts, good luck and best regards ! ;-)
Comment: I am using node 14
Comment: node --version: v14.17.6 and npm --version: 6.14.15
Comment: Does this answer your question: [Next.js SyntaxError "Unexpected token 'export'"](https://stackoverflow.com/questions/65936222/next-js-syntaxerror-unexpected-token-export)? Use [`next-transpile-modules`](https://github.com/martpie/next-transpile-modules) to transpile your library.
Answer: Changed on the library from "target": "es6", to "target": "es5", solved the issue


Show there exists $\lambda \in \sigma(A)$ such that $|\lambda - \lambda_0|<\epsilon$

Question: Let $A$ be a bounded self-adjoint operator on a Hilbert space $H$. Given $\lambda_0 \in \mathbb{C}$, suppose there exists some nonzero $\psi \in H$ such that
$$||A\psi - \lambda_0 \psi|| < \epsilon ||\psi||$$
Show there exists some $\lambda \in \sigma(A)$ such that $|\lambda - \lambda_0| <\epsilon$. Here we let $\sigma(A)$ denote the spectrum of $A$.
My thoughts were as follows:
Let $f:\sigma(A) \rightarrow \mathbb{C}$ be defined by $f(\lambda) = \lambda - \lambda_0$. Then, the above inequality becomes
$$||f(A)\psi||< \epsilon ||\psi||$$
Now, note that by the Spectral Theorem
$$\sup_{\lambda \in \sigma(A)}|\lambda - \lambda_0|= \sup_{\lambda \in \sigma(A)}|f(\lambda)|  = ||f(A)|| = \sup_{\psi \in H \setminus\{0\}} \frac{||f(A) \psi||}{||\psi||} $$
This seems close to what we want, but since we are taking the supremum here, it doesn't appear that we can easily use the assumption.
Any help would be greatly appreciated!
Reference: Exercise 7.9.b in Quantum Theory for Mathematicians by Hall.
Comment: What is "finite a bounded"?
Comment: My bad, it was a typo. I fixed it.
Answer: It suffices to use the fact that
$$\|(\lambda_0-A)^{-1}\|=\frac1{d(\lambda_0,\sigma(A))}$$
for $\lambda_0\in\rho(A),$ where $d(\lambda_0,\sigma(A))=\inf_{\lambda\in\sigma(A)}|\lambda-\lambda_0|$. This is exactly Exercise 7.9.a in Quantum Theory for Mathematicians by Hall
If $\lambda_0\in\sigma(A)$, then everything is OK. Assume that $\lambda_0\in\rho(A)$. To prove the desired result, it suffices to show that $d(\lambda_0,\sigma(A))<\epsilon$. Suppose that $d(\lambda_0,\sigma(A))\geq \epsilon$, then we have
$$\|(\lambda_0-A)^{-1}\|\le\frac1\epsilon,$$
which implies that
$$\|(\lambda_0-A)^{-1}(\lambda_0-A)\psi\|\le\frac1\epsilon\|(\lambda_0-A)\psi\|,$$
a contradiction to the assumption that $\|A\psi-\lambda_0\psi\|<\epsilon\|\psi\|$. So $d(\lambda_0,\sigma(A))<\epsilon$.
Comment: Oh nice!!  Thank you so much!
Answer: Just to add two comments:

The result holds for any normal operator $A$. If $A$ is normal, so is $(A-\lambda_0)^{-1}$ (if $\sigma_0\not\in \sigma(A)$), and $\|(A-\lambda_0)^{-1}\|$ is equal to its spectral radius, which is obviously $\max_{\lambda\in\sigma(A)}\frac{1}{|z-\lambda_0|}=\frac{1}{d(\sigma(A), \lambda_0)}$ by the spectral mapping theorem. Now we can apply @Feng's answer.

The result fails for non-normal operator $A$. E.g. $A=\begin{pmatrix} 1 & 1 \\ 0 & 1 \end{pmatrix}, x=\begin{pmatrix} 1 \\ -1 \end{pmatrix}, \lambda_0=0$, we have $\|Ax\| = 1 = \frac{\sqrt 2}{2} \|x\| \le 0.8\|x\|$, but $\sigma(A) = \{1\}$.


Drush not fully installed

Question: I have installed Drush 8.2.3 globally on a Lubuntu 18.04 image. This was done without Composer (I used the default install instructions here)
However, if I run drush topic and select any topic number from the list I get
phar:///usr/local/bin/drush/examples/sync_via_http.drush.inc: No such file or directory
more: stat of phar:///usr/local/bin/drush/examples/sync_via_http.drush.inc failed: No such file or directory

What gives?
Answer: This is a known issue - Topic command does not work when using Phar. Searching the issue queue is always recommended. Since the current version is Drush 9, I don't expect this to be fixed.
Comment: thank you for pointing out the issue queue, I will in the future.

Drush not fully installed


What does 0.1 inning mean in baseball stats?

Question: Baseball-reference labels Adam Ottavino as 0.1 IP (innings pitched).

Similarly, Jordan Montgomery gets 5.2 IP. What does that mean? How is this stat calculated?
Comment: It's just a ternary point, not a decimal point :)
Answer: Pitchers IP or "innings pitched" stats are recorded as the number of outs that the defense was able to generate, listed in innings, during the time when the the player is the pitcher of record.  Three outs is equivalent to one inning.
Any partial innings are shown as the number of whole innings, plus the number of outs after a decimal.

6 outs = 2 innings
7 outs = 2.1 innings
8 outs = 2.2 innings
9 outs = 3 innings

It is also common that if a pitcher starts an inning but has to leave before any outs are recorded, the inning count has a plus sign (+) next to it.  So if Smith pitches the first four innings, then faces 3 batters in the fifth without recording an out before leaving, that line could be "IP: 4+"
In your example, the pitchers earned the following number of outs.

Montgomery: 17 outs
Green: 6 outs
Ottavino: 1 out
Holder: 3 outs
Total: 27 outs (9 innings)

Although the decimal notation that is commonly used does not seem to be mentioned, the practice of recording outs as fractions of an inning is detailed in the MLB rulebook.  9.02(c)(1) lists that the number of innings pitched is an official stat to be recorded and has the following comment:

Rule 9.02(c)(1) Comment: In computing innings pitched, the Official Scorer shall count each putout as ⅓ of an inning. For example, if a starting pitcher is replaced with one out in the
sixth inning, the Official Scorer shall credit that pitcher with 5⅓ innings. If a starting pitcher is replaced with none out in the sixth inning, the Official Scorer shall credit that pitcher with 5
innings and make the notation that that pitcher faced batters in the sixth, noting the number of batters faced. If a
relief pitcher retires two batters and is replaced, the Official Scorer shall credit that pitcher with ⅔ of an inning pitched. If a relief pitcher enters a game and his team initiates a successful
appeal play that results in one out, the officer scorer shall credit such relief pitcher with ⅓ of an inning pitched.


Putting tables into two columns in a responsive webpage

Question: I am currently working on a class project and I am almost done, however I cannot get my calendar page to work properly. I am supposed to create each calendar month using tables, so no javascript or arrays. The calendar pages also needs to be responsive.
I already made each month as a table and I need to put these tables into 2 columns. The issue is that the columns are uneven and I attached a screenshot below to show my problem. I want January - June on the left side and July-December on the right side. I am confused on how to do this.
Each month is also supposed to have text listing important dates right next them. For example: 1st: New Years and 18:Martin Luther King Day should be next to the January table. When I try to put the text in the html code, I can never get the text to align properly. They were either below the tables or underneath them. I even tried tied putting all the text and calendar tables into one big table with four columns. I liked how it look, however I could not get this to be responsive since the table fell off the page in mobile view.
I would appreciate any help I can get.

CSS

.Calendar, th,td{
   color: black;
   border: 1px solid navy;
   background-color: #add8e6;
   border-collapse: collapse;
   margin-bottom:1%;
   margin-top:1%;

}

.eventDay{
   background-color:red;
}

.column{
   -moz-column-count: 2;
   -webkit-column-count: 2;
   column-count: 2;
}

@media screen and (max-width: 480px){
   .column{
   -moz-column-count: 1;
   -webkit-column-count: 1;
   column-count: 1;
   }
}

  January 2021

    Sun
    Mon
    Tues
    Wed
    Thurs
    Fri
    Sat

1

    2

    3
    4
    5
    6
    7
    8
    9

    10
    11
    12
    13
    14
    15
    16

    17

18

    19
    20
    21
    22
    23

    24
    25
    26
    27
    28

29

    30

    31

  February 2021

    Sun
    Mon
    Tues
    Wed
    Thurs
    Fri
    Sat

    1
    2
    3
    4
    5
    6

    7
    8
    9
    10
    11
    12
    13

    14

15

    16
    17
    18
    19
    20

    21
    22
    23
    24
    25
    26
    27

    28

  March 2021

    Sun
    Mon
    Tues
    Wed
    Thurs
    Fri
    Sat

    1
    2
    3
    4
    5
    6

    7
    8
    9
    10
    11
    12
    13

    14
    15
    16
    17
    18
    19
    20

    21
    22
    23
    24
    25

26

    27

    28
    29
    30
    31

  April 2021

    Sun
    Mon
    Tues
    Wed
    Thurs
    Fri
    Sat

    1

2

    3

    4
    5
    6
    7
    8
    9
    10

    11
    12
    13
    14
    15
    16
    17

    18
    19
    20
    21
    22
    23
    24

    25
    26
    27
    28
    29
    30

  May 2021

    Sun
    Mon
    Tues
    Wed
    Thurs
    Fri
    Sat

    1

    2
    3
    4
    5
    6
    7
    8

    9
    10
    11
    12
    13
    14
    15

    16
    17
    18
    19
    20
    21
    22

    23
    24
    25
    26
    27

28

    29

    30

31

  June 2021

    Sun
    Mon
    Tues
    Wed
    Thurs
    Fri
    Sat

    1
    2
    3
    4
    5

    6
    7
    8
    9
    10
    11

12

13

14

    15
    16
    17
    18
    19

    20
    21
    22
    23
    24
    25
    26

    27
    28
    29
    30

  July 2021

    Sun
    Mon
    Tues
    Wed
    Thurs
    Fri
    Sat

    1
    2
    3

4

    5
    6
    7
    8
    9

10

11

    12
    13
    14
    15
    16
    17

    18
    19
    20
    21
    22
    23
    24

    25
    26
    27
    28
    29

30

    31

  August 2021

    Sun
    Mon
    Tues
    Wed
    Thurs
    Fri
    Sat

    1
    2
    3
    4
    5
    6

7

8

    9
    10
    11
    12
    13
    14

    15
    16
    17
    18
    19
    20
    21

    22
    23
    24
    25
    26
    27
    28

    29
    30
    31

  September 2021

    Sun
    Mon
    Tues
    Wed
    Thurs
    Fri
    Sat

    1
    2
    3
    4

    5

6

    7
    8
    9
    10
    11

    12
    13
    14
    15
    16
    17
    18

    19
    20
    21
    22
    23

24

    25

    26
    27
    28
    29
    30

  October 2021

    Sun
    Mon
    Tues
    Wed
    Thurs
    Fri
    Sat

    1
    2

    3
    4
    5
    6
    7
    8
    9

    10

11

12

13

14

15

16

17

    18
    19
    20
    21
    22
    23

    24
    25
    26
    27
    28
    29
    30

    31

  November 2021

    Sun
    Mon
    Tues
    Wed
    Thurs
    Fri
    Sat

    1
    2
    3
    4
    5
    6

    7
    8
    9
    10

11

    12
    13

    14
    15
    16
    17
    18
    19
    20

    21
    22
    23

24

25

26

    27

    28

29

    30

  December 2021

    Sun
    Mon
    Tues
    Wed
    Thurs
    Fri
    Sat

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

    16
    17
    18

    19
    20
    21
    22
    23
    24

25

26

27

28

29

30

31

screenshot of calendar tables
Answer: This should solve your problem

.Calendar, th,td{
   color: black;
   border: 1px solid navy;
   background-color: #add8e6;
   border-collapse: collapse;
   margin-bottom:1%;
   margin-top:1%;

}
.div_left, div_right {
  display: flex;
  flex-flow: column;
}

.row_main {display: flex; justify-content: space-around;}

.eventDay{
   background-color:red;
}

.column{
   -moz-column-count: 2;
   -webkit-column-count: 2;
   column-count: 2;
   display: flex;
}

@media screen and (max-width: 480px){
   .column{
   -moz-column-count: 1;
   -webkit-column-count: 1;
   column-count: 1;
   }
  .row_main { flex-flow:column;}
}

  January 2021

    Sun
    Mon
    Tues
    Wed
    Thurs
    Fri
    Sat

1

    2

    3
    4
    5
    6
    7
    8
    9

    10
    11
    12
    13
    14
    15
    16

    17

18

    19
    20
    21
    22
    23

    24
    25
    26
    27
    28

29

    30

    31

  February 2021

    Sun
    Mon
    Tues
    Wed
    Thurs
    Fri
    Sat

    1
    2
    3
    4
    5
    6

    7
    8
    9
    10
    11
    12
    13

    14

15

    16
    17
    18
    19
    20

    21
    22
    23
    24
    25
    26
    27

    28

  March 2021

    Sun
    Mon
    Tues
    Wed
    Thurs
    Fri
    Sat

    1
    2
    3
    4
    5
    6

    7
    8
    9
    10
    11
    12
    13

    14
    15
    16
    17
    18
    19
    20

    21
    22
    23
    24
    25

26

    27

    28
    29
    30
    31

  April 2021

    Sun
    Mon
    Tues
    Wed
    Thurs
    Fri
    Sat

    1

2

    3

    4
    5
    6
    7
    8
    9
    10

    11
    12
    13
    14
    15
    16
    17

    18
    19
    20
    21
    22
    23
    24

    25
    26
    27
    28
    29
    30

  May 2021

    Sun
    Mon
    Tues
    Wed
    Thurs
    Fri
    Sat

    1

    2
    3
    4
    5
    6
    7
    8

    9
    10
    11
    12
    13
    14
    15

    16
    17
    18
    19
    20
    21
    22

    23
    24
    25
    26
    27

28

    29

    30

31

  June 2021

    Sun
    Mon
    Tues
    Wed
    Thurs
    Fri
    Sat

    1
    2
    3
    4
    5

    6
    7
    8
    9
    10
    11

12

13

14

    15
    16
    17
    18
    19

    20
    21
    22
    23
    24
    25
    26

    27
    28
    29
    30

  July 2021

    Sun
    Mon
    Tues
    Wed
    Thurs
    Fri
    Sat

    1
    2
    3

4

    5
    6
    7
    8
    9

10

11

    12
    13
    14
    15
    16
    17

    18
    19
    20
    21
    22
    23
    24

    25
    26
    27
    28
    29

30

    31

  August 2021

    Sun
    Mon
    Tues
    Wed
    Thurs
    Fri
    Sat

    1
    2
    3
    4
    5
    6

7

8

    9
    10
    11
    12
    13
    14

    15
    16
    17
    18
    19
    20
    21

    22
    23
    24
    25
    26
    27
    28

    29
    30
    31

  September 2021

    Sun
    Mon
    Tues
    Wed
    Thurs
    Fri
    Sat

    1
    2
    3
    4

    5

6

    7
    8
    9
    10
    11

    12
    13
    14
    15
    16
    17
    18

    19
    20
    21
    22
    23

24

    25

    26
    27
    28
    29
    30

  October 2021

    Sun
    Mon
    Tues
    Wed
    Thurs
    Fri
    Sat

    1
    2

    3
    4
    5
    6
    7
    8
    9

    10

11

12

13

14

15

16

17

    18
    19
    20
    21
    22
    23

    24
    25
    26
    27
    28
    29
    30

    31

  November 2021

    Sun
    Mon
    Tues
    Wed
    Thurs
    Fri
    Sat

    1
    2
    3
    4
    5
    6

    7
    8
    9
    10

11

    12
    13

    14
    15
    16
    17
    18
    19
    20

    21
    22
    23

24

25

26

    27

    28

29

    30

  December 2021

    Sun
    Mon
    Tues
    Wed
    Thurs
    Fri
    Sat

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

    16
    17
    18

    19
    20
    21
    22
    23
    24

25

26

27

28

29

30

31


HTTP Adaptive Bitrate Streaming

Question: Apple has included HTTP Adaptive Bitrate Streaming in the iPhone OS 3.0, in particular Safari handles this automatically.
I'd like to play with this in a low cost manner, but I expect it'll require a custom HTTP server in the worst case, and interesting PHP/etc scripting in the best case.
But first I need to know what the protocol differences or standard is.  HTTP is reasonably simple as a protocol, but adaptive bitrate means the file size is different, the chunk locations are different at different bitrates, etc.  For instance, does the client tell the server anything special about the stream as it's downloading, or is it all handled on the server side?
Eliminating buffering pauses for the end user is very attractive for both live and pre-recorded video streams, and doing both over HTTP is even better given many networks and gov'ts are limiting non port 80 traffic.

What are the technical details for HTTP adaptive bitrate streaming, especially Apple's implementation?

-Adam
Answer: Update
Looks like Apple made an IETF draft proposal, and some people are already working on segmenters:
HTTP Live Streaming - draft-pantos-http-live-streaming-01
http://tools.ietf.org/id/draft-pantos-http-live-streaming-01.txt
iPhone HTTP Streaming with FFMpeg and an Open Source Segmenter
http://www.ioncannon.net/programming/452/iphone-http-streaming-with-ffmpeg-and-an-open-source-segmenter/

Ok, looks like the HTTP server acts simply as a dumb HTTP server.  Poking around the example website provided by Akamai gives me enough info to get started with static content streaming.
http://iphone.akamai.com/
The whitepaper ( http://www.akamai.com/dl/akamai/iphone_wp.pdf ) provides information about the transport stream encoding, so the .ts streams are straightforward.

The encoder (or a separate segmenter
process) will produce H.264/AAC
content in a sequence of small content
segments, in MPEG-2 TS format (.ts).
There is also an M3U8 index file that
references the segments; in the case
of live content the M3U8 is
continuously updated to reflect the
latest content.
H.264 Encoding should be single-pass
Baseline Profile, frame re-ordering
disabled. Key frames are suggested
every 5 seconds, ideally an even
divisor of the chosen segment length.

The website provides an M3U8 file, which is simply an M3U playlist, but in the UTF-8 character encoding format.
That file then links to an M3U8 file for each bitrate.  I assume they must all have cuts at the same positions (every 2 or 10 seconds, for instance) so that switching can be seamless.  It appears to be completely client driven - the client decides how to measure bandwidth and which version it's going to get.
The contents of the main file are:
<code>#EXTM3U
#EXT-X-STREAM-INF:PROGRAM-ID=1, BANDWIDTH=860000
hi/prog_index.m3u8
#EXT-X-STREAM-INF:PROGRAM-ID=1, BANDWIDTH=512000
med/prog_index.m3u8
#EXT-X-STREAM-INF:PROGRAM-ID=1, BANDWIDTH=160000
lo/prog_index.m3u8
</code>
Then each of the other files are:
hi/prog_index.m3u8
<code>#EXTM3U
#EXT-X-TARGETDURATION:10
#EXT-X-MEDIA-SEQUENCE:0
#EXTINF:10,
fileSequence0.ts
#EXTINF:10,
fileSequence1.ts
#EXTINF:10,
fileSequence2.ts
#EXTINF:10,
fileSequence3.ts
#EXTINF:1,
fileSequence4.ts
#EXT-X-ENDLIST
</code>
med/prog_index.m3u8
<code>#EXTM3U
#EXT-X-TARGETDURATION:10
#EXT-X-MEDIA-SEQUENCE:0
#EXTINF:10,
fileSequence0.ts
#EXTINF:10,
fileSequence1.ts
#EXTINF:10,
fileSequence2.ts
#EXTINF:10,
fileSequence3.ts
#EXTINF:1,
fileSequence4.ts
#EXT-X-ENDLIST
</code>
lo/prog_index.m3u8
<code>#EXTM3U
#EXT-X-TARGETDURATION:10
#EXT-X-MEDIA-SEQUENCE:0
#EXTINF:10,
fileSequence0.ts
#EXTINF:10,
fileSequence1.ts
#EXTINF:10,
fileSequence2.ts
#EXTINF:10,
fileSequence3.ts
#EXTINF:1,
fileSequence4.ts
#EXT-X-ENDLIST
</code>
This works with the HTML 5 video tag:
<code><video width="640" height="480" >
   <source src="content1/content1.m3u8" />
</video>
</code>
Still a lot of unanswered questions, but this is probably enough to get started.
-Adam
Answer: Akamai describes it as such:

Starting with iPhone OS version 3.0
  and QuickTime X, you can send
  streaming audio and video over HTTP
  from an ordinary web server for
  playback on iPhone, iPod touch, or
  other devices, such as desktop
  computers, without the limitations of
  Progressive Downloads.
The new streaming protocol supports
  Multiple Bitrates and automatically
  switches to the optimal bit-rate based
  on network conditions for a smooth
  quality playback experience. This
  implementation also provides for media
  encryption and user authentication
  over HTTPS, allowing publishers to
  protect their work. Both Live and On
  demand content can be delivered using
  the 3.0 specification.
HTTP Streaming to the iPhone consists
  of three parts: the server component,
  the Akamai network, and the client
  software.
In a typical configuration, a hardware
  encoder takes audio-video input and
  turns it into an MPEG-2 transport
  stream containing H.264 video and AAC
  or HE-AAC audio. The encoded stream is
  then split into a series of short
  media files by a stream segmenter. The
  segmenter also creates and maintains
  an index file containing the list of
  short media files that were created.
  These files are placed on a web
  server.
A media player built into the iPhone
  OS is provided a link to the index
  file, it then requests the media files
  in order and plays them without any
  pauses or gaps between segments

So you apparently need the stream segmenter in order to properly create content.  The HTTP server is generic in this technology.
Comment: What, then, is the format of the index file, and does the stream segmenter do anything other than create new keyframes and split the streams up?  And, further, could this be done dynamically?  I wonder if the protocol supports live streaming then, which would require the index file be updated frequently, and the client to understand that it needs to request the index frequently...
Comment: Akamai's white paper on the subject gives a few more clues: http://www.akamai.com/dl/akamai/iphone_wp.pdf seems to indicate that the splitter provides an M3U8 file, which is a UTF-8 format M3U playlist.  Still no information on the specific format of that file with regards to the bit stream...
Answer: No windows segmenter - iPhone segmenter is not working properly for unknown reasons. You must be registered iPhone developer to be able to download the segmenter
Answer: Svitoch, do you have snow leopard? it comes with apple stream segmenter. just type in man mediastreamsegmenter to see the manual.

HTTP Adaptive Bitrate Streaming


Jmeter how to read file path within csv file

Question: Is it possible to pass in file path or read from another file within csv? My test setup is something like that.
Jmeter Test
Http request -> body data -> "items": "${__property(${items})}",

CSV data config
Id,Name,Items
1,MyName,\input\items_json.txt

I want to include a file in csv items column and in jmeter test, it will read and post items json.
Answer: Got it working with this.
"items": ${__FileToString(${__property(${Items})},,)},

Answer: Not really, being a Configuration Element CSV Date Set Config is initialised before anything else so you will have to consider another approach, i.e.:

__CSVRead() function
__StringFromFile() function
__FileToString() function()

Functions are being evaluated exactly where they're called so this way you can use them for parameterization. See Apache JMeter Functions - An Introduction to learn more about JMeter Functions concept


How can I alter the form to add a new validation handler?

Question: I'm on Drupal 8. I have created a new media bundle (permissions_json) which can be created from /media/add/permissions_json, where administrator user can upload specifically formatted JSON files, and I can upload to it all fine and dandy.
I'd like to validate the file uploaded and rename it. The problem is that I can't find a way to hook into the form. Implementing hook_form_FORM_ID_alter() with gp_mcs_media_permissions_json_add_form_alter() or gp_mcs_form_media_permissions_json_add_form_alter() doesn't have any effect. Even the following implementation didn't have any effect.
function gp_mcs_form_alter(&$form, &$form_state, $form_id) {
  dpm($form);
}

If I put a simple exit() on the module's page stops the website, so the file is accessible. I just can't figure out how to add validation to this add media form.
How can I alter the form to add a new validation handler?
Answer: The form ID for an entity is a string that is usually returned from EntityForm::getFormId(), if the class used for the form doesn't override that method.
This means that, by default, the form ID follows the <entity>_<bundle>_<operation>_form schema, where the <operation> part is omitted, when operation is default.
Since the Media module doesn't have a class that overrides EntityForm::getFormId(), the correct ID for the form that creates a new Media entity whose bundle is permissions_json is media_permissions_json_add. This means that a module whose machine name is gp_mcs can alter that form by implementing hook_form_FORM_ID_alter() with a function named gp_mcs_form_media_permissions_json_add_alter. (Note that the form ID is between form and alter.)


Avoiding duplicate image upload file to Parse.com in Swift

Question: I have created a user profile edit page in the ViewController. When user edit only textfields and hit save button even though the picture is the same it will still upload it again. I want to check if the image is the same, skip the upload of the current image. Also parse uses same image file name so checking by name will not work, I have no idea what else to use. Any ideas?
Here is my code:
    let imageUploadData = UIImageJPEGRepresentation(imageUpload.image!, 1)
        if (imageUploadData != nil) {
                //Here what I tried:
            if (currentImage.image != imageUploadData) {
                print("Image will be uploaded")
                let imageFileObject = PFFile(data: imageUploadData!)
                myUser.setObject(imageFileObject!, forKey: "license_image")
            }else {
                 print("Image is the same, skipping upload")
            }
        }
        myUser.saveInBackgroundWithBlock {(success: Bool, error:NSError?) -> Void in
        self.clearAllNotice()  //Clear activity indicator

        if (error != nil) {
            print("...")
        }
        if (success) {
            print("Saving")
        }

What have I tried, mentioned in comments below
let userImageFile = PFUser.currentUser()?.objectForKey("license_image") as! PFFile
        userImageFile.getDataInBackgroundWithBlock {(imageData: NSData?, error: NSError?) -> Void in
            if (error == nil) {
                let image = UIImage(data:imageData!)
                if image == self.imageUpload.image {
                    print("image is the same")
                }
                else {
                    print("image not the same")
                }
            }
        }

I also tried this:
let userImageFile = PFUser.currentUser()?.objectForKey("license_image") as! PFFile
        userImageFile.getDataInBackgroundWithBlock {(imageData: NSData?, error: NSError?) -> Void in
            if (error == nil) {
                let image = UIImage(data:imageData!)
                let imageFileObject = PFFile(data: imageUploadData!)
                if ((image?.isEqual(imageFileObject)) != nil){
                    print("image is the same")
                }
                else {
                    print("image not the same")
                }
            }
        }

No luck
Answer: Just get the data of the image that they already have saved, and compare it to the data of the image that's about to be saved, and if it's the same the don't allow them to continue or whatever your use case is.
Comment: I fixed the problem for now, I separated the task into different buttons


Why does this integral equal $1$ when $n=1$?

Question: As part of a boundary value problem, I did the following integral:
$b_n = 2\int^1_0 (30 \sin(\pi x) - 100 (1-x)) \sin (n\pi x) dx$
next step:
$b_n = 2\int^1_0 (30 \sin(\pi x)sin (n\pi x) - (100 (1-x)) \sin (n\pi x) dx$
we can break this up
$ = 60\int^1_0 \sin(\pi x)sin (n\pi x) - 200\int^1_0((1-x)) \sin (n\pi x) dx$
and integrating the two parts, the first half via the product-to-sum identity
$ = 60\int^1_0 \frac{1}{2}[\cos(\pi x- n\pi x) - \cos(\pi x+ n\pi x)]dx -  200\int^1_0((1-x)) \sin (n\pi x) dx$
using inegration by parts on the second half, with $u= 1-x$ and $du = -dx$, $dv = \sin (n\pi x) dx$ and $v = \frac{\cos (n\pi x)}{n \pi}$
$ = 60\int^1_0 \frac{1}{2}[\cos(\pi x- n\pi x) - \cos(\pi x+ n\pi x)]dx -  200[(1-x)(\frac{\cos (n\pi x)}{n \pi})+\int^1_0\frac{\cos (n\pi x)}{n \pi}dx]$
$$ = \left[ 60 \frac{1}{2}[\frac{\sin(\pi x- n\pi x)}{\pi - n\pi } - \frac{\sin(\pi x+ n\pi x)}{\pi + n\pi}] -  200[(1-x)(\frac{\cos (n\pi x)}{n \pi})+\frac{\sin (n\pi x)}{(n \pi)^2}]\right]^1_0$$
And when I do the algebra I get:
$$= 30 [\frac{\sin(\pi - n\pi )}{\pi - n\pi } - \frac{\sin(\pi + n\pi )}{\pi + n\pi}] -  200\left(\frac{\sin (n\pi )}{(n \pi)^2}\right)  +  200(\frac{1}{n \pi})$$
Here's what I don't get. If n= 1 the part multiplied by 30 goes to 0/0. Does that mean I can count it as 1? That's what the text notes, that it is 0 if $n \neq 1$ and 1 if $n=1$, but I just wanted to be sure I understood this and did the whole integration correctly.
thanks
Comment: "If n= 1 the part multiplied by 30 goes to 0/0. Does that mean I can count it as 1?" You certainly can't, whatever your text says! You have to treat n=1 as a special case, and perform the calculation step by step.
Comment: ok, so what is that special case? That is, should i plug in n=1 earlier on (like before I do the integration, when it is still a cosine term) and go from there? Problem is, I still end up with a zero in the denominator...
Comment: Oh wait,, the $\cos(\pi x - \pi x)$ (when n=1) is a 1, and that means it's just x in the integration which is 1... I got it...
Comment: Exactly!${}{}{}$
Answer: You can justify the step if you consider the parameter-dependent integral
$$I(\alpha) = \int_0^1 \cos (\alpha\pi x)\,dx.$$
For $\alpha \neq 0$, you have
$$\begin{align}
I(\alpha) &= \frac{\sin (\alpha\pi x)}{\alpha\pi}\bigl\lvert_0^1\\
&= \frac{\sin (\alpha\pi)}{\alpha\pi}.
\end{align}$$
The integrand is continuous and depends continuously on $\alpha$, hence $I(\alpha)$ depends continuously on $\alpha$, and
$$I(0) = \lim_{\alpha\to 0} I(\alpha) = \lim_{\alpha\to 0} \frac{\sin (\alpha\pi)}{\alpha\pi} = 1.$$
But you need to let $\alpha$ assume non-integer values for that. It's at least as easy to just plug in $0$ and compute $\int_0^1 1\,dx$.


Textarea and Textbox in asp.net

Question: We are able to provide a connection to a textbox using ADO.net to the database...but if we are willing to specify a particular region for our text then we are unable to use textarea in this case as far as sql connection through sql server is concerned.We are bound to use multiline textbox for this situation.Why textarea doesn't support connectin with the database?
Can anybody help me out???
Answer: Put a multi-line textbox on your asp.net form and view the form in a browser. Right click on your form in the browser and select "View Source" (or your favorite browser's equivalent).  Examine the source to find your multi-tline textbox, and you'll discover that it already is a textarea.
Furthermore, as far as your browser is concerned there is no such thing as a textbox.  It's really just an <input > element who type attribute is set to "text".

Textarea and Textbox in asp.net


An AJAX HTTP error ocurred. HTTP Result Code: 500 (while trying to rebuild content access perms)

Question: I have installed a module that ask me everytime to rebuild content Access Permissions, but every time I try to do it, it shows me an error I do not have idea why is it happening. Please help
<code>An AJAX HTTP error ocurred. HTTP Result Code:  500 Debugging information follows: Path: /batch?id=172&op=do Status Text: Service unavailable (with message)
Response Text:
</code>
Please check the image for more details
Comment: Could you mention which module did you installed? How much content (nodes) do you have on your site?
Comment: I installed the sub-groups for organic groups module https://www.drupal.org/project/og_subgroups and I do not have much nodes like 100 nodes
Answer: The problem with this was the server, the server was refusing the ajax request, maybe a php memory problem I have migrated my drupal website to a VPW
Comment: I am facing same problem, i restarted the apache and mysql but still getting the ajax 500 error in my complete site where we are using ajax
Comment: Try another hosting


How are percentages determined in volleyball?

Question: How is it determined that a reception or an attack is "perfect" in volleyball? For an attack it is fairly clear it the attack directly scores a point, but there isn't such a clear criterion for receiving.
Answer: First of all, there are no definite "rules" for determining the quality of attack or reception. Scouts use certain programs (like this) to collect information about how well players performed in a match but the assessment scheme employed may be different from program to program.
Concerning the attack, yes, scoring is obviously optimal, be it by directly touching the opponent's ground (with the ball, of course), using the block, etc.
With the reception it's somewhat harder as there is no definite "scale" to measure its quality. Teams with an extremely fast-paced play might prefer flat receptions, for example. Anyway, I consider a perfect reception a reception which enables the setter to "do everything" with the ball, that is, play every kind of combination1 with every pace (possibly including an attack by the setter himself/herself). You could use a scale where
<code>0 = disaster; reception directly results in an error
1 = at least playable; some other player except the setter can set the ball
2 = fast play confined; the setter can set the ball but e.g. a fast ball to the middleblocker is hard/impossible
3 = perfect; the setter can play every pace to every player
</code>
Here you can find the FIVB statistics from the World Championship 2014. Maybe this gives you a better idea of the assessment of receptions.

1  Alright, you might argue that someone like Luciano de Cecco could play everything from even the base line but we can ignore that, I think.


C separar string com vírgulas em vetores

Question: Quero separar cada linha de um arquivo em 2 vetores: v[i].date and v[i].value.
Porém, quando rodo o código nenhum valor que imprimo está correto, e os outputs sao valores aleatórios.
Há algo que eu deveria mudar?

Input
  02/20/18,11403.7
  02/19/18,11225.3
  02/18/18,10551.8
  02/17/18,11112.7
  02/16/18,10233.9

<code>#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>

typedef struct
{
    char *date;
    long int *value;
}vetor;

int main(int argc,char **argv)
{
    FILE *btc;

    if((btc=fopen("BTC.csv", "r")) == NULL  )
    {
        printf("not found btc\n");
        exit(-1);
    }

    long int a=0;

    char linha[256];
    char *token = NULL;

    while (fgets(linha, sizeof(linha), btc) != 0)
    {
            a++;
    }

    vetor *v;

    v=(vetor*)malloc(a*sizeof(vetor));

    char linha2[256];

    while (fgets(linha2, sizeof(linha2), btc) != 0)
    {
        for(int i=0;i<a;i++)
        {
            fscanf(btc,"%[^,]s",v[i].date);
            fscanf(btc,"%d[^,]",&v[i].value);
            fseek(btc, +1, SEEK_CUR);
        }
    }

    fclose(btc);
    return 0;
}
</code>
Comment: Não seria equivalente a [esta pergunta](https://stackoverflow.com/questions/12911299/read-csv-file-in-c)?
Comment: Também... note que você esta lendo o arquivo 2x. Na segunda passada você deve voltar ao inicio do arquivo.. tente utilizar a função `rewind(btc)` para voltar o arquivo ao estado inicial antes do segundo while.
Comment: Amigo, fiz uma pergunta similar ontem, e obtive uma boa resposta, que pode lhe ajudar nisso ai também, já que são apenas duas colunas. [Parsing colunas de números de um arquivo CSV em C](https://pt.stackoverflow.com/questions/284913/parsing-colunas-de-n%C3%BAmeros-de-um-arquivo-csv-em-c/284917#284917)
Answer: Em sua estrutura vetor você define dois ponteiros: um ponteiro para char (date) e outro ponteiro para long int (value).
Para efetivamente armazenar os valores lidos você precisa alocar o espaço necessário e fazer com que cada um destes ponteiros aponte para o espaço de memória respectivo.


How do I combine two arrays in PHP based on a common key?

Question: I'm trying to join two associative arrays together based on an entry_id key. Both arrays come from individual database resources, the first stores entry titles, the second stores entry authors, the key=>value pairs are as follows:
array (
    'entry_id' => 1,
    'title' => 'Test Entry'
)

array (
    'entry_id' => 1,
    'author_id' => 2

I'm trying to achieve an array structure like:
array (
    'entry_id' => 1,
    'author_id' => 2,
    'title' => 'Test Entry'
)

Currently, I've solved the problem by looping through each array and formatting the array the way I want, but I think this is a bit of a memory hog.
$entriesArray = array();
foreach ($entryNames as $names) {
    foreach ($entryAuthors as $authors) {
        if ($names['entry_id'] === $authors['entry_id']) {
            $entriesArray[] = array(
                'id' => $names['entry_id'],
                'title' => $names['title'],
                'author_id' => $authors['author_id']
            );
        }
    }
}

I'd like to know is there an easier, less memory intensive method of doing this?
Comment: If the solution is a sql one, shouldn't this page be tagged differently and have some db table details?
Answer: Is it possible you can do a JOIN in the SQL used to retrieve the information from the database rather than fetching the data in multiple queries? It would be much faster and neater to do it at the database level.
Depending on your database structure you may want to use something similar to
SELECT entry_id, title, author_id
FROM exp_weblog_data
INNER JOIN exp_weblog_titles
ON exp_weblog_data.entry_id = exp_weblog_titles.entry_id
WHERE field_id_53 = "%s" AND WHERE entry_id IN ("%s")

Wikipedia has a bit on each type of join
Otherwise the best option may be to restructure the first array so that it is a map of the entry_id to the title
So:
array(
    array(
       'entry_id' => 1,
       'title' => 'Test Entry 1',
    ),
    array(
       'entry_id' => 3,
       'title' => 'Test Entry 2',
    ),
)

Would become:
array(
    1 => 'Test Entry 1',
    3 => 'Test Entry 2',
)

Which would mean the code required to merge the arrays is simplified to this:
$entriesArray = array();
foreach ($entryAuthors as $authors) {
    $entriesArray[] = array(
        'id' => $authors['entry_id'],
        'title' => $entryNames[$authors['entry_id']],
        'author_id' => $authors['author_id']
    );
}

Comment: -1 How much are you sure that `It would be much faster and neater to do it at the database level.` Don't you think connecting to database, join two tables or more and returning the result would be much slower. I strongly recommend you reading 'MySQL High Performance' book to get grasp of database and indexing. Joining two tables at application level is faster beside that there would much more chance that MySQL fetch the result faster, because each query will be fetched by its PRIMARY KEY that is fast. It would much more ideal if you want to cache it on the web application.
Comment: Its an expression engine website, so I'm not entirely sure, my SQL queries are:

    SELECT entry_id, field_id_5 AS title_ie FROM exp_weblog_data WHERE field_id_53 = "%s"

and:

    SELECT entry_id, title, author_id FROM exp_weblog_titles WHERE entry_id IN ("%s")

There is a distinct WHERE clauses in each query and my SQL knowledge is limited, can I combine both queries into one?
Answer: I've rearranged some of my code to allow for a single SQL query, which looks like:
$sql = sprintf('SELECT DISTINCT wd.field_id_5, wd.entry_id, mb.email, mb.screen_name
            FROM `exp_weblog_data` wd
            INNER JOIN `exp_weblog_titles` wt
            ON wt.entry_id=wd.entry_id
            INNER JOIN `exp_members` mb
            ON mb.member_id=wt.author_id
            WHERE mb.member_id IN ("%s")
            AND wd.entry_id IN ("%s")',
            join('","', array_unique($authors)),
            join('","', array_unique($ids))
);

This solves my problem quite nicely, even though I'm making another SQL call. Thanks for trying.
Answer: In response to your comment on Yacoby's post, will this SQL not give the output you are after?
SELECT exp_weblog_data.entry_id, exp_weblog_data.field_id_5 AS title_ie, exp_weblog_titles.author_id
FROM exp_weblog_data LEFT JOIN exp_weblog_titles
ON exp_weblog_data.entry_id = exp_weblog_titles.entry_id
WHERE exp_weblog_data.field_id_53 = "%S"

Every entry in exp_weblog_data where field_id_53 = "%S" will be joined with any matching authors in exp_weblog_titles, if a an entry has more than one author, two or more rows will be returned.
Answer: see http://php.net/manual/en/function.array-merge.php
Comment: If you read the question it becomes clear that that isn't what is wanted. I think the example arrays shown are single elements of a larger array.
Comment: array_merge will only append the second array to the first, I want to join them by `entry_id` which is a unique key in both arrays


Starlike region in $\mathbb R^n$ is contractible.

Question: Let $X \subset \mathbb R^n$ be starlike. Thus we got a $x_0 \in X$ s.t. for every $x \in X$ there is a line connecting $x$ and $x_0$. Denote that line as $\gamma_x:I \to X : t \mapsto (1-t)x + tx_0$. I want to show that $X$ is contractible. This is true, if $1_X$ (identity on $X$) is homotopic to a constant function $f$ which we choose as $f:X \to X : x \mapsto x_0$. Letting $h:X \times I \to X : (x,t) \mapsto \gamma_x(t)$, we see that $h$ is a homotpoy between $1_X$ and $f$, IF $h$ is continuous.
My question: Why is $h$ continuous ? I don't think that this trivially follows from the fact that all $\gamma_x$ are continuous.
Answer:
I don't think that this trivially follows from the fact that all $\gamma_x$ are continuous.

That's right, it doesn't follow from that (one needs to use the shape of the $\gamma_x$ to deduce continuity).
But, we have a continuous
$$H \colon \mathbb{R}^n\times I \to \mathbb{R}^n;\quad H(x,t) = (1-t) x + t x_0.$$
Hence the restriction of $H$ to $X\times I$ is continuous. And since $X$ is star-shaped, the image of that restriction is contained in $X$, and thus the continuity of $h$ follows.
$$
\begin{matrix}
X\times I & \overset{\iota\times \operatorname{id}}{\hookrightarrow} & \mathbb{R}^n\times I\\
\downarrow h & & \downarrow H\\
X & \overset{\iota}{\hookrightarrow} & \mathbb{R}^n
\end{matrix}
$$
By definition of the subspace topology, $h$ is continuous if and only if $\iota\circ h$ is continuous. But $\iota\circ h = H\circ (\iota \times \operatorname{id})$, and the latter is continuous.
Answer: The mapping $h$ is a polynomial on $X \times I \subset \mathbb{R}^{n+1}$.


Let "Availability Calendars" start on monday

Question: I created this website http://peace-in-the-city.be/en/book-now and on that page you will see I used a Calendar to show the availability of the apartment. ( http://drupal.org/project/availability_calendars )
I tried to let the calendar start on Monday. I googled for the solutions and did change my regional settings local to start of the week to Monday. It worked after that for a couple days. But for some reasons it went back to Saturday. Changing the regional setting has no effect anymore now.
At this point, I'm clueless... Any tips, links and ofcourse working solutions are welcome.
PS. I did not change anything in the rAvailability Calenda module. I'm just install modules - enable/disable - or change configuration.
Comment: I think if you will go to `Configuration > Regional` and re-select Monday and save it will be all right.
Comment: Thanks for the quick answer NishantP. But i tried that already and nothing is changing. It changed it the beginning, but the next day it was back to Saturday. Changing it now to any day does nothing anymore :-(
Comment: Are you using https://www.drupal.org/project/availability_calendars or https://www.drupal.org/project/calendar? Please link appropriate module and be consistent about name you use in title and body of your question, to avoid confusion.
Answer: As a best practice whenever an issue like this arises - disable the module, uninstall, flush all cache, verify settings for regional locale is set to start on Monday.
Now re-enable the module. Flush all cache. Re-configure. And see if things are working as expected.
As an added additional option if you care to contribute to the community, on a fresh install of Drupal, attempt to recreate the issue that "potentially" caused this issue to arise by re-tracing any steps you may have taken (other contributed modules, other seemingly unrelated changes, etc.). If you're able to trace what caused the issue, then perhaps the potential bug can be fixed.
Of course, regardless if the uninstall, reinstall works and functionality doesn't again fail after a few days then you have solved your issue! This should be a fairly typical go-to strategy of troubleshooting for any module issue.
Comment: (Did this fix the problem? If so let's get this marked so people know it works.)


How to use "ErrorMessageResourceType" in DataAnnotations in Windows Store (Metro) app

Question: In my Windows Store (Metro) app I am using DataAnnotations for my objects. Everything works fine.
Now I try to place my strings into Resource.resw files.
The DataAnnotations need 2 properties to be filled: ErrorMessageResourceName and ErrorMessageResourceType. How do I use ErrorMessageResourceType with the new resource types?
public class Person : Entity
{
    private string _firstName;

    [Required( ErrorMessageResourceName = "GenericFieldRequired", ErrorMessageResourceType = typeof( ??? ))]
    public string FirstName {
        get { return _firstName; }
        set { SetPropertyChanged( ref _firstName, value, this ); }
    }
}

Any suggestions?
UPDATE:
I found a Visual Studio tool which automatically generates the Resources.cs file:
Resw Generator
Answer: After a lot of digging I think I understand why you are having issues.
In other project types the Resource file is automatically converted into a class with static methods called the name of the resource key.
There isn't a way really to do this automatically so I wrote a T4 Template that can help you out with this.
<#@ template debug="false" hostspecific="True" language="C#" #>
<#@ assembly name="System.Core" #>
<#@ import namespace="System.Linq" #>
<#@ import namespace="System.Text" #>
<#@ import namespace="System.Xml" #>
<#@ assembly name="System.Xml" #>
<#@ import namespace="System.IO" #>
<#@ import namespace="System.Collections.Generic" #>
<#@ output extension=".cs" #>
using Windows.ApplicationModel.Resources;
<#
  var namespaceName = System.Runtime.Remoting.Messaging.CallContext.LogicalGetData("NamespaceHint");
#>
namespace <#= namespaceName #>
{
    public class ResourceHelper
    {
        private static readonly ResourceLoader resourceLoader = new ResourceLoader("Resources");
<# using (XmlReader reader = XmlReader.Create(Host.ResolvePath("Resources.resw")))
        {
             bool found=reader.ReadToFollowing("data");
             while(found)
             {
                reader.MoveToFirstAttribute();
                string name = reader.Value;

#>
            public static string <#= name #>
            {
                get
                {
                    return resourceLoader.GetString("<#= name #>");
                }
            }
<#
                found=reader.ReadToFollowing("data");
            }
        }#>

    }
}

If you place the template in the same folder as your resource file it will output a file called ResourceHelper.cs. This can then be used in your object model:-
 [Required(ErrorMessageResourceName = "validation_string", ErrorMessageResourceType = typeof(ResourceHelper))]

Note there are a few limitations. Firstly, I'm not very good at T4 templates, so the code can probably be vastly improved. For now you must ensure the name you give your resource will result in a valid method name - don't put spaces in there!
Secondly the template won't automatically generate when you add a new key/value in your resource file, you must go into the template and hit save.
Apart from that it should work fine - hope it helps!
Comment: This is a nice approach for the problem. Thank you very much. I din't think of that. There are some minor problems, but I can work them out myself. Will look into the T4 syntax a bit deeper now.


Mascara em campo input

Question: Olá
Eu tenho um input onde eu insiro um valor em moeda R$1.000,00, eu quero que o campo tenha uma mascara para ajudar o usuário no preenchimento, mas eu quero que o javascript não pegue o valor com a mascara, mas sem a mascara, seja exibido no console o valor assim: 100000.
Obrigado
Answer: Exemplo simples usando JavaScript

String.prototype.reverse = function(){
  return this.split('').reverse().join('');
};

function mascaraMoeda(campo,evento){
  var tecla = (!evento) ? window.event.keyCode : evento.which;
  var valor  =  campo.value.replace(/[^\d]+/gi,'').reverse();
  var resultado  = "";
  var mascara = "##.###.###,##".reverse();
  for (var x=0, y=0; x<mascara.length && y<valor.length;) {
    if (mascara.charAt(x) != '#') {
      resultado += mascara.charAt(x);
      x++;
    } else {
      resultado += valor.charAt(y);
      y++;
      x++;
    }
  }
  campo.value = resultado.reverse();
}

Exemplo de mascara para Moeda em JavaScript

<input type="Text" size="12" onKeyUp="mascaraMoeda(this, event)"  value="">
Answer: Aconselho o uso da biblioteca https://igorescobar.github.io/jQuery-Mask-Plugin/
exemplo abaixo de sua utilização

$(document).ready(function(){
   $('.money').mask('000.000.000.000.000,00', {reverse: true});

  $(".money").change(function(){
    $("#value").html($(this).val().replace(/\D/g,''))
  })

});

<input class="money" id="input" type="text">

Comment: Perfeito, Obrigado

Mascara em campo input


Using Font Awesome with jQuery SVG

Question: With a little help from this question, I was able to show font awesome icons in static SVG.  But our app uses jQuery SVG, and it doesn't seem to be allowing SVG escape characters.  Here's a demo showing both running side by side:
http://jsfiddle.net/scruffles/m6Z7Y/4/
<text x="30" y="30">&#xf040</text>

Renders as a pencil, but
svg.text(g, 30, 30, '&#xf040');

renders as &#xf040
Comment: Just as a tip, you should not use jQuery SVG wiht jQuery versions 1.8 or higher. It has some conflicts with those versions. For example .width() and .height() return strings ("30px") instead of numbers. I ended up just using plain jQuery and to dynamically create elements use: $(document.createElementNS('http://www.w3.org/2000/svg', "rect")); instead of $("")
Comment: possible duplicate of [SVG text element with Unicode characters](http://stackoverflow.com/questions/5830991/svg-text-element-with-unicode-characters)
Answer: As per this answer, you should use svg.text(g, 30, 30, '\uf040'); instead.
http://jsfiddle.net/mblase75/m6Z7Y/6/
Comment: @TusharGupta It's nearly identical to the original ``.
Comment: how did you find this `\uf040'` ?
Answer: In JavaScript, instead of using the entity, you can either use raw Unicode in your JavaScript source (copy/paste the character), or use a Unicode escape sequence in your plain ASCII JavaScript code:
svg.text(g, 30, 60, '');       // A unicode f040 character
svg.text(g, 30, 30, '\uf040');

Demo: http://jsfiddle.net/m6Z7Y/7/

Also, note that XML entities begin with an ampersand and end with a semicolon—&…;—so you need a semicolon at the end for valid XML markup:
<text x="30" y="30"></text>

Answer: I generated an object with the Font Awesome names and aliases as keys and unicode characters as values. That way you can make things more readable like this:
svg.text(g, 30, 60, FONT_AWESOME.pencil);

Here is the full list: https://github.com/the-grid/the-graph/blob/master/the-graph/font-awesome-unicode-map.js

Using Font Awesome with jQuery SVG


How can I filter my fetched data and load into tableview?

Question: I am using Firebase database. I fetched the data and want to filter and display only the information that matches the users selection.
I have used a conditional statement to look for the matched value and append the list, however, I cannot get the table to load. When I print the variable, it prints 0. Need help thanks.
<code>   override func viewDidLoad() {
    super.viewDidLoad()

    projectlbl.text = "Brand: \((repair?.brand)!) Model: \((repair?.modelNumber)!)"

    refResources = Database.database().reference().child("resources");

    let selectedProject = "\((repair?.modelNumber)!)"

    //observing the data changes
    refResources!.observe(DataEventType.value, with: { (snapshot) in
        //if the reference have some values
        if snapshot.childrenCount > 0 {

            //clearing the list
            self.resourceList.removeAll()

            //iterating through all the values
            for resources in snapshot.children.allObjects as! [DataSnapshot] {
                //getting values
                let resourceObject = resources.value as? [String: AnyObject]
                let id  = resourceObject?["id"]
                let RSSSubCat  = resourceObject?["RSSSubCat"]
                let RSSBrand = resourceObject?["RSSBrand"]
                let RSSModelNumber = resourceObject?["RSSModelNumber"]
                let RSSTitle = resourceObject?["RSSTitle"]
                let RSSUrl = resourceObject?["RSSUrl"]

                //creating resource object with model and fetched values
                let resource = resourceModel(id: id as! String?, RSSSubCat: RSSSubCat as! String?, RSSBrand: RSSBrand as! String?, RSSModelNumber: RSSModelNumber as! String?, RSSTitle: RSSTitle as! String?, RSSUrl: RSSUrl as! String?)

                //appending it to list
                print(snapshot.childrenCount)

                if selectedProject == resource.RSSModelNumber {
                    print(selectedProject)
                    self.resourceList.append(resource)
                    self.diagResTable.reloadData()
                } else {
                    return
                }

            }

            //reloading the tableview
            self.diagResTable.reloadData()
        }
    })
</code>
Comment: Your mistake is that If the first item of `resources` doesn't match the condition it exits the function with `return`. Rather than fetching all objects and filter them use a predicate to fetch only objects which match the predicate.
Comment: let selectedModelNumber = (self.refResources?.child("RSSModelNumber").queryEqual(toValue: selectedProject))

I am trying to implement this predicate but I am not sure how. I have been combing over firebase docs and I still confused.
Comment: I'm not familiar with Firebase but **every** serious database provides fetching data filtered by a predicate.
Comment: I got it thank you for your input!
Answer: Needed to change the listener... Simple yet overlooked.
<code>       let selectedModelNumber = (self.refResources?.queryOrdered(byChild: "RSSModelNumber").queryEqual(toValue: selectedProject))

    //observing the data changes
    selectedModelNumber!.observe(DataEventType.value, with: { (snapshot) in
</code>


Contador em um valor de um dicionário

Question: Sou iniciante em programação e estou fazendo um exercício no qual eu preciso contar os votos de determinados números de acordo com o número da camisa do jogador. Por exemplo, se eu digitar no programa 23, 3 vezes, o número 23 terá 3 votos. Gostaria de saber se há algum modo de ir acrescentando o número de votos no valor da chave.
while numero_camisa != 0:
numero_camisa = int(input('Informe o número da camisa do jogador ou zero para sair: '))
if numero_camisa < 0 or numero_camisa > 23:
    print('Número da camisa inválido, favor informar um número entre 1 e 23.')
votos_atletas[numero_camisa] = #acrescentar o número de votos conforme o número da camisa.

Meu código até aqui, ficou assim. Agora fica a dúvida, existe um modo de acrescentar o número de votos de acordo com o que o usuário for informando ?
Comment: Esse exercício se encontra no site https://wiki.python.org.br/ExerciciosListas, exercício nº 18.
Answer: Você precisa acessar o valor atual do dicionário para o valor de numero_camisae aumentar esse valor em 1.
Antes de ver a resposta, tente fazer você mesmo desta forma. Como você abre o valor atual de votos do jogador numero_camisa? Como você faz para atribuir valor a uma variável?

votos_atletas[numero_camisa] = votos_atletas[numero_camisa] + 1

Comment: Muito obrigado, tinha me esquecido, tentei atribuir o valor de todas as formas, mas esqueci de atribuir a chave do valor, muito obrigado!
Comment: De nada. Aceita a resposta se funcionou.
Answer: O Python possui, além da estrutura de dicionários que pode ser utilizada, uma estrutura nativa na biblioteca collections para a solução deste problema: Counter. Basta você armazenar todos os votos em uma lista:
from collections import Counter

votos = []

while True:
    numero_camisa = int(input('Número da camisa: '))
    if numero_camisa == 0:
        break
    elif 0 < numero_camisa < 23:
        votos.append(numero_camisa)
    else:
        print('Número inválido')

votacao = Counter(votos)

print(votacao)

Veja funcionando no Repl.it
Se a entrada fosse, por exemplo, [1, 2, 2, 3, 2, 4], a saída seria:
Counter({2: 3, 1: 1, 3: 1, 4: 1})

Comment: Não sabia dessa, vai me ajudar bastante nos estudos, obrigado por compartilhar.

Contador em um valor de um dicionário


Structure Constants for $ 2 $ by $ 2 $ Matrices

Question: The space of $2 \times 2$ matrices is $4$-dimensional. For a generic choice of $3$ matrices $X$, $Y$, and $Z$, we can take a basis to be $\{\mathrm{Id}_2, X, Y, Z\}$. The following fact seems, experimentally, to be true:
Expand the three products $YX$, $ZY$, and $XZ$ in this basis:
$$ \begin {align*}
YX &= a_{yx} \mathrm{Id} + b_{yx}X + c_{yx}Y + d_{yx}Z \\[1.2ex]
ZY &= a_{zy} \mathrm{Id} + b_{zy}X + c_{zy}Y + d_{zy}Z \\[1.2ex]
XZ &= a_{xz} \mathrm{Id} + b_{xz}X + c_{xz}Y + d_{xz}Z
\end {align*}
$$
Then it seems that we always have the following relations among these structure constants:
$$ b_{yx} = d_{zy}, ~~ c_{yx} = d_{xz}, ~~ c_{zy} = b_{xz} $$
I do not see why this is true. Does anyone know a proof or explanation?
Comment: First, the choice can't be that generic because the matrices must still be linearly independent (just like vectors in $\mathbb{R}^4$) to form a basis. For example, $c_{yx} = d_{xz}$ breaks if you take $Y$ as the zero matrix and $X$ and $Z$ non-zero such that $XZ$ is non-zero.
Comment: Yes, by "generic" I don't mean "arbitrary". I mean that they are taken from an open dense subset of the set of triples (the set of linearly independent triples).
Answer: Being a linear space, those matrices cannot be that generic. Indeed, it must be
$0=aId+bX+cY+dZ\Rightarrow\,a=b=c=d=0$, i.e, linearly independent. Let's then assume that's the case.
The Jacobi identity
$$[x,[y,z]]+[y,[z,x]]+[z,[x,y]]=0\\
[x,\{yz-zy\}]+[y,\{zx-xz\}]+[z,\{xy-yx\}]=0\\
[x,yz]+[y,zx]+[z,xy]\,=\,[x,zy]+[y,xz]+[z,yx]
$$
From the LHS
$$xyz-yzx+yzx-zxy+zxy-xyz=0$$
and from the RHS, using those three relations of yours
$$[x,zy]=c_{zy}[x,y]+d_{zy}[x,z]\\
[y,xz]=b_{xz}[y,x]+d_{xz}[y,z]\\
[z,yx]=b_{yx}[z,x]+c_{yx}[z,y]
$$
which adding together and grouping leads to
$$0=(c_{zy}-b_{xz})[x,y]+(d_{zy}-b_{yx})[x,z]+(d_{xz}-c_{yx})[y,z]$$
As those 3 commutators have to be linearly independent, it follows the identities you were looking for.
PS: One example of such three base matrices is that of the Pauli matrices. The commutator subspace $\langle[A,B]\rangle$ is clearly $3-dimensional$ (because of the commutation relations of the pauli matrices).
Hence, the same must be true when using the basis elements $x,y,z$ for which
$$[A,B]=a[x,y]+b[z,x]+c[y,z]$$
Comment: Because they span the commutator subspace of $[A,B]$...I admit this needs to be detailed. I assumed it'd be trivial as that's the case for the Pauli matrices...
Comment: Looks neat, but why do the three commutators have to be linearly independent? E.g. if $x$ and $y$ commute, how do you know that $c_{zy}-b_{xz}=0$?
Comment: Thanks! This is a nice argument.


Prove or give Counterexample: Is this a Basis.

Question: Prove or give a counterexample: If $v_1, v_2, v_3, v_4$ is a basis of $V$ and $U$ is a subspace of $V$ such that $v_1,v_2 \in U$ and $v_3, v_4 \notin U$, then $v_1, v_2$ is a basis of $U$.
My guess would be that it's true since we have a list of 4 vectors in $V$ and $U$ is a subspace in $V$ and $v_1, v_2$ should be linearly independent. Not sure how to prove that it is a basis.
Comment: Your guess is wrong: $U$ could be three dimensional.
Answer: Consider $V = \Bbb R^4$ and take the standard basis i.e $v_i=e_i$ for $V$. Let $U$ be the subspace of $V$ with basis $\{(1,0,0,0),(0,1,0,0),(0,0,1,1)\}$. So clearly $v_3, v_4 \notin U$ but $U$ is not 2 dimensional.
Answer: $V:=\mathbb{F}^4$.
$U:=\{(x,y,z,0)|x,y,z\in\mathbb{F}\}$.
$U$ is a subspace of $V$.
$v_1:=(1,0,0,0)$.
$v_2:=(0,1,0,0)$.
$v_3:=(0,0,1,1)$.
$v_4:=(0,0,0,1)$.
$v_1,v_2\in U$.
$v_3,v_4\notin U$
$v_1,v_2,v_3,v_4$ is a basis of $V$.


Efeito em jQuery não funciona com datepicker

Question: Galera montei um input com um efeito, que ocorre ao inserir um valor no input, o problema e que o mesmo efeito não funciona usando o data picker no input. Ou seja quando coloca uma data o efeito não ocorre, ficando texto em cima da data.
Alguém sabe como resolver isso?

$('.data').datepicker({
  'autoclose': true
});
$('.form_campos').on('focus blur', function(e) {
  $(this).parents('.form-group').toggleClass('focused', (e.type === 'focus' || this.value.length > 0));
}).trigger('blur');
.form-group {
  margin-top: 20px;
  position: relative;
  display: flex;
  height: 45px;
  float: left;
}
.control-label {
  opacity: 0.4;
  pointer-events: none;
  position: absolute;
  transform: translate3d(5px, 22px, 0) scale(1);
  transform-origin: left top;
  transition: 240ms;
  z-index: 2;
}
.form-group.focused .control-label,
.form-group-select.focused .control-label {
  opacity: 1;
  transform: scale(0.75);
}
.form_campos {
  height: 31px;
  width: 100%;
  color: #484848;
  z-index: 1;
  align-self: flex-end;
  padding: 5px;
  outline: none;
  border: 0 solid #484848;
  border-bottom-width: 1px;
  background: transparent;
}
.form_campos:hover,
.form_campos:focus {
  border-color: #0091FF;
}
.form_disabled,
.form_disabled:hover,
.form_disabled:focus {
  border-color: #D7D7D7;
}

  DATA
  <input type='text' class='efeito_input efeito_input form_campos data' id='inputNormal' name='validade'>

Comment: Vê a minha resposta.
Answer: Isso acontece porque perdes o focus no input, uma das soluções pode ser de fazer um focus:
$('.data').datepicker({
  'autoclose': true,
}).on('hide', function(e) {
    $(this).parents('.form-group').toggleClass('focused', (e.type === 'focus' || this.value.length > 0));
});

Aqui a funcionar, mas faz ali uma ligeira impressão. Vê se serve.

$('.data').datepicker({
  'autoclose': true,
}).on('hide', function(e) {
    $(this).parents('.form-group').toggleClass('focused', (e.type === 'focus' || this.value.length > 0));
});

$('.form_campos').on('focus blur', function(e) {
  $(this).parents('.form-group').toggleClass('focused', (e.type === 'focus' || this.value.length > 0));
}).trigger('blur');
.form-group {
  margin-top: 20px;
  position: relative;
  display: flex;
  height: 45px;
  float: left;
}
.control-label {
  opacity: 0.4;
  pointer-events: none;
  position: absolute;
  transform: translate3d(5px, 22px, 0) scale(1);
  transform-origin: left top;
  transition: 240ms;
  z-index: 2;
}
.form-group.focused .control-label,
.form-group-select.focused .control-label {
  opacity: 1;
  transform: scale(0.75);
}
.form_campos {
  height: 31px;
  width: 100%;
  color: #484848;
  z-index: 1;
  align-self: flex-end;
  padding: 5px;
  outline: none;
  border: 0 solid #484848;
  border-bottom-width: 1px;
  background: transparent;
}
.form_campos:hover,
.form_campos:focus {
  border-color: #0091FF;
}
.form_disabled,
.form_disabled:hover,
.form_disabled:focus {
  border-color: #D7D7D7;
}

  DATA
  <input type='text' class='efeito_input efeito_input form_campos data' id='inputNormal' name='validade'>

Comment: Ok funcionou 100% aqui. Obrigado


Buscar elemento CLASS com value em espaço

Question: Estou fazendo uma automação com Selenium C# e o única referencia padrão da tag é uma class referenciada por outras classes:

Já tentei:
.FindElement(By.ClassName("slds-form-element slds-form-element_readonly"))

Porém me retorna um erro dizendo que não é possivel localizar class com espaços
Answer: Use da seguinte forma:
findElement(By.xpath("//div[@class='slds-form-element slds-form-element_readonly']"));

Ou:
findElement(By.cssSelector("div[class='slds-form-element slds-form-element_readonly']"));


F barre chord on an SG guitar

Question: I began learning guitar on an SG style guitar. Based on the thigh position when seated, or the strap position when standing, I noticed that the neck of the guitar is slightly shifted toward the fretting hand compared to other popular designs. I understand that this is why the SG design is notorious for "neck dive". I found this design made learning open chords quite difficult due to my wrist extension and contortion at the first 3 frets. In particular, learning the F barre was exceptionally hard on this guitar design.
I'm wondering if this was just a personal negative experience or is it widely appreciated that the SG guitar design can be more physically demanding when learning open and barre chords? Worded another way, is the SG a bad design for a complete beginner?

Edit for context
I'm not trying to identify the "best guitar design" for a beginner. Rather, I'm curious. Many have commented on the general complexity of executing a perfect F barre, but I'd like to note that, with the SG design, I also found it hard to execute an A major chord, which is comparably easy.
Having struggled with certain open chords and the F barre on an SG, I tried other guitar designs including Stratocasters, Superstrats and Les Pauls, and I found my wrist was far less bent at the first 3 frets. As a result, I switched to a Superstrat and have since had no trouble with the F barre.
I ask this question because after searching forums online, I didn't find any mention of wrist angle and open chords based on guitar design, but it seems to be well-documented that on an SG the neck will be shifted more toward your fretting hand due to the position at which the neck joins the guitar body.
I'm wondering if my experience was generalizable, as I'd like to be informed when a friend asks me for first-guitar advice in the future.
Comment: Sounds plausible enough. Most SG players I can think of use it more for single-note stuff or powerchord-heavy licks, not much for full open- or bar chords. But Todd is right, the full F chord is a bit challenging in the beginning even when playing a nylonstring guitar seated in classical position with a footrest, and then you definitely can't blame neck-heaviness or anything like that...
Comment: i think this isnt a specifically SG problem - F barre chords are never easy for beginners as you're trying to fret all the strings at once, pushing against the tension that the Nut brings. Try using an A shape, barred, at the   7th till your hands get stronger ?  if the neck is diving its perhaps becuase the SG copy has  body made of lighter wood than Gibson use.
Answer: It's not the guitar. The F barre chord is usually a challenging chord for beginners on every guitar. Personally, I never play the F barre chord at the first fret and I've been playing for 25+ years. It's just too uncomfortable for my playing style and guitar position, and not worth it. I play it without a barre by leaving off the high F note and either leaving off the low F or fretting it with my thumb.
A major factor in ease of playing barre chords is the neck profile (thickness and shape) and the width of the neck. The thicker or wider the neck, the harder it can be to get your hand all the way around to barre. According to Gibson, the Standard SG has a width at the nut of 1.6875", and a thickness (profile) at the nut of .800". In comparison, a Fender American Strat has a width at the nut of 1.685" and thickness at the nut of .820". Other guitars may be wider/thicker or thinner/narrower than the SG, but the SG does not have an unusually large neck that should make it harder than usual to play barre chords.
Regarding what is called "neck dive" by bass players, who have the problem on many popular bass models (because the necks are long and the tuning machines are heavy), I think a lot of people work to mitigate it by getting a strap that is less slippery. If you're ok with leather, a suede strap seems to help a lot. There are most likely synthetic straps that help with neck dive as well. If you have a favorite musical instrument retailer, I would ask someone there about straps that will help keep the SG in place.
Comment: with all due respect it's a bit of an opinion that the F barre chord in "bad for beginners in every guitar".  I think you are also promoting false ideology about guitar playing and teaching.  This is simply not true.  Proper education, proper set up, and proper posture on the student part should lead to relaxed, smooth execution.  Please reconsider your post.
Comment: @ggcg If I changed it to "**difficult** for beginners on every guitar", would that seem more appropriate? I've taught guitar for many years and I've taught guitarists of all ages with all different types of guitars of various quality levels, and the F barre chord and the Bb major barre chord have been very difficult for all of them. Would you agree with my overall point that it's not that the asker has a Gibson SG that is the cause of the trouble?
Comment: @ggcg Does lowering the nut notches help with the increased fret spacing in first position? Because for me that's a bigger problem than the action. Would you say that there are no especially difficult chords for beginners? I'm curious if the F barre chord is not any harder than the rest, is there anything that is more difficult?
Comment: Have you played every guitar?  The comment is simply not true.  Beginners should be encouraged to learn to do things correctly rather than fed false information that would lead to a form of non-learning.  Let's not get into a resume comparison either.  I too have taught guitar, etc, since 1985.  The statement seems like hyperbole.
Comment: Actually I would disagree on the point about the guitar being the problem.  Gibson's are great guitars but they are not without issues.  One that I've experienced on every new Gibson is that the shape of the frets and the notch in the bridge will cut strings.  My 335 had to have those parts filed down to prevent frequent string breaks.  Now I can leave a set on for years with no breaks (though they do get muddy).  Many guitars have the nut groves cut too high making 1st pos. playing very difficult.  But when filed down 1st pos. feels like 5th pos.  Proper set up is key!
Comment: You change one thing without the other.  Lowering nut notches, adjusting truss rod, adjusting bridge...  When the guitar is properly adjusted it becomes easier to play.  All chords are "difficult" to the hand that never played them.  I am not going to engage in answering poorly presented questions.  You have not clearly stated why you think F barre is "harder" to play than some other chord.  Or why certain other chords are easy.  This entire narrative is speculative hyperbole.
Comment: @ggcg Sorry, I'm not trying to argue with you. The frets are farther apart at the first fret, which AFAIK isn't affected by the setup at all. For my hands (and the hands of my students), that increased fret spacing makes it harder to fret barre chords at the first fret. Perhaps your experience is different.
Comment: You are stating that the difficulty is a universal thing and not a function of you or your relationship with the guitar or proper training etc.  You are making a blanket statement about everything.  Furthermore to say that using these chords is a "waste of time" injects a sort of prejudice into the conversation that does nothing to offer a real answer to the post.  As an educator I take umbrage with this tack.  People reading it with no formal training might take your words as authority on music education and that is not appropriate.  Try learning new teaching methods to help your students.
Comment: Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/78940/discussion-between-todd-wilcox-and-ggcg).
Answer: I had an Epiphone SG for a long time, and I dn't remember any particular difficulty with F.
That said, I play rock and that rarely, if ever, requires a full F barre chord. Power chords usually do the trick, or something tinkly on the top 4 strings.
One thing that may be a factor is the height of the nut. If the action (distance from fret to string) is high at the 1st fret, then anything around that area is going to be hard to play because you're trying to squash a string the to fret when it's only an inch or two away from the nut, which is holding it upwards. The string doens't have the length to flex. F barre would be the absolute hardest, perhaps Bb being difficult too.
That doens't answer the issue of the 'neck dive' but it culd be one reason why you're finding F hard to play on that guitar.
Answer: The ability to play an F barre chord in first position depends on your posture.  On Classical guitar with proper sitting posture it's actually quite easy to play without any hand tension.  I've never played an SG but I have noticed that there are certain chord forms and patterns that are easy to play when seated and impossible to play standing.  The opposite is true too, standing leads to a more open picking arm and it's easier to pick fast and smooth but while seated the right arm starts to cramp (at least for me).
Comment: It will also depend on the relative positions of the guitar (any one) sitting/standing. Most folk will sling it lower when standing, changing the geometry. Also consider it rests on a leg (either one) seated, but centres when standing. No wonder there's a difference!

F barre chord on an SG guitar


Does the sus4 work better on a dominant chord?

Question: Is it just chance or does the sus 4 usually happen on a dominant chord. The beatles used this often and I have only examples where they used it on dominant chords. Is this because the sus 4 creates more tention over dom7 chords? Also, in the vocal melodies in many songs, the sus 4 note is used a lot but not ever over the triad version of the chord. It almost always appears when the 7th is used.
Can someone please shed some light on this?
Answer: When the label sus4 comes up things get tricky, because that label is from jazz/rock/pop which so often doesn't actually use the chord as a real suspension.
This is a traditional suspension...

...the first bar is a G7 and the second bar is plain C major, but notice the F - the seventh of G7 - is suspended (held over from G7) in the first beat of the C chord and then resolves down to the E on the second beat.
The typical thing is for the sus4 to happen on the plain triad after the dominant seventh.
Here is an example from Mozart's K 333...

This is not the only way a suspension gets handled, and sometimes the sus4 chords are used without any resolution, but the example above is the traditional origin of suspensions.
Also, there is a particular harmonic sequence of seventh chord that may interest you. It isn't exactly what your question is about, because the suspension involves a seventh rather than a fourth. Here is an example...

...where the third of one chord is suspended to form a seventh in the next chord which then becomes the third of the next chord. Again, the suspensions are sevenths rather than fourths, but it is a common example showing suspensions used on all diatonic chords except the tonic.

EDIT
The suspension can happen on the dominant too. Compared to the classical example above this is an older style. I think in Mozart's time this would have sounded conservative, or bit formal, Church-style. Here are some example from model cadences from Fenaroli...
Comment: "The typical thing is for the sus4 to happen on the plain triad after the dominant seventh": historically, the typical thing is for the sus4 to happen *on* the dominant seventh.  This was happening in the late middle ages long before anyone thought of using a suspension on the final chord (and long before the concept of chords had even developed).  This answer suggests that the assumption in the question is off the mark, but it is not.
Comment: @Phoog, notice that I said "this isn't the only way a suspension is handled." The important thing was to give a clear example of a suspension over a _plain triad_, because the OP seems to think it's used only with seventh chords. Anyway, post an answer with that usage from the late Middle Ages.
Comment: Hm.  Maybe I will, thanks for the suggestion.  (I did notice that you said they're handled in other ways; I was only taking exception to the identification of the "typical" 4-3 suspension.)
Comment: "in Mozart's time this would have sounded conservative, or bit formal, Church-style": indeed, the same was true in earlier times.  A quick look at Summer from Vivaldi's Four Seasons, Bach's Brandenburg No. 1, and Handel's Water Music shows a preference for I-V-I or I(6/4)-V-I cadences that persisted into the symphonies of Haydn and Mozart.
Comment: I'm not sure what you're getting at. The point is about which chord gets the suspension, V or I. Putting it on V is the "conservative" style.
Comment: The main point is that "in Mozart's time" is misleading, because that distinction had existed for decades before his birth. A related point is that the first chord in a I(6/4)-V-I cadence is usually best analysed as dominant chord with a double suspension rather than a true tonic chord. Such cadences were popular at least from the late 17th century well into the 19th. The double 9-8 and 4-3 suspension in the Mozart example here arose from the 17th century (and later) French fashion of applying an ornament to the final note of a phrase, so that wasn't particularly new either.
Comment: It's funny how you put words into my mouth. I didn't say the distinction formed in Mozart's time, or that the Mozart cadence was new. I presented two types of suspensions from two master sources. One _is_ more conservative than the other. There isn't much more to it than that.
Comment: I'm not putting words into your mouth; I'm noting a misleading inference that would naturally be made.  The sentence containing the phrase "in Mozart's time" is correct in the same way that it is correct to say that the piano was an important instrument in Brahms's time.  While it is true, it could easily be misinterpreted.
Answer:
Is it just chance or does the sus 4 usually happen on a dominant chord?

It is not chance.  The suspended fourth has its origin in the dominant chord, before chords were even thought of as such.  Indeed, it has its origins in the 7-6 suspension that was common in the early 1400s before polyphonic compositions commonly had bass parts.
John Dunstaple (or Dunstable) is widely credited with having introduced a new style of composition to the continent, known as fauxbourdon, based on parallel thirds and sixths.  A common cadential formula was
X: 1
L: 1/2
K: Amin
M: none
V:1 clef=bass
C2 B,2 C2 |]
V:2 clef=bass
E,2 D,2 C,2 |]

Later, in the baroque period, this would be figured thus:
X: 2
L: 1/2
K: Amin
M: none
V:1 clef=bass
C2 B,2 C2 |]
V:2 clef=bass
E,2 D,2 C,2 |]
w: 6 6

In practice, this basic cadential framework would more likely be altered rhythmically:
X: 3
L: 1/2
K: Amin
M: none
V:1 clef=bass
z C2 B, C2 |]
V:2 clef=bass
E,2 D,2 C,2 |]

This introduces the common cadential suspension that would later be figured 7-6:
X: 4
L: 1/2
K: Amin
M: none
V:1 clef=bass
z C2 B, C2 |]
V:2 clef=bass
E,2 D,2 C,2 |]
w: _ 7~6

An example may be seen at measure 35 in this Agnus dei.  Here is a fragment of the outer two voices, for reference, transposed for comparison with the above examples:
X: 5
L: 1/2
K: Amin
M: none
V:1 clef=bass
B,2 G,2 C2 B, C4 |]
V:2 clef=bass
z G,2 E, C, D,2 C,4 |]
w: _ _ _ _ 7~6

One of the famous continental composers influenced by Dunstaple was Guillaume Du Fay (or Dufay).  His music reflects the new fashion for adding a fourth part below the tenor.  (This part was called the contratenor bassus to distinguish it from the contratenor altus.  The word contratenor was eventually dropped from both names, giving us the modern bass and alto parts.)
The role of the bass voice in the cadential formula under consideration was indeed largely the familiar role it has in the modern authentic cadence.  That is, it has the root of what came to be known as the dominant chord.  For example:
X: 6
L: 1/2
K: Amin
M: none
V:1 clef=bass
C2 B,2 C2 |]
V:2 clef=bass
E,2 D,2 C,2 |]
V:3 clef=bass
C,2 G,,2 C,2 |]

Because the tenor is no longer the lowest voice, the figures change.  In the homophonic example above, there are no figures, because the chords are now all in root position, but of course the same rhythmic alterations may be applied:
X: 7
L: 1/2
K: Amin
M: none
V:1 clef=bass
z C2 B, C2 |]
V:2 clef=bass
E,2 D,2 C,2 |]
V:3 clef=bass
C,2 G,,2 C,2 |]

In this case, the suspension that was formerly a 7-6 suspension becomes the 4-3 suspension that you are asking about:
X: 8
L: 1/2
K: Amin
M: none
V:1 clef=bass
z C2 B, C2 |]
V:2 clef=bass
E,2 D,2 C,2 |]
V:3 clef=bass
C,2 G,,2 C,2 |]
w: _ 4~3

Finally, an example from Du Fay's Missa l'homme armé, at the end of the last Kyrie, again with the alto part omitted, and again transposed for easier comparison with the other examples (the timestamp in the link is roughly measure 80 in the video; the example below begins at the end of measure 82):
X: 9
L: 1/2
K: Gmin
M: none
V:1 clef=bass
z C2 D2 C2 =B, C4 |]
V:2 clef=bass
G, G, G, F,2 E, D,2 C,4 |]
V:3 clef=bass
z E,2 D, B,, C, G,,2 z2 C,2 |]
w: 6 ___ 4~3

(Later, when it became common for the final chord to include its third, it also became common for the alto voice to move to that note from the doubled root of the dominant chord.  This descending melodic third was frequently filled with a passing tone, which gave rise to the 4-3 suspension discussed in Michael Curtis's answer.  It also eventually became the 7th of the dominant 7th chord.  But all of this happened rather later; it wasn't for another century or so that it became usual for the final chord to have a third.  If you look at the video of the Du Fay cadence excerpted above, however, you can see the sort of thing that led to this:  The alto drops from the fifth scale degree to the third and then moves back up to the fifth, thereby avoiding the third in the final sonority.  Interestingly, there is a passing tone on the way up, but not on the way down.)
Answer: sus4 works on every major and minor chord as you can see e.g. in Bachs little prelude BWV 924

It is also used in the final chord on the tonic Isus4->323 (instead of the plagal cadence IV-I, if you remind this kind of "amen" as the final clause of "let it be" (famiredo ... of course we have here more than just the sus4 ... but here's another well known example :

edit:

It almost always appears when the 7th is used.

Can someone please shed some light on this?
The light may turned on if you write down a progression of chords in the circle of fifths or a fifth fall sequence: you will recognize that the 7th of a chord will be the suspended 4th of the next chord ... etc.
em7 (d=7
am7 (d=4/g=7) ->
dm7 (g=4/c=7) ->
G7 (c=4/f=7) ->
Cj7 (f=4/b=7 ->
Fj7 (b=4 etc.
could be this what you mean?
Comment: IV-V is not a plagal cadence, and IVsus4 is not diatonic in a major key.
Comment: yes, this was a "typo" ;) I've edited it. What do you mean with IV4? I didn't mention this one.
Comment: *"sus4 works on every major and minor chord"* Not true; in C major, F major is the IV chord. However, Fsus4 contains a B♭, which is not diatonic to C major.
Comment: yes, and what I mean is: the 4sus works on every degree, even on IV and even this is a #4 suspense. The question was how far is the sus4 of the dominant a special case. My answer is the: the 4th can be suspended on every degree ... (who said that it has to be diatonic? in a fifth fall sequence you have all kind of sus4 and also in a chain of ii7sus4 - V7sus4.
Comment: A favorite example of mine is the open chord `B7sus4` of _vensus_ by Shocking Blue.