How to include SVG in a block markup?

Question: I'm building a custom markup for a block but the SVG part is not rendered. Everything else is rendered correctly.
class HomeSocial extends BlockBase
{

    /**
     * {@inheritdoc}
     */
    public function build()
    {
        $markup = '
';
        $markup .= '<svg width="26.383960" height="21.428597" viewBox="0.736608 -42.857194 26.383960 21.428597"
xmlns="http://www.w3.org/2000/svg">
<path d="M27.120568 -40.312548C26.149585 -39.894021 25.094896 -39.592681 24.006725 -39.475493C25.128378 -40.145137 25.982174 -41.199826 26.383960 -42.455408C25.346012 -41.835987 24.174136 -41.383978 22.952036 -41.149603C21.964312 -42.204291 20.558060 -42.857194 19.001139 -42.857194C16.004483 -42.857194 13.593766 -40.429736 13.593766 -37.449821C13.593766 -37.031294 13.643989 -36.612767 13.727695 -36.210981C9.241082 -36.445356 5.239962 -38.588216 2.578128 -41.869470C2.109378 -41.065897 1.841520 -40.145137 1.841520 -39.140672C1.841520 -37.265669 2.795762 -35.608301 4.252237 -34.637318C3.364959 -34.670800 2.527905 -34.921917 1.808038 -35.323703C1.808038 -35.306962 1.808038 -35.273480 1.808038 -35.256738C1.808038 -32.628387 3.666299 -30.452045 6.143981 -29.949812C5.691971 -29.832625 5.206479 -29.765660 4.720988 -29.765660C4.369425 -29.765660 4.034603 -29.799143 3.699781 -29.849366C4.386166 -27.706506 6.378356 -26.149585 8.755591 -26.099361C6.897330 -24.642887 4.570318 -23.789091 2.042413 -23.789091C1.590404 -23.789091 1.171876 -23.805832 0.736608 -23.856055C3.130584 -22.315875 5.976570 -21.428597 9.040189 -21.428597C18.984398 -21.428597 24.425252 -29.665214 24.425252 -36.813660C24.425252 -37.048035 24.425252 -37.282411 24.408511 -37.516786C25.463200 -38.286876 26.383960 -39.241118 27.120568 -40.312548ZM27.120568 -40.312548"></path></svg>';
        $markup .= '
';

        return array(
            '#markup' => $markup,
            '#cache' => array(
                'max-age' => 3600,
            ),
        );
    }

Do I neet to allow SVG tag somewhere in the configuration?
Comment: Use inline_template instead of markup, or better a theme function.
Answer: Use inline_template instead of markup, or a theme function (as suggested by Ivan Jaros in a comment also).
Refer to class InlineTemplate for way more details. Here is a partial quote of it:

Provides a render element where the user supplies an in-line Twig template.
Properties:

#template: The inline Twig template used to render the element.
#context: (array) The variables to substitute into the Twig template. Each variable may be a string or a render array.

Usage example:
$build['hello']  = [
  '#type' => 'inline_template',
  '#template' => "{% trans %} Hello {% endtrans %} {{name}}",
  '#context' => [
    'name' => $name,
  ]
];

Comment: Yes. This should be accepted as correct answer.

I am having issues adding a block code to a comment. But context is not required. You can just have the svg tag in the template value.
Answer: Drupal 8 has moved away from using #markup like in your example. While you still can use it there are some limitations. Certain attributes can't be set and certain tags can't be used.
Generally if you want to follow best practice, you should make theme functions and template file, in your example it's pretty simple.
PHP code in module
/**
 * Implements hook_theme().
 */
function hook_theme() {
  return array(
    'svg' => array(
      'variables' => array('svg_attibutes' => [], 'path_attributes' => []),
    ),
  );
}

Add the svg.html.twig template file in the templates folder:

;
  <svg {{ svg_attributes }}>
    <path {{ path_attributes }}></path>
  </svg>

Doing the above, your render array would become
$render = [
  '#theme' => 'svg',
  '#svg_attributes' => [...],
  '#path_attributes' => [...],
];

Doing it this way also has the advantage that you can in theme debug can see where markup is coming from, you can make theme suggestions or invoke them directly fx using
$render = [
  '#theme' => 'svg__awesome',
  ...

While the initial work is a bit more, it gives a lot of readability and help you working in good way, where markup and logic is separated.
Answer: You have to use the Drupal\Core\Render\Markup::create() method. In your case, the render array should become:
return array(
    '#markup' => \Drupal\Core\Render\Markup::create($markup),
    '#cache' => array(
        'max-age' => 3600,
    ),
);

Comment: This worked for me when rendering SVGs with a #radios element. I overrode template_preprocess_form_element_label() and wrapped the `title` key: `$variables['title']['#markup'] = \Drupal\Core\Render\Markup::create($variables['title']['#markup']);`
Answer: A convenient and simple way is yo use the include() function in your Twig Block template:
  {% include('themes/path/to/your/logo.svg') %}

How to include SVG in a block markup?


iOS - What exactly does allKeys: return in an NSArray, and how to alphabetize?

Question: I'm trying to create an array of the keys from an NSMutableDictionary, and then sort it alphabetically.  What I've got right now is:
_currentItemsArray = (NSMutableArray *)[_currentItemsDict allKeys];
[_currentItemsArray sortUsingSelector:@selector(caseInsensitiveCompare:)];

but it's throwing an exception.  Specifically:
-[__NSArrayI sortUsingSelector:]: unrecognized selector sent to instance 0x1e54ddb0

My research is telling me that that means the values of _currentItemsArray aren't NSString's.  But what else would they be, when the keys of the source NSMutableDictionary are NSString's?
And either way, is this the best way to sort an allKeys array alphabetically?
Comment: You can't just cast something to another class and expect it to magically convert.  No programming language works like that.
Comment: @SrikarAppal Read the code, that's not the problem.
Answer: The correct method for a NSArray is sortedArrayUsingSelector:.
NSArray *sortedKeys = [_currentItemsArray sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)];

Answer: NSArray *sortedKeys = [[dict allKeys] sortedArrayUsingSelector: @selector(caseInsensitiveCompare:)];

NSLog("%@", sortedKeys);

Answer: One does not simply cast an NSArray pointer to NSMutableArray pointer. Your currentItemsArray may be an NSMutableArray, but no amount of (NSMutableArray *) casts can make NSArray mutable. You'll have to use NSArray methods:
NSArray *array =  [[_currentItemsDict allKeys] sortedArrayUsingSelector:@selector(whatever)];

Comment: Thank you!  And an upvote for the Boromir reference.
Comment: Btw, I fully trust that what you say is true, but can you clarify something for me: the reason I tried to cast it that way is because I got an "assigning NSMutableArray from NSArray" warning, but when I put the `(NSMutableArray *)` cast in front just on a lark, the warning went away.  Is that an XCode issue, not being smart enough to recognize that I'm attempting something impossible?  Or is there some other reason why that would make the warning go away?  I'm only asking so I can avoid doing similarly pointless things in the future...
Comment: You'll just have to pay more attention. If AB is subclass of A, then all AB may be treated as A, but not all A can be treated as AB.
Answer: -[NSMutableDictionary allKeys] returns an NSArray. The order of the items is not predetermined but it usually is alphabetical. Anyway, since the return value is an NSArray you cannot use -sortUsingSelector as this method is only available on NSMutableArrays. You should use another method like -[NSArray sortedArrayUsingSelector:] instead.


Add result to view with webservice

Question: In my drupal 8 Commerce, I have a view with product and filter criteria.
And I want to know, if it's possible to add result to this view with a result of webservice.
I try to inspect $view->result in hook_views_pre_render
and the result is view\ResultRow with entity Product

Is it possible to add results without creating an entity and from an webservice just read information like this schema:
/myviewurl

Product 1 (from drupal db)
Product 2 (from drupal db)
Product 3 (from drupal db)
Product 4 (from webservice not in db)
Product 5 (from webservice not in db)
Product 6 (from webservice not in db)
Answer: Try hook_views_pre_render hook to alter view result if only you need to display result. You just need to prepare the webservice result as per hook_views_pre_render result data.

Add result to view with webservice


Accidentally messed up /etc/passwd

Question: I accidentally modified the default shell program /bin/bash for my user in /etc/passwd. I didn't set a root password in my ubuntu server installation.
Now I can't even login. Is there anything I can do?
Answer: Or .. start your box in single user mode and modify your passwd file - ubuntu single user mode link.
Answer: Boot up into a live disk, mount the partition and fix /etc/passwd :)

Accidentally messed up /etc/passwd


how to add the text which the user enters in the edit text box into the listview?

Question: I have created an layout which contains the listview. I have added a button to it, which on clicked gives an alert dialogue box with an edit text box and two options OK and CANCEL.
I want to add the item which the user enters in the edit text box into the listview. Can any one help me out how to add it?
this is the code which shows me the Alert dialogue box, the value has to be shown as the items of the listview.
<code> if(v.getId() == addbtn.getId())
    {
    AlertDialog.Builder alert = new AlertDialog.Builder(this);

    alert.setTitle("Add new location");

    // Set an EditText view to get user input
    final EditText input = new EditText(this);
    alert.setView(input);

    alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int whichButton) {
    Editable value = input.getText();
    // Do something with value!
    }
    });

    alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int whichButton) {
    // Canceled.
    }
    });

    alert.show();

    }
</code>
Answer: You should use an ArrayAdapter and bind it to your ListView. When the user enters a new value, add it to the ArrayAdapter and call mListView.notifyDataSetChanged().
There is a good example of setting up a ListView and ArrayAdapter here http://anujarosha.wordpress.com/2011/11/17/how-to-create-a-listview-using-arrayadapter-in-android/


Error:(72) error: junk after document element

Question: I'm reading this code and I'm still don't know how to fix it.
I can't check the app, cuz it doesn't work cuz of those mistakes.
I have tried to reread the whole code my CTRL+ALT+L and it reformated the code, but the errors are still here.
I added a comments where i see the errors - I have 3 errors. Into message I'm getting comment: Error:(72) error: junk after document element.
That would be nice, if you can help me. Thx
<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/music"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:text="@string/this_is_main_menu"
        android:textSize="20sp"
        android:textStyle="bold" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:baselineAligned="false"
        android:orientation="horizontal" />

    <RelativeLayout
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:orientation="vertical"
        tools:ignore="NestedWeights" />

    <android.support.v7.widget.CardView
        android:id="@+id/menuPlayer"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_margin="8dp"
        app:cardCornerRadius="2dp"
        app:cardElevation="8dp">

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <ImageView
                android:layout_width="match_parent"
                android:layout_height="0dp"
                android:layout_marginTop="16dp"
                android:layout_weight="1"
                android:src="@drawable/ic_headset_black_24dp" />
            <TextView
                style="@style/menuItemText"
                android:layout_width="match_parent"
                android:layout_height="0dp"
                android:layout_weight="1"
                android:gravity="center"
                android:text="@string/player"
                android:textAlignment="center"
                android:textStyle="bold" />
        </RelativeLayout>

    </android.support.v7.widget.CardView>

</RelativeLayout>

    <LinearLayout
    android:layout_width="0dp"
    android:layout_height="match_parent"
    android:layout_weight="1"
    android:orientation="vertical">

    <android.support.v7.widget.CardView
    android:id="@+id/menuPlaylists"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_margin="8dp"
    app:cardCornerRadius="2dp"
    app:cardElevation="8dp">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <ImageView
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_marginTop="16dp"
            android:src="@drawable/ic_playlist_play_black_24dp" />

        <TextView
            style="@style/menuItemText"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:gravity="center_vertical"
            android:text="@string/playlist"
            android:textAlignment="center"
            android:textStyle="bold" />

    </RelativeLayout>

</android.support.v7.widget.CardView>

</LinearLayout>

<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:baselineAligned="false"
android:orientation="horizontal">

<LinearLayout
    android:layout_width="0dp"
    android:layout_height="match_parent"
    android:layout_weight="1"
    android:orientation="vertical"
    tools:ignore="NestedWeights">

    <android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/menuAlbums"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_margin="8dp"
        app:cardCornerRadius="2dp"
        app:cardElevation="8dp" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <ImageView
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_marginTop="16dp"
            android:layout_weight="1"
            android:src="@drawable/ic_library_music_black_24dp" />

        <TextView
            style="@style/menuItemText"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1"
            android:gravity="center_vertical"
            android:text="@string/albums"
            android:textAlignment="center"
            android:textStyle="bold" />
    </LinearLayout>

