Delayed Flip-Card Transition on Page Load Then Loop

Question: I'm having a bit of brain block here and can't seem to figure this one out at the moment.
I have four flip-cards that flip down vertically on hover, currently. What I'm trying to achieve here is have the flip-cards flip down on page load, one at a time after the other, with no hover, and then once the fourth card has flipped down, reset all, and loop the same set of transitions over again, infinitely.
I'm sure it's some crystal clear answer that my brain is just not comprehending at the moment. I've tinkered around with it so much that I've just reset it back to hover.
P.S. sorry for the CSS mess I kinda let it go in my many attempts to find a solution. Any help is much appreciated!!
Here's the HTML:

Test

This is a test

Test

This is a test

Test

This is a test

Test

This is a test

And here's the CSS:
.flip-card1 {
    background-color: transparent;
    width: 60%;
    height: 150px;
    margin-left: 75px;
    perspective: 1000px;
}

.flip-card-inner1 {
    position: relative;
    border-radius: 10px;
    width: 100%;
    height: 100%;
    text-align: center;
    transition: transform 2s;
    transform-style: preserve-3d;
    box-shadow: 0 4px 8px 0 rgba(0,0,0,0.2);
    transform-origin: bottom;
}

.flip-card1:hover .flip-card-inner1 {
    transform: rotatex(-180deg);
    perspective: 1000px;
}

.flip-card-front1, .flip-card-back1 {
    position: absolute;
    width: 100%;
    height: 100%;
    backface-visibility: hidden;
}

.flip-card-front1 {
    background-color: transparent;
    color: black;
    z-index: 2;
    border-radius: 10px;

}

.flip-card-back1 {
    background-color: #2980b9;
    color: white;
    border-radius: 10px;
    transform: rotatex(-180deg);
    z-index: 1;
}

.flip-card2 {
    background-color: transparent;
    width: 60%;
    height: 150px;
    margin-left: 75px;
    perspective: 1000px;
}

.flip-card-inner2 {
    position: relative;
    border-radius: 10px;
    width: 100%;
    height: 100%;
    text-align: center;
    transition: transform 2s;
    transform-style: preserve-3d;
    box-shadow: 0 4px 8px 0 rgba(0,0,0,0.2);
    transform-origin: bottom;
}

.flip-card2:hover .flip-card-inner2 {
    transform: rotatex(-180deg);
    perspective: 1000px;
}

.flip-card-front2, .flip-card-back2 {
    position: absolute;
    width: 100%;
    height: 100%;
    backface-visibility: hidden;
}

.flip-card-front2 {
    background-color: transparent;
    color: black;
    z-index: 2;
    border-radius: 10px;
}

.flip-card-back2 {
    background-color: #2980b9;
    color: white;
    border-radius: 10px;
    transform: rotatex(-180deg);
    z-index: 1;
}

/*FLIP-CARD3 ANIMATION*/
.flip-card3 {
    background-color: transparent;
    width: 60%;
    height: 150px;
    margin-left: 75px;
    perspective: 1000px;
}

.flip-card-inner3 {
    position: relative;
    border-radius: 10px;
    width: 100%;
    height: 100%;
    text-align: center;
    transition: transform 2s;
    transform-style: preserve-3d;
    box-shadow: 0 4px 8px 0 rgba(0,0,0,0.2);
    transform-origin: bottom;
}

.flip-card3:hover .flip-card-inner3 {
    transform: rotatex(-180deg);
    perspective: 1000px;
}

.flip-card-front3, .flip-card-back3 {
    position: absolute;
    width: 100%;
    height: 100%;
    backface-visibility: hidden;
}

.flip-card-front3 {
    background-color: transparent;
    color: black;
    z-index: 2;
    border-radius: 10px;
}

.flip-card-back3 {
    background-color: #2980b9;
    color: white;
    border-radius: 10px;
    transform: rotatex(-180deg);
    z-index: 1;
}

.flip-card4 {
    background-color: transparent;
    width: 60%;
    height: 150px;
    margin-left: 75px;
    perspective: 1000px;
}

.flip-card-inner4 {
    position: relative;
    border-radius: 10px;
    width: 100%;
    height: 100%;
    text-align: center;
    transition: transform 2s;
    transform-style: preserve-3d;
    box-shadow: 0 4px 8px 0 rgba(0,0,0,0.2);
    transform-origin: bottom;
}

.flip-card4:hover .flip-card-inner4 {
    transform: rotatex(-180deg);
    perspective: 1000px;
}

.flip-card-front4, .flip-card-back4 {
    position: absolute;
    width: 100%;
    height: 100%;
    backface-visibility: hidden;
}

.flip-card-front4 {
    background-color: transparent;
    color: black;
    z-index: 2;
    border-radius: 10px;
}

.flip-card-back4 {
    background-color: #2980b9;
    color: white;
    border-radius: 10px;
    transform: rotatex(-180deg);
    z-index: 1;
}

Here it is in jsfiddle
Answer: use setInterval to add class for animation in sequnce and use jquery delay method to remove the same class after time.
use below code snippet for same logic.
NOTE : removed all hover selectors.

$(document).ready(function(){
  var i = 0;
  setInterval(function(){

   $(".flip-card-inner"+ i).addClass("hoverit").delay( 1000 - (i*20) ).queue(function(){
      $(this).removeClass("hoverit").dequeue();
   });

  if(i == 4) {
    i = 0;
  }
  i++;

  }, 1000);

});
.hoverit {
    transform: rotatex(-180deg);
    perspective: 1000px;
}

.flip-card1 {
    background-color: transparent;
    width: 60%;
    height: 150px;
    margin-left: 75px;
    perspective: 1000px;
}

.flip-card-inner1 {
    position: relative;
    border-radius: 10px;
    width: 100%;
    height: 100%;
    text-align: center;
    transition: transform 2s;
    transform-style: preserve-3d;
    box-shadow: 0 4px 8px 0 rgba(0,0,0,0.2);
    transform-origin: bottom;
}

.flip-card-front1, .flip-card-back1 {
    position: absolute;
    width: 100%;
    height: 100%;
    backface-visibility: hidden;
}

.flip-card-front1 {
    background-color: transparent;
    color: black;
    z-index: 2;
    border-radius: 10px;
}

.flip-card-back1 {
    background-color: #2980b9;
    color: white;
    border-radius: 10px;
    transform: rotatex(-180deg);
    z-index: 1;

}

/*FLIP-CARD2 ANIMATION*/
.flip-card2 {
    background-color: transparent;
    width: 60%;
    height: 150px;
    margin-left: 75px;
    perspective: 1000px;
}

.flip-card-inner2 {
    position: relative;
    border-radius: 10px;
    width: 100%;
    height: 100%;
    text-align: center;
    transition: transform 2s;
    transform-style: preserve-3d;
    box-shadow: 0 4px 8px 0 rgba(0,0,0,0.2);
    transform-origin: bottom;
}

.flip-card2:hover .flip-card-inner2 {
    transform: rotatex(-180deg);
    perspective: 1000px;
}

.flip-card-front2, .flip-card-back2 {
    position: absolute;
    width: 100%;
    height: 100%;
    backface-visibility: hidden;
}

.flip-card-front2 {
    background-color: transparent;
    color: black;
    z-index: 2;
    border-radius: 10px;
}

.flip-card-back2 {
    background-color: #2980b9;
    color: white;
    border-radius: 10px;
    transform: rotatex(-180deg);
    z-index: 1;
}

/*FLIP-CARD3 ANIMATION*/
.flip-card3 {
    background-color: transparent;
    width: 60%;
    height: 150px;
    margin-left: 75px;
    perspective: 1000px;
}

.flip-card-inner3 {
    position: relative;
    border-radius: 10px;
    width: 100%;
    height: 100%;
    text-align: center;
    transition: transform 2s;
    transform-style: preserve-3d;
    box-shadow: 0 4px 8px 0 rgba(0,0,0,0.2);
    transform-origin: bottom;

}

.flip-card-front3, .flip-card-back3 {
    position: absolute;
    width: 100%;
    height: 100%;
    backface-visibility: hidden;
}

.flip-card-front3 {
    background-color: transparent;
    color: black;
    z-index: 2;
    border-radius: 10px;
}

.flip-card-back3 {
    background-color: #2980b9;
    color: white;
    border-radius: 10px;
    transform: rotatex(-180deg);
    z-index: 1;
}
/*FLIP-CARD4 ANIMATION*/
.flip-card4 {
    background-color: transparent;
    width: 60%;
    height: 150px;
    margin-left: 75px;
    perspective: 1000px;
}

.flip-card-inner4 {
    position: relative;
    border-radius: 10px;
    width: 100%;
    height: 100%;
    text-align: center;
    transition: transform 2s;
    transform-style: preserve-3d;
    box-shadow: 0 4px 8px 0 rgba(0,0,0,0.2);
    transform-origin: bottom;
}

.flip-card-front4, .flip-card-back4 {
    position: absolute;
    width: 100%;
    height: 100%;
    backface-visibility: hidden;
}

.flip-card-front4 {
    background-color: transparent;
    color: black;
    z-index: 2;
    border-radius: 10px;
}

.flip-card-back4 {
    background-color: #2980b9;
    color: white;
    border-radius: 10px;
    transform: rotatex(-180deg);
    z-index: 1;
}

Test

This is a test

Test

This is a test

Test

This is a test

Test

This is a test

Answer: Are you trying to do this with just CSS? If so you could use keyframes to create the 'auto-flip' effect. Here's the updated fiddle, it seems to break the hover state. If you also need the hover state you may need to use JS. Which I can help with as well. Edit: In the fiddle I change the transition origin to center. I just thought it looked better with the animation.
@keyframes flip {
      0% {
        transform: rotatex(0deg)
      }
      25% {
        transform: rotatex(-180deg)
      }
      50% {
        transform: rotatex(0deg)
      }
      100% {
        transform: rotatex(0deg)
      }
}


How do do I play these parts on piano?

Question: Here is a piece of music by Yanni which is arranged for Piano, how should I play the parts I've shown with a circle and what are they called in music? Do they have any special name or is it called a special technique? I myself think that the base-line should be played continuously (something like legato). Am I right?

Comment: Agreed, that question covers the technique. As to the rest of this question: There is no special name for this technique; those are simply two bass voices played simultaneously.
Answer: The idea is that the dots in bass clef with downtails are held for the two beats. It could be done with pedalling, or just held on by the finger that plays each of those notes.

How do do I play these parts on piano?


coordinate transformation and tensor

Question: A 2 dimensional Euclidean space is represented by two different coordinate systems: the Cartesian system $(x_1,x_2)$ and an alternative system $(\xi^1,\xi^2)$ where
$$x_1=\frac{1}{\sqrt2}(\xi^1+\xi^2)$$
$$x_2=\frac{1}{\sqrt2}(\xi^1-\xi^2)$$
A quantity $e(i,j)$ is defined such that in both coordinate systems
$$
e(1,1)=e(2,2)=0,$$
$$
e(1,2)=1$$
$$e(2,1)=-1$$
Do the quantities $e(i,j)$ represent the components of a tensor?
I am not sure how to start.  Can anyone help me plz?
Answer: To show that this quantity is a tensor we need to show that coordinate representation of the quantity is invariant under a change of coordinates.
The question stipulates that, for the vectors with coordinates $\left(\begin{array}{c}x_1\\x_2\end{array}\right)$ and $\left(\begin{array}{c}y_1\\y_2\end{array}\right)$ in the cartesian system, the matrix representation of the quantity implies
$$
\left(x_1,\  x_2 \right)\left(\begin{array}{cc}0&1\\-1&0\end{array}\right)\left(\begin{array}{c}y_1\\y_2\end{array}\right){}={}x_1y_2-x_2y_1\,.
$$
Note, also, that this form must also hold for the alternative coordinate system as well. That is, if the vectors have the alternative coordinates $\left(\begin{array}{c}\xi_1\\\xi_2\end{array}\right)$ and $\left(\begin{array}{c}\zeta_1\\\zeta_2\end{array}\right)$, respectively, then we must also have
$$
\left(\xi_1,\  \xi_2 \right)\left(\begin{array}{cc}0&1\\-1&0\end{array}\right)\left(\begin{array}{c}\zeta_1\\\zeta_2\end{array}\right){}={}\xi_1\zeta_2-\xi_2\zeta_1\,,
$$
for this to be a tensor. However, by direct substitution using the given change of coordinates transformation, we see that
$$
\begin{eqnarray*}
x_1y_2-x_2y_1&{}={}&\dfrac{1}{2}\bigg(\left(\xi_1+\xi_2\right)\left(\zeta_1-\zeta_2\right)-\left(\zeta_1+\zeta_2\right)\left(\xi_1-\xi_2\right)\bigg)\newline
&&\newline
&{}={}&\zeta_1\xi_2-\zeta_2\xi_1\newline
&&\newline
&{}\ne{}&\xi_1\zeta_2-\xi_2\zeta_1\,.
\end{eqnarray*}
$$
Therefore, the quantity is not a tensor!

coordinate transformation and tensor


Where does this equation come from?

Question: Since I study 3 years i ask myself very often where does this equation come from?
$$e^{i\theta} = \cos(\theta)+i \sin(\theta)$$
Is it found by series expansion?
Comment: Technically, it can be taken as a definition. But it substantially amounts to the evaluation of Taylor series for complex $x$ $$e^x=\sum_{k=0}^\infty \frac{x^n}{n!}\\ \sin x=\sum_{k=0}^\infty \frac{(-1)^nx^{2n+1}}{(2n+1)!}\\ \cos x=\sum_{k=0}^\infty \frac{(-1)^nx^{2n}}{(2n)!}$$
Comment: Close-voters, what are you thinking? The "missing context" close reason is code for closing of homework questions where the asker doesn't show any attempt to approach the problem himself. This is clearly not a homework question (there's no conceivable homework problem that would go like this), but a question about _understanding_ the theory; as such the "missing context" close reason is inapplicable to it.
Comment: Yes expand out the series for $\exp$ and the result falls into place using absolute convergence and the ability to rearrange.
Comment: For more information, see https://en.wikipedia.org/wiki/Euler%27s_formula
Comment: @HenningMakholm If anything, I'd look for a *duplicate* target, of which I'm sure there are several (although I'm not particularly adamant about closing).
Answer: This result is commonly shown via Taylor series, as explained in the comments, and is well-known. I'd like to offer a different sort of proof, for those who are interested, that I believe is easier yet less well-known.
Consider the second order linear differential equation
$$y''=-y$$
We know the most general solution is:
$$y = A\cos{x}+B\sin{x}$$
But $$y = e^{ix}$$ is also a solution, and by existence and uniqueness theorems, that means $$e^{ix} = A\cos{x}+B\sin{x}$$
for some $A,B$. Plugging in $x=0$ for the expression and its first derivative, we see that $A = 1, B = i$.
Thus, $$e^{ix} = \cos{x}+i\sin{x}$$
Comment: I think your argument is what in Logic is called Petitio Principii, and although it seems correct, it is not really a proof. The relation $e^{ix}=cos(x)+i\sin(x)$ is really a definition, rather than a proposition. In your argument, what is the definition of "$e^{ix}$" that you are using? And how do you know what its derivative is and why?
Comment: I'm not sure you can *prove* $A\cos x + B\sin x$ is the most general solution, or *prove* the existence and uniqueness theorems you need, without assuming the result somewhere along the way. But it's a nice argument to *motivate* why the result is true. And you seem to have brushed under the carpet the fact that $x$ itself might be complex!
Comment: Nice, and upvoted. But ... what definition of $e^{ix}$ are you using? If the power series then this answer may be the one in the comments, thinly disguised.
Comment: @alephzero I guess that most of the "proofs" of this relation stem from a lack of understanding the difference between "proof of a proposition" and "motivation of a symbol/choice" in Mathematics. Technically, the "proof" here above is plain wrong. Also, it seems that not everyone has clear the difference between an equation and an identity.

Where does this equation come from?


Entity reference field search by custom field

Question: In my setup, a user can own more entities of a specific content type but the ownership is stored in the entity. The user entity does not 'know' anything about this. I know without context it seems weird but in my case, it made more sense like this instead of having an entity reference field on the user.
Now I'm trying to build an Entity Reference Display for a view so that for certain autocomplete fields I can search for users by either their name or the title of the entities they own. I created a view before that showed all the users and all of their entities so I was hoping I can reuse that field here but it seems like if I set the entity reference field to search by this field as well it just adds this view field's id to the query as if it was a user's field and it gives (of course) column not found SQL exception.
I've also tried to add a join with a view query alter hook but I could not figure out how to get the text entered by the user as that seems to be neither in exposed_raw nor in args.
Any ideas?
Edit:
Here is how my relationship is set up:
Entity -> Field referencing a paragraph that describes the ownership -> field referencing a user
And here is what I tried based on @stevekeiretsu's comment:

I set up a relation to paragraphs that have that field referencing a
user
Then I added another relation to content that has that field referencing this paragraph.
Then I added the Title field of content to the view

The problem is that it still does not show anything. If I set the relations to required I have no results.
Comment: I think I know what you mean about the 'weird' entityref setup.  I have a site where things have a 'place' entityref, rather than places having a 'things' entityref, which I think is the exact same concept, probably for the same reason (shame core doesnt support bidirectional entityrefs).  I have created views with this.  And yet, I am not quite sure how to answer your question, or even how to explain exactly what I need you to clarify.  Does your view have any relationships configured under the 'advanced' section?
Comment: Well... I did not know about the relationships option... Now I did my research and I can see how this can help me but it is still not working. I edit the question whit what I tried here. Thanks
Comment: Ah, there is a paragraph entity 'in the middle'.  That would complicate things.  In my setup the entityref field is directly on the entity.  Fundamentally, is this a view of users or a view of content type?
Comment: Of users as I want to use it for an entity reference field of type user
Answer: Ok, I found the issue:
SELECT
users_field_data.created AS users_field_data_created,
users_field_data.uid AS uid,
field_member_users_field_data.id AS field_member_users_field_data_id,
field_number_ownership_paragraphs_item_field_data.nid AS field_number_ownership_paragraphs_item_field_data_nid
FROM
    users_field_data as users_field_data
    LEFT JOIN paragraph__field_member as paragraph__field_member
        ON
        users_field_data.uid = paragraph__field_member.field_member_target_id AND
        paragraph__field_member.deleted = '0'

LEFT JOIN paragraphs_item_field_data as field_member_users_field_data
    ON
    paragraph__field_member.entity_id = field_member_users_field_data.id

LEFT JOIN node__field_number_ownership as field_member_users_field_data__node__field_number_ownership
    ON
    /** HERE **/
    field_member_users_field_data.id = field_member_users_field_data__node__field_number_ownership.field_number_ownership_target_revision_id AND
    field_member_users_field_data__node__field_number_ownership.deleted = '0'

LEFT JOIN node_field_data as field_number_ownership_paragraphs_item_field_data
    ON
    /** AND HERE **/
    field_member_users_field_data__node__field_number_ownership.entity_id = field_number_ownership_paragraphs_item_field_data.vid

INNER JOIN
    user__roles as user__roles ON users_field_data.uid = user__roles.entity_id   AND user__roles.deleted = '0'
WHERE (user__roles.roles_target_id = 'member')
ORDER BY users_field_data_created DESC
LIMIT 11 OFFSET 0

This is the SQL generated by the View. As you can see it is using entity_id against vid and id against target_revision_id in the joins. This may be a bug or my lack of some fundametal drupal stuff. Please let me know if that is the case: Until then, I came up wiht this query alter to solve this problem:
function aci_ssp_views_query_alter(ViewExecutable $view, QueryPluginBase $query) {
    // Ifs view id is what i'm looking for
    $tables = $query->getTableQueue();

    $tbl1 = 'field_member_users_field_data__node__field_number_ownership';
    $tables[$tbl1]['join']->leftField = 'revision_id';
    $tables[$tbl1]['join']->configuration['left_field'] = 'revision_id';

    $tbl2 = "field_number_ownership_paragraphs_item_field_data";
    $tables[$tbl2]['join']->field = 'nid';
    $tables[$tbl2]['join']->configuration['field'] = 'nid';
}


Android findViewById gets null. Already tried cleaning project, setcontentview first

Question: Help! I am getting the findViewById null return value problem.  I did tons of research and already clearned project, put setContentView ahead,  but it still fail! The xml layout works fine because if i set my custom view's back ground to blue, the view will have blue color as expected when running the app.  But i just cant use findViewById
layout xml:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >

<shaotian.android.blackboard.BBView
    android:id="@+id/bBView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

</FrameLayout>

custom view class, its parent class extends android's view class already:
package shaotian.android.blackboard;
import java.util.Observable;
import java.util.Observer;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
public class BBView extends shaotian.android.blackboard.View {

public BBView(Context context) {
    super(context);
    // TODO Auto-generated constructor stub
    TextView txt=new TextView(context);
    this.setBackgroundColor(Color.BLUE);

}
public BBView(Context context, AttributeSet attr)
{super(context);
this.setBackgroundColor(Color.BLUE);
}

public BBView(Context context,AttributeSet attr,int sty)
{
    super(context,attr,sty);
    this.setBackgroundColor(Color.BLUE);
}

@Override
protected void onDraw(Canvas canvas) {
    // TODO Auto-generated method stub
    super.onDraw(canvas);
}

public void update(Observable arg0, Object arg1) {
    // TODO Auto-generated method stub

}

}
Activity class:
package shaotian.android.blackboard;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class BlackBoardActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    BBView view=(BBView)findViewById(R.id.bBView1);

}
}

Comment: post this class shaotian.android.blackboard.View ...
Comment: If your layout file is really called `layout.xml` you *should* consider calling `setContentView(R.layout.layout);` instead of `setContentView(R.layout.main);`.
Comment: setContentView(R.layout.layout);
Answer: You are calling the wrong super constructor here:
public BBView(Context context, AttributeSet attr)
{
   super(context);
   this.setBackgroundColor(Color.BLUE);
}

Should be:
public BBView(Context context, AttributeSet attr)
{
   super(context, attr);
   this.setBackgroundColor(Color.BLUE);
}

Also, in the pasted code for the activity I don't see the import for R, make sure you import your project's R file, and not com.android.R by mistake.


Open an image in a new pop up window when form submit button is clicked in Drupal 7

Question: I have a form with only a submit button in it and I want to display an image in a new pop up window whenever form submit button is clicked in Drupal 7 node.
function custommodule_my_form($form, &$form_state) {
$imgurl = $form_state['build_info']['args'][1];
$form['submit'] = array(
    '#value' => 'Print Coupon',
    '#type' => 'submit',
);
return $form;
}

The image is present in the loaded node and I already have its URL inside a variable $imgurl.
Now how can add an attribute in this form so that $imgurl opens up in a new window whenever this submit button is clicked.
$form['submit']['#attributes']['onclick'] = ??

Answer: You can give like this:
$form['submit'] = array(
        '#type' => 'submit',
        '#value' => t('Submit'),
        '#attributes' => array(
            'onclick' => 'function_name()'),
        )
    );

Answer: I would inject a bit of js code to listen to your click and show the popup with the image. You can open the popup url before the page reloads or after.
You may want to have a url path to a page that shows the image so that it will not get downloaded. e.g.
http://yoursite.com/showcoupon/[unique id of coupon]

Answer: I resolved it like this:
 $form['submit']['#attributes']['onclick'] = "javascript: newwindow=window.open('$imgurl','height=500,width=300');";