</LinearLayout>

</LinearLayout>

<LinearLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:orientation="vertical"
tools:ignore="ExtraText">

<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/menu"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_margin="8dp"
    app:cardCornerRadius="2dp"
    app:cardElevation="8dp" />

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_marginTop="16dp"
        android:layout_weight="1"
        android:src="@drawable/ic_settings_black_24dp" />

    <TextView
        style="@style/menuItemText"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:gravity="center_vertical"
        android:text="@string/frame"
        android:textAlignment="center"
        android:textStyle="bold" />
</LinearLayout>

</LinearLayout>

    </RelativeLayout>

Answer: Note: There can be multiple causes of this, so I try addressing them all to handle different cases, since there are multiple reasons why there's a problem.

Case 1: Multiple roots in a singel file by intent
For one, you define multiple document root tags in the same fine. Split them into multiple files, or use a single root. This means this isn't allowed:
somefile.xml:
<tag>...</tag>
<tag>...</tag>
<tag>...</tag>

It has to be:
<tag>
    <tag>...</tag>
    <tag>...</tag>
</tag>

Case 2: Single layout
However: Your source seems to have an unwanted tag closing. After you close the CardView:
<RelativeLayout (first tag>
....

    </android.support.v7.widget.CardView>

</RelativeLayout>
<Another layout>

Remove the </RelativeLayout> tag; it exists at the end of the file, which is why it's marked as an unexpected token. It doesn't close anything because the layout it should close already is closed. Remove the early closing of the RelativeLayout and it'll fix the other issues too, as they come as a result of the early tag closing
Answer: Try to remove the  below line which is on line number 70:
</RelativeLayout>

which is above your first error  and then try it.


Thread 1: signal SIGABRT on button clicked

Question: I am implementing a logout button in my project.
I attached it by using the touch up inside event. When logout clicked, the user is redirected to login view controller but for some strange reason the application dies after a few seconds with the following error. Thread 1: signal SIGABRT.
Logout clicked: (all this method does is erasing the username and redirecting to "Login" view controller)
<code>-(IBAction)logout {

[[NSUserDefaults standardUserDefaults] setObject:nil forKey:@"User"];

[self dismissViewControllerAnimated:NO completion:nil];

UIViewController * vc = [self.storyboard instantiateViewControllerWithIdentifier:@"Login"];
[self presentViewController:vc animated:NO completion:nil];

}
</code>
Login page has nothing when it loads.
Answer: Your signature for logout is all wrong.  You should change the message line to:
<code>-(IBAction) logout:(id) sender {
</code>
You can ignore sender if you like.  Your touch up inside is expecting to send a message to a method which has a parameter, and yours doesn't.  That's why you're crashing.
Answer: Try changing your code with this:
<code>-(IBAction)logout {

    [[NSUserDefaults standardUserDefaults] setObject:nil forKey:@"User"];

    [self dismissViewControllerAnimated:NO completion:^{
        UIViewController * vc = [self.storyboard instantiateViewControllerWithIdentifier:@"Login"];
        [self presentViewController:vc animated:NO completion:nil];
    }];

}
</code>
Probably you are showing the new viewController before the old one has been dismissed, even if you do that not animated.
Comment: The problem was as Owen mentioned. I had to add the :(id)sender. As the touch up inside expects to send a parameter to a method. My method did not have a parameter, therefore it failed.


How can I use POSIX ACLs on an NFSv4 mount in Linux?

Question: I have recently transitioned a Linux fileserver from offering only NFS v3 to also offering NFS v4.  All of our clients happily started using NFS v4 automatically.  Unfortunately, this effectively broke ACL management for the handful of users that use them, since the POSIX tools they're used to no longer work.  (Worse, ls no longer indicates files that have ACLs, so they're more hidden than they used to be.)
I'm getting pushback from the users who don't want to learn new tools just because our storage system changed software (plus the fileserver is actually storing the ACLs on disk as POSIX ACLs, so the transition to NFSv4 ACLs feels a little silly, what with every system involved running some variant of Linux).
I can just force the clients to use NFS v3 for the users who don't want to learn NFSv4 ACLs, but is there a way to run NFS v4 clients but have the POSIX ACL programs work?  Preferably without straying too far from the distribution's standard repositories.
The clients are running Fedora.  (Currently they're on Fedora 23, but they get upgraded a lot, what with Fedora doing releases every six months or so.)  The server is running Scientific Linux 7 and ZFS on Linux.
Answer: There are patches for libacl to do some kind of mapping between nfs4 and Posix ACLs. They seem to be unmaintained. I've never tried it.
http://www.citi.umich.edu/projects/nfsv4/linux/acl-patches/
http://www.citi.umich.edu/projects/nfsv4/linux/using-acls.html
https://datatracker.ietf.org/doc/html/draft-ietf-nfsv4-acl-mapping-05
Comment: Ooof.  That's a good answer, but 2007 is *ancient* and I'd have to maintain my own fork of libacl.  If that's my only option, the recalcitrant users get to live with NFS v3 mounts.  :)
Comment: Maybe there were/are distros using these patches? You could recommend these ones to your users ;)  Or experienced users may try these patches on their own local libacl  + coreutils build and give you feedback :)


Tonal Compatibility

Question: Considering: that finding the Ionian Mode's Phrygian location, suggests counting back 3 degrees from C'- Bb, Ab, 'G', starting from 'G'- play the 'Eb' Scale.
The Answer', I have been serching for the last 18 months is: IF' I am playing the Eb' Scale from G;, and others, are playing the Ionian 3rd, E'Phrygian, is the Tonality between the 2 compatible?
Comment: The phrase "the Ionian mode's Phrygian location" doesn't make any sense. Ionian is one mode, Phrygian is a different mode. You can have C Ionian, D Ionian, F# Ionian, etc. you can have C Phrygian, D Phrygian, F# Phrygian. Every Ionian scale shares pitches with some Phrygian (and Dorian, and Lydian, etc) scale, but you can't have the "Phrygian of the Ionian". E Phrygian has the same notes as C Ionian, D Ionian has the same notes as F# Phrygian. The tonic note of any Phrygian scale will always have an Ionian scale with a tonic a major third lower that uses the same pitches.
Answer: No. G Phrygian uses all the notes from the parent scale of Eb. E Phrygian uses the notes from the parent scale C. They are not the same set of notes. I suspect you meant:
'If I play the Eb scale, and start on G (the 3rd, therefore G Phrygian), if others are playing the Ionian of Eb, are we all using the same notes?' Then, since Eb is the parent, then - yes!
Eb Ionian = F Dorian = G Phrygian = Ab Lydian = Bb Mixolydian = C Aeolian = D Locrian. As far as notes contained therein are concerned.
Comment: @DonnGoodside The thing to remember about modes is that not only are the notes you're playing important but the tonal center. so while you are playing the same notes in Eb Ionian and G Phrygian, "home" feels different. If we were just concerned about what notes we were playing and not the tonal center, there would be no real need for modes.

Tonal Compatibility


Duplicates in an array

Question: I have an array that looks like this:
$array[1]['first__name'] = 'john';
$array[1]['last_name']   = 'anderson';
$array[1]['sum']         = 100;

$array[2]['first__name'] = 'john';
$array[2]['last_name']   = 'anderson';
$array[2]['sum']         = 200;

$array[3]['first__name'] = 'julie';
$array[3]['last_name']   = 'Scott';
$array[3]['sum']         = 300;

$array[4]['first__name'] = 'Eva';
$array[4]['last_name']   = 'Scott';
$array[4]['sum']         = 300;

$array[5]['first__name'] = 'john';
$array[5]['last_name']   = 'anderson';
$array[5]['sum']         = 300;