So, the complete form code now becomes:
$form['submit'] = array(
    '#value' => 'Print Coupon',
    '#type' => 'submit',
);
$form['submit']['#attributes']['class'][] = 'form-submitone';
$form['submit']['#attributes']['onclick'] = "javascript: newwindow=window.open('$imgurl','height=500,width=300');";
return $form;


converting custom object to NSData Swift

Question: I have been researching all over the interweb, especially Stack overflow, and my own references I have at home, but I have not been able to figure out what is wrong with my code. I have spent most of my day trying to figure this issue out, and I hope somebody here can help point me in the correct direction.
Setup:
I have a chess app that I am building in Swift 3.0, and the structure is as follows: BoardModel is the class that holds all of the data about the game, Piece is a class within board model which holds data about itself within the BoardModel, Piece also has a PieceType enum for .knight, .king, etc.
The BoardModel has a 2D array of Piece representing the chess board. Now, with each move, I want to save the game data in Game Center, but before I can even try to store the game data, the encoding throws an error and that is where I am. The error just points at AppDelegate with the statement: "Thread: 1 signal SIGABRT".
Here is the code that is the problem along with the Piece class:
let pieceData = NSKeyedArchiver.archivedData(withRootObject: board.board[0][0])  // where the error is thrown

class Piece: NSObject, NSCoding {
    var isSelected: Bool
    var type: PieceType
    var isWhite: Bool
    var isFirstMove: Bool
    var symbol: String!
    var position: (row: Int, col: Int)!

    override init() {
        isSelected = false
        type = PieceType.empty
        isWhite = true
        isFirstMove = true
    }

    required init(coder aDecoder: NSCoder) {
        isSelected = aDecoder.decodeBool(forKey: "isSelected")
        type = aDecoder.decodeObject(forKey: "type") as! BoardModel.PieceType
        isWhite = aDecoder.decodeBool(forKey: "isWhite")
        isFirstMove = aDecoder.decodeBool(forKey: "isFirstMove")
        symbol = aDecoder.decodeObject(forKey: "symbol") as! String
        position = aDecoder.decodeObject(forKey: "position") as! (Int, Int)
    }

    func encode(with aCoder: NSCoder) {
        aCoder.encode(isSelected, forKey: "isSelected")
        aCoder.encode(type, forKey: "type")
        aCoder.encode(isWhite, forKey: "isWhite")
        aCoder.encode(isFirstMove, forKey: "isFirstMove")
        aCoder.encode(symbol, forKey: "symbol")
        aCoder.encode(position, forKey: "position")
    }

    init(isSelected: Bool, type: PieceType, isWhite: Bool, isFirstMove: Bool, symbol: String, position: (Int, Int)) {
        self.isSelected = isSelected
        self.type = type
        self.isWhite = isWhite
        self.isFirstMove = isFirstMove
        self.symbol = symbol
        self.position = position
    }

    func setPosition(to newPosition: (row: Int, col: Int)) {
        position = newPosition
    }
}

Comment: what is PieceType? is Enum or Custom object(NSObject)?
Comment: @jigneshVadadoriya the PieceType is enum
Comment: Have you provided an NSCoder for the position data type? Try to comment out the position from your code and see if you still crash. You will probably need to provide an NSCoder for the PieceType too depending upon how you implemented it.
Answer: if your Enum is like this PieceType and type is Int
enum PieceType : Int {
    case empty
    case notEmpty

}

Then write encode and decode method  like this way
 required init(coder aDecoder: NSCoder) {
        isSelected = aDecoder.decodeBool(forKey: "isSelected")
        type = PieceType(rawValue: aDecoder.decodeObject(forKey: "type") as! Int)!
        isWhite = aDecoder.decodeBool(forKey: "isWhite")
        isFirstMove = aDecoder.decodeBool(forKey: "isFirstMove")
        symbol = aDecoder.decodeObject(forKey: "symbol") as! String
        position = aDecoder.decodeObject(forKey: "position") as! (Int, Int)
    }

    func encode(with aCoder: NSCoder) {
        aCoder.encode(isSelected, forKey: "isSelected")
        aCoder.encode(type.rawValue, forKey: "type")
        aCoder.encode(isWhite, forKey: "isWhite")
        aCoder.encode(isFirstMove, forKey: "isFirstMove")
        aCoder.encode(symbol, forKey: "symbol")
        aCoder.encode(position.row, forKey: "position.row")
        aCoder.encode(position.col, forKey: "position.col")
    }

i have check bellow code and it work's
 let pice = Piece(isSelected: true, type: .empty, isWhite: true, isFirstMove: true, symbol: "Test", position: (2, 10))
 let pieceData = NSKeyedArchiver.archivedData(withRootObject:pice)
 print(pieceData)

And Out put is
386 bytes

Comment: this only works with blank pieces like you have instantiated in your example. It won't work with-----------------------

let somePiece = BoardModel.Piece(isSelected: false, type: BoardModel.PieceType.knight, isWhite: true, isFirstMove: true, symbol: "Wknight", position: (0, 1))
Comment: I removed the position instance and that worked, but I need the position, so I need to figure out to do. @jvarela, commented on my question and said to provide an NSCoder for position, but I am unsure of how to do this.
jignesh, do you have any idea of how best to do this?
Comment: let me try on other way
Comment: can you add the code of  PieceType enum? in your question
Comment: the PieceType isn't an issue, what you added for PieceType is perfect, but it's the position tuple that is throwing the error, so I think I will just remove the tuple from piece, and just have a row and a column variable for each piece to indicate the position both as Integer
Comment: no require to change variable in tuple also it works
Comment: Have you try my answer?
Comment: For position  you need to add in encode method
aCoder.encode(position.row, forKey: "position.row")
aCoder.encode(position.col, forKey: "position.col")


$\bar S$ is the smallest closed subsets of $X$ which contains $S$

Question: There is indeed a very similar question asked [See Proving closure of S is the smallest closed set containing S. but the content is too advance for a starter in analysis like me and the focus of question is not the same. So I have decided to raise my question here:
Let $X$ be a metric space and $S$ be a subset in $X$. Show that

$\bar S$ is the smallest closed subsets of $X$ which contains $S$.

[ Here, define $\bar S$ as the closure of $S$ in $X$, where the closure is the set containing all the adherent points of $S$ in $X$. We also define $x \in S$ an adherent point of $S$ if $B(x,r) \cap S \neq \emptyset$ for all $r>0$.]
The question is reduced to proving the following:

$\bar S$ is indeed closed in X.
$\bar S$ contains $S$, i.e. $S \subset \bar S$.
$\bar S$ is indeed the smallest in the sense that if $J \subset X$ satisfies 1. and 2., then $\bar S \subset J$.

The first two is rather straightforward and I cannot formulate the proof of the third claim. Here, I would also like to write down my proof for 1. and 2. Feel free to comment on it or provide your proof so that I can learn from you.
Proof of 1.:
Consider $X \setminus \bar S$. For any $x \in X \setminus \bar S$, $x \notin \bar S$. It implies that there exists $r_x >0$ such that $B(x,r_x) \cap S = \emptyset$. Now, for any $y \in B(x,r_x)$, choose $r=min \{ d(x,y), r-d(x,y)\}$. Then $B(y,r) \subset B(x,r_x)$. It follows that $B(y,r) \cap S = \emptyset$, proving that $X \setminus \bar S$ is open.
Proof of 2.:
It is trivial since for any $x \in S$, $x \in B(x,r) \cap S$ for all $r >0$.
Please tell me your thoughts in proving the third claim. Thanks in advance.
Comment: Do you know that the intersection of two closed sets is s a closed set? If so, if $\overline{S}\not\subseteq J$ then $J\cap \overline{S}$ is a closed set and $S\subseteq J\cap\overline{S} \subsetneq \overline{S}$. Prove that isn't possible.
Comment: Prove that a closed set contains all of its adherent points.  Then apply the obvious fact that if $S\subseteq T$, all points adherent to $S$ are also adherent to $T$.
Comment: I have added the definition of $\bar S$. Thanks for reminding. Let me also try Thomas's ideas.
Answer: Ad 2.) This follows since any $x\in S$ is adherent to $S$. (We have $B(x,r)\cap S\supset \{x\} \neq \emptyset$ for any $r>0$.)
Ad 1.) Let $x\in X \backslash \bar S$. Then there exists $r_x$ such that $B(x,r_x)\cap S =\emptyset$ (since otherwise $x\in\bar S$). By 2.) we have $S\subset \bar S$ thus $B(x,r)\cap \bar S \supset B(x,r)\cap S = \emptyset$. This proves $B(x,r_x)\subset X\backslash \bar S$ and therefore $X\backslash \bar S$ is open. Hence $\bar S$ is closed.
Ad 3.) Let $J\subset X$ closed such that $S\subset J$. Assume $x\in\bar S\backslash J$. Then there exists $r_x$ such that $B(x,r_x)\cap J = \emptyset$ (since $J$ is closed). By definition of $\bar S$ we have $B(x,r_x)\cap S \neq\emptyset$. We conclude
$$\emptyset \neq B(x,r_x)\cap S \subset B(x,r_x)\cap J =\emptyset$$ -- a contradiction. Thus $\bar S\subset J$.
Alternative 3.) The closure operation is monotone thus $S\subset J$ implies $\bar S \subset \bar J=J$.
Answer: Note that $J=\overline{J}$. As $J$ is closed, then $X\setminus J$ is open. Taking  a point in $X\setminus J$ there would be an open ball fully contained in $X\setminus J$, hence that point would not be in  $\overline{J}$. Then use the simple fact that $\overline{S}\subseteq \overline{J}$, as advised in comments.


Advantages and disadvantages of using Windows versus Linux print server?

Question: I have a small network that I am building that looks like this:

The printer (center) is an old Laserjet 4si with JetDirect set to Ethernet. The machine connected to the BEFSX41 VPN hub is Windows XP and the machines connected to the Airport Express hub are Linux based. The JetDirect card in the 4si is the card made specifically for the 4si with 3 ports (BNC, LocalTalk and Ethernet).
My understanding is that to get the printer to work, I need to designate a PC as a print server. My three options as far as I can tell are:
(1) Have each machine be its own print server and connect to the printer directly. There is no risk of a collision because only one machine will be printing at any given time. However, there may be an issue of connecting and disconnecting different machines to the printer. I am not sure whether the JetDirect can support multiple simultaneous connections.
(2) Have the Windows XP box function as the print server.
(3) Have one of the Linux boxes connected to the Airport function as the printer server.
What are the relative advantages and disadvantages of each approach?
Comment: It has been ages, but IIRC a JetDirect card already is a print server, you don't need any others... You simply point your printer drivers at the IP-address of the JetDirect card.
Answer: My understanding is that to get the printer to work, I need to designate a PC as a print server
The JetDirect card is a print server. You can connect each workstation directly to the printer via the printer ip address. All you need on the workstations is the appropriate printer driver.


Note duration changes when transcribing