I want to compare the values of sum where first_name = john, last_name = anderson and save the highest. The rest I would like to remove.
Comment: Count your sum (array_walk()?) and then apply [array_unique()](http://de3.php.net/manual/en/function.array-unique.php)?
Comment: you need to walk your array and compare it... but maybe you can avoid this situation on step where you add it? you can recursively search array for array(first_name,last_name) , and if sum is bigger, just override the sum?
Answer: $highest = 0;
foreach ($array as $v){
  if ($v['first_name'] == 'john' && $v['last_name'] == 'anderson'){
    if ($v['sum'] > $highest){$highest = $v['sum'];
  }
}
echo $highest;

Answer: How about this?
$scores = array();
foreach( $array as $row ) {
    $name = $row['first_name'] . ' ' . $row['last_name'];
    if( !isset( $scores[$name] ) || ( $row['sum'] > $scores[$name] ) ) {
        $scores[$name] = $row['sum'];
    }
}

Answer: This will also work :)
$array[1]['first_name'] = 'john';
$array[1]['last_name']   = 'anderson';
$array[1]['sum']         = 100;

$array[2]['first_name'] = 'john';
$array[2]['last_name']   = 'anderson';
$array[2]['sum']         = 300;

$array[3]['first_name'] = 'julie';
$array[3]['last_name']   = 'Scott';
$array[3]['sum']         = 300;

$array[4]['first_name'] = 'Eva';
$array[4]['last_name']   = 'Scott';
$array[4]['sum']         = 300;

$array[5]['first_name'] = 'john';
$array[5]['last_name']   = 'anderson';
$array[5]['sum']         = 200;

$cond = array('first_name' => 'john', 'last_name' => 'anderson');

array_walk($array, function($node, $key) use ($cond, &$array) {
    foreach($cond as $k => $v) {
        if(!isset($node[$k]) || $node[$k] != $v) {
            unset($array[$key]);
        }
    }
});
uasort($array, function($a, $b){
    return intval($a['sum']) - intval($b['sum']);
});

$result = end($array);

Duplicates in an array


Read a text file and add to a list


Difference between home-use and office-use laptops

Question: I'm looking for some ammunition for upper management.
One of the things I get asked on a regular basis is...
"How come the laptops we buy for the office are so expensive when I can get a cheap  from Best Buy."
So some of my standard answers are;

Metal hinges
Durable case
Outstanding customer support
3 year warranty (standard, not purchased extra)

What else is there?
Comment: There is a large, visible difference between a commercial oven and a home oven, even to a lay-person.  The PC industry try hard to say "everything has an Intel CPU and Windows", so the differences are far less obvious.
Comment: Does this happen in other industries? Does a restaurant owner balk at a $10,000 commercial oven when you can get a consumer oven for $500 at Sears?
Comment: I guess fundamentally the problem is that consumer gear doesn't list "breaks easily" and "doesn't exactly work right" on the list of features and benefits.
Comment: I work in data mining, and we purchase gaming laptops, as they let us analyze datasets on fast GPUs, have crazy max RAM, and big 1080p screens.
Answer: My thoughts ...
1- Durability and serviceability -- the "business class" systems are designed and engineered to be standardized and easily serviced.
2- Standard components and designs -- a line of machines are similar, so the techs don't have to figure out a bunch of systems.  This is reliably worth several hundred dollars per machine over it's life.
3- Preloaded OS - XP/Vista Pro is required to join a domain, but most consumer laptops have XP/Vista home.  There is $100 of the difference right there.
4- Warranty and Support differences between consumer and business.
If they insist, I suggest you buy a Dell consumer model and a similar Dell business model and show the differences, or take some pictures and make a report.
EDIT - someone downvoted .. how about a comment to indicate why?  Corrections and differing viewpoints are welcomed!
Comment: I agree with points 1, 2, and 4.  Preloaded OS's and office software (at least in larger environments) don't really matter as MS EA agreements are usually in effect.
Comment: Dayton -- the MS agreements aren't available for small companies.  We have < 200 PCs; I wish I could get an EA instead of having to keep track!  And I get this very question every few months from come busybody in Accounting or a department manager.
Comment: Add MS Office to this list: the consumer price won't include it.
Comment: Point taken.  However, even in smaller offices, I usually don't purchase office with the PC as I'm usually transferring licenses.  MS does have some newer licensing programs though that can help out with the < 1000 desktop/user count orgs.  (And no I'm not getting paid by MS to say that.)
Comment: some people are just pricks about downvoting, rise above the - besides I just upvoted you so they're down 2, you're up 8 :)
Comment: Picked this one as the answer as it has the most votes.  Lots of other great reasons out there.  Thanks for the help everyone.
Comment: @Chopper3 - Thanks!  Nothing personal taken from the downvote, I would just like to know why .. the downvoter thinks I am missing something, and the point of the site is to exchange info
Answer: In addition to the specific reasons, I find that drawing an analogy to a different business unit helps to put these scary technology concepts into a comfortable framework.

Question - I can buy TurboTax for $50 to do my taxes, why do we need to pay an entire department to do the same thing for the company?
Answer - because it's more complicated.

IT pays more money for a laptop than Joe User at Best Buy because your IT department has different/bigger priorities (which the other answers have enumerated quite well).
It may also help to assure them that if you could meet business need by buying $500 laptops for everyone, you would be thrilled to do so, but it would just be too expensive in the long run.
Answer: (this is partially covered in The Practice of System and Network Administration's chapter on desktop machines)
Basically, consumer laptops use the cheapest video chip, sound processor, etc. that the vendor can find that week. A business-class laptop changes chipsets once or twice a year, on a schedule that is predictable. This gives you the ability to certify your applications with the new chipsets.
The business-class laptops are also significantly faster, more powerful, and more durable. You can buy the consumer laptops, but you'll spend more time listening to customers whine about how slow they are and managers will hear excuses like, "the project is late but it's my laptop's fault".
The real problem here is that the management people that ask this question aren't involved enough to understand these things.  As Dilbert's boss once said, "Anything I don't understand must be easy to do."   You might want to build up a comparison chart with them and make it an apples-to-apples comparison: show that the video card will be slower (in management terms: MS-Excel spreadsheets will display updates and scroll slower), that repair costs are going to be high (maybe you'll have to stock a "loaner laptop" that sits idle most of the time), etc.  Let them be involved in building up the comparison chart.  Heck, if it turns out that the differences are things that they don't care about, you might switch to the cheaper equipment!
More importantly: if you do this project with a manager, they'll be able to explain to the other managers in their language what the result is.  That may be more valuable than anything else.
Comment: +1 for manager-to-manager translation
Answer: One thing would be "crapware" that comes on almost every home-class laptop or PC.
This is used to subsidize the cost of consumer grade laptops, but most business class laptops would not include this stuff (since businesses don't want to put up with having to remove it all) and are subsequently going to cost a bit more.
Answer: I like to put it to the management like this.
A laptop you buy at Best Buy or another store for home use is made to be used continuously for at most 2-3 hours, and on occasion, not everyday for 6-9 hours.  The materials that a home-use laptop is made out of show its purpose is for home use, as they are made out of plastic, and cheap metal.
A laptop made for business use, contains durable plastic, and sometimes plastic/metal compounds to increase it's ruggedness.  The keyboards are manufactured in a more durable way, the way the laptop dissapates heat is more reliable, and ensures that it lasts longer.  The hinges have much more care given to them.  Business class laptops are also serviceable.  That is, the memory, hard drive, and other important system components are accessible to your technical support department should you need an upgrade.  Also, the warranty on a business class laptop is much better.
Remember to remind them that there is much more to a laptop than CPU, Memory and Hard Drive, such as the choice in motherboards, chipsets, and manufacturing processes.  The reason they're more expensive is because most intelligent businessmen will not put up with the crap that gets put in stores like Best-Buy, because the ROI is just that terrible.
Answer:
Standardize equipment
(that way you don't have to be supporting XYZ manufacturers and models).  This would lower their support cost in the long run.  This is a big one for our company.
Warranty and service agreements
These might end-up being cheaper with and enterprise solution (depending on the number of clients and sector).  If you're in the Education sector, you most-likely will receive educational pricing on your purchases.
Customer Support
We have a representative we contact every single time we need to make a purchase, have questions, or need to arrange a return of some kind.  You will NEVER get that with a 'consumer-class' purchase.
Answer: I would expect he's comparing the cheapest lowest spec machine at Best Buy, that is also on a limited time special offer to a higher spec'd machine that you require for the office. For the same machine you buy in the office, it's probably still going to be a similar price at Best Buy. This is on top of the other arguments such as support, standardization, reliability.
Answer:
availability of docking station that can handle two independent displays [ it's usually both docking station and graphics card. to be precise ].
standarisation
Comment: LOVE standardization.  I'm super lazy and hate to spend all day creating a new image.
Answer: More stable hardware - we buy mostly HPs, and for any model, they keep the specs stable for about a year.  We've never bought consumer HPs, but when were buying Dells and went with the cheaper Inspirons, the hardware specs would change every month, which makes imaging a hassle.
Answer: Buy your laptops and machines from someone like Dell and chances are you can run a standard build, improving support, security and downtime as if something goes wrong software-wise you can rebuild the machine in an hour or so, not a day.
Answer: I would say warranty, support, and detailed specs.  I guess you could say you're "paying a premium" to be able to fully customize the machine and know exactly what's in the box.  Standardization is definitely one of the major reasons we buy direct from Dell.
Answer: Warranty and spare parts for business laptops (system boards, RAM, hard drives) are kept in stock by manufacturers a lot longer for business laptops.
IBM will still sell you a part for a T20 series laptop, even if they have to have it shipped from another country.  From a consumer laptop from that timeframe, you'd be looking at getting one off eBay and hoping you could steal a part.
Answer: Some differences:

Best Buy laptops comes with XP Home/Vista Home.  Business Laptops come with XP Pro/Vista Business.  That's $100 right there.
The Best Buy prices doesn't include MS Office, or if it does it's only Office Basic (another $100-150)
Business laptop prices usually include a better warranty.
Answer: Here's a big difference I see.  If we have a Dell business laptop that breaks, we call Dell, and they come to us to fix it usually within the same day.  If we have a laptop from Best Buy, we have to go to them to fix it, they can't fix it the same day, and it's sent off for 2 weeks.  The data on the hard drive will usually be wiped as well.
Answer: 1) Longer more stable lifecycle e.g.:
2)Firmware and drivers are maintained longer
3)You typically wont have to build a new image for the same model over the lifetime of the model, even if different components are used between later and earlier versions the different components will often be driver compatable
4)The manufacturer keeps spares for the projected life of the model. A lot of the time with a consumer model, this is not the case, so if your laptop goes tits up and there are no spares but you still have warranty you may end up with different components or even a different but "equivalent" laptop as a replacement.
5) docking stations
Answer: We order either Dell Latitude e5500 or Dell Vostro 1720 laptops for our staff. The main differences that we see between these and consumer-level machines are:

Built-in port for a docking station
Able to downgrade to WinXP with our licensing (we re-image them right away anyway)
No "Button of Doom" or what Dell calls the Media Direct button. For some reason, the few consumer laptops that we do have set up with our WinXP image completely brick themselves when that button is pressed. We have no idea why, but it's a killer.

Because I work at an educational institution with a Dell Direct partnership, we tend to get prices comparable to the consumer shops anyway.
Answer: Turn the question around and ask what other business-critical functions are bought at the cheapest end of the market. It makes sense to get cheapo envelopes and paper-clips but do his salesmen drive scooters, is the office a Starbucks and does he duplicate documents by hand or by photocopier?
Day-one hardware costs for laptops is 15%-20% of the total cost of ownership for that asset, if he wants cheap today he'll pay for it later.
Answer: Another option that I don't find on home laptops is hard drive passwords. The business Del's we use at work have this so if it gets stolen none of the data can be accessed. You could use truecrypt for this but it's a lot nicer to have it built into the machine.
Answer: Last place I worked used consumer crap before I got there.
We bought a few business grade laptops and compared them side by each, and let everyone vote which they liked better.
Smaller, sleeker, docking station, lighter, smaller power packs, longer battery option, better built those were the key points.  (The OS and speed never mattered since people knew this was dependant on the processor installed, etc)
I still by the business line for myself.  They are just better.
Also I found the business line of products with Dell, their support centers were almost always NA based rather then the far east.  They treated their business customers at a higher level.  Also as you buy more you'll get better discounts, but the discounts typically only will apply to business line.  My standard discount with Dell was about 10 to 15% and we were only a company of 30 people at the time.


How create java class object in javascript using RHINO

Question: How create CUSTOM java class object in java-script using RHINO..?
We can use classes which is in rt.jar but not other custom class
Comment: Do you mean you want to create an `Object` which is of a type not found in rt.jar? Or you actually want to create a `Class` object?
Comment: i just wants to create an object of a class which is not found in rt.jar that mean it was written by me....on any one..
BY useing Rhino

and also how can  implemented in eclipse if u can...
Comment: Hello Simon, maybe you could rephrase your question to say what you actually seem to be asking, in case other people look it up. As I understand it, you are asking how to use a custom Java Class from inside an Eclipse Environment. And also, please don't use "PLZ HELP" or similar phrases in your questions, they don't add any information.
Answer:
compile class use a package
make a jar file
set classpath of that jar
use importPackage(Packages.)
start rhino..
now it will work.


App closes on start when trying to run react-native run-ios

Question: I'm facing some issues with running react-native run-ios on my react native project.
After the command the app as loading, black screen appears for a few seconds and then the app is closes.
Here is a log from WebStorm.
info Found Xcode workspace "Actors.xcworkspace"
info Launching iPhone 11 (iOS 14.3)
info Building (using "xcodebuild -workspace Actors.xcworkspace -configuration Debug -scheme Actors -destination id=5508C928-BADB-4FE5-8426-9B1461397EC3")
(node:44088) Warning: Accessing non-existent property 'padLevels' of module exports inside circular dependency
(Use `node --trace-warnings ...` to show where the warning was created)
success Successfully built the app
info Installing "/Users/michaelionia/Library/Developer/Xcode/DerivedData/Actors-gzwkhkgvbultrlcjeogpfwamtnzi/Build/Products/Debug-iphonesimulator/Actors.app"
info Launching "org.name.Actors"
success Successfully launched the app on the simulator

When I'm running react-native run-android the app workings good with all libraries.
I've tried to run the project from xCode , but facing the same issue , the app opens with back screen and 0 Errors.
Here is a log from xcode
2021-02-15 10:43:06.728730+0200 Actors[44637:1250270] You've implemented -[<UIApplicationDelegate> application:performFetchWithCompletionHandler:], but you still need to add "fetch" to the list of your supported UIBackgroundModes in your Info.plist.
2021-02-15 10:43:06.728839+0200 Actors[44637:1250270] You've implemented -[<UIApplicationDelegate> application:didReceiveRemoteNotification:fetchCompletionHandler:], but you still need to add "remote-notification" to the list of your supported UIBackgroundModes in your Info.plist.
2021-02-15 10:43:06.866897+0200 Actors[44637:1251130] [] nw_protocol_get_quic_image_block_invoke dlopen libquic failed
2021-02-15 10:43:06.904031+0200 Actors[44637:1250270] [native] Running application main ({
    initialProps =     {
    };
    rootTag = 1;
})
2021-02-15 10:43:06.930218+0200 Actors[44637:1250270] [native] 'SplashScreen.storyboard' file is missing. Fallbacking to 'SplashScreen.xib' file.
2021-02-15 10:43:06.930558+0200 Actors[44637:1250270] [native] 'SplashScreen.xib' file is missing - 'expo-splash-screen' will not work as expected.
2021-02-15 10:43:06.966657+0200 Actors[44637:1250270] *** Terminating app due to uncaught exception 'ERR_NO_SPLASH_SCREEN', reason: 'Couln't locate neither 'SplashScreen.storyboard' file nor 'SplashScreen.xib' file. Create one of these in the project to make 'expo-splash-screen' work (https://github.com/expo/expo/tree/master/packages/expo-splash-screen#-configure-ios).'
*** First throw call stack:
(
    0   CoreFoundation                      0x00007fff20420af6 __exceptionPreprocess + 242
    1   libobjc.A.dylib                     0x00007fff20177e78 objc_exception_throw + 48
    2   Actors                              0x0000000101dc49e9 -[EXSplashScreenViewNativeProvider createSplashScreenView] + 2185
    3   Actors                              0x0000000101dc19bd -[EXSplashScreenController initWithViewController:splashScreenViewProvider:] + 221
    4   Actors                              0x0000000101dc3878 -[EXSplashScreenService showSplashScreenFor:splashScreenViewProvider:successCallback:failureCallback:] + 312
    5   Actors                              0x0000000101dc36a5 -[EXSplashScreenService showSplashScreenFor:] + 149
    6   Actors                              0x0000000101dc4075 -[EXSplashScreenService application:didFinishLaunchingWithOptions:] + 181
    7   Actors                              0x00000001021fdc9c -[UMAppDelegateWrapper application:didFinishLaunchingWithOptions:] + 476
    8   Actors                              0x0000000101d8567e -[AppDelegate application:didFinishLaunchingWithOptions:] + 574
    9   UIKitCore                           0x00007fff2468d0f1 -[UIApplication _handleDelegateCallbacksWithOptions:isSuspended:restoreState:] + 232
    10  UIKitCore                           0x00007fff2468ec73 -[UIApplication _callInitializationDelegatesWithActions:forCanvas:payload:fromOriginatingProcess:] + 3919
    11  UIKitCore                           0x00007fff24694681 -[UIApplication _runWithMainScene:transitionContext:completion:] + 1237
    12  UIKitCore                           0x00007fff23cbd907 -[_UISceneLifecycleMultiplexer completeApplicationLaunchWithFBSScene:transitionContext:] + 122
    13  UIKitCore                           0x00007fff2424bdb6 _UIScenePerformActionsWithLifecycleActionMask + 88
    14  UIKitCore                           0x00007fff23cbe416 __101-[_UISceneLifecycleMultiplexer _evalTransitionToSettings:fromSettings:forceExit:withTransitionStore:]_block_invoke + 198
    15  UIKitCore                           0x00007fff23cbdeda -[_UISceneLifecycleMultiplexer _performBlock:withApplicationOfDeactivationReasons:fromReasons:] + 474
    16  UIKitCore                           0x00007fff23cbe247 -[_UISceneLifecycleMultiplexer _evalTransitionToSettings:fromSettings:forceExit:withTransitionStore:] + 819
    17  UIKitCore                           0x00007fff23cbdadb -[_UISceneLifecycleMultiplexer uiScene:transitionedFromState:withTransitionContext:] + 345
    18  UIKitCore                           0x00007fff23cc5d73 __186-[_UIWindowSceneFBSSceneTransitionContextDrivenLifecycleSettingsDiffAction _performActionsForUIScene:withUpdatedFBSScene:settingsDiff:fromSettings:transitionContext:lifecycleActionType:]_block_invoke + 178
    19  UIKitCore                           0x00007fff241556ab +[BSAnimationSettings(UIKit) tryAnimatingWithSettings:actions:completion:] + 871
    20  UIKitCore                           0x00007fff2426865e _UISceneSettingsDiffActionPerformChangesWithTransitionContext + 240
    21  UIKitCore                           0x00007fff23cc5a79 -[_UIWindowSceneFBSSceneTransitionContextDrivenLifecycleSettingsDiffAction _performActionsForUIScene:withUpdatedFBSScene:settingsDiff:fromSettings:transitionContext:lifecycleActionType:] + 361
    22  UIKitCore                           0x00007fff23ae896f __64-[UIScene scene:didUpdateWithDiff:transitionContext:completion:]_block_invoke + 797
    23  UIKitCore                           0x00007fff23ae7419 -[UIScene _emitSceneSettingsUpdateResponseForCompletion:afterSceneUpdateWork:] + 253
    24  UIKitCore                           0x00007fff23ae85a8 -[UIScene scene:didUpdateWithDiff:transitionContext:completion:] + 208
    25  UIKitCore                           0x00007fff24692b20 -[UIApplication workspace:didCreateScene:withTransitionContext:completion:] + 508
    26  UIKitCore                           0x00007fff2417dab7 -[UIApplicationSceneClientAgent scene:didInitializeWithEvent:completion:] + 358
    27  FrontBoardServices                  0x00007fff25aa20ae -[FBSScene _callOutQueue_agent_didCreateWithTransitionContext:completion:] + 391
    28  FrontBoardServices                  0x00007fff25acab41 __94-[FBSWorkspaceScenesClient createWithSceneID:groupID:parameters:transitionContext:completion:]_block_invoke.176 + 102
    29  FrontBoardServices                  0x00007fff25aafad5 -[FBSWorkspace _calloutQueue_executeCalloutFromSource:withBlock:] + 209
    30  FrontBoardServices                  0x00007fff25aca80f __94-[FBSWorkspaceScenesClient createWithSceneID:groupID:parameters:transitionContext:completion:]_block_invoke + 352
    31  libdispatch.dylib                   0x00000001035329c8 _dispatch_client_callout + 8
    32  libdispatch.dylib                   0x0000000103535910 _dispatch_block_invoke_direct + 295
    33  FrontBoardServices                  0x00007fff25af07a5 __FBSSERIALQUEUE_IS_CALLING_OUT_TO_A_BLOCK__ + 30
    34  FrontBoardServices                  0x00007fff25af048b -[FBSSerialQueue _targetQueue_performNextIfPossible] + 433
    35  FrontBoardServices                  0x00007fff25af0950 -[FBSSerialQueue _performNextFromRunLoopSource] + 22
    36  CoreFoundation                      0x00007fff2038f38a __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 17
    37  CoreFoundation                      0x00007fff2038f282 __CFRunLoopDoSource0 + 180
    38  CoreFoundation                      0x00007fff2038e764 __CFRunLoopDoSources0 + 248
    39  CoreFoundation                      0x00007fff20388f2f __CFRunLoopRun + 878
    40  CoreFoundation                      0x00007fff203886d6 CFRunLoopRunSpecific + 567
    41  GraphicsServices                    0x00007fff2bededb3 GSEventRunModal + 139
    42  UIKitCore                           0x00007fff24690e0b -[UIApplication _run] + 912
    43  UIKitCore                           0x00007fff24695cbc UIApplicationMain + 101
    44  Actors                              0x0000000101d85eb0 main + 112
    45  libdyld.dylib                       0x00007fff202593e9 start + 1
    46  ???                                 0x0000000000000001 0x0 + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException
*** Terminating app due to uncaught exception 'ERR_NO_SPLASH_SCREEN', reason: 'Couln't locate neither 'SplashScreen.storyboard' file nor 'SplashScreen.xib' file. Create one of these in the project to make 'expo-splash-screen' work (https://github.com/expo/expo/tree/master/packages/expo-splash-screen#-configure-ios).'
terminating with uncaught exception of type NSException
CoreSimulator 732.18.6 - Device: iPhone 11 (5508C928-BADB-4FE5-8426-9B1461397EC3) - Runtime: iOS 14.3 (18C61) - DeviceType: iPhone 11
(lldb) .

I've tried to delete podfile.log and run pod install from ios directory.
Comment: The error it throws tells you to go here:
https://github.com/expo/expo/tree/master/packages/expo-splash-screen#-configure-ios

It looks like your app is not configured correctly for iOS.
Comment: check if file called SplashScreen.storyboard exists inside your ios project
Comment: Hi @HassanKandil, The file exist inside ios/projectName ...
Comment: try to: Remove application from the device-
Restart device-
Build again if all of that doesn't work delete derived data. Xcode Preference->Locationtab->Derived data
Comment: In XCode, switch to `General` tab and what is under `App Icons and Launch Images`?
Comment: Hi @LeriGogsadze , Under `App Icon and Lauch Images` I have AppIcon and SplashScreen
Answer: In Info.plist find <key>UILaunchStoryboardName</key>, right under this line you should see <string>SplashScreen.storyboard</string>, remove this .storyboard part and it will work.


Problem Creating dynamic Id for textbox in asp.net mvc

Question: I have 3 textboxes in three different tab control and i want to generate textbox id like textbox plus concatenate the tab number
for(int i=0;i<3;i++)
{
    <%: Html.TextBoxFor(e=>e.vcr_LinkName + i)%>
}

its not working but when i change it to
 for(int i=0;i<3;i++)
    {
        <%: Html.TextBox("vcr_LinkName" + i)%>
    }

it works fine. but i want to use textboxfor instead of textbox
Answer: You can't really use textboxfor in this way as you don't have a property on your model that you want to bind it to. You do, however, have a few other options.
You could have a list of strings on your model and do something like this:
for(int i = 0; i < 3; i++)
{
    <%:Html.TextBoxFor(x => x.LinkNames[i])%>
}

You could build your own helper like this:
public static MvcHtmlString TextBoxWithSuffix<TModel, TProperty>(this HtmlHelper helper, Expression<Func<TModel, TProperty>> expression, string suffix)
{
    var id = ExpressionHelper.GetExpressionText(expression);
    return helper.TextBox(string.Format("{0}{1}", id, suffix);
}

And use it like this:
for(int i = 0; i < 3; i++)
{
    <%:Html.TextBoxWithSuffix(x => x.vcr_LinkName, i.ToString())%>
}


Least squares fitting using cosine function?

Question: Hello I am trying to fit a harmonic of the form $$y = b + c\cos(x)$$ to four data points (0,6.1) (.5,5.4) (1,3.9) (1.5,1.6) using least squares for homework. I know that the error $= Y_i - f(x_i)$ but am pretty confused with the partial derivatives and linear algebra part of this question. Apparently the professor wants only $y=b+c\cos(x)$ and not $y=b+c\cos(x)+d\sin(x)$
I get two equations from taking the derivative of $E = \sum_{i=0}^n [y_i - (b+c\cos(x_i))]^2$, with respects to $b$ and $c$.
$$ \frac{dE}{db} = bn + \sum_{i=0}^n c\cos(x_i) = \sum_{i=0}^n y_i $$ and
$$ \frac{dE}{dc} = b\cos(x_i) + \sum_{i=0}^n c\cos^2(x_i) = \sum_{i=0}^n \cos(x_i) y_i $$
Putting this into matrix form gives me:
$$ \left[ \begin{array}{cc|c}
n & \sum_{i=0}^n (x_i) &  \sum_{i=0}^n (y_i) \\
\sum_{i=0}^n \cos(x_i) & \sum_{i=0}^n \cos^2(x_i) &  \sum_{i=0}^n \cos(x_i)y_i \\
\end{array}\right] $$
which lands me with $$ \left[\begin{array}{cc|c}
4 & 3 & 17 \\
2.48862 & 2.067077 & 13.05931
\end{array}\right] $$
Sorry for the terrible formatting | is meant to make this an augmented matrix (the four data points are included at the top). Anyways
I'm not really sure how to solve this matrix so I assume I did something wrong with the partial derivatives. Is there anyone out there that could be so helpful as to let me know what I did wrong or any hints on how to solve this system if it is indeed solvable?
Comment: Thanks for fixing that formatting issue for me. Still unclear where I am missing here hopefully somebody can help!
Answer: The solution of @user147263 relies on calculus. Another option is to exploit linear algebra.
Form linear system
Start with a series of data points $(x_{k}, y_{k})_{k=1}^{m}$, and the trial function
$$
y(x) = c_{1} + c_{2} \cos x,
$$
We have the linear system
$$
\begin{align}
  A c & = y \\
    \left[
      \begin{array}{cc}
         1 & \cos x_{1} \\
         1 & \cos x_{2} \\
         \vdots & \vdots\\
         1 & \cos x_{m}
      \end{array}
    \right]
    \left[
      \begin{array}{c}
         c_{1} \\
         c_{2}
      \end{array}
    \right]
    & =
    \left[
      \begin{array}{c}
         y_{1} \\
         y_{2} \\
         \vdots \\
         y_{m}
      \end{array}
    \right]
\end{align}
$$
Find the solution vector $c$ which minimizes the sum of the squares of the residuals:
$$
r^{2}(c) = \lVert A c - y \rVert_{2}^{2} = \sum_{k=1}^{m} (y_{k} - c_{1} - c_{2} \cos x_{k})^2.
$$
Normal equations: Form the normal equations
$$
  A^{T}A c = A^{T}y.
$$
Solve linear system
The solution vector is
$$
  c = (A^{T}A)^{-1} A^{T}y.
$$
Defining the $m-$vector
${\mathbf{1}} =
\left[ \begin{array}{c} 1 \\ 1 \\ 1 \\ 1 \end{array} \right]$,
and the the $m-$vector
$\eta =
\left[ \begin{array}{c} \cos x_{1} \\  \cos x_{2} \\  \cos x_{3} \\  \cos x_{4} \end{array} \right]$, the system matrix has the column vector form
$A = \left[ \begin{array}{c} \mathbf{1} & \eta \end{array} \right]$, and the   product matrix is
$$
  A^{T} A =
      \left[
      \begin{array}{cc}
         \mathbf{1} \cdot \mathbf{1} & \mathbf{1} \cdot \eta \\
         \eta \cdot \mathbf{1} & \eta \cdot \eta
      \end{array}
    \right] =
%
      \left[
      \begin{array}{cl}
         m & \sum_{k=1}^{m} \cos x_{k} \\
         \sum_{k=1}^{m} \cos x_{k} & \sum_{k=1}^{m} \cos^{2} x_{k}
      \end{array}
    \right]
$$
with inverse
$$
  ( A^{T} A )^{-1} =
      (\det (A^{T}A))^{-1}
      \left[
      \begin{array}{rc}
         \eta \cdot \eta & -\mathbf{1} \cdot \eta \\
         - \mathbf{1} \cdot \eta & m
      \end{array}
    \right]
$$
where the determinant is
$$
\det (A^{T}A) = m (\eta \cdot \eta) - (\mathbf{1}\cdot \eta)^{2}.
$$
For the data set above, $x =
      \left[
      \begin{array}{l}
         0 \\
         0.5 \\
         1 \\
         1.5
      \end{array}
    \right]$, $\ $
$\eta =
      \left[
      \begin{array}{l}
         1 \\
         0.877583 \\
         0.540302 \\
         0.0707372
      \end{array}
    \right]$, $\ $
$y =
      \left[
      \begin{array}{c}
         6.1 \\
         5.4 \\
         3.9 \\
         1.6
      \end{array}
    \right]$, $\ $
and $\mathbf{1} =
      \left[
      \begin{array}{c}
         1 \\
         1 \\
         1 \\
         1
      \end{array}
    \right].$
The inner products are
$$
\begin{align}
  \mathbf{1} \cdot \mathbf{1} &= 4, \\
  \mathbf{1} \cdot \eta = \eta \cdot \mathbf{1} &= 2.48862, \\
  \eta \cdot \eta & = 2.06708.
\end{align}
$$
The matrices are
$$
  A =
    \left[
      \begin{array}{rl}
         1 & 1 \\
         1 & 0.877583 \\
         1 & 0.540302 \\
         1 & 0.0707372
      \end{array}
    \right], \quad
%
  A^{T}A =
    \left[
      \begin{array}{rl}
         4 & 3 \\
         3 & 3.5
      \end{array}
    \right], \quad
%
  (A^{T}A)^{-1} =
    \det (A^{T}A)^{-1}
    \left[
      \begin{array}{rr}
         2.06708 & -2.48862 \\
         -2.48862 & 4
      \end{array}
    \right].
$$
The determinant is $\det (A^{T}A) = 2.07509$. The solution vector is
$$
c =
    \left[
      \begin{array}{c}
         c_{1} \\
         c_{2}
      \end{array}
    \right]
  =
    \left[
      \begin{array}{r}
         1.27258 \\
         4.78565
      \end{array}
    \right]
$$
Check result
The solution curve is plotted against the data points.

A contour plot showing $r^{2}$ as a function of the solution vector $c$ with a white dot marking the solution.
Answer: Differentiating $E = \sum_{i=0}^n [y_i - (b+c\cos(x_i))]^2$ I get
$$
\frac{\partial E}{\partial b} = -2 \sum_{i=0}^n [y_i - (b+c\cos(x_i))]
$$
and
$$
\frac{\partial E}{\partial c} = -2 \sum_{i=0}^n [y_i - (b+c\cos(x_i))]\cos (x_i)
$$
The way you wrote up the derivatives, turning them into equations half-way through writing, is a mess.
If you are going to split the sum, do it correctly: $\sum_{i=0}^n b = (n+1)b$, not $nb$. Alternatively, you could begin indexing with $i=1$, not with $i=0$.
Keeping the present notation, I get the system
$$
(n+1)b +c \sum_{i=0}^n  \cos(x_i) = \sum_{i=0}^n y_i
$$
$$
 b\sum_{i=0}^n  \cos(x_i)  +c \sum_{i=0}^n  \cos^2(x_i) = \sum_{i=0}^n y_i \cos (x_i)
$$
Here $n=3$, so $n+1=4$. You have $\sum_{i=0}^n   (x_i)$ in place of $\sum_{i=0}^n  \cos(x_i)$.
Comment: I figured it was me being dumb with partial derivatives thanks a ton for the help I was going crazy trying to figure this out!


Find Cov(x,y) as a function of x

Question: Prove that in any bivariate distribution,
$$Cov[x,y] = Cov_x[x,E[y|x]] = \int_x(x - E[x]) E[y|x] f_x(x) dx. $$
(Note that this is the covariance of x and function of x.)
Source: Econometric Ananlyis (William Greene) Appendix B.8.1
Edit: The question is not a homework problem, although I was looking to prove it on my own. Prior to reading the answer below, I was stuck regarding how the $y$ in $Cov[x,y]$ got replaced by $E[y|x]$ in $Cov_x[x,E[y|x]]$. I guessed that was not much progress, so refrained from posting my attempt at solving. Thank you.
Comment: Please add the [tag:self-study] tag & read its
[wiki](https://stats.stackexchange.com/tags/self-study/info). Then tell us
what you understand thus far, what you've tried & where you're stuck. We'll
provide hints to help you get unstuck. Please make these changes as just
posting your homework & hoping someone will do it for you is grounds for closing.
Answer: First write the definition of covariance,
$$cov_x(X,E(Y|X)) = E_x (X E(Y|X)) - E(X)E_x(E(Y|X)).$$
Continue by writing the definition of expected value of continuous R.V
$$\int_x x E(Y|X) f_x dx - E(X) \int_x E(Y|X) f_x dx = \int_x (x - E(X)) E(Y|X) f_xdx.$$
According to the law of total expectation, the second term is $E(X)E_x(E(Y|X)) = E(X)E(Y)$. We will write the first term as,
$$\int_x x E(Y|X) f_x dx = \int_x x f_x \int_y y f_{y|x} dy dx = \int_x x f_x \int_y y \frac{f_{x,y}}{f_x}dy dx = \int_x \int_y x y f_{x,y} dy dx $$
We obtain that,
$$ \int_x \int_y x y f_{x,y} dy dx = E(XY).$$
Combining the two, we obtain the first equality.
Comment: can you point to the inconsistencies?

Find Cov(x,y) as a function of x


List of dictionaries with multiple values per key as Dataframe

Question: I want to convert a list of dictionaries with multiple values per key to a Dataframe.
d = [
    {'2020-12-31 00:00:00': [123, 456, 789, 321]},
    {'2021-05-06 00:00:00': [999, 888, 777, 666]}
]

The Dataframe should look like this:

index
Date
value1
value2
value3
value4

0
2020-12-31 00:00:00
123
456
789
321

1
2021-05-06 00:00:00
999
888
777
666

I know that creating a Dataframe with a list of dictionaries is easily achievable with pd.DataFrame(dictionaries) but i would like to split the values into separate columns.
I appreciate any help.
Comment: `pd.DataFrame(d).stack().apply(pd.Series).add_prefix('Value_')` ??
Comment: https://stackoverflow.com/questions/44663903/pandas-split-column-of-lists-of-unequal-length-into-multiple-columns
Answer: pd.DataFrame(d).stack().apply(
    pd.Series).add_prefix(
    'Value').reset_index().rename(columns={'level_0':'index', 'level_1':'Date'})

Output
    index Date               Value0 Value1  Value2  Value3
0   0     2020-12-31 00:00:00   123  456    789     321
1   1     2021-05-06 00:00:00   999  888    777     666


Gaps Vertically Using Dividers

Question: I'm having a problem in CSS. Basically, there are many dividers with the same class (30% in width) that should go along the page.
Here's the page
I want three dividers across stacking up on each other. The first part works, but they aren't stacking up on each other. There are gaps (varying in size) between these dividers (vertically).
Question: How do I get rid of these gaps?
Code of the main index.php (PHP involved):

<?php
    foreach ($rules as $key=>$value)
    {
        if ($blockmethod == 1)
        {
            echo '
';
                echo '

' . $value['title'] . '

';

                echo '
';
                    echo '
';
                        foreach ($value['rules'] as $rule)
                        {
                            echo '
' . $rule . '
';
                        }
                    echo '
';
                echo '
';
            echo '
';
        }
        else
        {
            if ($current == 1)
            {
                $display = 'left';
            }
            else if ($current == 2)
            {
                $display = 'right';
            }
            else if ($current == 3)
            {
                $display = 'center';
            }
            else
            {
                $display = 'left';
            }

            echo '
';
                echo '

' . $value['title'] . '

';

                echo '
';
                    echo '
';
                        foreach ($value['rules'] as $rule)
                        {
                            echo '
' . $rule . '
';
                        }
                    echo '
';
                echo '
';
            echo '
';
            $current++;

            if ($current > 3)
            {
                $current = 1;
            }
        }
        $cycles++;
    }
?>

CSS Code:
/* OTHER */

.background
{
    width: 100%;
    height: 100%;
    position: fixed;
    left: 0px;
    top: 0px;
    z-index: -1;
    background-image: url('images/bg.jpg');
}

.bgcolor
{
    background-color: rgba(0,0,0,0.85);
    height: 100%;
    width: 100%;
    z-index: -1;
    position: fixed;
}

.mainpage
{
    color: #FFFFFF;
}

.rules_title
{
    background-color: #466D92;
    text-align: center;
    border-radius: 2px 2px 0px 0px;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
}

.rules_list
{
    background-color: #252729;
    word-wrap: break-all;
    padding: 0px;
    margin: 0px;
    border-radius: 0px 0px 2px 2px;
    min-height: 100px;
    padding: 5px 5px 5px 5px;
}

/* METHODS */
.rules_section-method1
{
    width: 30%;
    height: auto;
    padding: 5px 5px 5px 5px;
    position: relative;
    margin-left: 25px;
    float: left;
    vertical-align: top;
}

.rules_section-method2
{
    width: 33%;
    height: auto;
    padding: 5px 5px 5px 5px;
    margin-left: 25px;
    display: inline-block;
    vertical-align: top;
}

#left
{
    float: left
}

#right
{
    float: right;
}

#center
{
    text-align: center;
}

You may have already noticed but I've attempted two methods here. I would prefer if method #1 worked. However, I did try another method which involved setting the first divider to the ID "left", the next divider to "right", and so on. Sadly, that also didn't work.
Any advice/help is highly appreciated!
Thanks.
Answer: I'd recommend using the CSS3 column-width and column-gap properties.  Check out this example:
http://www.bootply.com/118335 is a good example (bootstrap isn't necessary).  The keys important parts are:

display: inline-block; width: 100%; on each "rules-section"
column-gap and column-width set on the containing div for the rules-sections
Comment: yep, Modernizr is pretty great.  IE9 is the big one there, but works on most modern browsers (vendor prefixed - Autoprefixer generally takes care of that though.)

Gaps Vertically Using Dividers


Use form select value in PHP function

Question: I understand PHP is server side, and Javascript is client side.
I am trying to update a table on the screen (without causing a reload) on a changed selected value in a dropdown using form select:
<code>            <form method="post" action="search.php" role="form">
                <div class="form-group">
                  <select name="minPrice" class="form-control" style="height:50px;" id="minPrice">
                    <option value="0">Min Price</option>
                    <option value="10000">$10,000+</option>
                    <option value="20000">$20,000+</option>
                    <option value="30000">$30,000+</option>
                    <option value="40000">$40,000+</option>
                    <option value="50000">$50,000+</option>
                    <option value="60000">$60,000+</option>
                    <option value="70000">$70,000+</option>
                    <option value="80000">$80,000+</option>
                    <option value="90000">$90,000+</option>
                    <option value="100000">$100,000+</option>
                  </select>
                </div>
            </form>
</code>
In order to update the screen, I must access a 3rd party API in PHP.
I am using the following function in Javascript in order to update the search results when the user selects a different value in the dropdown.
<code>$("#minPrice").on("change", function(){
    updateSearchResults(this);
});
</code>
However, I cannot access the selected option value when I make a call to PHP.
So my question is:
Is there a way to access the selected option value when I make the PHP call to the server WITHOUT reloading the current page?
Comment: I believe you are expecting the value to go from JS to PHP. This won't happen directly.Check other SO answers for this. Additionally, why aren't you using AJAX?
Comment: what does `updateSearchResults` function do?
Comment: As far as getting the value is concerned, try this: https://jsfiddle.net/rayon_1990/m1d7Ldhv/
Comment: @SatejS I was able to get it to work, however I am not using AJAX. I am using jQuery. to respond to your question, why should I be using AJAX? Is there a benefit to this over making the call over jQuery?
Answer: Do an ajax post with your changed selected value:
<code>$("#minPrice").on("change", function() {
   updateSearchResults(this);
});

function updateSearchResults(minPrice) {
    $.ajax({
        type: 'POST',
        url: 'urlToYourPhp',
        data: 'minPrice=' + minPrice.val(),
        success: function(response) {
            console.log(response);
            // Handle the response from your php without the need to reload
        },
        dataType: 'html' // or: 'json' if your API returns json
    });
}
</code>
Comment: how do you go about using multiple variables in the 'data' section?

Use form select value in PHP function


getting a JS file() through axios and firebase

Question: I am trying to get a uploaded photo from Firebase using Axios and transform it into an File() object. I uploaded this photo in an other part of my app and saved a url to it in a registration. Now I am trying to get the file back from storage using the url. Problem is, it needs to be an File() object. I know how I can use the url to just display the image but that is not the goal.
This is my request:
fileFromURL(url, filename) {
  const imageFile = new File([''], 'filename');
  const config = {
    headers: {
      'Content-Type': imageFile.type,
    },
  };
  this.$axios.get(url, config)
    .then((response) => {
      // Here I am trying to transform the response to an File() object.

      const byteString = btoa(response.data);
      const ab = new ArrayBuffer(byteString.length);
      const ia = new Uint8Array(ab);
      for (let i = 0; i < byteString.length; i += 1) {
        ia[i] = byteString.charCodeAt(i);
      }
      const blob = new Blob([ia], { type: 'image/jpeg' });
      const file = new File([blob], filename);
    })
    .catch(() => {
      this.$q.notify({
        color: 'negative',
        position: 'top',
        message: 'Loading failed',
        icon: 'report_problem',
      });
    });
},

These are the response headers:
accept-ranges: bytes
access-control-expose-headers: Content-Length, Date, Server, Transfer-Encoding, X-GUploader-UploadID, X-Google-Trace
alt-svc: quic=":443"; ma=2592000; v="44,43,39"
cache-control: private, max-age=0
content-disposition: inline; filename*=utf-8''avatar.jpg
content-length: 1740563
content-type: image/jpeg
date: Mon, 04 Mar 2019 16:43:31 GMT
expires: Mon, 04 Mar 2019 16:43:31 GMT
last-modified: Wed, 27 Feb 2019 17:27:52 GMT
server: UploadServer
status: 200

and this is part of the response:
{data: "�PNG
↵↵
IHDR�x�� IDATx���w�%E�…���������������������������� �(�%�5IIEND�B`�", status: 200, statusText: "", headers: {…}, config: {…}, …}
config: {adapter: ƒ, transformRequest: {…}, transformResponse: {…}, timeout: 0, xsrfCookieName: "XSRF-TOKEN", …}
data: "�PNG
↵↵
IHDR�x�� IDATx���w�%E�"
headers: {date: "Mon, 04 Mar 2019 16:43:31 GMT", x-guploader-uploadid: "AEnB2UqVnwrANAK9hLdD6vQZA_HAIIzgmMz1EA5foN16jLnfuBcNSB0TIFr4C59I3cA4CRhnN2UloR5tdBK4UQ5IDihbpelJRQ", content-length: "16965", last-modified: "Wed, 27 Feb 2019 17:27:32 GMT", server: "UploadServer", …}
request: XMLHttpRequest {onreadystatechange: ƒ, readyState: 4, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload, …}
status: 200
statusText: ""
__proto__: Object

As you can see the data is filled with a long string (16246 characters).
So how can I change this into a File() object?
Comment: What is the goal then?
Comment: The goal is to have a File object that I can feed into an plugin that only takes file objects.
Answer: You can configure axios to return the response as a Blob directly, so you don't have to convert it yourself with:
responseType: 'blob'
fileFromURL(url, filename) {
  // *removed quotes from filename, typo I guess?
  const imageFile = new File([''], filename);
  const config = {
    // *removed headers as we don't know the file type anyway, I guess?
    responseType: 'blob'
  };
  this.$axios.get(url, config)
    .then((response) => {
      const file = new File([response.data], filename);
  });
}

Demo:
Comment: Yes, this is the solution. Thank you.


How to send value from powershell script to the jenkinsfile

Question: I have to send buildId value from powershell script to the jenkinsfile pipeline. I am trying something like below. Is this right approach?
powershell script
if($out -match "buildId-") {

            $splitline = $out.Split("-")
           echo "splitline: " $splitline
            $buildId= $splitline[1]
            echo "buildId: " $buildId
            $buildIds= $env:$buildId.Value
        }

then want to use that build to pass as a parameter to trigger the build job.
Jenkinsfile
build job: 'build_Test', parameters: [validatingString(name: 'buildId', value: '$buildIds'), string(name: 'TASK', value: 'build')]

Comment: How are you executing the script? Can you share the section of the Pipeline that executes the Script?
Answer: You can give it a shot, but I'm not sure simply adding it to an environment variable will allow you to access the value from the Jenkinsfile. You can find more about this problem in this question. However, you maybe able to achieve your goal via the EnvInject plugin, or simply store the value in a file in your workspace and access it via Jenkins later.


preprocessing and input format for gradient boosted trees

Question: I'm using MlLib library de Spark and trying to perform Gradient-Boosted Trees algorithm on my data, that has mostly categorical features (and just two numerical features). in the example given in Spark documentation they are using LibSVMFile, that has only numerical values. But my data is json file, containing the categorical features, that I can easily parse into the Spark Dataframe, but no in LibSVMFile. In the description of algorithm though it's clearly said that

GBTs handle categorical features

along with
do not require feature scaling, and are able to capture non-linearities and feature interactions.

As I understand this introduction, I don't need to make preprocessing of categorical features and their conversion into dummy variables, as well as I don't need to scale my numerical features and create the additional ones to model interactions and non-linearity (PolynomialExpansion) .
But in the same time the input for algorithm is RDD[LabeledPoint], that is a Vector[Double] as far as I know. So I don't quite understand how will algorithm handle categorical data if it only accepts the Double as input?
I guess, I can misunderstand the introduction or even the mechanism of algorithm, so maybe I need perform come hashing on categorical features, but I don't find any documentation about preprocessing the data for Gradient Boosted Trees, so your help and advice will be appreciated.
Answer: It seems like your problem is with the programming side and not the statistics.
Scaling is not needed for most tree based algorithms, but you should still pass the correct data format to the library you are using. If your tool requires doubles as input, convert your categorical variables to doubles.
For exemple, map a 3-level categorical variables A,B,C to 0,1,2 or any numerical value you want.


Uniqueness Proof: Related to Division Algorithms

Question: Regarding the statement: Let $a\in \mathbb {Z}$, $b\in \mathbb {Z}$. Then there exists integers q and r such that $a = qb+r$ where $0\le r \le b$.
Let $S$ $=$ $\lbrace a-qb: q\in \mathbb {Z}, a-qb \ge 0 \rbrace$
Why does S have to be non-empty?
Answer: Think in terms of modular arithmetic:
$$a \equiv r\ (\text{mod}\ b) \implies a = qb + r$$
In other words, $a\ (\text{mod}\ b)$ will always give a non-negative remainder $r$ such that $0 \leq r \lt b$, so there will always be at least one element in $S$.
Answer: If $a>0$, let $q=0$: then $a-qb=a>0$, so $a\in S$. If $a<0$ and $b<0$, let $q$ be any integer greater than $\frac{a}b=\frac{|a|}{|b|}>0$; then $a-qb=q|b|-|a|>0$, and again we have a member of $S$. If $a<0$ and $b>0$, let $-q$ be any integer greater than $\frac{|a|}b=\frac{-a}b$; then $-qb>-a$, so $qb<a$, and $a-qb>0$, yet again giving us a member of $S$. The only remaining case is $a=0$; if $b>0$, let $q=-1$, and if $b<0$, let $q=1$. (The case $b=0$ should be excluded in the statement of the theorem.)
Comment: Why does |a|/b = -a/b in the third case?
Comment: @Jake: Because $|a|=-a$ when $a<0$.


Is this a member of an exponential family?

Question: I strongly believe that this distribution does not belong to the exponential family:
$f(x;\theta) = \frac{\theta}{2}^{|x|}(1 - \theta)^{1-|x|}I_{\{-1, 0, 1\}}(x)$.
I have to write $f(x;\theta)$ as $a(\theta)b(x)\exp(c(\theta)d(x))$, I don't think this can be done. All I can do is write:
$f(x;\theta) = \exp(|x|\log(\theta) + (1-|x|)\log(1-\theta))I_{\{-1, 0, 1\}}(x)$.
Comment: Or just look at the factorisation $|x|(\log(\theta)-\log(1-\theta))$.
Comment: You can try to factorise the coefficients of $|x|$ in the exponential.
Comment: Think in this way: $f(x;\theta) = 1-\theta$ for x = 0, $=\frac \theta 2$ for $x$ = -1 or +1. It is kind of multinomial distribution.
Answer: Since
$$f(x;\theta) = \frac{\theta}{2}^{|x|}(1 - \theta)^{1-|x|}\mathbb{I}_{\{-1, 0, 1\}}(x)=\frac{1}{2}\left\{\frac{\theta}{(1-\theta)}\right\}^{|x|} \mathbb{I}_{\{-1, 0, 1\}}(x)$$the likelihood associated with a sample $(x_1,\ldots,x_n)$ is
$$L(\theta|x_1,\ldots,x_n)=\prod_{i=1}^n f(x_i;\theta)=
\frac{1}{2^n}\left\{\frac{\theta}{(1-\theta)}\right\}^{\sum_{i=1}^n|x_i|} $$
which factorises through the unidimensional
$$\sum_{i=1}^n|x_i|$$
for all $n$'s. Thus an exponential family.


Panel Data- FE vs RE

Question: I am trying to understand the different Panel Data models and I am getting confused by the different terms that people use, i.e., Random effect models and Random effects estimators and Fixed effect models and Fixed effect estimators- are these 4 all different?
Is it the case that you can have a fixed effect estimator in a random effects model and if you do that your estimate is not consistent?
For context, I am running a panel data analysis in STATA and after conducting a Hausman Test my p-value is more that 0.05 indicating I should use a random effects model. Does this mean I simply use the ,re output as my result or does it mean there's something in my variables and controls that needs to be changed or considered?
I am running a regression of total inflow migration on gov spending on healthcare per capita. My other x variables are population density, share of elderly, total tax revenue, GDP per capita and gini.
I understand that I am not to include variables that do not vary over time within a country- or is that only for fixed effects? So I'm not sure if my x variables are 'correct'
I'm sorry these are quite a few questions but any help at all would be GREATLY appreciated. The more that I try to read about panel data models, the more I get myself confused so if someone could explain for my specific case that would be amazing. Thank you!!
Answer: RE model: panel data model with some restrictions on the individual effects (such as being uncorrelated with the regressors for linear panel data models).
FE model: panel data model without such restrictions (so the individual effects can be correlated with the regressors).
FE estimator: A particular estimator, also known as 'within-group' estimator, usually for linear panel data models with strictly exogenous regressors; can be computed by Stata's xtreg, fe.
RE estimator: A particular FGLS estimator for the linear error component model (the error term = individual effects ($u_i$) + idiosyncratic error ($e_{it}$), where $u_i$ and $e_{it}$ are mutually uncorrelated, $e_{it}$ are homoskedastic and serially uncorrelated); can be computed by Stata's xtreg, re.
FE estimator is consistent for both FE and RE models. RE estimator is consistent for RE models but inconsistent for FE models in general.

Panel Data- FE vs RE


List of ports and applications

Question: How do I get a list of active ports and applications using them in a Windows Server 2003 box?
Any free utilities?
Thanks
Answer: TCPView is pretty handy.
Comment: Damn - beat me to it. :) Yeah, TCPView does exactly what you're asking for.
Answer: netstat -o is already on the system.
Comment: `-a` is necessary for the listening ports to be listed as well.  `-o` will only list active connections with pid.
Comment: + 1 for netstat. I usually run netstat -a -n -o
Answer: nmap -v hostname
Nmap is the most thorough port scanner ever made.
Comment: He's not asking to scan for open ports.  He's wanting to know what ports are being used by what processes on his computer.
Answer: What about SysInternals (now Microsoft) tools like Process Explorer or TCPView?
Answer: Another useful utility is fport. It's a bit like netstat -o, but it shows the process name and application path in addition to the PID.
Comment: fport definitely doesn't work with Win7 or Win2K8. I haven't tried it but may do the same for Win2K3.
Comment: I know it works on 2003, but you are correct for Win7 (64-bit, anyway). Thanks for the tip, I wasn't previously aware of this. It's too bad, because it's a handy little tool.

List of ports and applications


AWS RedHat Enterprise EC2 Billing Confusion

Question: Does AWS RHEL EC2 billis per second or per hour?
So If I run an ec2 for 30min, will it be billed for just 30 min? or an hour?
I've seen that aws supports per-second billing for linux, is it applicable for RHEL too? As it has seperate cost assositat with it.
Also using Spot Instances.
So in summery will I be billed by hour or by seconds?
Comment: posted an answer with pricing specifically for rhel instances. If it helped you an upvote/acceptance would help others in the future.
Answer: According to faq
https://aws.amazon.com/partners/redhat/faqs/
Whether it is on demand of spot instances

Red Hat Enterprise Linux on Amazon EC2 is offered at either a flat, hourly rate with no commitment (On-Demand or Spot Instances) or through a one-time, upfront payment (Reserved Instances). Both purchase options include Amazon EC2 compute charges and Red
Comment: @Anwar Hossain, In short, it's hourly. As you can see in the link provided by @Jatin Mehrotra, ` Pricing is per instance-hour consumed for each instance type. Partial instance-hours consumed are billed as full hours`.
Comment: Got it, Thanks. So if I want to go for partial bill, I should go for CentOS?


How do I prove this seemingly simple trigonometric identity

Question: $$a = \sin\theta+\sin\phi\\b=\tan\theta+\tan\phi\\c=\sec\theta+\sec\phi$$
Show that,   $8bc=a[4b^2 + (b^2-c^2)^2]$
I tried to solve this for hours and have gotten no-where. Here's what I've got so far :
$$
\\a= 2\sin(\frac{\theta+\phi}{2})\cos(\frac{\theta-\phi}{2})
\\ b = \frac{2\sin(\theta+\phi)}{\cos(\theta+\phi)+\cos(\theta-\phi)}
\\c=\frac{2(\cos\theta+\cos\phi)}{\cos(\theta+\phi)+\cos(\theta-\phi)}
\\a^2 = \frac{\sin^2(\theta+\phi)[\cos(\theta+\phi)+1]}{\cos(\theta+\phi)+1}\\\cos(\theta-\phi)=\frac{ca}{b}-1\\\sin^2(\frac{\theta+\phi}{2})=\frac{2a^2b}{4(ca+b)}$$
Comment: Have you tried substituting the trigonometric forms for each variable into the final equation and seeing if the two sides are equivalent?
Comment: @Ari What do you mean exactly ?
Answer: Hint: Divide both sides of $8bc=a[4b^2 + (b^2-c^2)^2]$ by $bc$. You will end up with this:
$$8 = a[4\frac{b}{c}+bc(\frac{b}{c}-\frac{c}{b})^2]$$
Take the RHS and you can prove that it is equal to 8.
Process: Calculate $\frac{b}{c}$ from the given equations.
$$b = \frac{\sin (\theta + \phi)}{\cos \theta. \cos \phi}$$
$$c = \frac{\cos \theta + \cos \phi}{\cos \theta. \cos \phi}$$
$$\frac{b}{c} = \frac{2\sin(\frac{\theta + \phi}{2}).\cos(\frac{\theta + \phi}{2})}{2\cos(\frac{\theta + \phi}{2}).\cos(\frac{\theta - \phi}{2})}$$
$$\frac{b}{c} =  \frac{\sin(\frac{\theta + \phi}{2})}{\cos(\frac{\theta - \phi}{2})}$$
You will end up with:
$$\frac{b}{c}-\frac{c}{b}=-\frac{\cos \theta. \cos \phi}{\cos(\frac{\theta - \phi}{2}).sin(\frac{\theta + \phi}{2})}$$
$$bc(\frac{b}{c}-\frac{c}{b})^2 = \frac{\sin (\theta + \phi)(\cos \theta + \cos \phi)}{\cos^2 \theta. \cos^2 \phi}\frac{\cos^2 \theta. \cos^2 \phi}{\cos^2(\frac{\theta - \phi}{2}).\sin^2(\frac{\theta + \phi}{2})}$$
$$ = \frac{2\sin(\frac{\theta + \phi}{2}).\cos(\frac{\theta + \phi}{2})2\cos(\frac{\theta + \phi}{2}).\cos(\frac{\theta - \phi}{2})}{\cos^2(\frac{\theta - \phi}{2}).\sin^2(\frac{\theta + \phi}{2})}$$
$$ = \frac{4\cos^2 (\frac{\theta + \phi}{2})}{\cos(\frac{\theta - \phi}{2})\sin (\frac{\theta + \phi}{2})}$$
$$4\frac{b}{c} + bc(\frac{b}{c}-\frac{c}{b})^2 = \frac{4}{\cos (\frac{\theta - \phi}{2})}(\sin(\frac{\theta + \phi}{2})+\frac{\cos^2 (\frac{\theta + \phi}{2})}{\sin(\frac{\theta + \phi}{2})})$$
$$= \frac{4}{\cos (\frac{\theta - \phi}{2})\sin(\frac{\theta + \phi}{2})}$$
$$a[4\frac{b}{c} + bc(\frac{b}{c}-\frac{c}{b})^2] = 4\frac{\sin \theta + \sin \phi}{\cos (\frac{\theta - \phi}{2})\sin(\frac{\theta + \phi}{2})}$$
$$ = 4\frac{2\cos (\frac{\theta - \phi}{2})\sin(\frac{\theta + \phi}{2})}{\cos (\frac{\theta - \phi}{2})\sin(\frac{\theta + \phi}{2})}$$
$$= 8$$
Comment: Try to get the result from where I left and let me know in case you need any help.
Comment: @DavidSebastian Updated. You just need to know a few formulae like $\sin 2\theta = 2\sin \theta\cos \theta$ and $\cos A + \cos B = 2\cos (\frac{A+B}{2})\cos (\frac{A-B}{2})$
Comment: @DavidSebastian Provided with the entire answer. Hope you got it now.
Comment: I'm sorry but I couldn't see how you got the expression for $\frac{b}{c}$.
Comment: Ok. I'll post the steps for it.
Comment: That would be really great. :)
Comment: Sorry. The value that I posted is for $\frac{b}{c}-\frac{c}{b}$. Posted the actual value for $\frac{b}{c}$.
Comment: Thank you for your help it's very much appreciated but I don't see how you got to the 3rd step from the 2nd. I must be missing something here.
Comment: Okay. But how do I prove that the RHS is equal to 8 in your last step ?
Answer: $\color{red}{c^2=\sec^2\theta+\sec^2\phi+2\sec\theta\sec\phi\tag{1}}$
$\color{blue}{b^2=\tan^2\theta+\tan^2\phi+2\tan\theta\tan\phi\tag{2}}$
$(1)-(2)$ gives,
$\begin{align}\left(c^2-b^2\right) & =\sec^2\theta+\sec^2\phi+2\sec\theta\sec\phi-\tan^2\theta-\tan^2\phi-2\tan\theta\tan\phi\\ &=2(1+\sec\theta\sec\phi-\tan\theta\tan\phi)\\&=2\left(1+\dfrac{1}{\cos\theta\cos\phi}-\dfrac{\sin\theta\sin\phi}{\cos\theta\cos\phi}\right)\\&=\dfrac{2}{\cos\theta\cos\phi}(1+\cos(\theta+\phi))\\&=\dfrac{4\cos^2\left(\dfrac{\theta+\phi}{2}\right)}{\cos\theta\cos\phi}\end{align}$
$\color{darkgreen}{\therefore\left(c^2-b^2\right)^2=\dfrac{16\cos^4\left(\dfrac{\theta+\phi}{2}\right)}{\cos^2\theta\cos^2\phi}\tag{3}}$
$\color{brown}{4b^2=\dfrac{4\sin^2(\theta+\phi)}{\cos^2\theta\cos^2 \phi}=\dfrac{16\sin^2\left(\dfrac{\theta+\phi}{2}\right)\cos^2\left(\dfrac{\theta+\phi}{2}\right)}{\cos^2\theta\cos^2 \phi}\tag{4}}$
$$\boxed{4b^2+\left(b^2-c^2\right)^2=\dfrac{16\cos^2\left(\dfrac{\theta+\phi}{2}\right)}{\cos^2\theta\cos^2 \phi}}$$

$c=\dfrac{\cos\theta+\cos\phi}{\cos\theta\cos\phi}=\dfrac{2\cos\left(\dfrac{\theta+\phi}{2}\right)\cos\left(\dfrac{\theta-\phi}{2}\right)}{\cos\theta\cos\phi}$
$b=\dfrac{\sin(\theta+\phi)}{\cos\theta\cos\phi}=\dfrac{2\sin\left(\dfrac{\theta+\phi}{2}\right)\cos\left(\dfrac{\theta+\phi}{2}\right)}{\cos\theta\cos\phi}$
$a=2\sin\left(\dfrac{\theta+\phi}{2}\right)\cos\left(\dfrac{\theta-\phi}{2}\right)$

$$\boxed{\dfrac{8bc}{a}=\dfrac{32\sin\left(\dfrac{\theta+\phi}{2}\right)\cos^2\left(\dfrac{\theta+\phi}{2}\right)\cos\left(\dfrac{\theta-\phi}{2}\right)}{2\sin\left(\dfrac{\theta+\phi}{2}\right)\cos\left(\dfrac{\theta-\phi}{2}\right)\cos^2\theta\cos^2 \phi}=\dfrac{16\cos^2\left(\dfrac{\theta+\phi}{2}\right)}{\cos^2\theta\cos^2 \phi}}$$
Answer: It is much more convenient to simplify algebraic expressions using only two variables $t$ and $T$ together for tangent of each half angle than struggling with Trig functions:
$$ t = \tan(\theta/2); T = \tan(\phi/2); $$
$$ sth = 2 t/(1 + t^2) ; tth = 2 t/(1 - t^2);secth = (1 + t^2)/(1 - t^2); $$
$$ sph = 2 T/(1 + T^2); tph = 2 T/(1 - T^2); secph = (1 + T^2)/(1 - T^2); $$
$$ a = sth + sph; b = tth + tph; c = secth + secph; $$
Each of $ 8\,b\,c $  and $ a[4b^2 + (b^2-c^2)^2] $ are brought to a common denominator simplifying them separately to :
$$ \dfrac{32\, (t + T)\, ( t\, T-1)^2 ( t\, T+1)} {(t^2 -1)^2 (T^2 -1)^2} $$
Comment: I must confess that I'm a bit irritated to see that your answer, based on the same core idea as mine, has gained more upvotes in less time. Not that I begrudge you the reputation, but I'd really like to understand what people like about your answer as opposed to mine. Is it the shortness due to the fact that you omit expanded forms for $a,b,c$ and have the final value in unexpanded factors? Or is it the fact that I had omitted the initial $t=\tan(\theta/2)$ in my answer until just now? In any case, it seems you contributed something people like, and I'm happy for you about that.
Comment: @MvG: I cannot say what appealed to others.. I can only mention what I did; the $ 8 b c $ part I did by hand, where  (t+T), ( t T + 1) etc. are preserved throughout as separate bracketable quantities till the end. Second part,left it to CAS. By alloying a heavy expression one loses sight of individual elements also elegance of algebraic handling. You mentioned factoring though at the end of your post, and it factors out to same result ( u = T ).The half angle suggests itself from the post as fairly straight elementary Trig. Anyways for your last comment, schoenen Dank!
Comment: @MvG: In actual working (that seems to be long struggle) using trigonometric quantities we are still doing algebraic manipulations. In this case better use algebra from the beginning itself.
Answer: I'd use the tangent half-angle substitution:
\begin{align*}
t&=\tan\frac\theta2 &
\sin\theta&=\frac{2t}{1+t^2} &
\tan\theta&=\frac{2t}{1-t^2} &
\sec\theta&=\frac{1+t^2}{1-t^2}
\\
u&=\tan\frac\phi2 &
\sin\phi&=\frac{2u}{1+u^2} &
\tan\phi&=\frac{2u}{1-u^2} &
\sec\phi&=\frac{1+u^2}{1-u^2}
\end{align*}
Then you have
\begin{align*}
a &= \frac{2 t^{2} u + 2 t u^{2} + 2 t + 2 u}{t^{2} u^{2} + t^{2} + u^{2} + 1} \\
b &= \frac{-2 t^{2} u - 2 t u^{2} + 2 t + 2 u}{t^{2} u^{2} -  t^{2} -  u^{2} + 1} \\
c &= \frac{-2 t^{2} u^{2} + 2}{t^{2} u^{2} -  t^{2} -  u^{2} + 1}
\end{align*}
\begin{multline*}
8bc=a[4b^2 + (b^2-c^2)^2] =\\
32\frac{t^{4} u^{3} + t^{3} u^{4} - t^{3} u^{2} - t^{2} u^{3} - t^{2} u - t u^{2} + t + u}{t^{4} u^{4} - 2 t^{4} u^{2} - 2 t^{2} u^{4} + t^{4} + 4 t^{2} u^{2} + u^{4} - 2 t^{2} - 2 u^{2} + 1}
\end{multline*}
The great benefit here is that after that first step, choosing to use that formulation, you almost don't have to think at all any more. From there on it's a straight-forward computation in rational functions. I left that to my computer algebra system, but if you are careful you can certainly do it by hand as well. The fact that my CAS expanded all those polynomials automatically makes the formulas above perhaps look more complicated than they really are, haven't tried.
Comment: Since I received a downvote for this, I'd be happy for an explanation *why* you consider this answer not useful. I don't mind the loss in reputation, but I'm genuinely curious about the rationale behind that vote. I hope the voter is still around and will drop me a line.
Answer: \begin{align*}4\cos^2(\theta)\cos^2(\phi)b^2 &= 4\cos^2(\theta)\cos^2(\phi)(\tan(\theta) + \tan(\phi))^2 \\
&= 4(\sin(\theta)\cos(\phi) + \cos(\theta)\sin(\phi))^2 \\
&= 4\sin^2(\theta + \phi) \\
&= 16\sin^2((\theta + \phi)/2)\cos^2((\theta + \phi)/2) \\
&= 16(1 - \cos^2((\theta + \phi)/2))\cos^2((\theta + \phi)/2) \\
&= 16\cos^2((\theta + \phi)/2) - 16\cos^4((\theta + \phi)/2)\end{align*}
 \begin{align*}c^2 - b^2 &= \sec^2\theta + \sec^2\phi + 2\sec(\theta)\sec(\phi) - (\tan^2\theta + \tan^2\phi + 2\tan(\theta)\tan(\phi)) \\
&= 2 + 2\sec(\theta)\sec(\phi) - 2\tan(\theta)\tan(\phi)\end{align*}
\begin{align*}\cos(\theta)\cos(\phi)(c^2 - b^2) &= 2(\cos(\theta)\cos(\phi) + 1 - \sin(\theta)\sin(\phi)) \\
&= 2(1 + \cos(\theta + \phi)) \\
&= 4\cos^2((\theta + \phi)/2)\end{align*}
 $cos^2(\theta)\cos^2(\phi)(b^2 - c^2)^2 = 16\cos^4((\theta + \phi)/2$
$cos^2(\theta)\cos^2(\phi)(4b^2 + (b^2 - c^2)^2) = 16\cos^2((\theta + \phi)/2$
 \begin{align*}8\cos^2(\theta)\cos^2(\phi)bc/a &= 8\cos^2(\theta)\cos^2(\phi)(\tan(\theta) + \tan(\phi))(\sec(\theta) + \sec(\phi))/(\sin(\theta) + \sin(\phi)) \\
&= 8(\sin(\theta)\cos(\phi) + \cos(\theta)\sin(\phi))(\cos(\theta) + \cos(\phi))/(\sin(\theta) + \sin(\phi)) \\
&= 8\sin(\theta + \phi)(\cos(\theta) + \cos(\phi))/(\sin(\theta) + \sin(\phi)) \\
&= \frac{8(2\sin((\theta + \phi)/2)\cos((\theta + \phi)/2))(2\cos((\theta + \phi)/2)\cos((\theta - \phi)/2))}{2\sin((\theta + \phi)/2)\cos((\theta - \phi)/2)} \\
&= 16\cos^2((\theta+\phi)/2)\end{align*}
The desired result follows.
Answer: First, observe that adding or subtracting a tangent with a secant of like variables simplifies much more readily than adding tangents of different variables or secants of different variables (just look at the nasty formulas you obtained for $b$ and $c$!). We find.
$$\tan{x}+\sec{x}=\frac{\sin{x}}{\cos{x}}+\frac{1}{\cos{x}}=\frac{\sin{x}+1}{\cos{x}},$$
and
$$\tan{x}-\sec{x}=\frac{\sin{x}}{\cos{x}}-\frac{1}{\cos{x}}=\frac{\sin{x}-1}{\cos{x}}.$$
We can take advantage of this and avoid most of the masochistic clutter produced by trying to use the angle addition formulas first.
The difference of squares $b^2-c^2$ then simplifies as follows:
$$\begin{align}
b^2-c^2
&=\left(b+c\right)\cdot\left(b-c\right)\\
&=\left(\frac{\sin{\theta}+1}{\cos{\theta}}+\frac{\sin{\varphi}+1}{\cos{\varphi}}\right)\cdot\left(\frac{\sin{\theta}-1}{\cos{\theta}}+\frac{\sin{\varphi}-1}{\cos{\varphi}}\right)\\
&=\frac{\sin^2{\theta}-1}{\cos^2{\theta}}+\frac{\sin{\theta}+1}{\cos{\theta}}\cdot\frac{\sin{\varphi}-1}{\cos{\varphi}}+\frac{\sin{\varphi}+1}{\cos{\varphi}}\cdot\frac{\sin{\theta}-1}{\cos{\theta}}+\frac{\sin^2{\varphi}-1}{\cos^2{\varphi}}\\
&=-1+\frac{\left(\sin{\theta}+1\right)\left(\sin{\varphi}-1\right)+\left(\sin{\theta}-1\right)\left(\sin{\varphi}+1\right)}{\cos{\theta}\cos{\varphi}}-1\\
&=\frac{2\sin{\theta}\sin{\varphi}-2}{\cos{\theta}\cos{\varphi}}-2\\
&=2\left[\tan{\theta}\tan{\varphi}-\sec{\theta}\sec{\varphi}-1\right].
\end{align}$$
As you can see, this does a much better job of streamlining the algebraic manipulations of the problem.
Comment: excellent answer !
Comment: Thank you very much for your answer but I have a problem. You've got an expression for $b^2-c^2$. I'm sure there's good reason but I don't see any. So how could I get to showing $8bc=a[4b^2+(b^2-c^2)^2]$ from there ?
Answer: $$(c-\sec\theta)^2-(b-\tan\theta)^2=1$$
$$\implies b^2-c^2=2b\tan\theta-2c\sec\theta$$
Put $\tan2A=\dfrac{2\tan A}{1-\tan^2A},\sec2A=1/\cos2A=\dfrac{1+\tan^2A}{1-\tan^2A}$ to form Quadratic Equation in $\tan\dfrac\theta2$
We shall reach at the same equation if we start with $$(c-\sec\phi)^2-(b-\tan\phi)^2=1$$
So the roots of the Quadratic Equation will be $\tan\dfrac\theta2,\tan\dfrac\phi2$
Utilize Vieta's formula
in $\tan\dfrac{\theta+\phi}2=\dfrac{\tan\dfrac\theta2+\tan\dfrac\phi2}{1-\tan\dfrac\theta2\tan\dfrac\phi2}\cdots$
So, we can find $\sin(\theta+\phi)$ using $\sin2B=\dfrac{2\tan B}{1+\tan^2B}$
From $b=\tan\theta+\tan\phi=\dfrac{\sin(\theta+\phi)}{\cos\phi\cos\theta},$ we can find
$\cos\phi\cos\theta$
From $c=\sec\theta+\sec\phi=\dfrac{\cos\theta+\cos\phi}{\cos\phi\cos\theta},$ we can find $\cos\phi+\cos\theta$
Now, $(\cos\phi+\cos\theta)^2+(\sin\phi+\sin\theta)^2=2+2\cos(\phi-\theta),$ which will give us $\cos(\phi-\theta)$
Finally use Werner's formula  $\cos(\phi-\theta)+\cos(\phi+\theta)=2\cos\phi\cos\theta$


Use a model field to query another model field in django

Question: I have two models in our django app
class Reg(models.Model):
   transactions = ManyToMany
   price = IntegerField

class Transaction(models.Model)
   amount = IntegerField

Now I would like to make a lookup like:
Registration.objects.filter(reg__price==transaction__amount)

Previously we used the following approach:

Registration has a property is_paid that computes wether a transaction with equal amount exists
[r for r in Registration.objects.filter(...) if r.is_paid]

This is ofc very query-consuming and inefficient.
I wonder whether there would be a better way to do this!
Any hint is appreciated :)
Comment: You did not construct the fields, you should write `IntegerField()` and `ManyToMany('Transaction')`.
Comment: Furthermore it is not very clear when an invoice is paid? If the *sum* of the transactions sum up to `amount`?
Comment: @WillemVanOnsem this was obviously pseudo-code. For the second though, well, if enough transaction amount exists to cover the price == paid
Answer: You can use an F expression for such a query:
from django.db.models import F

Registration.objects.filter(price=F('transactions__amount'))

This will filter all Registration instances whose price is equal to one of their transactions' amount. If you want all transactions amounts' sum to be equal or more than the registration price, you can use annotations to aggregate each registration's Sum:
paid_registrations = Registration.objects.\
   annotate(ta=Sum('transactions__amount')).\  # annotate with ta sum
   filter(price__lte=F('ta'))  # filter those whose price is <= that sum


Como inserir Grid dinâmica na interface XAML do WPF

Question: Escrevi um método que cria uma Grid dinamicamente:
private void createMyGrid(int l, int c)
{
    //Create grid
    Grid DynamicGrid = new Grid();
    DynamicGrid.ShowGridLines = true;

    //Create lines
    for(int i=0; i<l;i++)
    {
        DynamicGrid.RowDefinitions.Add(new RowDefinition());
    }

    //create columns
    for (int j = 0; j < c; j++)
    {
        DynamicGrid.ColumnDefinitions.Add(new ColumnDefinition());
    }

    // Display grid into a Window
    this.Content = DynamicGrid;

}
A MainWindow.xaml está assim:
<Window x:Class="dinamicButtonBasics.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:dinamicButtonBasics"
    mc:Ignorable="d"
    Title="MainWindow" Height="450" Width="800">
<Grid x:Name="mainGrid">
    <Grid x:Name="myGrid">

    </Grid>
</Grid>

É possível fazer com que a minha"myGrid" passe a ser a que eu criei dinamicamente?
De outra forma, como posso substituir a "myGrid" pela que é criada pela função?
Answer: Afinal era simples ...
public MainWindow()
{
    InitializeComponent();
    myGrid.Children.Clear();
    myGrid.Children.Add(createMyGrid(3,4));
}

... mas a função foi alterada assim:
private Grid createMyGrid(int l, int c)
{
    //Create grid
    Grid DynamicGrid = new Grid();
    DynamicGrid.ShowGridLines = true;

    //Create lines
    for(int i=0; i<l;i++)
    {
        DynamicGrid.RowDefinitions.Add(new RowDefinition());
    }

    //create columns
    for (int j = 0; j < c; j++)
    {
        DynamicGrid.ColumnDefinitions.Add(new ColumnDefinition());
    }

    //Add buttons ti the grid
    populateGrid(DynamicGrid);

    return DynamicGrid;
}