Question: I am trying to transcribe a song. In the beginning it seemed to be 100 bpm because the notes aligned nicely when quantizing in Cubase. But then suddenly a few notes came that were 1/3 of a second apart. Is there any way to have 1/3 second in 100bpm (maybe some kind of tuplet?) or do I have to add tempo changes back and forth in these tricky parts?
Comment: Are you able to determine what is the tempo, and whether it changes or not, by listening to the music? If not, why? Perhaps what you need is practicing _ear training_ together with some basics with music notation (those two often come together).
Comment: On the other hand... tempo changes do happen. Please edit to 1) direct us to the song if possible, and 2) establish how comfortable you are with ideas like tempo, beat, and note values, so we can answer at the appropriate level.
Comment: @Emil One of the coolest things about this piece is the non-standard tuning. The G string is tuned down to a D, an octave below the normal D string. This gives it "growly," rattly quality from its reduced tension. And around 1:10 and following, he does double stops, playing the melody on the (normal) D string while using the detuned string as an open drone, or playing in octaves by putting the same finger on both strings.
Comment: Ah, yeah, as @user1079505 comments, it's far easier to understand music in a not-so-analytical way as in the posing of the question. Unlikely that it's really tempo changes... more likely that it's something like triplets inserted in an otherwise-eighth-notes (or other binary) situation.
Comment: I added the name of the piece. I think it is pretty new as in less than or approximately a century so I don't think I can share my transcription but have to keep it private. But I am a newbie when it comes to folk music so not sure. I am kind of comfortable, I just have to look up definition of tuplet sometimes. I kind of know how to read beats as they relate to a bar but I forget which one is supposed to be emphasised.
Comment: I think the b in bpm is supposed to be counting the note that is in the equality sign of the tempo mark, but which one you choose there is just guesswork to me (make the notes pretty maybe?), so I don't really know difference of 100bpm and 200bpm for example.
Comment: Transcription questions are off-topic. But just to get you started: this is an easy one, 6/8 at ~70bpm, no tempo changes, no tuplets.
Comment: Well my question is about whether 0.33333 seconds is possible in 100bpm, not about any specific song. I removed the song now to make it on topic.
Comment: Seems to be in 6/8, 55 or 110 bpm, depending how it's counted. Can't hear any tuplets.
Comment: It aligns down to the millisecond with 100bpm in the beginning, so I don't think 55bpm can be right.
Comment: Why downvotes? It should not be off topic now- it is not about transcribing any particular song.
Comment: It's unfortunate that you deleted the identifying information. But the important part is that you need to understand about "rubato", and about rhythm. There are many, many genres (including Swedish fiddle music) that either don't care about quantizing perfectly, or actually condemn it (my freshman music school class got a lecture titled "Please Don't Play in Time"). You can't determine a tempo—or even rhythms—simply by aligning to a time grid on a computer.
Comment: But bottom line: *No*, this piece has no *significant* tempo change; *Yes*, you should expect it to regularly go out of sync with an artificial metronome or time grid; *No*, you would not need to reflect slight variations in tempo in a transcription; *No*, you should not use unusual note values as a way to notate rubato or tempo changes (though a few eccentric composers have done so); and *no*, "fast notes" don't always mean a tempo change; they can just be shorter rhythmic notes.
Comment: It was a pain to import the midi into musescore with weird note lengths so I ended up having to do a lot of postprocessing work guesstimating the notes there. But I finally got the piece on paper so I can practice it with more confidence :-) I am a bit uncertain about the chords though but it doesn't matter that much to me. Unfortunately the low notes seem out of range of my violin so I might have to transpose it if I want to solo play it on the violin...
Answer: OK, we're not allowed to transcribe this piece for you.  But we can suggest how to go about transcribing a piece, and we need something to demonstrate on!   Perhaps the piece you mentioned in your original question (still visible in the edit history) will do :-)
Listen to the music. Yes, some notes do align with q=100.  But are these the ones you should using for your tempo map?   Where are the main beats, the places you'd kick the bass drum if playing the tune?  Look at the waveform in Cubase. (Any alignment with the bars & beats grid is pure coincidence.) I'm hearing the main beats where I've marked.  'Dum...dum Dum...dum Dum....dum Dum...dum...'

Do you agree?   You should also be able to hear there's a triple subdivision going on - 'One, 2, 3 One, 2, 3...' a waltz  rather than a One, 2, 3, 4' march or rock beat.  So think 3/4 (or 6/8) rather than 4/4.  Now you've got a framework for your transcription.  There are tools in Cubase to align a tempo map with the audio, if that's the way you want to proceed.  Hint - if the tempo's pretty constant (as this piece is, until a slow-down at the very end) don't try to align fussily, with a tempo event on every beat.   Strike an average.
Comment: Btw, although there a bunch of other guesses in the comments, I'm 95% sure from experience with other Swedish folk music that this counts as a waltz, and should be considered 3/4 rather than any kind of /8.
Comment: I tend to agree it's a waltz, and 3/4 would be the conventional notation.  It could conceivably be notated in 3/8 though.  It's the top number that matters!
Answer: As some comments have mentioned, it's hard to guage without more information.
Strictly speaking, it's possible for notes to be any duration apart in any time signature playing any rate of BPM. This is because, while your DAW shows you a nice grid of notes, this is a somewhat artificial construct used to make things easier for a computer. Music is for people though: notes can be played whenever it sounds good. The same goes for pitches - we have standard notes, but a violin or fretless bass can plan between notes just as easily as on them.
Players also bend time intentionally, unintentionally, and endlessly. It's quite unlikely that if this is a live recording the timing is perfectly aligned with your grid the whole way through.
If you'd like to notate it, ask whether it's possible you have some rounding error or have mistaken the time signature. If so, it's quite likely one of the following:
If you're in 6/8 (or similar) and you're referring to a beat as three 8ths:

A "beat" is 0.6s second long
An 8th would be 0.2 seconds long
Three 16ths would be 0.3 seconds long

That's very close to three beats per second, and would imply they are playing a note every three 16ths (See the second bar in the Musink screenshot below). This is a pretty standard syncopation pattern.
If you're in 4/4, a quarter would be 0.6s long and a sixteenth would be 0.3 seconds long, which is pretty close to 1/3rd of a second - certainly within error for recording.

Note duration changes when transcribing


Show that $T(v)$ and $T(v)-v$ are eigenvectors of $T$

Question:
Let $V$ be a vector space, $T:V\to V$ be linear s.t. $T\circ T=T$, $v\in V$ s.t. $T(v)\neq 0$ and $T(v)\neq v$.
  Show that $T(v)$ and $T(v)-v$ are eigenvectors of $T$. What are their eigenvalues?

Attempt:
It's clear that since $T(T(v))=T(v)$ we derive that $T(v)$ is an eigenvector with a corresponding eigenvalue of $1$. However, the struggle is with $T(v)-v$ since $T(T(v)-v)=T(T(v))-T(v)$ and the fact that $T(v)\neq v$ apparently hints that  a certain trick is required.
Comment: No trick.  It's just that the zero vector is never an eigenvector.
Answer: Note that$$T\bigl(T(v)\bigr)-T(v)=T(v)-T(v)=0.$$Since $T(v)\neq v$, this proves that $T(v)-v$ is an eigenvector with eigenvalue $0$.
Answer: We have $T(T(v)) = (T \circ T)(v) = T(v)$ therefore $T(T(v) - v) = 0$.


Make HTML form and table by using JavaScript code.

Question: I have tried to make Form and Table using JavaScript code in HTML page. But the code in not in the correct way. So I need to make the Form and Table in JavaScript way. And HTML code of the Form and Table are display as cooment in the following code.

Comment: Oh, you want to use jQuery without including it?
Comment: Do I need to use JQuery link here?
Comment: try full code in my answer.
Comment: thank you. I need to add JQuery in this code. :)
Comment: I have add your code . It works now. thank you.
Answer: Try changing the appendTo body functions
//form.appendTo('');
form.appendTo('body');

//table.appendTo('');
table.appendTo('body');

Comment: I have tried but it does not work after I modified the code as you said.
Answer: Add jQuery library like

in your page and use .appendTo('body'); instead of .appendTo('');

function clickFunction(e) {
  document.getElementsByName('inputvalue')[0].innerHTML =
    document.getElementsByName('name')[0].value;
  e.preventDefault(); //fallback
  return false;
}

var form = $('<form>');
var input = $('<input>', {
  type: 'text',
  name: 'name'
});
var button = $('<input>', {
  type: 'button',
  value: 'Done',
  onclick: 'clickFunction(event)'
});
input.appendTo(form);
button.appendTo(form);
form.appendTo('body');

var table = $('
');
var tr = $('
');
var td_1 = $('', {
  text: 'Data input'
});
var td_2 = $('');
var label = $('', {
  name: 'inputvalue'
});
label.appendTo(td_2);
td_2.appendTo(tr);
td_1.appendTo(tr);
tr.appendTo(table);
table.appendTo('body');

Full Code

Answer:

whatever html content you would like to use in javascript, just paste it inside document.write();
Comment: I need separately each HTML contains.Then I can add them as I wish. Therefore< I couldn't use like this.


RewriteRules not stopping with LAST flag?

Question: I seem to be having trouble with Apache 2.2's Rewrite module (running on FreeBSD 8).  My .htaccess file is as follows:
Options -Indexes

RewriteEngine on
RewriteRule ^xpaste$ cross.php [L]
RewriteRule ^x([a-f0-9]*)$ cross.php?id=$1 [L]
RewriteRule ^(gen|[a-f0-9]+)$ index.php?$1 [L]
RewriteRule ^(.*)$ index.php [L]

Yet somehow, the last rule overrides the other three.  As soon as I comment it out, the other rules work as expected:

www.example.com/xpaste opens cross.php
www.example.com/x132633 opens cross.php?id=132633
www.example.com/gen opens index.php?gen

I've tried various combinations of L, NS, and S=n flags on each RewriteRule, but unless I comment out the last rule, everything gets directed to index.php. How do I make Apache stop processing the RewriteRules once it finds a match?
Answer: RewriteRule generates an INTERNAL REDIRECT, then processing to be repeated starting from the first RewriteRule(RewriteRule ^xpaste$ cross.php [L]). You need add RewriteCond before last RewriteRule:
 RewriteEngine on
 RewriteRule ^xpaste$ cross.php [L]
 RewriteRule ^x([a-f0-9]*)$ cross.php?id=$1 [L]
 RewriteRule ^(gen|[a-f0-9]+)$ index.php?$1 [L]
 RewriteCond %{REQUEST_URI} !^/(cross|index)\.php$
 RewriteRule ^(.*)$ index.php [L]

Comment: Is there any more generic solution, something to tell Apache "don't process this rule if you're already handling a redirect"?
Comment: http://httpd.apache.org/docs/current/mod/mod_rewrite.html "[...] that if the RewriteRule generates an internal redirect[...], this will reinject the request and will cause processing to be repeated..."
Comment: @DoktorJ You can use a condition to check against the `REDIRECT_STATUS` environment variable. This is empty on the initial request and set to a non-empty string after the first rewrite (specifically, it's set to the HTTP status code).
Answer: NS on the last rule should have worked. Could also do it on the other rules, with no harm. I'm getting to where I'm doing '[L,NS]', adding an NS wherever there's an L.
RewriteEngine on
RewriteRule ^xpaste$ cross.php [L]
RewriteRule ^x([a-f0-9]*)$ cross.php?id=$1 [L]
RewriteRule ^(gen|[a-f0-9]+)$ index.php?$1 [L]
RewriteRule ^(.*)$ index.php [L,NS]

I haven't tested these yet, but there's also an interesting approach here, for your more generic solution, using an IS_SUBREQ variable.
https://stackoverflow.com/questions/9555247/can-anyone-think-of-when-a-sub-request-rewrite-is-useful
This post mentions REDIRECT_STATUS variable also.
http://www.webmasterworld.com/apache/4299003.htm
Comment: "NS on the last rule should have worked." - No it shouldn't have (and nor would the `IS_SUBREQ` server variable help here). A _subrequest_ (which is what the `NS` flag blocks) is not the same as an _internal rewrite_ - which is what's happening here. A subrequest is different and can be triggered by other modules such as mod_dir, SSI and HTTP error states. However, the `REDIRECT_STATUS` _environment variable_ IS an option here.


JMX not available for spring boot application when running standalone

Question: I have a spring boot application with an embedded Jetty and need to monitor the application using JMX.
I can access JMX infomation with jconsole as long as I start the application inside my windows development environment (JConsole offers the process to connect to on its own)
But as soon as a run the application as executable jar with the parameters below, the ports will not be available and I cannot connect with jconsole
<code>-Dcom.sun.management.jmxremote
-Dcom.sun.management.jmxremote.port=9010
-Dcom.sun.management.jmxremote.ssl=false
-Dcom.sun.management.jmxremote.authenticate=false
-Dcom.sun.management.jmxremote.local.only=false
-Djava.rmi.server.hostname=[server ip]
-Djava.rmi.activation.port=9011
</code>
netstat -tulpn does neither return port 9010 nor port 9011, and I cannot connect via jconsole.
MBeans etc. are available since I expose the JMX information as JSON, using jolikai, which is working fine but does not fit into our monitoring infrastructure.
Answer: try the following parameters.
<code>set JMX_OPTIONS=-Dcom.sun.management.jmxremote.port=8014
set JMX_OPTIONS= %JMX_OPTIONS% -Dcom.sun.management.jmxremote.ssl=false
set JMX_OPTIONS= %JMX_OPTIONS%-Dcom.sun.management.jmxremote.authenticate=false
set JMX_OPTIONS= %JMX_OPTIONS%-Dcom.sun.management.jmxremote.localConnectorAddress=10.250.0.10
</code>


Why doesn't "exit" show as a PowerShell command?

Question: Noticed something curious today. We all (probably) know exit will end your current PowerShell session (or exit a remote PSSession). However, neither Get-Command or Get-Alias return anything for it (errors truncated below):
Get-Command exit # ==> The term 'exit' is not recognized as the name of a cmdlet....
Get-Alias exit # ====> This command cannot find a matching alias....

So... what is it?
Answer: exit is a keyword, not a command/cmdlet. See about_Language_Keywords for more information.
Others keywords (eg. if) also exhibit the same behavior when used with Get-Command / Get-Alias.


How find this minimun of this $\frac{xy}{x^5+xy+y^5}+\frac{yz}{y^5+yz+z^5}+\frac{xz}{x^5+xz+z^5}$

Question: let $x,y,z>0$ and such
$$x+y+z=1$$
Find minimum of the
$$\dfrac{xy}{x^5+xy+y^5}+\dfrac{yz}{y^5+yz+z^5}+\dfrac{xz}{x^5+xz+z^5}$$
I have find this maximum
note
$$\dfrac{xy}{x^5+xy+y^5}\le -243\dfrac{x+y}{841}+\dfrac{23031}{1682}$$
see
http://www.wolframalpha.com/input/?i=xy%2F%28x%5E5%2Bxy%2By%5E5%29%2B243*%28x%2By%29%2F841-23031%2F1682
But for minimum value,I can't,(maybe use AM-GM) Thank you,
Comment: I can't see it being anything except $81/29.$  If all three have to be positive, then there will be trade-offs if $x \neq y \neq z$ because of the cyclic symmetry of the function to minimize.  So $x = y = z = 1/3.$  But I can't prove it.
Comment: For $g(x,y)=xy/(x^5+xy+y^5)$ if $\partial_x^2 g(x,y) < 0$ for $0<x,y\leq 1$, which some graphing may suggest, then I think there is an argument using Lagrange multipliers that $x=y=z$ is where the min occurs. But it is too late now...
Comment: Lagrange multipliers looks hairy.  I'm guessing there's a trick.
Comment: @John Lagrange multipliers work if $g_x(x,y)$ is one-to-one for all $y<1$. All the symmetries work out otherwise in just a fine manner (with some argument).
Answer: The max is $\dfrac{81}{29}$ and min is $\dfrac{.25}{2*(0.5)^5+.25}$, a simple method is let two varies equal$(x=y)$ and have a function of $x$, see graphic below:

edit :to prove max, consider $xy \le \dfrac{x^2+y^2}{2}, x^5+y^5 \ge 2(\dfrac{x^2+y^2}{2})^{\frac{5}{2}},\dfrac{xy}{x^5+xy+y^5}\le \dfrac{x^2+y^2}{x^2+y^2+4(\dfrac{x^2+y^2}{2})^{\frac{5}{2}}}=\dfrac{p}{p+4(\dfrac{p}{2})^{\frac{5}{2}}}=f(p)$
$f(p)$ is concave and mono decreasing  function and $x^2+y^2+z^2 \ge \dfrac{1}{3}$ ,so we can quickly know the max will be got when $x=y=z$
Comment: Hello,the max is how prove it? becasue I think $$\dfrac{xy}{x^5+xy+y^5}\le\dfrac{23031}{1682}-\dfrac{243}{841}(x+y)$$ is not easy prove
Comment: @math110 this value is wrong!$\dfrac{xy}{x^5+xy+y^5}< 1 \implies $ max $<3$,but $\dfrac{23031}{1682}>13,x+y<1 \to $ Max $>12$


Using Stokes theorem to find the integral of a vector field over the curve of intersection of two surfaces

Question:
Find $\int_C{ \vec{F} \cdot \vec{dr}},$ where $F(x, y, z) = \langle 2 x^2 y , 2 x^3 /3, 2xy\rangle$ and $C$ is the curve of intersection of the hyperbolic paraboloid $z = y^2 - x^2$ and the cylinder $x^2 + y^2 = 1$, oriented counterclockwise as viewed from above.

I tried to parametrize the region but have no idea what to do after that.
Comment: What was the result of your attempt to parametrize the region?
Comment: i have a feeling that the parametrization thing was wrong ... as in Stokes theorem you take the curl. The curl in this cause is <2x, -2y, 0>. Now I think i need to find the double integral of this curl but I dont know how to do that over the region S. What limits would I take and what is dS?
Comment: The rgion $S$ is the part of paraboloid $z=y^2-x^2$ bounded by the cylinder $x^2+y^2=1$. So that's the parametrization you want, with $x,y$ being parameters.
Comment: ok so for the parametrization, if i equate the two equations i get z = 2y^2 - 1 and then r(u, v) = .
Comment: No, that's wrong. The surface you integrate over is the cylinder, $z=y^2-x^2$. This is  what goes into the formula for $\vec r$. The other surface is just there to set the boundary, you will need it only when you decide on the boundaries of integration.
Comment: So do I do this the other way and take z = y^2 - x^2 -> z + x^2 = y^2 -> (substituting in other equation) 2x^2 + z^1 = 1?
Comment: Does the question explicitly ask you to use Stroke's theorem? The line integral itself is relatively easy to integrate if you parametrize $C$ as $[0,2\pi] \ni \theta \mapsto (x,y,z) = (\cos\theta,\sin\theta,-\cos(2\theta))$.
Comment: @achille-hui It does not state i have to use Stokes. Could you explain how you got that parametrization? I seem to be having trouble with that.
Answer: In the comments we reduced this to integrating $\langle 2x, -2y,0\rangle$ over the part of paraboloid $z=y^2−x^2$ that lies within the cylinder $x^2+y^2=1$. Note that the Stokes theorem was already used, the rest is just a run-of-the-mill computation of a surface integral. So if you are uncertain about how this is done, that would be the topic to revisit. Some points to keep in mind

You need a parametric equation $\vec r(u,v)$ and the parameter domain in the $uv$-plane. So there will be two distinct steps: first you'll get a parametric equation, and then figure out the values the parameters take.
The formula for $\vec r(u,v)$ comes from the surface over which you integrate. Do not combine the equations of both surfaces just because you have them. Use only the one over which you will integrate, which is the paraboloid.
The parameter domain is where you bring the other surface into consideration. Think of it as a cookie-cutter slicing the first surface. How does it cut through the first one? Draw a sketch.
Answer: Since the intersection lies on the surface $z = y^2 - x^2$ and the dependence of $z$ is linear, this means once you know how to parametrize $(x,y)$, you know how to parametrize
$z$.
Since the other surface is $x^2 + y^2 = 1$ which doesn't depend on $z$ explicitly,
we can parametrize it like what we do to a circle in the plane.
The question tells us when you look
at it from the top, the intersection runs counterclockwisely, this means the ordinary
parametrization of unit circle in the plane
$$[0,2\pi] \ni \theta \quad\mapsto\quad (x,y) = (\cos\theta, \sin\theta) \in \mathbb{R}^2$$
provide the parametrization we need for the $(x,y)$ part.
When $(x,y) = ( \cos\theta,\sin\theta )$,
$z = y^2 - x^2 = -\sin^2\theta + \cos^2\theta = -\cos(2\theta)$.
The parametrization we need for the intersection is given by
$$[0,2\pi] \ni \theta \quad\mapsto\quad (x,y,z) = (\cos\theta, \sin\theta, -\cos(2\theta))\in \mathbb{R}^3$$
and the line integral becomes
$$\int_C \vec{F}(\vec{r})\cdot \vec{r}
= \int_0^{2\pi} \left( 2 x^2 y \frac{dx}{d\theta} + \frac{2}{3} x^3 \frac{dy}{d\theta} + 2xy \frac{dz}{d\theta}\right) d\theta$$
Before we rush to substitute above parametrization into RHS and blindly integrate.
One should sit back and analysis the integrand first. We find
$$2 x^2 y \frac{dx}{d\theta} + \frac{2}{3} x^3 \frac{dy}{d\theta}
= \frac{d}{d\theta}\left( \frac23 x^3 y \right)$$
is a total differential and its integral over any closed contour vanishes. As a result,
your integral reduces to
$$\int_0^{2\pi} 2\sin\theta\cos\theta d(-\cos(2\theta))
= 2\int_0^{2\pi} \sin^2(2\theta) d\theta = 2\pi$$


React Component Props typed with two Omit<...> | Omit<....> throwing TS error 2339. Property x does not exist on Pick | Pick

Question: Example of the problem. I have a component that takes the following props:

interface OwnProps {
    text: string;
    tKey: string;
    color: string;
    height: number;
}

I want the component to accept these props, but enforce that you can only pass in either the text prop or the tKey prop, but not both. So I wrote it like so:
interface Props {
    text: string;
    tKey: string;
    color: string;
    height: number;
}

type OwnProps = Omit<Props, 'text'> | Omit<Props, 'tKey'>;

const Component = ({text, tKey, color, height}: Props) {
....
}

OwnProps type seems right. However within the component when I am de-structuring the props typescript throws a ts-2339 error. When I do a similar set up using interfaces like:
interface BaseProps {
    color: string;
    height: number;
}

interface PropsText extends BaseProps {
    text: string;
    tKey?: never;
}

interface PropsTKey extends BaseProps {
    tKey: string;
    text?: never;
}

Typescript is fine with that. I am wondering if there is something about the Omit, or the type that typescript is not happy about. Ideally finding a solution where you can use the Omit would be great.
Thanks in advance for the help.
Answer: The examples you gave are not equivalent:

Omit removes the property completely, so types which omit a different property have different set of properties.
Your interfaces both have same set of properties.

To make an union of exclusive options, modify your OwnProps:
type OwnProps = (Omit<Props, 'text'> & {text?: never}) | (Omit<Props, 'tKey'> & {tKey?: never});

const Component = ({text, tKey, color, height}: OwnProps) => {
  // return ...
}

Comment: Aaah. That makes sense. Thanks so much for the response!


Using a view with a superlayer as a layer mask

Question: I have a view that I want to overlay with a transparent black layer whose edges match the view exactly. The view does not clip its bounds, so subviews may be hanging off.
The obvious solution is the mask property of CALayer, but the docs say that the mask layer "must not have a superlayer" or the behavior is undefined.
I was hoping that using the presentationLayer of that view would be an effective workaround, but I don't think I fully understand what presentation layers are, as that property returns nil.
Does anyone have tips on how I could mask my transparent black layer to match the shape of the view over which it will be drawn? Thanks.
Answer: There's a less obvious solution to this that should work better than masking: a blend-mode filter, specifically source-atop. If you add your transparent layer as a sibling of the layers it's supposed to dim, and assign it the appropriate CI compositing filter, it will dim those layers without affecting anything outside of their boundaries. As a bonus, you'll get correct antialiasing at the edges, unlike the masked-overlay approach.
Here's an example. For illustrative purposes I made the dimming layer only half the height of the area it covers, but you'd of course want to make it larger.

let container = CALayer()
container.backgroundColor = NSColor.systemBlue.cgColor
container.frame = CGRect(x: 0, y: 0, width: 200, height: 200)

let dimmedRoot = CALayer()
let dimmedLayer1 = CALayer()
dimmedLayer1.frame = CGRect(x: 20, y: 20, width: 100, height: 100)
dimmedLayer1.backgroundColor = NSColor.systemGreen.cgColor
dimmedLayer1.transform = CATransform3DMakeRotation(0.3, 0, 0, 1)

let dimmedLayer2 = CALayer()
dimmedLayer2.frame = CGRect(x: 80, y: 80, width: 100, height: 100)
dimmedLayer2.backgroundColor = NSColor.systemPurple.cgColor
dimmedLayer2.transform = CATransform3DMakeRotation(-0.1, 0, 0, 1)

let dimmingLayer = CALayer()
dimmingLayer.frame = CGRect(x: 0, y: 50, width: 200, height: 100)
dimmingLayer.backgroundColor = NSColor(white: 0, alpha: 0.5).cgColor
dimmingLayer.compositingFilter = CIFilter(name: "CISourceAtopCompositing")

dimmedRoot.sublayers = [ dimmedLayer1, dimmedLayer2, dimmingLayer ]

container.addSublayer(dimmedRoot)

Comment: CA's hit testing isn't aware of compositing filters; it would be complicated and expensive to figure out whether a given set of filters ended up resulting in a transparent pixel. I think you might be able to solve that by making `dimmingLayer` a custom CALayer subclass and overriding the `containsPoint` function to return false.
Comment: Hmm.. Clicking the `dimmingLayer` where its frame does *not* intersect any sibling still results in its window receiving a `sendEvent` message. Would you consider this a bug? Presumably, a borderless window should not handle events when transparent pixels are clicked. Maybe you can file a radar?
Comment: Worth noting that I'm still seeing mismatched antialiasing when using the `compositingFilter` approach. At least, when the dimmed view is a super ellipse: https://github.com/aleclarson/react-native-super-ellipse-mask/blob/99aec94dfd19a3d835a1e27e3b6c15a299a8bd54/ios/SuperEllipseMask.m


Selected child nodes text retrieval not working properly in tree view list

Question: In my c# windows application, I have a tree view list box with checkboxes set to true. At runtime my program checks for the nodes of this tree view inside an xml file..In my application I have hidden the parent nodes checkboxes using the code shown below:
public const int TVIF_STATE = 0x8;
    public const int TVIS_STATEIMAGEMASK = 0xF000;
    public const int TV_FIRST = 0x1100;
    public const int TVM_SETITEM = TV_FIRST + 63;

    [DllImport("user32.dll")]
    static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, IntPtr wParam,
    IntPtr lParam);

    public struct TVITEM
    {
        public int mask;
        public IntPtr hItem;
        public int state;
        public int stateMask;
        [MarshalAs(UnmanagedType.LPTStr)]
        public String lpszText;
        public int cchTextMax;
        public int iImage;
        public int iSelectedImage;
        public int cChildren;
        public IntPtr lParam;

    }

    void tree_DrawNode(object sender, DrawTreeNodeEventArgs e)
    {
        if (e.Node.Level == 1)
            HideCheckBox(e.Node.Parent);
        e.DrawDefault = true;
    }

    private void HideCheckBox(TreeNode node)
    {
        TVITEM tvi = new TVITEM();
        tvi.hItem = node.Handle;
        tvi.mask = TVIF_STATE;
        tvi.stateMask = TVIS_STATEIMAGEMASK;
        tvi.state = 0;
        IntPtr lparam = Marshal.AllocHGlobal(Marshal.SizeOf(tvi));
        Marshal.StructureToPtr(tvi, lparam, false);
        SendMessage(this.taskslctor_treeview.Handle, TVM_SETITEM, IntPtr.Zero, lparam);
    }

What I now want is that I should be able to check any child nodes selected(at runtime) and if any selected I should be able to add the text of selected child node in to an array list(since multiple checkboxes can be selected) and if none selected message box appears as none selected.
Before hiding the parent checkboxes,when I tried the code below, it worked fine..But now(after hiding the parent checkboxes) this doesn't work..
public void checkednodes()
    {
        foreach (TreeNode node in taskslctor_treeview.Nodes)
        {
            if (node.Checked)
            {
                check.Add(node.Text);
                MessageBox.Show(check.ToString());
            }
        }
        if (check.Count == 0)
        {
            MessageBox.Show("Atleast one task needs to be selected!!", "Error");
        }
    }

Any immediate help would be really appreciated...since my work is on hold now..
Comment: Your `Level-1 nodes` don't have any `CheckBoxes` so you can't use the `Checked` properties, What actually do you want? You want to check the `Checked` of the child nodes? As I said, the `Level-1 nodes` **don't have** any `CheckBoxes`, the `Checked` property is useless on them.
Comment: @KingKing:So, no other way to check for any selected child nodes and get their corresponding text??
Comment: check out my answer to get the solution, if it's not, leave some comment so that I can improve the answer.
Answer: From your comment, looks like you just need to check the child nodes, not the level-1 node, so this should work for you:
//Use this to get all the Checked child nodes under a Parent node
private List<TreeNode> GetCheckedNodes(TreeNode node){
  List<TreeNode> nodes = new List<TreeNode>();
  if(node.Checked) nodes.Add(node);
  foreach(TreeNode n in node.Nodes)
    nodes.AddRange(GetCheckedNodes(n));
  return nodes;
}

 check.Clear();
 foreach (TreeNode node in taskslctor_treeview.Nodes) {
    foreach(TreeNode childNode in GetCheckedNodes(node)){
        check.Add(childNode.Text);
    }
 }
 MessageBox.Show(check.ToString());
 if (check.Count == 0){
    MessageBox.Show("Atleast one task needs to be selected!!", "Error");
 }

UPDATE
To get both Checked and Unchecked nodes, you should declare 2 List<TreeNode> which stores the nodes respectively, then you just need a recursive loop to fill the 2 lists, like this:
List<TreeNode> checkedNodes = new List<TreeNode>();
List<TreeNode> uncheckedNodes = new List<TreeNode>();
private void FillNodeLists(TreeNode node){
  if(node.Checked) checkedNodes.Add(node);
  else uncheckedNodes.Add(node);
  foreach(TreeNode n in node.Nodes)
     FillNodeLists(n);
}
//then just use the 2 Lists (such as loop through them)

Comment: Thanks..Brilliant!!!
This works fine...But I could see the text of selected checkboxes getting repeated in the arraylist.
Suppose if I have selected 3 checkboxes, then in my thinking, arraylist size should be upto3(from 0 to 2),but when I give the 4th index to print it print the same result of 0 itself.Why it is so??
Comment: @vysakh maybe you've tried it multi-times continuously, you need to clear the `check` before adding new Text each time.
Comment: Else, I would like to do as when I click a button I should be able to disable all the other checkboxes(which is not selected by the user at the runtime)..Is this possible?
Comment: @vysakh see my update for a little modified code which works better than 2 separate methods (one for getting checked nodes and one for getting unchecked nodes)
Comment: Not like this..I have asked like when I click a button, it should disable all the checkboxes which are not selected at that moment..Is this possible??
Comment: @vysakh **It's possible**, but it's too much code here. You should ask in another question such as `How to disable a TreeNode`... The difficulty is to mimic the `Disabled look of the CheckBox`, if your `TreeNode` doesn't have `CheckBox`, we can do it in a simpler way.
Comment: But I dont think that is possible since the user has to select the option needed for them...Any way I will ask as another question..

Thanks for this..


Tem como escolher a moeda que o numral.js vai formatar por paramentro

Question: Eu gostaria de saber se tem alguma maneira de escolher a moeda em que o numeral vai formatar, passando ela por parâmetro, eu nao gostaria de usar o locale, pq em algumas situações nao vai funcionar, estou usando assim pra formatar agr:
this.valueFormatted = numeral(value).format("$0,0.00")

dessa forma me retorna o valor em R$, mas eu gostaria de por exemplo passar como parametro um US$, e assim me retornar ja formatado nessa moeda
Comment: Veja como [criar uma localização](http://numeraljs.com/#locales) com *numeraljs* e veja também [esse exemplo](https://ideone.com/XLfEhA) usando os objetos nativos.
Answer: O valor por defeito é em US$. Se não quiseres usar o locale "pt-br" tens que adicionar o símbolo separadamente.
var us = numeral(1000).format("$0,0.00")
console.log(us)
var br = "R" + numeral(1000).format("$0,0.00")
console.log(br);


Trying ssh tunel at startup

Question: I need that my server (raspberry/raspbian) execute a shell command at process startup (and not at login).
It is a command to let my server "ssh tunel" to a database :
ssh -fNg -L 3307:127.0.0.1:3306 <myuser>@<remoteIP> -p 22 -i <myprivatekey>

A website hosted on my server (HTTP/apache2) uses this tunel to log to its databse.
No one is logging in to the server, I saw rc.local as a solution but I think it only works by logging in?
Answer: Try solution with crontab from here
#crontab -e
@reboot  /home/user/test.sh

Note, that if does not wotk from non-super-user set, try with sudo:
sudo crontab -e
@reboot  /home/user/test.sh

Of cause, put right command or script after @reboot

Trying ssh tunel at startup


$AM=I$, where $M$ is a rectangular matrix with full column rank, prove that $A=M^+$?

Question: $AM=I$, where $M$ is a rectangular matrix with full column rank, then $A=M^+ $(Moore-Penrose pseudoinverse)?
Comment: If that's the case, then the statement in your question is incorrect. The Moore-Penrose pseudoinverse is uniquely defined, whereas $A$ is just a left-inverse of $M$. One-sided inverses of matrices are not unique; there are multiple matrices which can play the role of $A$.
Comment: What is $M^{+}$? The [pseudo-inverse](http://en.wikipedia.org/wiki/Moore%E2%80%93Penrose_pseudoinverse)?
Comment: @EuYu: yes, MP pseudoinverse
Answer: It appears that all but one of the defining properties of the Moore-Penrose pseudo-inverse are satisfied. The missing one is
$$
(MA)^H = MA.
$$
As EuYu pointed out, $A$ is just a left-inverse.
A counter-example would be:
$$
M = \pmatrix{1 \\ 0}.
$$
Then all matrices of type
$$
A = \pmatrix{ 1 & a}
$$
satisfy your assumptions, but only for $a=0$ the product $MA$ is Hermitian, thus
$$
M^+ = \pmatrix{ 1 & 0}.
$$


Is there any way to use multiple source tables in FROM clause without using JOIN in SQL Server?

Question: I can implement one nested SELECT statement in the FROM clause like this and it works:
SELECT [table1].[ID] as [table_1_ID]
FROM
(SELECT [ID] FROM  [the_table_1] WHERE [address] like 'street5' ) as [table1]

Ideally, I wish to add multiple similar nested SELECT statement inside the FROM clause without using join, to end up something like this (the following code obviously doesn't work)
 SELECT [nested_selects].[table1].[ID]  as [table_1_ID],
        [nested_selects].[table2].[ID]  as [table_2_ID]
    FROM (
    (SELECT [ID] FROM  [the_table_1] WHERE [address] like 'street5' ) as [table1],
    (SELECT [ID] FROM  [the_table_2] WHERE [address] like 'street5' ) as [table2]
    ) as [nested_selects]

(From each source table I need only one single value. WHERE clause does that.)
I know how to do it with JOIN, but for some reason I wish to do it without JOIN.
Is such a thing possible in SQL Server?
Comment: No - if you're "combining" tables in any way, you are **joining** them - just depends on the style of the syntax you're using to express this - stick with the proper, explicit `JOIN` rather than messy, old, discouraged other ways.....
Comment: It's a style that's been **discouraged** to be used since 1992 when the SQL-92 standard was published - don't start using it - do use **proper ANSI/ISO** `JOIN`s !
Comment: What you have there is still a `JOIN`, it's called a `CROSS JOIN`. But you then seem to think that you can reference inside the subquery using 3 part naming. `[nested_selects].[table1].[ID]` would *not* reference the column `ID` in the inner subquery `table` inside the outer subquery `nested_selects`; It would try to reference the column `ID` in the object `table1` (which doesn't exist in the context of that part of the query) in the **schema** `nested_selects`. This feels like an [XY Problem](http://xyproblem.info). What is the *actual* problem you're trying to solve here?
Comment: For some scenarios, you can use `CROSS APPLY` on individually selected rows to get roughly the same effect as regular joins would. However, depending on the query this can be far less efficient than doing proper joins. People often think  "joins are slow" when the real issue is that the engine doesn't know how to perform the join efficiently due to missing (unique) indexes, out of date statistics or a skewed distribution of data. Solving those problems properly pays dividends much more than going out of your way to second-guess the engine.
Comment: @marc_s Thank you. You mean using stored procedures? Then might it be possible to do that?
I know it's not a good approach, it's just a test for one particular application. Actually to compare the query time with the JOIN method.
Comment: *And, just to mention that using 3 part naming to reference a column is due to be deprecated in SQL Server.*
Comment: @marc_s In fact that 3 part naming approach was just to clarify my question. I know it doesn't work and I don't mind about solving it this way. My question is simple if there is "any" way to solve it without JOIN.
Comment: Thank you.
My idea was that since my query result is just one row (one single value from each table) and since JOIN matches all my big tables' rows based on my chosen key, there might be any chance that picking my single desirable values from each table (using WHERE condition) can be faster in processing time. Because matching all other rows based on KEY is not useful for me.
Comment: @JeroenMostert Thank you. I didn't know that speed of JOIN query is dependent on the structure of the data. However, the reply from "allmhuran" solved my problem for now. For usual tasks I will stick to the normal `join` statement.
Answer: If you can guarantee that only a single value will be returned from the subqueries, you can nest the selects inside the select. You don't need a from at all (I have replaced your like with =):
select
   table_1_id = (SELECT [ID] FROM  [the_table_1] WHERE [address] = 'street5' ),
   table_2_id = (SELECT [ID] FROM  [the_table_2] WHERE [address] = 'street5' );

You don't technically have to enforce this guarantee. But if you happen to get more than one row back for a subquery in the select, SQL with throw a Subquery returned more than 1 value error. So, either put a unique constraint on address, or add something to each sub-select that guarantees only one row is returned.
Comment: That doesn't guarantee a single value result. There could be more than one distinct ID value for a given address: `create table t(id int, address varchar(20); insert t values (1, 'street5'), (2, 'street5'); select distinct ID from t where address = 'street5';` You can guarantee a single row with operators like `top 1`, or aggregate functions like `min()` or `max()`, or by putting a unique constraint on `address` in both tables, and always searching based on equality (not `like`)
Comment: Nope, distinct won't help you. If it's possible to return more than one `ID` value for a given `address` argument, then you need to decide how to handle that. Do you pick one at "random"? If it can ever happen, you can't assume you will get a single row back. You either have to strictly enforce it, or write the application in such a way that it can handle multiple rows being returned (ie, go back to using `from`)
Comment: Thank you. It answered my question.
For avoiding "more than 1 value" issue I just added DISTINCT and it works. `SELECT DISTINCT [ID] FROM [the_table...`
Comment: I understand your point. Here "address" is a fake name. In my data, it can rarely be not unique. For me it's enough if I prevent error by `distinct`. I think it does prevent error. Doesn't it?
Comment: Yeah, a random row/value would be fine. Then I can also write `SELECT top(1) [ID] FROM [the_table...]`. I tried it and it works.


Inspecting and clearing .NET MemoryCache. RAM keeps building up

Question: We use the .NET memorycache for big collections of data. We need the cache to sometimes clear and we use
Runtime.Caching.MemoryCache.Default.Remove("keyhere")
for that. Unfortunately i see almost no drop in the amount of RAM used by w3wp.exe, which build up to about 64GB during the day before it recycles the entire pool and everyone loses their session_ID and have to login to our application again.
I have tried running
System.Threading.Thread.Sleep(200)
GC.Collect()
GC.WaitForPendingFinalizers()

But this seems to have no effect.
Clearing the entire cache with
Runtime.Caching.MemoryCache.Default.Trim(100)

Also barely makes any difference.
I feel like a lot of collections just remain in the RAM without being actually used or referenced by any of the cache entries / keys.
How do i make sure there is no memory leak or that collections are stored multiple times? Or is there a way to find out what collections (with keys and sizes) the memorycache/w3wp.exe RAM is filled with at some point?
Im quite lost at this point.
Edit: Example of how i currently add a collection to the cache (VB.NET):
Private m_Companies_All As Core._CompanyCollection
        //Gets all Active Companies that are available within the current CustomerConfig
        Public Property Companies_All As Core._CompanyCollection Implements ICustomerConfig.Companies_All
            Get
                Dim xCacheKey As String = Me.CacheKey("Core.Companies_All")
                Dim xCacheItem As Runtime.Caching.CacheItem = Runtime.Caching.MemoryCache.Default.GetCacheItem(xCacheKey)
                If xCacheItem Is Nothing Then
                    m_Companies_All = Core._CompanyCollection.All(Core._Company.eStates.Active, Me)
                    xCacheItem = New Runtime.Caching.CacheItem(xCacheKey, m_Companies_All) // Add CacheItem to the Cache for 20m
                    Dim xCachePolicy As New Runtime.Caching.CacheItemPolicy With {.AbsoluteExpiration = DateTimeOffset.UtcNow.AddMinutes(20)}

                    //Insert into Cache
                    Runtime.Caching.MemoryCache.Default.Add(xCacheItem, xCachePolicy)
                End If

                //xItem Is Not Nothing
                m_Companies_All = xCacheItem.Value
                Return m_Companies_All
            End Get
            Set(value As Core._CompanyCollection)
                m_Companies_All = value
            End Set
        End Property

Comment: Have you profiled the memory use? https://michaelscodingspot.com/memory-profilers-principles/
Comment: `Runtime.Caching.MemoryCache.Default.Trim(100)` are you in fact using the default cache?
Comment: Have you tried adding a [CacheItemPolicy](https://learn.microsoft.com/en-us/dotnet/api/system.runtime.caching.cacheitempolicy) to automatically expire cache items?
Comment: Could you show how you add a typical big-collection entry in the cache?
Comment: I edited the original post with an Example. I am indeed using the default cache. Is this bad practice? And if so, why?
Comment: "it recycles the entire pool and everyone loses their session_ID" -> use out-of-process session state to avoid the session state being lost on a recycle event. E.g. [Out-of-Process Session State (In State Server) in ASP.NET](https://www.c-sharpcorner.com/UploadFile/2124ae/out-of-process-session-state-in-state-server-in-Asp-Net/).
Answer: Just create a class called clsMemory and write this code:
Imports System.Runtime.InteropServices

Public Class clsMemory
    <DllImport("KERNEL32.DLL", EntryPoint:="SetProcessWorkingSetSize", SetLastError:=True, CallingConvention:=CallingConvention.StdCall)> _
    Friend Shared Function SetProcessWorkingSetSize(ByVal pProcess As IntPtr, ByVal dwMinimumWorkingSetSize As Integer, ByVal dwMaximumWorkingSetSize As Integer) As Boolean
    End Function

    <DllImport("KERNEL32.DLL", EntryPoint:="GetCurrentProcess", SetLastError:=True, CallingConvention:=CallingConvention.StdCall)> _
Friend Shared Function GetCurrentProcess() As IntPtr
    End Function

    Public Sub New()
        Dim pHandle As IntPtr = GetCurrentProcess()
        SetProcessWorkingSetSize(pHandle, -1, -1)
    End Sub
End Class

Then in some Form window just add a button and write this:
 Dim MemClass As New clsMemory()
 MemClass = Nothing

Maybe it will work for you as it works for me for many years.


Elevation with OSM

Question: I've been working on a routing app for the last few months and it's near completion now. The final feature I want to add is elevation. So when when running/cycling through a path, I would also wanna add the elevation data, so I know SRTM provides elevation data..but I don't know the best way to merge this with the osm xml file I'm using.
Comment: crosspost: https://help.openstreetmap.org/questions/42412/elevation-with-osm-in-my-routing-app-best-way-to-merge-srtm-with-the-osm-xml-file
Answer: I don't know if there already is a program to do that. But if you have to implement it by yourself, do something like this:
SRTM is a grid based elevation-dataset. So you can easily look up for every node in your routingnet the nearest elevation-point on the grid (for finer data you can use interpolation).
For routing you already need to split up the ways at intersections. After that i would add a Tag to every way to measure the elevation (not only the difference between the start- and endpoint but). E.g. you can add two tags: one for the positive elevation, one for the negative (divides by the length of the way).
Btw: use PBF or O5m instead of XML. It is smaller and better to process.

Elevation with OSM


Obstruction for nonzero section of nonorientable vector bundle

Question: Suppose we have real $n$-vector bundle $p:E\to X$ over some $CW$-complex $X$. It is well-known that if $E$ is orientable (i.e. $\pi_1X$ acts on orientation of fibers trivially) then the obstruction to construct a nonzero section of $E$ is Euler class $e\in H^n(X,\mathbb Z)$.
In case $E$ is nonorientable one can define the orientation sheaf
$\newcommand{\ZZ}{\widetilde{\mathbb Z}}$ $\ZZ$ (which fiber over a point $x$ is $H^{n-1}(p^{-1}(x)\setminus0,\mathbb Z)$), and then define the obstruction to construct a nonzero section of $E$ as certain element $\newcommand{\ee}{\widetilde{e}}$ $\ee\in H^n(X,\ZZ)$.
I have difficulties with computing $\ee$ in particular cases and with some properties of $\ee$. E.g. how to understend that $\ee(TM)=\chi(M)$ (with right orientation -- how to chose this orientation?). Is there any litrature describing this characteristic class and how to work with?
Answer: I studied local coefficients and put an explonation in the article, see $\S$2.2-2.3. Here is the answer for the questions (Proposition 3):
A local orientation of the manifold and a local orientation of the fibers of its tangent bundle naturally determine one another.
In other words, for $E=TM$ we have a canonical isomorphism $\widetilde{\mathbb{Z}}_M\otimes\widetilde{\mathbb{Z}}_E\simeq\mathbb{Z}$.
Here $\widetilde{\mathbb{Z}}_E$ and $\widetilde{\mathbb{Z}}_M$ are the orientation sheafs.
So the index of a zero of any section of $TM$ is a well defined integer and does not depend of the (local) orientation.
Therefore we can
use the same strategy as in orientable case, e.g. in [Prasolov, Elements of Combinatorial and Differential Topology, chapt. 5, $\S$4.2].
Triangulate $M$ and consider a vector field which has a single zero of index $(-1)^k$ at the center of every $k$-simplex.
Then the sum of the indices of the zeroes of this vector field equals $\chi(M)$.
Note that the total index is an invariant of the vector bundle $TM$,
since it is a Poincaré dual of an obstruction class, which lays in $H^n(M;\widetilde{\mathbb{Z}}_E)$
So for any other vector field with isolated zeroes the total index still equals $\chi(M)$.


Simple confirmation popup dialog box

Question: How is it possible to create simple confirmation popup dialog boxes in Drupal 7?
I've searched a lot, but I found tons of non-working suggestions and code.
Comment: If you found solutions that do not work (for you, or not at all) please tell us which solutions you tried out, and why it didn't work for you.
Comment: Also give us a little more description of what the confirmation is for.
Answer: I got it!!!
Here's a simple 100% functioning exmple:
<code>$form['delete'] = array(
    '#type' => 'submit',
    '#value' => t('Delete'),
    '#attributes' => array('onclick' => 'if(!confirm("Really Delete?")){return false;}'),
);
</code>
I hope this helps.
Happy coding :)
Comment: You'd be better off setting a class in attributes and then picking up that class in a javascript Drupal.behaviors wrapper.
Comment: you should accept this if it solved your problem (click the check mark below the vote count)
Comment: @Chaulky I want to check it, but a popup box showed up telling me that i can accept it tomorrow but not today! Don't worry, i check it tomorrow :)
Answer: Drupal has a native confirm_form() function, but it is server side rather than Javascript based, which is what I assume you mean.
Answer: There is a sandbox module which enables this type of functionality to be built relatively easily:
https://www.drupal.org/sandbox/cmcintosh/2644004

Simple confirmation popup dialog box


No data is being display in the gridview

Question: I have created a form and added a gridview, I am trying to retrieve data from a  SQL Server database. When I run my code I don't get any error or data displayed in the gridview. Please help..
private void Form1_Load(object sender, EventArgs e)
{
    string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;

    using (SqlConnection con = new SqlConnection(CS))
    {
        con.Open();
        SqlCommand cmd = new SqlCommand("Select * from tblProductInventory", con);
        dataGridView1.DataSource = cmd.ExecuteReader();
    }
}

Comment: ?!! `dataGridView1.DataSource = cmd.ExecuteReader(); `
Comment: Take a look at [CRUD Operations using DataGridView, DataTable and TableAdapter](https://stackoverflow.com/a/36274706/3110834) or to get most out of the designer, take a look at a [Quick start to create a data application](https://stackoverflow.com/a/37824444/3110834)
Answer: string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;

SqlConnection conn = new SqlConnection(CS);
    conn.Open();
    string query = "Select * from tblProductInventory";

    SqlCommand cmd = new SqlCommand(query, conn);

    DataTable t1 = new DataTable();
    using (SqlDataAdapter a = new SqlDataAdapter(cmd))
    {
        a.Fill(t1);
    }

    dataGridView1.DataSource = t1;

Answer: Use DataAdapter to fill the DataTable.
 private void Form1_Load(object sender, EventArgs e)
        {
            DataTable dataTable= new DataTable();
            string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
            using (SqlConnection con = new SqlConnection(CS))
            {
              con.Open();
              SqlCommand cmd = new SqlCommand("Select * from tblProductInventory", con);
              SqlDataAdapter adapter = new SqlDataAdapter(cmd);
              adapter.Fill(dataTable);
              dataGridView1.DataSource = dataTable;
            }
       }

Comment: i tried with this  dataGridView1.DataBind();    ... it shows erros saying it does exist
Comment: i tried this code and getting error on this line: adapter.Fill(dataTable); InvalidOperationException
Comment: i am getting as InvalidOperationException was unhandled.. and this line is being selected adapter.Fill(dataTable);
Comment: Thanks alot. this works fine.. can you share me where did you learn this ado.net c# windowform. this will be big help if you can share
Comment: so many blogs over internet. https://msdn.microsoft.com/en-us/library/jj943772.aspx
Answer: The ExecuteReader method reads data from the given table(from database) and it builds a DataReader for you.
You cannot directly populate a datagridview with command.ExecuteReader.You need to either use a DataReader or a DataTable.
DataTable Example :
  DataTable dt = new DataTable()
  using (SqlDataAdapter ada = new SqlDataAdapter(cmd))
{
    ada.Fill(t1);
}
 MyDatagrid.Datasource = dt;

Now i would never suggest using a DataTable as it is both time consuming and hindrance to performance.Rather go with a DataReader.
DataReader Example:
''It is better to create a class to handle your data :)

  public class MyData
{
    private int age;

    public int Age
    {
        get { return age; }
        set { age = value; }
    }
    private string name;

    public string Name
    {
        get { return name; }
        set { name = value; }
    }

    private int id;

    public int Id
    {
        get { return id; }
        set { id = value; }
       }
    }

  ''Ever heard of ArrayList...It's amazing :)

  ArrayList myarray= new ArrayList();

  '''Now let's fix the main issue :)

  SqlDataReader reader = command.ExecuteReader();
  while (reader.Read())
  {
  MyData data = new MyData();
  data.Id = (int)reader[0];
  data.Name = reader[1].ToString();
  data.Age = (int)reader[2];
  myArray.Add(data);
  }
  myDataGrid.DataSource = sequence;

Comment: If you are really interested in performance dump ArrayList in favor of List


How to exactly center content within it's parent?

Question: to better understand the css box model I did some exercising today.
My goal is to exactly center the unordered list within its parent div. I know that i have to manually set a width in order to use margin 0 auto, but as you can see, the unordered list isn't perfectly centered with the paragraph text, because the li elements have a width of 80%.
Is there any chance to automatically set the width to the longest li element or do i have to try to set the width manually as close as possible to the text ending?
I hope you guys know what i try to explain here :D
And here's the code:

#wrapper {
    border: 5px solid black;
    width: 50%;
    margin: 0 auto;
}

#first {
    box-sizing: border-box;
    border: 5px solid black;
    width: 50%;
    margin: 10px auto;
    padding: 0;
    padding-top: 10px;
    padding-bottom: 10px;
    list-style: none;

}

#first li {
    border: 2px solid green;
    width: 80%;
    margin: 0 auto;
    white-space: nowrap;
}

#second {
    list-style: none;
    padding: 0;
    border: 2px solid pink;
    width: 50%;
    margin: 0 auto;
}

#second li {
    border: 2px solid blue;
    margin: 0 auto;
}

Item 1

Item 1.1

Item 2

Item 3

Retro 3 wolf moon DIY, crucifix letterpress literally ethical. Brunch ethical shabby chic mumblecore, cronut ramps cred. Single-origin coffee marfa helvetica heirloom, cold-pressed flexitarian tumblr vinyl pop-up mlkshk cronut direct trade twee brunch. Ramps beard roof party, echo park whatever bespoke direct trade seitan. Etsy small batch dreamcatcher, photo booth fashion axe tilde fixie sriracha hammock beard squid craft beer. Banh mi yr green juice, truffaut DIY crucifix chartreuse tacos hoodie readymade vinyl occupy four loko try-hard. Retro knausgaard paleo, tousled blue bottle cornhole letterpress.

Comment: please be clear (maybe its me) , you want the ul to be perfectly centered (they already are) ? or is it something else?
Comment: everything seems to be centered to me
Comment: Yes, the li elements (green boxes) are perfectly centered, but the text within like "Item 1" isn't perfectly entered to the paragraph.
Answer: I am quite confident that the following is the best possible way to vertically center ANYTHING. That means that you don't need to care about the parent's size, the child's size, or anything at all. Seriously.
Fiddle: http://jsfiddle.net/h1zd0z5c/5/
The major trick here is: Make the child display: inline-block!!!!!
As you'll see this will facilitate centering along both axes.
There's 2 different aspects to it:
1) Horizontal centering
Super easy! Because the child is inline-block, all we need to do is set text-align: center on the parent.
2) Vertical centering
Here's the tricky part. We'll use vertical-align: middle on the child to accomplish this. It sounds like it should do exactly what we want, doesn't it? There's a gotcha here however, and it's one of the most poorly understood aspects of css that I regularly encounter: vertical-align is not relative to the parent's size - it's relative to the tallest sibling!
So the hack around this is to ensure that the child element ALWAYS has a sibling that is height: 100% so that the height of the tallest sibling is the same as the height of the parent. Personally, I find that the most elegant way to accomplish this is to take advantage of the before pseudo-selector (https://developer.mozilla.org/en-US/docs/Web/CSS/%3A%3Abefore) to insert 100% height content in the parent.
Check out the fiddle - it leaves you with 2 highly reusable classes that just need to be applied to parent and child element; the .centered-content, and .centered-content > .content elements.
Note
You asked to center a ul element which is no problem, but just note that in the example I decided to remove the ul's padding - this is because ul elements have a decent bit of left-padding which causes them to appear as if they aren't centered even when they really are.
Comment: Worked for me. And thanks for explaining vertical-align, might need that in the future :)
Answer: Use text-align property. just added it to css of  #first li

#wrapper {
    border: 5px solid black;
    width: 50%;
    margin: 0 auto;
}

#first {
    box-sizing: border-box;
    border: 5px solid black;
    width: 50%;
    margin: 10px auto;
    padding: 0;
    padding-top: 10px;
    padding-bottom: 10px;
    list-style: none;

}

#first li {
    border: 2px solid green;
    width: 80%;
    margin: 0 auto;
    white-space: nowrap;
  text-align: center;
}

#second {
    list-style: none;
    padding: 0;
    border: 2px solid pink;
    width: 50%;
    margin: 0 auto;
}

#second li {
    border: 2px solid blue;
    margin: 0 auto;
}

Item 1

Item 1.1

Item 2

Item 3

Retro 3 wolf moon DIY, crucifix letterpress literally ethical. Brunch ethical shabby chic mumblecore, cronut ramps cred. Single-origin coffee marfa helvetica heirloom, cold-pressed flexitarian tumblr vinyl pop-up mlkshk cronut direct trade twee brunch. Ramps beard roof party, echo park whatever bespoke direct trade seitan. Etsy small batch dreamcatcher, photo booth fashion axe tilde fixie sriracha hammock beard squid craft beer. Banh mi yr green juice, truffaut DIY crucifix chartreuse tacos hoodie readymade vinyl occupy four loko try-hard. Retro knausgaard paleo, tousled blue bottle cornhole letterpress.


Using screws for guitar pickup magnets

Question: I am trying to make a single coil guitar pickup. The problem is, I can't find any cylinder-shaped ceramic or alnico magnets in my country.
Can I put screws (or another conductive material) where the magnets are supposed to be and somehow put a little magnet touching the screws to make it work? If I can, how would I do that?
Plus, the pole pieces for humbuckers are pretty expensive here- so can I use screws instead of those?
Thanks
Comment: The word 'screw' is a little ambiguous. To a lot of us it means a woodscrew, which is tapered by design. As such, it wouldn't produce a similar magnetic effect at each end. A bolt, or setscrew, with parallel sides, would be preferrable. Or even a nail, with the head and point removed.
Comment: It doesn't have to be a screw. It can be anything I can easily (and preferably cheaply) find.
Answer: If you are interested in making your own pickups for guitar, you can find all the materials needed online along with instructions on how to magnetize the pole pieces and wire for winding the coils. Allparts and Stewart Macdonald are in the U.S., but I'm pretty sure they can ship their stock parts world wide. You might see what they have to offer and decide for yourself if it interests you.
Answer: Engineering info.
As stated in Wikipedia,

Many electromagnetic coils have a magnetic core, a piece of
ferromagnetic material like iron in the center to increase the
magnetic field.The current through the coil magnetizes the iron, and
the field of the magnetized material adds to the field produced by the
wire. This is called a ferromagnetic-core or iron-core coil. A
ferromagnetic core can increase the magnetic field and inductance of a
coil by hundreds or thousands of times over what it would be without
the core. A ferrite core coil is a variety of coil with a core made of
ferrite, a ferrimagnetic ceramic compound.

Choice of core material thus affects the magnitude of the signal created for a given string vibration amplitude (not to mention some dependence on frequency).  Then there's the "saturation" effect, where some materials reach their max possible magnetic field strength.
All this is to say that pretty much any metal that will sustain the magnetic field caused by interaction between the string's motion and the magnet (full core or button on top) and thus generate the desired AC electrical signal in the coil.  Sound quality and gain and the like depend on how serious you want to get into the theory and practice of E&M .
If you go with some hardware-store screws, definitely pick ones which a magnet can latch onto. There might be some stainless-types out there which could be problematic.
edit
There's a decent introduction to coil & core behavior, with pictures, at electronics-tutorials.
Comment: So in theory, it should work well with the appropriate metal, but I'm guessing it will not be as good as putting magnets for a single-coil pickup. And i think it would be better to do less wrappings since the magnetic field is definitely weaker.

Using screws for guitar pickup magnets