text:
Q: While loop not displaying all results from query
I'm having problems showing all the results in my modal. There are three rows I want to display in the modal: Billing months for June 2016, May 2016, and April 2016, but only the latest(June 2016) will show. Here's the part of my code:
if(isset($_GET['id']))
                        {

                            $page_id = $_GET['id'];

                            $select_query = "SELECT * FROM billing_info INNER JOIN customer_login ON billing_info.account_no=customer_login.account_no WHERE billing_info.account_no='$page_id' ";

                            $run_query = mysqli_query($conn,$select_query);

                            while($row = mysqli_fetch_array($run_query))
                            {
                                $id = $row['user_id'];
                                $cust_fname = $row['cust_fname'];
                                $cust_mname = $row['cust_mname'];
                                $cust_lname = $row['cust_lname'];
                                $branch = $row['branch'];
                                $account_no = $row['account_no'];
                                $billing_month = $row['billing_month'];
                                $pres_reading = $row['pres_reading'];
                                $prev_reading = $row['prev_reading'];
                                $payment_status = $row['payment_status'];
                                $due_date = $row['due_date'];
                                $int_pres = intval($row["pres_reading"]);
                                $int_prev = intval($row["prev_reading"]);
                                $difference = $int_pres-$int_prev;
                                $payment = $difference*26.678;

                                $cust_fname = ucfirst($cust_fname);
                                $cust_mname = ucfirst($cust_mname);
                                $cust_lname = ucfirst($cust_lname);
                                $branch = ucfirst($branch);

                    ?>

 X

    <form method="get" action="customer_view.php?id=<?php echo $id; ?>" name="id" enctype="multipart/form-data">

<?php echo $cust_fname." ".$cust_mname." ".$cust_lname." - ".$account_no." - ".$branch." Details" ?>

                    Billing Month
                    Present Reading
                    Previous Reading
                    Payment
                    Status
                    Due Date
                    Water Usage (in m3)
                    Edit

                    <?php echo $billing_month; ?>
                    <?php echo $pres_reading; ?>
                    <?php echo $prev_reading; ?>
                    <?php echo "Php " . $payment; ?>
                    <?php echo $payment_status; ?>
                    <?php echo $due_date; ?>
                    <?php echo $difference; ?>

                    <a href="billing_edit_posts.php?edit=<?php echo $id; ?>">Edit

                    Add Billing Information

</form>
</style>

</form>

                <?php } }?>

A: You should loop/parse the data only for
 and  Not for all tag like
 and
 outer the table. Html will loop all of inside { ... } sign.
Then, your style code should be placed the upper (not fix with html/php). This your code should be:

<?php

if (isset($_GET['id'])) {//open the isset
    $page_id = $_GET['id'];
$select_query = "SELECT * FROM billing_info INNER JOIN customer_login ON billing_info.account_no=customer_login.account_no WHERE billing_info.account_no='$page_id' ";

$run_query = mysqli_query($conn, $select_query);
?>

 X

        <form method="get" action="customer_view.php?id=<?php echo $id; ?>" name="id" enctype="multipart/form-data">

<?php
while ($row = mysqli_fetch_array($run_query)) { //open the while
    $id = $row['user_id'];
    $cust_fname = $row['cust_fname'];
    $cust_mname = $row['cust_mname'];
    $cust_lname = $row['cust_lname'];
    $branch = $row['branch'];
    $account_no = $row['account_no'];
    $billing_month = $row['billing_month'];
    $pres_reading = $row['pres_reading'];
    $prev_reading = $row['prev_reading'];
    $payment_status = $row['payment_status'];
    $due_date = $row['due_date'];
    $int_pres = intval($row["pres_reading"]);
    $int_prev = intval($row["prev_reading"]);
    $difference = $int_pres - $int_prev;
    $payment = $difference * 26.678;

    $cust_fname = ucfirst($cust_fname);
    $cust_mname = ucfirst($cust_mname);
    $cust_lname = ucfirst($cust_lname);
    $branch = ucfirst($branch);
    ?>

<?php echo $cust_fname . " " . $cust_mname . " " . $cust_lname . " - " . $account_no . " - " . $branch . " Details" ?>

                        Billing Month
                        Present Reading
                        Previous Reading
                        Payment
                        Status
                        Due Date
                        Water Usage (in m3)
                        Edit

                        <?php echo $billing_month; ?>
                        <?php echo $pres_reading; ?>
                        <?php echo $prev_reading; ?>
                        <?php echo "Php " . $payment; ?>
                        <?php echo $payment_status; ?>
                        <?php echo $due_date; ?>
                        <?php echo $difference; ?>

                        <a href="billing_edit_posts.php?edit=<?php echo $id; ?>">Edit

                        Add Billing Information

<?php } //while closing
?>

        </form>
        </style>

        </form>

Hopefully it will be success for you ;)


text:
Q: android non unique view id I have a LinearLayout that contains a ViewStub which points to a ViewFlipper. The ViewStub is *statically assigned its layout reference values on startup (currently, next version will be dynamic). Located within the ViewFlipper are 10 RelativeLayouts each with its own assortment of buttons, edittexts, textviews, etc.
On about half of those pages is a TogggleButton
<ToggleButton
    android:id="@+id/dontNeed"
    android:textOn="DON'T NEED"
    android:textOff="DON'T NEED"
    android:layout_width="200dp"
    android:layout_alignParentBottom="true"
    android:layout_height="100dp"
    android:textSize="36sp"
    android:layout_centerHorizontal="true"
    android:background="#AA0000"
    android:layout_marginBottom="25dp"
/>

Specific views, when used, will assign recommendation values to others based on some calculations. This button well let the system know the user does not require any information from the current page.
If I have this same button on many pages, does it require a unique ID for each page? This is based in terms of attaching listeners to each of the buttons. Does each button "dontNeed" require a separate ID or will attaching the non unique id to a listener use all of them?

A:
If I have this same button on many pages, does it require a unique ID for each page?

That depends on where and how you are calling findViewById() to retrieve the widget. The widget ID must be unique enough that, when you call findViewById() on something (the activity, the ViewFlipper, a child container within the ViewFlipper, etc.), that you are guaranteed to get your desired widget back.

will attaching the non unique id to a listener use all of them?

You do not attach an "id to a listener", "non unique" or otherwise. You attach a listener to a widget.

redpajama_set_name: RedPajamaStackExchange


text:
Q: JSLint: Disallow state. in Redux connect functon Need to write a (custom) ESLint rule for this:
Good:
connect((state, props) => {
  return {
     organizations: Organization.getActive(state, props.user),
    ...
    <prop>: Model.scope(state, prop...),

  };
})(MyComponent);

Bad: All the stuff in there
connect((state, props) => {
  return {
     organizations: state.organizations, //archived? suspended? or really all?
  };
})(MyComponent);

Bad: Filtering in place.
connect((state, props) => {
  return {
     organizations: filter(state.organizations, {
       status: Organization.ACTIVE
     }),
  };
})(MyComponent);

All that should be needed is to disallow state.<something> within the connect function as a starting point and make tweaks as needed.


text:
Q: Open bootstrap modal with Js ( not working ) I am curently building a website and I need to open a modal automaticaly when I go to a page, here is the code:
http://pastebin.com/bhSL82j8
It isnt working.
EDIT : http://pastebin.com/mGtR1VK1
It isnt working anyway

A: You need to open your modal when the page is loaded. Use something like this to make it happen:
$(document).ready(function() {
  $('#modal').modal();
});


text:
Q: Iterating through grouped object data in Vue My data comes from an API as follows
{
   "ALBUMS":[
      {
         "ID":"1",
         "TITLE":"'THE BEST OF"
      },
      {
         "ID":"2",
         "TITLE":"MADE IN ENGLAND"
      },
   ],
   "PLAYLISTS":[
      {
         "ID":"5",
         "TITLE":"SUNSET SESSIONS"
      },
       "ID":"2",
         "TITLE":"POOLSIDE SESSIONS"
      }
   ],
}

I want to list all titles and types (album or playlist).
The following that I came up with only gives me the first child from albums and playlists:

{{index}}

{{item[0].title}}

My desired result would be:
Album
The Best Of

Album
Made In England

Playlist
Sunset Sessions

Playlist
Sunset Sessions

A: Looks like you were missing the second level of your data hierarchy. See the following snippet for an example of how it might work with the data you've provided

new Vue({
  el: "#app",
  data: {
   "ALBUMS":[
      {
         "ID":"1",
         "TITLE":"'THE BEST OF"
      },
      {
         "ID":"2",
         "TITLE":"MADE IN ENGLAND"
      },
   ],
   "PLAYLISTS":[
      {
         "ID":"5",
         "TITLE":"SUNSET SESSIONS"
      },
      {
         "ID":"2",
         "TITLE":"POOLSIDE SESSIONS"
      }
   ],
  },
})

   Album
     {{album.TITLE}}

     Playlist
     {{playlist.TITLE}}


text:
Q: Need resolution for AngularJS net::ERR_INSECURE_RESPONSE error I am able to make REST API call using Postman/browser by passing Authorization token. However when I make the same call using AngularJS it's getting errored out. It's returning net::ERR_INSECURE_RESPONSE
I would like to know what can be possibly causing this error and how to fix this.
$http.get('https://hostname:8443/medrecdb-records', {
    headers: {
    'Authorization': 'Basic YWRtaW46UGFzc3dvcmQx' }})
   .then(function (response) {
       $scope.drug = response.data;
       console.log("Response is: " + response);
 }).catch(function (response) {
        // Handle error
        var data = response.data;
        var status = response.status;
        var statusText = response.statusText;
        var headers = response.headers;
        var config = response.config;
        console.log("Response data is: " + data);
    });


text:
Q: How to clean a file_field? <% if f.object.header_image.present? %>
              <%= image_tag f.object.header_image.url, class:"img-responsive"%>
            <% end %>
            <%=f.file_field :header_image, class:"form-control"%>

I can successfully upload new file. But How I can just empty my column?
I have an image set, and now I want to set NO Image for :header_image. Just nil value.
I have just only the "Upload new file" button.
I want let the user choose If he want to add a new photo (and substitute the previous one) or just let an empty field (no photo)
If I just set a nil value, Carrierwave will automatically destroy the picture

A: In your form, if the image is present add a checkbox below the picture that user must check if he want to delete it, then from the controller in the update action you can destroy the picture. Probably there would be another solutions.


text:
Q: New privilege tracker - 'Track the next one' banner misplaced when you've also earned a new badge I'll admit that this is a rare case, but when you've earned a new privilege and a badge you've tracked, the dark blue 'banner' which contains the 'Track the next one' button seems to be positioned too high, leaving an 'empty' gray line at the bottom of the widget. I suspect this happens because the height of the badge tracker widget in this case is higher than would be normally.

Tested with the latest Safari and Firefox on macOS Mojave.


text:
Q: Why does my color printer only print in black on one computer but print in color for the rest? Our home network has an HP Laserjet 200 color m251nw printer installed that had been working just fine for all machines on the network. But now one machine (A) will not print color although other machines (B, C) can still print color. This suggests it's local to the A machine. I've rebooted the A machine and rebooted the printer, with no improvement.
I have logged onto A as a different admin user and it still won't print color, suggesting it's not a CurrentUser setting. I have also verified that it won't print color from several different apps, e.g Word and Chrome.
If it's not user level or app level, it seems it must be machine level. Does anyone know of a machine level setting that may have gotten inserted or changed to produce this behavior?
Thank you for any ideas or assistance.


text:
Q: Array loses values when in foreach This has me stumped. I can print_r the array called $item_pages and it outputs all of the keys and values correctly. However, once that array is used within the foreach, it seems to become empty. This is the array when I print_r outside of the foreach:
Array ( [0] => 1 [1] => 6 [2] => 12 [3] => 15 [4] => 16 [5] => 17 [6] => 18 [7] => 19 [8] => 78 [9] => 79 [10] => 87 [11] => 90 [12] => 94 [13] => 95 [14] => 98 [15] => 99 [16] => 102 [17] => 103 [18] => 105 [19] => 107 [20] => 108 [21] => 110 [22] => 111 [23] => 112 [24] => 113 [25] => 114 [26] => 119 [27] => 120 [28] => 121 [29] => 125 [30] => 126 [31] => 134 [32] => 135 [33] => 136 [34] => 138 [35] => 142 [36] => 186 [37] => 193 [38] => 197 [39] => 198 [40] => 199 [41] => 206 [42] => 327 [43] => 452 [44] => 470 [45] => 487 [46] => 601 [47] => 614 [48] => 630 [49] => 684 [50] => 726 [51] => 727 [52] => 789 [53] => 871 )

Here's the controller:
    public function view_item_pages() {

    if ($this->input->is_ajax_request()) {

      $item_id = $this->input->post('item_id');
      $this->data['item_id'] = $item_id;
      $this->data['pages'] = $this->affiliate_model->get_all_affiliates();
      $this->data['item_pages'] = $this->item_model->get_item_pages($item_id);

      $this->load->view('/admin/item/pages', $this->data);

    }

  }

Here's the view:
<fieldset>

            <input type="checkbox" class="checkbox" id="select_all">
            ID
            Name

        <?php foreach ($pages as $page):

            $checked = FALSE;

            if (!empty($item_pages)) {
                if (in_array($page['aff_id'], $item_pages)) {
                    $checked = TRUE;
                }
            }
        ?>

                <?php echo form_checkbox('page', $page['aff_id'], $checked); ?>
                <?php echo $page['aff_id']; ?>
                <?php echo $page['name']; ?>

        <?php endforeach; ?>

</fieldset>

So if I do the following, the array works:
    <?php print_r($item_pages); ?>

    <?php foreach ($pages as $page):

        $checked = FALSE;

        if (!empty($item_pages)) {
            if (in_array($page['aff_id'], $item_pages)) {
                $checked = TRUE;
            }
        }
    ?>

If I do this, it doesn't return anything, it's like doing echo '';:
   <?php foreach ($pages as $page):

        print_r($item_pages);

        $checked = FALSE;

        if (!empty($item_pages)) {
            if (in_array($page['aff_id'], $item_pages)) {
                $checked = TRUE;
            }
        }
    ?>

A: In your controller print $pages. If $pages is empty the execution does not enter the foreach loop inside the view.
$this->data['pages'] = $this->affiliate_model->get_all_affiliates();
print_r($this->data['pages']);


text:
Q: No instance for (Data.Vector.Generic.Base.Vector ...) when using Hasql.TH I have a query I'm running in Hasql using Hasql.TH, and I'm encountering an error I've never seen before (see below). I'm seen this SO question/answer which references the version of vector, but (a) I'm using stack so these things should be resolved (right?); (b) the version of vector isn't highlighted in the error, and I'm not pinning the version in my package.yaml, so I don't think that's the problem (but I'm not sure how to verify this).
So, is is plausible that this is to do with versions of the library (I've never seen this sort of thing happen) or is there another issue I'm missing?
The query is as follows:
writeEvents :: [EventRow 'NewRecord] -> Session [EventID]
writeEvents =
  flip statement $
    dimap
      (unzip7 . map eventToRow)
      (toList . fmap (mkEventID . toInteger))
      [vectorStatement|
    insert into events (
      title,
      description,
      url,
      venue_id,
      start_date,
      end_date,
      origination
    ) (
      select
        cols.title,
        cols.description,
        cols.url,
        venues.id,
        cols.start_date,
        cols.end_date,
        cols.origination
      from unnest (
        $1 :: text[],
        $2 :: text?[],
        $3 :: text?[],
        $4 :: text[],
        $5 :: timestamptz[],
        $6 :: timestamptz[],
        $7 :: text[]
      ) as cols (title, description, url, venue_name, start_date, end_date, origination)
      left join venues on (cols.venue_name = venues.name)
    )
    returning (id :: int4)
  |]

1. No instance for (Data.Vector.Generic.Base.Vector [] (Maybe Text))
       arising from a use of 'Data.Vector.Generic.foldl''
   • In the first argument of 'hasql-1.6.3:Hasql.Private.Encoders.dimension', namely
       'Data.Vector.Generic.foldl''
     In the first argument of 'hasql-1.6.3:Hasql.Private.Encoders.array', namely
       '((hasql-1.6.3:Hasql.Private.Encoders.dimension
            Data.Vector.Generic.foldl')
           (hasql-1.6.3:Hasql.Private.Encoders.element
              (hasql-1.6.3:Hasql.Private.Encoders.nullable
                 hasql-1.6.3:Hasql.Private.Encoders.text)))'
     In the first argument of 'hasql-1.6.3:Hasql.Private.Encoders.nonNullable', namely
       '(hasql-1.6.3:Hasql.Private.Encoders.array
           ((hasql-1.6.3:Hasql.Private.Encoders.dimension
               Data.Vector.Generic.foldl')
              (hasql-1.6.3:Hasql.Private.Encoders.element
                 (hasql-1.6.3:Hasql.Private.Encoders.nullable
                    hasql-1.6.3:Hasql.Private.Encoders.text))))'```

A: As per the errors, this is because there is no Vector instance for [] (i.e. the list functor). I needed to map my tuple of lists to a tuple of vectors. Somewhat annoyingly, in my example I'm having to use a 7-tuple, for which there is no readily available unzip7 in vector, therefore I had to write vecunzip7:
vecunzip7 :: [(a, b, c, d, e, f, g)] -> (Vector a, Vector b, Vector c, Vector d, Vector e, Vector f, Vector g)
vecunzip7 xs =
  ( fromList . map (\(a, _, _, _, _, _, _) -> a) $ xs,
    fromList . map (\(_, b, _, _, _, _, _) -> b) $ xs,
    fromList . map (\(_, _, c, _, _, _, _) -> c) $ xs,
    fromList . map (\(_, _, _, d, _, _, _) -> d) $ xs,
    fromList . map (\(_, _, _, _, e, _, _) -> e) $ xs,
    fromList . map (\(_, _, _, _, _, f, _) -> f) $ xs,
    fromList . map (\(_, _, _, _, _, _, g) -> g) $ xs
  )


text:
Q: Could not find json-1.8.1 in any of the sources I'm doing a project using react-rails but when I run
bundle install

I get
Could not find json-1.8.1 in any of the sources

Specifically, this is the entire error
Gem::Ext::BuildError: ERROR: Failed to build gem native extension.

    current directory: /Users/montana/.rvm/gems/ruby-2.3.0/gems/json-1.8.1/ext/json/ext/generator
/Users/montana/.rvm/rubies/ruby-2.3.0/bin/ruby -r ./siteconf20160629-5602-i1di2t.rb extconf.rb
creating Makefile

current directory: /Users/montana/.rvm/gems/ruby-2.3.0/gems/json-1.8.1/ext/json/ext/generator
make "DESTDIR=" clean

current directory: /Users/montana/.rvm/gems/ruby-2.3.0/gems/json-1.8.1/ext/json/ext/generator
make "DESTDIR="
compiling generator.c
In file included from generator.c:1:
./../fbuffer/fbuffer.h:175:47: error: too few arguments provided to function-like macro invocation
    VALUE result = rb_str_new(FBUFFER_PAIR(fb));
                                              ^
/Users/montana/.rvm/rubies/ruby-2.3.0/include/ruby-2.3.0/ruby/intern.h:797:9: note: macro 'rb_str_new' defined here
#define rb_str_new(str, len) __extension__ (    \
        ^
In file included from generator.c:1:
./../fbuffer/fbuffer.h:175:11: warning: incompatible pointer to integer conversion initializing 'VALUE' (aka 'unsigned long') with an expression of type 'VALUE (const char *, long)' (aka 'unsigned long (const char *, long)') [-Wint-conversion]
    VALUE result = rb_str_new(FBUFFER_PAIR(fb));
          ^        ~~~~~~~~~~
1 warning and 1 error generated.
make: *** [generator.o] Error 1

There's been various posts about this on stackoverflow, and have tried most "solutions' but none seem to work for me, I also ran
gem list | grep json

It says I have the json gem via
 json (1.8.3)
 multi_json (1.10.1)

I've tried to stop spring, updating the gems, & bundler. I've also ran
rbenv rehash

To no avail, still getting this error, any input would be highly appreciated.

A: I had a problem last time on Ubuntu, i tried to install this library and it worked as well.
sudo apt-get install libgmp3-dev

You can refer document at: Failed to build gem json native extension

A: You may want to lower down your ruby version or bump json version up. See: https://github.com/flori/json/issues/229
Had a quick look at json 1.8.1 gemspec and no mention of ruby 2.3.0 support as of today.


text:
Q: click() and prop() method on checkbox element not working in Wordpress with Jquery but hide() method works I want to automatically check a category checkbox when creating a new post in Wordpress. I have the following simple .js file:
jQuery(document).ready(function($) {
  console.log('js file loaded');

        waitForElm('#inspector-checkbox-control-4').then((elm) => {
        console.log('Element is ready');
        $('#inspector-checkbox-control-4').hide();
        console.log('checked');
    });

function waitForElm(selector) {
  ...snip...
}

This works as expected and the checkbox is hidden. However, when I try to change the method on the checkbox to .check() or .prop('checked', true), the checkbox doesn't get checked. There are no errors in the console.
I should note that when clicking the checkbox manually, an svg element shows up below the checkbox element to show the tick.
I also tried clicking on all the parent elements of the checkbox but that didn't work either. Does anyone know how I can get this to work?


text:
Q: Normalize to sum to unity, but assign minimum value I want to normalize some sample that I have to sum to unity:
$$
W = \sum_{i=1}^{n} w_i
$$
$$
normalized_i = w_i/W
$$
However, it might happen that the values of normalized drop below 0.05 for some $w_i$. Whenever this is the case, I want to set the normalized value to 0.05. Is there a nice way of writing this down?
So far, I've (1) calculated W without the thresholding to 0.05, (2) thresholded all normalized values using the max(normalized, 0.05) operator, (3) calculated W again and (4) did the normalization again. This takes four equations though.
Is there a nice way to write this shorter?
The background/context for my question is the following:
I'm applying a sequential data assimilation scheme, which means I am using several noisy models to propagate the state of a system probabilistically in time. Each model has a certain amount of runs initially. The model-predicted state is updated with observations to obtain an optimal estimate for the system state. In the next cycle (propagate-update) the normalized weights shall determine with how many runs a model contributes to the next model-prediction of the state. "Good" (=closer to OBS) models shall get more runs, "bad" models less. However, "bad" models should not obtain no runs, otherwise they disappear from the ensemble. This is why normalized_i should not drop below 0.05, in this case.

A: It is inconsistent to normalize at any particular fixed percentage like 5% for each factor. For example, for 25 factors, the average weight would be 4% such that reweighing is not possible while maintaining each factor >5%. However, what is being attempted is to introduce memory to an algorithm. One way to do that is to use a running average of some type. For that, a cumulative, exponential, or weighted memory will never drop factors entirely. A simple moving average of the last $n$ trials can drop factors when $n>N$ and $N$ is the number of trials.


text:
Q: Use gsap with nuxtjs I want to use gsap in combination with ScrollMagic. ScrollMagic is already implemented and it works fine, but when I want to use animation.gsap i get the error

These dependencies were not found:
  * TimelineMax in ./node_modules/scrollmagic/scrollmagic/uncompressed/plugins/animation.gsap.js
  * TweenMax in ./node_modules/scrollmagic/scrollmagic/uncompressed/plugins/animation.gsap.js

Therefore I installed gsap via npm
npm i gsap

and imported TimelineMax and TweenMax
if (process.browser) {
    const sm = require('ScrollMagic')

    require('gsap/TimelineMax')
    require('gsap/TweenMax')

    require('scrollmagic/scrollmagic/uncompressed/plugins/animation.gsap')
    require('scrollmagic/scrollmagic/uncompressed/plugins/debug.addIndicators')

    Vue.prototype.$sm = sm
    Vue.prototype.$smController = new sm.Controller()
}

and in my nuxt.config.js file i added gsap to the vendor array
vendor: ['gsap', 'ScrollMagic', 'vuebar', 'vee-validate'],

and in my component i use this code for a paralax-effect
new this.$sm.Scene({
    triggerElement: '#js-introduction-paralax',
    triggerHook: 'onEnter'
})
    .duration('200%')
    .setTween('#js-introduction-paralax', {
        backgroundPosition: '50% 100%'
        ease: Linear.easeNone
    })
    .addIndicators()
    .addTo(this.$smController)

but i still get the error that the dependecies were not found
UPDATE
I also tried to import it in this way
import { TweenMax, TimelineMax, Linear } from 'gsap'
or seperated
import TweenMax from 'gsap/TweenMax';
import TimelineMax from 'gsap/TimelineMax';

but same result
I also tried to make aliases
resolve: {
    modules:[
      path.resolve(__dirname), path.resolve(__dirname, "node_modules")
    ],
    alias: {
        "TweenMax": path.resolve('node_modules', 'gsap/TweenMax'),
        "TimelineMax": path.resolve('node_modules', 'gsap/TimelineMax'),
        "gsap": path.resolve('node_modules', 'gsap'),
    }
},

also same result
When i write in the console
window.TweenMax

I get this
ƒ (target, duration, vars) {
            TweenLite.call(this, target, duration, vars);
            this._cycle = 0;
            this._yoyo = (this.vars.yoyo === true || !!this.vars.yoyoEase);
            this._repeat = this.vars.repe…

so something is loaded...

A: It maybe useful for you.
I also have some errors like you, and I found a solution to my problem here.
import ScrollMagic from 'scrollmagic'
import {
    TweenMax,
    TimelineLite
} from 'gsap'

import 'imports-loader?define=>false!scrollmagic/scrollmagic/uncompressed/plugins/debug.addIndicators'
import 'imports-loader?define=>false!scrollmagic/scrollmagic/uncompressed/plugins/animation.gsap'

and don't forget to do
npm i scrollmagic imports-loader


text:
Q: ActionMailer's default_url_options: How to retrieve port automatically from DefaultOptions? I often have many Rails apps running in parallel, so I have configured them to use different ports:
# Change default port of development server, see http://stackoverflow.com/questions/18103316
require 'rails/commands/server'
module DefaultOptions
  def default_options
    super.merge!(Port: 3001)
  end
end

Now it's important that this also works for ActionMailer in development env:
config.action_mailer.default_url_options = {host: 'localhost:3001'}

But instead of hardcoding this, I'd like to set it directly from DefaultOptions. How is this possible?

A: Here is a small deviation from your code:
# config/boot.rb
require 'rails/commands/server'
module DefaultOptions
  PORT = 3001

  def default_options
    super.merge!(Port: PORT)
  end
end

# This line was part of the Stack Overflow answer you quoted, and is important
# With newer Ruby versions, you can call `prepend` directly
Rails::Server.prepend(DefaultOptions)

This follows the Stack Overflow answer you quoted, with the exception of extracting the port to the constant DefaultOptions::PORT. Now note that there is nothing magical about the name of the module DefaultOptions, it simply defines a plain module that is then prepended to Rails::Server. You could have named it however you wanted. When the development server launches, a new Rails::Server object is instantiated, and at some point the default_options method is called on that object. Because of the use of prepend, the method lookup will first reach the method you defined in DefaultOptions. The super in that method simply calls the original un-prepended default_options defined in Rails::Server.
The reason why it is "hard" to get the values in default_options is because it is an instance method, meaning you can access it only on an instance of Rails::Server class, and we don't typically have a hold of the server object. You could access it like this:
# config/development.config
require 'rails/commands/server'
Rails::Server.new.default_options[:Port]

But I think this is an unnecessary dependency and object creation. The name Rails::Server also implies we may want to have just one object of this class, and I wouldn't instantiate server objects just to get a hold of their configuration hash. Therefore, extracting the port out to a constant you can hold regardless of whether you have a reference to a server object - DefaultOptions::PORT - is cleaner in my mind.
So, now that we got a hold of DefaultOptions::PORT constant, you can use it in your mailer:
# config/development.rb
  config.action_mailer.smtp_settings = {
  :port => DefaultOptions::PORT,
  :address => '...',
  :user_name => '...',
  :password => '...',
  :domain => '...',
  :authentication => :plain
}

You could also consider having the mailer and port definition in a yaml file, so that you do not need to "sprinkle" parts of your configuration in different locations - it might save you some head banging later.
If you'd like to do this, you could create a wrapper class yourself that uses YAML.load_file to load your new yaml configuration file into a hash. Alternatively, check out Figaro gem, it gives a convenient way to place all Rails configurations in a single file - application.yml - and access them from everywhere using ENV.
If you were to use Figaro, for example, and have the PORT key in application.yml, then your code may look like this:
# config/boot.rb
require 'rails/commands/server'
module DefaultOptions
  def default_options
    super.merge!(Port: ENV['PORT'])
  end
end

Rails::Server.prepend(DefaultOptions)

# config/development.rb
config.action_mailer.smtp_settings = {
  :port => ENV['PORT'],
  :address => ENV['SMTP_SERVER'],
  :user_name => ENV['SMTP_LOGIN'],
  :password => ENV['SMTP_PASSWORD'],
  :domain => ENV['MAILER_DOMAIN'],
  :authentication => :plain
}

A: You can use the Rails::Server::Options to get the information you need and then configure the ActionMailer accordingly:
config.action_mailer.default_url_options = { host: Rails::Server.new.options[:Host], port: Rails::Server.new.options[:Port] }


text:
Q: Unlock Samsung SSD 840 PRO with hdparm My Samsung SSD 840 PRO is locked with a password set by using the BIOS. Every time I turn on the computer, I have to type in the password. Cause there is a BIOS bug, I am not able to change the password. But I want to remove the password completly.
I tried to use hdparm for unlocking it, but this step fails:
> hdparm -I /dev/sd?

...
Master password revision code 1
     supported
     enabled
     locked
not  frozen
not  expired: security count
...

> hdparm --user-master u --security-unlock PASSWORD /dev/sd?

Issuing SECURITY_UNLOCK command, password="PASSWORD", user=user
SECURITY_ERASE: Input/output error

> hdparm --user-master m --security-unlock PASSWORD /dev/sd?

Issuing SECURITY_UNLOCK command, password="PASSWORD", user=master
SECURITY_ERASE: Input/output error

Is it possible to use the hdparm security commands on that drive?


text:
Q: R: lubridate's dst() not working as expected I suspect I am doing something very silly, but I can't get the dst function in lubridate to work as expected.
library(lubridate)

x <- c("2016-01-01", "2016-06-01")

dst(x) # Returns c(FALSE, TRUE)
dst(as.Date(x)) # Returns c(FALSE, FALSE)

The result I expect in both cases is c(FALSE, TRUE). However, I only get the expected result if I pass dst a character vector and not with a Date object. I'm using OS X, my current timezone is PST (America/Los_Angeles).

A: dst() calls a piece of code which is essentially:
c(NA, FALSE, TRUE)[as.POSIXlt(x)$isdst + 2]

as.POSIXlt is by default:
as.POSIXlt(x=, tz="")

...which will take your system timezone by default. So, given your location in L.A., let's look at:
as.POSIXlt(x, tz="America/Los_Angeles")
#[1] "2016-01-01 PST" "2016-06-01 PDT"
c(NA, FALSE, TRUE)[as.POSIXlt(x, tz="America/Los_Angeles")$isdst + 2]
#[1] FALSE  TRUE

Everything is fine. Hooray. Now, let's try with as.Date(x)
as.POSIXlt(as.Date(x))
#[1] "2016-01-01 UTC" "2016-06-01 UTC"
as.POSIXlt(as.Date(x), tz="America/Los_Angeles")
#[1] "2016-01-01 UTC" "2016-06-01 UTC"

Ohhh. So, as.POSIXlt does not play nicely with Date objects, and always returns UTC instead of the local timezone, and seemingly ignores any tz= argument. And since UTC does not abide by any daylight savings, you will always end up with FALSE returned.
Looking at the R source code, this seems to be the case. In https://svn.r-project.org/R/trunk/src/main/datetime.c you can find:
# R call:
#> as.POSIXlt.Date
#function (x, ...)
#.Internal(Date2POSIXlt(x))

# source code:
#SEXP attribute_hidden do_D2POSIXlt(SEXP call, SEXP op, SEXP args, SEXP env)
#{
#...
setAttrib(ans, s_tzone, mkString("UTC"));

...as a hard-coded string.


text:
Q: Join two JSON files and create a new one I can't find a lookup table where all country codes are packed together with their names in different languages, so I have to create my own file.
Let's start with two languages, German and English.
German JSON file example:
[{"id":4,"name":"Afghanistan","alpha2":"af","alpha3":"afg"},
{"id":818,"name":"Ägypten","alpha2":"eg","alpha3":"egy"},
{"id":248,"name":"Åland","alpha2":"ax","alpha3":"ala"},
{"id":8,"name":"Albanien","alpha2":"al","alpha3":"alb"},
{"id":12,"name":"Algerien","alpha2":"dz","alpha3":"dza"}]

English JSON file example:
[{"id":4,"name":"Afghanistan","alpha2":"af","alpha3":"afg"},
{"id":248,"name":"Åland Islands","alpha2":"ax","alpha3":"ala"},
{"id":8,"name":"Albania","alpha2":"al","alpha3":"alb"},
{"id":12,"name":"Algeria","alpha2":"dz","alpha3":"dza"},
{"id":16,"name":"American Samoa","alpha2":"as","alpha3":"asm"},

I can read both files like that
with open('german.json') as fd:
    ger = json.load(fd)

Since we have unique ids for the countries we can join them together.
The result should look something like that
[{"id":4,"ger":"Afghanistan","eng":"Afghanistan","alpha2":"af","alpha3":"afg"},
{"id":818,"ger":"Ägypten","eng":"Egypt","alpha2":"eg","alpha3":"egy"},
{"id":248,"ger":"Åland","eng":"Åland Islands","alpha2":"ax","alpha3":"ala"},
{"id":8,"ger":"Albanien","eng":"Albania","alpha2":"al","alpha3":"alb"},
{"id":12,"ger":"Algerien","eng":"Algeria","alpha2":"dz","alpha3":"dza"}]

What's the most effective way to join the lists together considering that other languages can be added in the future?

A: As suggested in the comments it's easier to load the files into dataframes and merge them together.
A working solution would be
german = pd.read_json('world.json')
english = pd.read_json('world_en.json')

lookup = pd.merge(german, english, on='id')
lookup = lookup.drop(columns=['alpha2_y', 'alpha3_y'])
lookup = lookup.rename(columns={'name_x': 'de', 'name_y': 'en', 'alpha2_x': 'alpha2', 'alpha3_x': 'alpha3'})
lookup = lookup[['id', 'de', 'en', 'alpha2', 'alpha3']]

lookup.to_json('lookup.json', orient='records')

Only downside with this solution is we have to drop and rename more and more columns with more languages.


text:
Q: View restriction at a page level I want to create a page with a special view of one list, but I want that only one user can access this page. Is it possible? MOSS 2007

A: Since the page has to be stored in a library, you can simply break permissions on this single page and give permissions only to one user.

A: You can create a page in a Page Library and affect the good security to this item.  It would do the trick.  On the other side, your list view can't have security elements, so, if a user gets to the list, he will be able to view the list and the views.


text:
Q: Performing 'document.execCommand' on 'delete' keyevents - AngularJS I have created this demo plunkr to replicate the issue.
I want to apply strikeThroughcommand whenever a delete operation is performed. For example:
If user selects "Text" and press delete or backspace , it should become Test. It shouldn't get deleted.
Can someone help me on
$container.bind('keydown keyup', function (e) {
    console.log(e)
    if(e.keyCode===8 || e.keyCode===46){
        $document[0].execCommand('strikeThrough', false); // line 1
        e.preventDefault();  // line 2
    }
});

I can capture the events as below but line 1 and line 2 doesn't work together. So how stop delete event and apply execCommand ?

A: You did bind "twice".
It is not "don't work", it is "work twice".
Fix code as following:
$container.bind('keyup', function (e) {
    console.log(e)
    if(e.keyCode===8 || e.keyCode===46){
        $document[0].execCommand('strikeThrough', false); // line 1
        e.preventDefault();  // line 2
    }
});
$container.bind('keydown', function (e) {
    console.log(e)
    if(e.keyCode===8 || e.keyCode===46){
        e.preventDefault();  // line 2
    }
});


text:
Q: MSBuild error MSB3155 on Jenkins I am trying to build and publish a .net application through MSBuild in a Jenkins CI Server, and I am getting the errors bellow

*

*warning MSB3155: Item 'Microsoft.Sql.Server.Express.9.2' could not be located in

*warning MSB3155: Item 'Microsoft.Net.Framework.2.0' could not be located in

Does anybody know how to fix this problem? How could I install those components into my Bootstrapper files? (there is nothing at C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Bootstrapper)
I am using MSBuild 4.0 (because the solution was created in vs2010) and the target framework is 2.0.
Thanks

A: I solved this issue by installing a x64 version of the Microsoft Windows SDK...so the corretc path is C:\Program Files\Microsoft SDKs\Windows\v7.0A\Bootstrapper = Without the (x86) string.


text:
Q: How can I create an array of objects without creating extra instance variables? I am trying to solve the following question:

Implement a class called TriangleArray which has the following:
No other instance variables or constants allowed.

*

*An instance variable called list which is an array of Triangle objects.

*No other instance variables or constants allowed.

*Only one constructor which has two integer parameters. The first parameter called number is
the length of list. The second parameter called maxSize is the maximum size allowed for the

*The constructor initializes list to an array of Triangle objects.

*The sides of each Triangle object are randomly generated integers in the range from 1 to
maxSize.

*Getter and setter methods for list.

*A largest method with no parameters. The method returns the largest Triangle in list.

*A toString method which returns a description of each Triangle in list.

How can I populate the list full of random objects without using other instance variable?
Here is the code that I have so far:
import java.util.Random;
public class TriangleArray
{
  private Triangle[ ] list;
  // list is an array of "number" Triangle objects.
  // The maximum size of each Triangle edge is "maxSize".
  public TriangleArray (int number,  int maxSize);
  {
    list = new Triangle[number];

A: You can do this with the local variables in functions.
public TriangleArray (int number,  int maxSize) {
    list = new Triangle[number];
    Random random = new Random();
    for(int i = 0; i < number; list[i] = makeRandomTriangle(random, maxSize);
}

private function makeRandomTriangle(Random random, int maxSize) {
    int a = random.nextInt(maxSize) + 1,
        b = random.nextInt(maxSize) + 1;

    // |a - b| <= c <= (a + b) because of the triangle inequality
    int min = Math.max(a - b, b - a),
        max = Math.min(maxSize, a + b);
    int c = rand.nextInt((max - min) + 1) + min;
    new Triangle(a, b, x);
}

A: An instance variable, or field, is not the same as a local variable.
See: What is the difference between a local variable, an instance field, an input parameter, and a class field?
You can use local variables just fine, like:
public TriangleArray (int number,  int maxSize) {
  list = new Triangle[number];
  for(int i = 0; i < number; i++) {
    list[i] = makeTriangle(maxSize);
   }
}

private makeTriangle(maxSize) {
  Random r = new Random();

  do {
    int first = r.nextInt(maxSize - 1) + 1;
    int second = r.nextInt(maxSize - 1) + 1;
    int third = r.nextInt(maxSize - 1) + 1;

    int max = Math.max(first, Math.max(second, third));
  } while ((2 * max) - first - second - third) > 0);

  return new Triangle(first, second, third);
}

In this code you never create a new instance variable.

A: You do not need to use instance variables to fill in random numbers. You could use your java.util.Random or Math.random:
list = new Triangle[number];
for (int i = 0; i < list.length; i++) {
    int a = (int)(Math.random() * (maxSize + 1));
    int b = (int)(Math.random() * (maxSize + 1));
    int c = (int)(Math.random() * (maxSize + 1));

    //handle the triangle inequality:
    while (c > a + b || c < Math.abs(a - b)) {
        c = (int)(Math.random() * (maxSize + 1));
    }

    list[i] = new Triangle(a, b, c);
}

A: Assuming a Triangle object's constructor looks like:
public Triangle(int a, int b, int c) { ...

We initialize the array with:
Random r = new Random(); // random number gen
for ( int i = 0; i < number; i++ ) {
  int a = r.nextInt(maxSize-1) + 1; // randomly generate each side
  int b = r.nextInt(maxSize-1) + 1;
  int c = r.nextInt(maxSize-1) + 1; // this won't necessarily make a proper triangle
  list[i] = new Triangle(a, b, c);
}

We have to create a random number generator, then we have to iterate through the entire array of uncreated Triangles and create them. While iterating, we randomly generate each side a, b, and c, to a number from 1 to maxSize, then create the Triangle object at the current index.
The list is your instance variable, meanwhile the variables a, b, c, and r are all local variables to the constructor or whatever function you put them in.


text:
Q: Why do I get a 404 Error when attempting to get an access_token from google OAuth 2.0? I'm currently building a OAuth authorization to get email and profile info only.
I can get the code easy using the following:
def authorize
  base = "https://accounts.google.com/o/oauth2/auth?"
  params = {
    :scope => "https://www.googleapis.com/auth/userinfo.profile",
    :redirect_uri => "http://localhost:3000/oauth/callback/",
    :client_id => "id",
    :response_type => 'code'
  }
  redirect_to base + params.to_query
end

However, when I try to get the access token from Google, I get a 404 error:
def callback
  code = params[:code]
  client_id = 'id'
  client_secret = 'secret'
  redirect_uri = "http://localhost:3000/oauth/callback/"
  http = Net::HTTP.new('accounts.google.com', 80)
  path = "https://accounts.google.com/o/oauth2/token?"
  headers = {'Content-Type'=>"application/x-www-form-urlencoded" }
  parameters = "code=#{code}&grant_type=authorization_code&client_secret=#{client_secret}&client_id=#{client_id}&redirect_uri=#{redirect_uri}"
  resp, data = http.post(path,parameters,headers)
end

response code: 404  data: Google Home | Sign in

The page you requested is invalid.

I'm not entirely sure what the issue might be. I've tried to match with copy+paste the registered callback URL. I've checked my parameters multiple times and I cannot find what could be causing the error.
I'm following the Google documentation and registered with Google with the following information:
Client ID for web applications
Client ID: id
Client secret: secret
Redirect URIs: http://localhost:3000/oauth/callback/
JavaScript origins: none

A: Got it working!
Seems like i was missing a couple of things:

*

*Added the SSL settings for the HTTP request.

*Send the parameters as the body and not as part of the request.

*Put the content-type in the request correctly.

I hope this helps someone out there!
param = {
  :code => params[:code],
  :client_id => client_id,
  :client_secret => client_secret,
  :redirect_uri => "http://localhost:3000/oauth/callback/",
  :grant_type => 'authorization_code'
}

uri = URI.parse("https://accounts.google.com/o/oauth2/token")
http = Net::HTTP.new(uri.host, uri.port)
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
http.use_ssl = true
request = Net::HTTP::Post.new(uri.request_uri)
request["Content-Type"] = "application/x-www-form-urlencoded"
request.body = param.to_query
response = http.request(request)

A: If you are trying to get Google to redirect to:
:redirect_uri => "http://localhost:3000/oauth/callback/",

I suspect they can't find localhost. Give them your real IP number.


text:
Q: Bootbox + jQuery DataTables. Bootbox run function after pop-up I'm using Bootbox to display a pop-up that contains a table, this part works great.
But now I want to use the jQuery DataTables plugin on the just created table for sorting.
This requires me to call the DataTables plugin on the table I just created witthin the bootbox.
But I can't find any way to call a javascript/jQuery function after the bootbox pop-up has being created, if you write code inside the bootbox function it'll only happen when the bootbox pop up is closed.
How do I run a function after the bootbox pop-up has popped up and while it still is up?
$(document).on('click', ".myButton", function () {
        var userName = "
"+ ($(this).data("username")) +"
";
        var tableHeader = "

" +
                          "Header 1	" +
                          "Header 2	" +
                          "Header 3	" +
                          "

";
        var tableData = $(this).data("value");

        var table = "
" + tableHeader + "
" + tableData + "
" + "
";
        bootbox.alert(userName + table, function (result) {
        });
    });

What I need to place within this code is basically this
var oTable = $('#myTable').dataTable({
          null, null, null
        ]
    });

It is possible that I need to destroy and recreate the datatables between the pop-ups but that isn't the issue right now.

A: It actually worked to just place it after the bootbox call.
But can't this lead to desync issues? i.e if the user is on a slow computer or the table/bootbox is heavy then it'll try to call the dataTables plugin before the bootbox is actually finished
$(document).on('click', ".myButton", function () {
            var userName = "
"+ ($(this).data("username")) +"
";
            var tableHeader = "

" +
                              "Header 1	" +
                              "Header 2	" +
                              "Header 3	" +
                              "

";
            var tableData = $(this).data("value");

            var table = "
" + tableHeader + "
" + tableData + "
" + "
";
            bootbox.alert(userName + table, function (result) {
            });

            var oTable = $('#myTable').dataTable({
                null, null, null
            ]
            });
});


text:
Q: Logic behind finding a $ (2 \times 2) $-matrix $ A $ such that $ A^{2} = - \mathsf{I} $. I know the following matrix "$A$" results in the negative identity matrix when you take $A*A$ (same for $B*B$, where $B=-A$):
$$A=\begin{pmatrix}0 & -1\cr 1 & 0\end{pmatrix}$$
However, I am not certain how one would go about finding this matrix without guessing and checking. Is there some systematic way of doing so? I have tried by assuming the following:
$$\begin{pmatrix}a & b\cr c & d\end{pmatrix}^2 = \begin{pmatrix}-1 & 0\cr 0 & -1\end{pmatrix}$$
...and then get the following equations:
$$a*a+b*c=-1$$
$$a*b+b*d=0$$
$$a*c+c*d=0$$
$$b*c+d*d=-1$$
This only tells me that $a=-d$, and then as best I can tell leaves both $c$ and $d$ without a solution, so perhaps this isn't the best method, but its the only approach that's coming to mind.
Any suggestions?

A: the negative identity matrix $B = \pmatrix{-1&0\\0&-1}$  represents the half rotation. so if you pick the matrix $A = \pmatrix{0&-1\\1&0}$ representing quarter rotation, then you should have $A^2 = B = -I.$

A: The most systematic way I know to attack this problem is to break the set of all possible such $A$, i.e., $2 \times 2$ matrices with
$A^2 = -I \tag{1}$
into categories according to $\text{Tr}(A)$, the trace of $A$.  With
$A = \begin{pmatrix} a & b \\ c & d \end{pmatrix} \tag{2}$
we have
$A^2 = \begin{pmatrix} a^2 + bc & b(a + d) \\ c(a + d) & d^2 + bc \end{pmatrix}, \tag{2}$
as may be easily seen; note that
$\text{Tr}(A) = a + d. \tag{3}$
With
$A^2 = -I \tag{4}$
we have
$a^2 + bc = -1; \tag{5}$
$d^2 + bc = -1; \tag{6}$
$(a + d)b = b\text{Tr}(A) = 0; \tag{7}$
$(a + d)c = c \text{Tr}(A) = 0. \tag{8}$
If
$\text{Tr}(A) \ne 0, \tag{9}$
we see that
$b = c = 0, \tag{10}$
whence
$a^2 = d^2 = -1; \tag{11}$
thus
$a = \pm i \tag{12}$
and
$d = \pm i; \tag{13}$
there are no real solutions; furthermore since $\text{Tr}(A) \ne 0$ we must in fact have $a = d$, thus in this case we may only have
$A = \pm i I. \tag{14}$
The case $\text{Tr}(A) = 0$ yields
$d = -a;  \tag{15}$
we can thus choose $a = \alpha \in \Bbb C$ freely and then $d = -\alpha$.  (15) implies
$a^2 = d^2 = \alpha^2, \tag{16}$
so that both (5) and (6) become
$\alpha^2 + bc = -1, \tag{17}$
$bc = -1 - \alpha^2; \tag{18}$
in the event $\alpha \ne \pm i$ we can choose
$0 \ne \beta \in \Bbb C \tag{19}$
then set
$b = \beta, \tag{20}$
and find
$c = -\dfrac{1 + \alpha^2}{\beta} \ne 0; \tag{21}$
thus
$A = \begin{pmatrix} \alpha & \beta \\ -\dfrac{1 + \alpha^2}{\beta} & -\alpha \end{pmatrix}, \;\; \alpha, \beta \in \Bbb C, \; \beta \ne 0. \tag{22}$
The case $\alpha = \pm i$ forces
$bc = 0; \tag{23}$
thus, at least one, and perhaps both, of $b, c = 0$.  Now $A$ takes either the form
$A = \begin{pmatrix} \pm i & \beta \\ 0 & \mp i \end{pmatrix}, \;\;  \beta \in \Bbb C, \tag{24}$
or the transposed form
$A = \begin{pmatrix} \pm i & 0 \\ \beta & \mp i \end{pmatrix}, \;\;  \beta \in \Bbb C. \tag{25}$
Of course, if we require real $A$, then (11)-(14) are denied to us; only cases with $\text{Tr}(A) = 0$ are permitted; we can however choose $\alpha \in \Bbb R$ freely as we can $0 \ne \beta \in \Bbb R$; $1 + \alpha^2 \ne 0$ in this case, but $A$ is still given by (22), though (24), (25) are ruled out.
That's the most systematic analysis of this problem I know.  The observation that $\text{Tr}(A)$ provides a convenient classification of solutions is perhaps not a surprise in light of the importance of the trace, a similarity invariant, to a general understanding of matrices.  (Note that the equation $A^2 = -I$ is in fact preserved under similarity:  $(P^{-1}AP)^2 = A^2 = -I$.)  However, this line of analysis only works for matrices of size $2$.
A similar analysis of the case $A^2 = I$ may be found in my answer to this question; further commentary may there be found.
Finally, I for one would be very interested in seeing how these techniques carry over to matrices over other fields, such as the $GF(p^n)$ etc.; offhand, it seems as long as we are not in characteristic $2$, many of the arguments will fly.

A: If you assume that $A$ is invertible, then you can write:
$$
AA = -\mathbb{I}_2 \rightarrow A^{-1}AA = -A^{-1}\mathbb{I}_2 \rightarrow A = -A^{-1}\mathbb{I}_2
$$
But we know the inverse for a $2\times2$ matrix--and it's going to create a set of four linear equations for four variables:
$$
\begin{pmatrix}
a& b \\
c & d
\end{pmatrix} = \begin{pmatrix}
-d & b \\
c & -a
\end{pmatrix}
$$
This creates four equations:
\begin{align}
a = -d \rightarrow a + d = 0 \\
b = b \\
c = c \\
d = -a \rightarrow a + d = 0
\end{align}
This suggests that this is trues for all values of $a$ and $d$ such that $a + d = 0$ and any values of $b$ and $c$.  Let's check:
$$
\begin{pmatrix}
a & x \\
y & -a
\end{pmatrix}
\times \begin{pmatrix}
a & x \\
y & -a
\end{pmatrix}
=
\begin{pmatrix}
a^2 + xy & ax - ax \\
ay - ay & xy + a^2
\end{pmatrix}
$$
Then it's a matter of solving the equation $a^2 + xy = -1$.  For instance, we could choose $a = 2$ and $xy = -5$:
$$
\begin{pmatrix}
2 & -5 \\
1 & -2
\end{pmatrix}
\text{ and its inverse }
\begin{pmatrix}
-2 & -5 \\
1 & 2
\end{pmatrix}
\text{ both work}
$$
...obviously there are many more you could choose.  A general way would be:
$$
\begin{pmatrix}
a & b \\
-\frac{a^2 + 1}{b} & -a
\end{pmatrix}
\text{ or }
\begin{pmatrix}
a & -\frac{a^2 + 1}{b} \\
b & -a
\end{pmatrix}
$$
It may be worth noting that if $b = 0$ then $a^2 + 1 = 0$ must also be true so that the other value, $\frac{a^2 + 1}{b}$, can take on any value.  In this case we get: $a^2 = -1 \rightarrow a = \pm i$ and gives the equation $a^2 + 2xy = -1 \rightarrow -1 + 2*x * 0 = -1 \rightarrow -1 = -1$ (which is true for any value of $x$--the non-zero off diagonal).  So this gives the other answer as well:
$$
\begin{pmatrix}
\pm i & 0 \\
x & \mp i
\end{pmatrix}
\text{ or }
\begin{pmatrix}
\pm i & x \\
0 & \mp i
\end{pmatrix}
$$
You can have arbitrarily complex components.  For instance choose $a = 5i$.  This gives: $a^2 + xy = -1 \rightarrow -25 + xy = -1 \rightarrow xy = 24$.  So we could choose 6 and 4, 3 and 8, 2 and 12...or any two real values (or any two complex values--although they would have to be conjugates).  Another complex example:
$$
\begin{pmatrix}
5i & 3 \\
8 & -5i
\end{pmatrix}
$$
or perhaps:
$$
\begin{pmatrix}
3i+2 & -4 \\
3i - 1 & -3i - 2
\end{pmatrix}
$$

A: One reason that it is hard to describe a systematic procedure that will let you find that solution to $A^2=-I$ is that there are so many other solutions to this equation. A solution cannot have real eigenvalues, so the image of the first standard basis vector $e_1$ (which give the firs column of your matrix) cannot be a multiple of $e_1$ itself, but otherwise it can be any vector$~v$ whatsoever. Then $[e_1,v]$ will be a basis of $\Bbb R^2$, and one can arrange that $A\cdot v=-e_1$ (since one can choose the images of a basis freely when defining a linear map), which will ensure that $A^2=-I$ (an easy check).
But the example you gave is so obtained for the simplest choice of$~v$, namely $v=e_2$.


text:
Q: Vector $V^\mu$ vs the Lorentz contravariant components $V^a(x)$ The vector $V^\mu$ was related to the Lorentz contravariant components $V^a(x)$
\begin{equation}
V^a(x)=e^a_\mu(x) V^\mu
\end{equation}
where $V^\mu$ was contravariant under the general coordinate transformation.
(D-branes, Clifford Johnson Page 67)
Notice that $a$ and $\mu$ does not have to have the same dimension, and from the context it seemed that $V^a$ had less degree of freedom?($|\{a\}|\leq|\{\mu\}|$)
This looked like a dimension reduction procedure, but was different from the compatification, i.e. with the compatification procedure, the extra index($\mu=25$) was still there, just not observed under the low energy. But the Lorentz contravariant components eliminated the index completely. The similar thing was the basis from the world sheet to target space, but $V^a(x)$ and $V^\mu$ were obviously both the concept of the target space.
On the other hand, the $V^a(x)$ now dependent on the coordinate $x$, but not for $V^\mu$?(or was it an abbreviation?)
Could you give a hint of how the vector $V^\mu$ and the Lorentz contravariant components $V^a(x)$ was used?
Related:What is the Difference between Lorentz Invariant and Lorentz Covariant?

A: This is just a choice of basis of vector fields in a smooth manifold really. Let $(M,g)$ be a $D$-dimensional smooth manifold with Lorentzian metric. Let $U\subset M$ be one open set and let $x:U\to \mathbb{R}^D$ one local chart. Inside $U$ we have a basis of vector fields, the coordinate frame $\partial_\mu$. They allow you to expand a general vector field $X:M\to TM$, inside that open set, as $$X|_U = X^\mu \partial_\mu\tag{1}.$$
Now, this basis is not necessarily orthonormal. In fact the inner products between basis vectors gives you the metric components in the associate coframe basis, $$g_{\mu\nu}(x)=g\left(\partial_\mu,\partial_\nu\right),\quad x\in U\tag{2}$$
and it is clear that $g_{\mu\nu}\neq \eta_{\mu\nu}$ in general. We can, however, always find one orthonormal basis locally. Let us suppose we have found such a basis in another open set $U'\subset M$, and let us denote such a basis by $e_a$ where $a=0,\dots, D-1$ identifies the different vectors. Since each $e_a$ is just a vector, in the overlap $U\cap U'$, which we shall assume non-empty, we may expand each $e_a$ the coordinate basis: $$e_a = e_a^\mu \partial_\mu.\tag{3}$$
This defines a $D\times D$ matrix $e_a^\mu$ which contains the components of the vectors making up the orthonormal frame. Such orthonormal frame is what in Physics one often calls a vielbein.
Now consider the vector field $X$ again. Inside $U\cap U'$ we have two bases available: the coordinate basis $\partial_\mu$ and the vielbein $e_a$. We can expand $$X = X^\mu \partial_\mu = X^a e_a.\tag{4}$$
Denoting the inverse matrix of $e_a^\mu$ by $e^a_\mu$ you can easily check that the relation between components (4) implies is $X^a = e^a_\mu X^\mu$. For a general vector field both sets of components will depend on the manifold point you evaluate it, i.e., it will in general be non-constant.
There are two main uses for this:

*

*As usual, working with one orthonormal basis often gives great simplifications. This is something that should be familiar from linear algebra and all of Physics really.

*A deeper reason to introduce this construction is to be able to define the concept of spin structures and introduce spinor fields. It is not possible to give a self-contained discussion of this subject in this answer, but the basic idea is that $(M,g)$ has one natural ${\rm SO}(1,d-1)$ bundle defined over it, the bundle of orthonormal frames. A choice of vielbein $e_a$ on an open subset trivializes this bundle over the open set. If you choose an open covering of $M$ and define vielbeins on all of them, the way the vielbeins are matched on the overlaps basically define the structure of the bundle.
Now depending on the topology of $M$ you may use this construction to build a ${\rm Spin}(1,D-1)$ bundle over $M$ called bundle of spin frames. When this is done, you have one spin structure and you can define spinor fields over $M$. So, in a sense, to be able to introduce spinor fields in a general, possibly curved Lorentzian manifold $(M,g)$, the first step is to introduce vielbeins. A minor comment here is that not all manifolds admit spin structures and that those admiting spin structures might have more than one.

A: The $e^{a}_{\mu}$ objects are called vierbein field (or tetrads, or frame fields) and connect a general frame of coordinates (in which vectors are expressed as $V^{\mu}$) to a local frame of reference. The latter is very often a local inertial frame, but it doesn't need to be one in general.
The article on Frame fields in general relativity should clarify your doubts.


text:
Q: Inner Join: Is this an optimal solution? T1: employee [id, salary]
T2: department [name, employeeid]
(employeeid is a foreign key to T1's id)
Problem: Write a query to fetch the name of the department which receives the maximum salary.
My Solution:
SELECT DISTINCT name
FROM department AS a
INNER JOIN employee AS b ON a.employeeid = b.id
AND b.salary
IN (
    SELECT max( salary )
    FROM employee AS c
)

Edit: The problem statement is accurate, and we're not trying to find out the employee who has the highest salary. It says "....Department which receives.....", not "...employee who receives....".
Is this ok? Or can this be optimized?

A: GROUP BY the name of the department and order by SUM(salary).
SELECT department.name
FROM department
JOIN employee ON department.employeeid = employee.id
GROUP BY department.name
ORDER BY SUM(salary) DESC
LIMIT 1

A: How about:
SELECT employee.id, employee.salary, department.name
FROM department, employee
where
employee.id = department.employeeid and
employee.salary = (select max(salary) from employee)


text:
Q: Apple Pay Payment Services Exception merchantId=1234ABCD not registered for domain=xyz.com I experienced this error when my server made a session token request to start an "Apple Pay on the Web" session.

A: Causes of this error include:

*

*Registering the www or root merchant domain with Apple Pay but not redirecting one to the other, will cause this error.

*Merchant domain that hasn't been verified, or was verified once but Apple cannot reach the file /.well-known/apple-developer-merchantid-domain-association.txt on your domain.
Solution:
Go to the Apple Developer account, to Identifiers. Select Merchant IDs from the right drop-down. Select the merchant identifier.
Scrolling down to Merchant Domains I saw that my domain status was pending.
Select Verify then Download. Download the verification file and place it in the .well-known folder per Apple's instructions.

*You need valid payment processing certificate as well as a valid merchant identity certificate.


text:
Q: Auto grid sizing allowing nth max in a row in css I am trying to Auto-Sizing Columns in CSS Grid. Like if I have one child-div it will cover full space in mother-div. But if there are multiple child-div it will allow specific number of child-div in a row . Here I am using CSS grid. But I cant do it. Here is my code

css
.child-div {
    background-color: #257790;
    height: 100px;
    width: 100%;
}

.mother-div {
    display: grid;
    grid-template-columns: 1fr 1fr 1fr 1fr 1fr;
    grid-gap: 1em;
}

A: What you are looking is almost automatic, grid will behave like this almost out of the box.
You only need to set grid-auto-flow to the direction that you want
To limit the number of items per row, you need to set them to a specific column, using nth-child selector
this style:
.child-div:nth-child(5n+1) {
    grid-column: 1;
}

selects childs for n values 0, 1, 2, and so on, that in the formula 5n+1 gives values 1, 6, 11, 16, ...
All those children will go to column 1, that matches the requirement for 5 elements per row.

.child-div {
    background-color: #257790;
    height: 50px;
    width: 100%;
}

.child-div:nth-child(5n+1) {
    grid-column: 1;
}
.child-div:nth-child(5n+2) {
    grid-column: 2;
}
.child-div:nth-child(5n+3) {
    grid-column: 3;
}
.child-div:nth-child(5n+4) {
    grid-column: 4;
}
.child-div:nth-child(5n) {
    grid-column: 5;
}

.mother-div {
    margin: 10px;
    width: 500px;
    border: solid 3px black;
    display: grid;
    grid-gap: 1em;
    grid-auto-flow: column;
}

1

2

3

4

5

6


text:
Q: Error: Could not shut down embedded database: The database is open in exclusive mode; can not open additional connections [90135-200] I am using H2 DB for my JUnit testing and getting this error in my JUNIT test cases -
INFO [extShutdownHook] o.s.j.d.e.H2EmbeddedDatabaseConfigurer   o.s.j.d.e.AbstractEmbeddedDatabaseConfigurer.shutdown(AbstractEmbeddedDatabaseConfigurer.java:53) - ||||||||||||||--|Could not shut down embedded database: org.h2.jdbc.JdbcSQLNonTransientConnectionException: The database is open in exclusive mode; can not open additional connections [90135-200]
My DB Set up file looks like this -
@Configuration
@ComponentScan(basePackages={"com.sample.repository"})

public class SampleDBConfig {

JdbcTemplate jdbcTemplate = null;
DataSource dataSource = null;

@Bean
public JdbcTemplate jdbcTemplate()
{
if(jdbcTemplate == null){
    LOGGER.info("JdbcTemplate is null, so calling to create ");
    jdbcTemplate = new JdbcTemplate(getDataSource());
}else{
    LOGGER.info("JdbcTemplate is already set");
}
return jdbcTemplate;
}

@Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
     return new PropertySourcesPlaceholderConfigurer();
}

@Bean
DataSource getDataSource() {
  EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder();
  if(dataSource == null){
    dataSource = builder
            .setType(EmbeddedDatabaseType.H2)
            .addScript("classpath:folder/initial-setup.sql")
            .build();
}
return dataSource;
}

}

One of my JUNIT test class looks like this -
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SampleDBConfig.class)
public class XyxImplTest{

@Autowired
ClassInTestImpl classInTestImpl ;

@Test
public void testMethod(){
.......
}
}

And one of the classes am testing are like this -
@Component
@Transactional(rollbackFor = Exception.class)
public class ClassInTestImpl implements ClassInTest {

@Autowired
private JdbcTemplate jdbcTemplate;
.....

Am using SpringJUnit4ClassRunner.class for my JUNIT tests and invoking this DB set up class from each JUNIT test class using @ContextConfiguration(classes = SampleDBConfig.class). I do not want to execute the JUNIT tests sequentially, is there any way we can resolve this issue?


text:
Q: Is "together" used as a noun in these sentences?

*

*'It took us 22 years to tie the knot.. we may not have long together but I'll treasure these memories forever'. (from Source
  1)

*"Every time we touch I melt." Our eyes locked for a long moment afterwards, and I regretted the fact we were in public and didn't
  have long together. (from Source 2)

*'We didn't have long together, Roger, your real grandfather. (from Source 3)

It seems like "together" is used as a noun and "long" is an adjective modifying "together".
It's my first time I've come across this expression, but it doesn't sound quite correct, because I couldn't find out "together" can be used as a noun in any dictionaries.
So, my opinion is "long together" is the direct object of "have" because other than this, there seems to be no way to analyze those sentences.


text:
Q: jetpack compose. infinite call to observeAsState I monitor the behavior of a variable that is in the viewmodel using the observeAsState function. When I get the state I need, I switch to another screen, but after that my program hangs in an endless loop. What am I doing wrong, please tell me?
The image below shows the logs of the monitored variable from the viewmodel

The code below shows the only function in which I change the value of _loginStatus, which I need to track through observeAsState. Nowhere else does the value of _loginStatus change:
fun authorize(automaticLoad: Boolean = false) = CoroutineScope(Dispatchers.IO).launch {

        setStatus(Status.Loading())
        repository.authoriseAccount(storedLogin.value.orEmpty().trim(), storedPassword.value.orEmpty().trim(), getApplication()).let {
            withContext(Dispatchers.Main) {
                when (it) {
                    is Resource.Success -> {

                        _loginStatus.postValue(Status.Success(it.data))

                    }
                    is Resource.Error -> {
                        Log.e("AUTH", "auth error")
                        if (!automaticLoad){
                            _loginStatus.postValue(Status.Error("Incorrect login or password entered"))
                        }
                        else{
                            _loginStatus.postValue(Status.Error())
                        }
                    }

                }
                //_loginStatus.postValue(Status.Ready())
                _loginStatus.setValue(Status.Ready())
            }
        }
    }

Code in the Composable function:
val status by  viewModel.loginStatus.observeAsState()
    Log.e("tag", status.toString())

A: I had the same problem and I solved it this way
val status by  viewModel.loginStatus.observeAsState()
    Log.e("tag", status.toString())

LaunchedEffect(true) {
     viewModel.authorize()
 }

//whatever you want to do with the status variable

The reason is explained here: https://developer.android.com/jetpack/compose/side-effects


text:
Q: Boost log - cleanup & shutdown I have an initialization function which sets up boost log via add_common_attributes(), register_simple_formatter_factory(), register_sink_factory() and init_from_stream() (all are functions within namespace ::boost::log)
I want to be able to tear down the types I've registered later. It appears easy enough to remove the sinks and unregister attributes using the logging core. But there does not appear to be a way to tear down the registered formatters nor the registered sink factories. There also does not appear to be a way to cleanly tear down the logging core.
Am I missing something? Is there an example of doing this?
I'm originally using boost 1.55 however I've also looked through 1.57 and 1.58 to no avail.
Ultimately what I need to be able to do is create effectively a wrapper library which can be loaded from multiple applications to provide consistent logging without code duplication to set up. I need the ability to set up and tear down boost::log as part of unit testing the features and different configurations.


text:
Q: odoo how to set selected attribute in website-template I have a bit of trouble in Odoo, setting the selected attribute for a website-formular.
I have some data in an underlying model, which is displayed in a table inside the form. The lines are displayed correctly, but the values for the select-field are not set correctly. It always shows the first value in the select-list instead the saved value in the model.
    <t t-foreach="quote_lines" t-as="quote_line">

          <select t-attf-name="supplier_{{quote_line.line}}">
             <t t-foreach="categories" t-as="c">
                <t t-if="c.name==quote_line.supplier"><option t-field="c.name" selected="selected" /></t>
                <t t-if="c.name!=quote_line.supplier"><option t-field="c.name" /></t>
             </t>
          </select>

        ....

    </t>

The form is loaded into odoo and displays fine - except that the -tag ignores my selected attribute. When i look in the generated html, the select/option values are set, just this attribute is ignored.
Any hints what i'm doing wrong or just don't see?

A: Try using selected="True"
Also, take a look at how website_sale does for countries:

                  Country
                  <select name="shipping_country_id" class="form-control" t-att-disabled="  'disabled' if shipping_id >= 0 else ''">
                      <option value="">Country...</option>
                      <t t-foreach="countries or []" t-as="country">
                          <option t-att-value="country.id" t-att-selected="country.id == checkout.get('shipping_country_id')"><t t-esc="country.name"/></option>
                      </t>
                  </select>

https://github.com/odoo/odoo/blob/9.0/addons/website_sale/views/templates.xml#L1072-L1080


text:
Q: Python subprocess slower when python is executed from VBA Here is VBA
Sub patseersearchPats1()
    pyfile = "path/to/test.py"
    Set objShell = CreateObject("WScript.Shell")
    ccmd = "python" & " " & pyfile & " " & """" & Selection.Range.Text & """"
    objShell.Run ccmd, 0, False
End Sub

here is python
import subprocess
import os
import uuid
import sys
import time

appdata = os.getenv('APPDATA')
npp = os.path.join(appdata, r"npp.7\notepad++.exe") #path to minimalistic npp 7

def MsgBox(data):
    temp = os.path.join(appdata, str(uuid.uuid4()) + '.md')
    with open(temp, 'a', encoding='utf-8') as f:
        f.write(data + '\n')

    subprocess.call([npp, temp])
    time.sleep(1)
    os.remove(temp)

if __name__ == "__main__":
    MsgBox(sys.argv[1])

Python script when ran from cmd like this.
c:\test>python pyfile.py "string"
opens in flash, but using it from VBA takes lot of time.
tests:
directly running python:
less than one second.
from VBA
15-20 seconds.
so I think this is not a performance issue but a procedural issue.


text:
Q: Best way to store revision information for quick access to view or revert changes What I am looking for is the most optimal solution for storing content revisions in an MSSQL database. We have an application that allows users to make changes to small HTML content blocks similar to a wiki, but we need to have tight audit control over the changes. At any point in time, the manager might want to look at previously submitted contents or revert the entire HTML block back to the previous state.
I had it setup in the past where we had a primary table that stored the HTML information (along with various other meta tags) and then an audit table that kept a copy of the entire data row everytime a change was made. What I am wondering is if this is the best way to go, or should I just keep 1 table with all the current records and the changes in it and just have a flag that lets me know which one is the current one?

A: I have had decent success with doing a bit of both.
One table that has the current version of the record and one table with every version (and a timestamp and an edited by) in another table.
This gives you the advantage of having a complete copy of each version without the overhead of having to sort out the current version from all the others at runtime.  it also allows you to set much stricter permissions on the audit table and optionally implement the audit copy with triggers and completely hide the audit information from the rest of the app if you like that sort of thing.

A: One table with flags would be preferable IMHO.
The alternative adds in overhead (adding old record to archive table), with little in the way of benefit. Such is the efficiency of most SQL engines, that there is usually negligible overhead in finding the current version of a record compared to searching for the only record in the table.
In certain, high-volume applications, there might possibly be a case for the alternative, but not for a wiki.


text:
Q: Swift 2.0 'inout' function parameters and computed properties I'm testing Swift 2.0 beta right now and have found strange behaviour. Here is a sample code:
private func someFunc(inout someString: String) {
    print("Inside \'someFunc()\'")

    print(someString)
    someString = "Some another string"
}

private var someAncillaryInt = 42

print(someAncillaryInt)

private var someString: String {
    get {
        print("Inside \'getter\'")

        return "Some string"
    }
    set {
        print("Inside \'setter\'")
        someAncillaryInt = 24
    }
}

someFunc(&someString)
print(someAncillaryInt)

Output:

42
Inside 'getter'
Inside 'someFunc()'
Some string
Inside 'setter'
24

I don't understand why wasn't getter called while printing someString inside someFunc() and why was it when someFunc() got passed with someString.
One can assume that I don't understand intricacies of inout parameters yet and after being passed as inout parameter computed property stops being, em, "computed", but why then was 'setter' called when we set another value to someString?
Thanks!
UPD: I added answer below.
UPDATE 18/11/2015: Apple has updated their manual with detailed explanation of how inout params work.

A: Your confusion might be caused by choosing someString both as the
name of a global variable, and as the name of a parameter of the
someFunc() function.
print(someString) inside someFunc() prints the
value of the (local) function parameter, which is completely unrelated
(and hides) the global someString variable.
It becomes easier to understand if you rename the function parameter
private func someFunc(inout localString: String) {
    print("Inside \'someFunc()\'")
    print(localString)
    localString = "Some another string"
}

which is semantically identical (and therefore produces the same output).
You can think of
someFunc(&someString)

as the following:

*

*The value of someString is retrieved (using the getter method).

*someFunc() is executed, with the local parameter localString
set to the value of someString.

*On return from someFunc(), someString is set (using the
setter method) to the (possibly changed) value of the local parameter
localString.

More information can be found in https://devforums.apple.com/thread/230567 from the Apple Developer Forum,
for example:

Given the guarantee of a getter and setter, inout follows naturally:
  when calling a function with an inout argument, logically it calls the
  getter on the var/subscript and copies the value into a stack
  temporary which is guaranteed to have physical addressability.  The
  physical address of the temporary is passed to the inout argument of
  the function ... .  The callee does
  whatever it wants with that memory location (and never knows whether
  the thing passed in was computed or not).  When the callee returns,
  the setter is invoked to copy the value back into place.

and

It also guarantees that the getter/setter of a property passed inout
  will have its getter and setter called once regardless of what the
  callee does (this is important if the accessors have side effects or
  are expensive).

but it is also stated that the temporary copy is avoided if necessary.

A:
I don't understand why wasn't getter called while printing someString inside someFunc() and why was it when someFunc() got passed with someString.

getter wasn't called while printing someString inside someFunc() because it had already been called. We already have this string as the someString parameter internal to someFunc(); we don't need to get it again.
Your output reads:
Inside 'getter' //<-- that's the getter being called!
Inside 'someFunc()'
Some string
Inside 'setter'

Your code runs:
someFunc(&someString) //<-- that calls the getter!

This has nothing to do, by the way, with inout. You'd see the same thing (as far as the getter is concerned) if this had been a normal parameter.

A: @Martin R pointed me out on aforesaid thread and, specifically, comment #16 made by Chris Lattner (Swift's mastermind) which helped me to understand 'inout' behaviour. Thanks man!
Consider this code:
private var someString: String {
    get {
        print("Inside getter")

        return "Some string"
    }
    set {
        print("Inside setter")
    }
}

private func someFunc(inout stringArg: String) {
    let funcName = "`someFunc()\'"

    print("Inside " + funcName)

    let someDontMatter0 = 42, someDontMatter1 = 24

    print(stringArg)

    // sets temporary, not the original one. Hence, no calls to setter
    stringArg = "Some other string"
    stringArg = "No matter what string"

    print("These \(someDontMatter0) and \(someDontMatter1)")

    print("Leaving " + funcName)

    // when callee returns, calls the setter with "No matter what
    // string" as a `newValue'
}

// implicitly creates temporary initialised with `someString' value
// getting from `someString's getter.
someFunc(&someString)

For someone coming from C++ background it may seem that the output should be something like:

Inside `someFunc()'
Inside getter
Some string
Inside setter
These 42 and 24
Leaving `someFunc()'

When in fact the output is the following:

Inside getter
Inside `someFunc()'
Some string
These 42 and 24
Leaving `someFunc()'
Inside setter

Kinda funny, right?
This kind of counterintuitive behaviour for someone with C++ background is a result of more fundamental logic which underpins many facets of Swift. As one may get from Chris's comment the general way Swift compiler deals with inout properties is to create temporary object on a stack to store the original value there (hence, call the getter).
So, when you manipulate your inout parameter you deal with temporary object (with initial value you passed to the function) but not with the original one (for me, personally, it's kinda vague. But OK, one can deal with that). And finally:

When the callee returns, the setter is invoked to copy the value back into place

So, if one changes the code a bit:
private var someString: String {
    get {
        print("Inside getter")

        return "Some string"
    }
    set {
        print("Inside setter")
    }
}

private func someFunc(inout stringArg: String) {
    // before returning calls `someString's setter
}

// calls `someString's getter
someFunc(&someString)

the output will be:

Inside getter
Inside setter

Also, the same goes to stored properties:
private func someFunc() {
    var someString = "Some string" {
        willSet {
            print("Inside \'willSet\' with \'newValue\': \(newValue)")
        }
        didSet {
            print("Inside \'didSet\' with \'oldValue\': \(oldValue)")
        }
    }

    func someOtherFunc(inout stringArg: String) {
        print("Inside `someOtherFunc()\'")

        stringArg = "First string"
        stringArg = "Second string"

        print("Before leaving the function")
    }

    someOtherFunc(&someString)
}

someFunc()

Output:

Inside `someOtherFunc()'
Before leaving the function
Inside 'willSet' with 'newValue': Second string
Inside 'didSet' with 'oldValue': Some string

From Chris's response:

It also guarantees that the getter/setter of a property passed inout will have its getter and setter called once regardless of what the callee does (this is important if the accessors have side effects or are expensive)

Ok, but what if some method which takes inout parameter in some circumstances doesn't modify it (doesn't call the setter or doesn't modify that temporary variable, you name it)? Also, what if I conceived some important logic behind my computed variable's getter and setter and ran into that specific circumstances (just imagine that I open and close files inside getter/setter)? The getter and setter would be called when they had better not.
I'd really like to see the Chris's response in some form in Apple's final Swift 2.0 Programming Guide.


text:
Q: How should I model a database structure to store word information on flashcards? Words, base words, and flashcards
I recently posted this question, where I asked about modeling words and base_words in a database - now that I've landed upon having separate tables, a second issue has arisen: a user adds flashcards containing words, which link to a base word, and contains a full sentence from one of the texts in our database, along with other grammatical information from our database. I'd also like to keep track of how many words the user has learnt, as well as how many base words.
Considerations

*

*Given that I'd like to keep a count (and keeping track) of the user's learnt words separately from learnt base_words, this involves having a separate table (I think). In this table, in terms of normalization/denormalization, is it ok to store all the user's learnt word_ids in one array, and then learnt base_word_ids in another array?

*Given that the words, base words, and sentences will already be in the database, it seems pointless to duplicate the information onto their flashcards - however, given that the student needs to study the flashcards offline, does this require duplication, or am I misunderstanding database structures? My aim is that the student can study offline, and then when he comes back online, if there has been a change to the original DB data that he has on his flashcard, that it will be updated automatically. The only new information that will go on the flashcard is the user's personal notes.
Warm regards,
Michael

A: Generally speaking, databases don't store arrays.
It sounds like you need several tables to track different things.

*

*A "users" table which will store the userID (primary key), user's name, and so on.

*A "base_word" table to store the base word, a BaseWordID (primary key) and such.

*A "Users_Words" linking table. This table would have it's own primary key, a UserID foreign key to link to the Users table, a BaseWordID foreign key link to the base_word table, and a Learnt flag to track learnt or not (possibly other columns, too?)

If they need access to the data "offline," that's not duplicating the data. That's generating a "report" from the data. This might be an HTML page derived from the data that is printed (or printed to PDF), for example. Or an Excel file dump of the data.


text:
Q: Background colour not animating on mouse hover I am designing a webpage and I want to make a "Contact Us" page. I want the .emailSelectorContainer's background to be animated to another colour. But it doesn't seem to work. Here is the code;
$(".emailSelectionContainer").hover(function(){

        $(".mailImage").attr("src", "photos/mailHover.png");

        $(".emailSelectorContainer").animate({'backgroundColor': '#f5f5f5'},400);

    }, function(){

        $(".mailImage").attr("src", "photos/mail.svg");
        $(".emailSelectorContainer").animate({'backgroundColor': '#000'},400);

    });

Thanks in advance.

A: I have simply used @keyframes in css to solve the smooth transition.

A: Per the jQuery docs

All animated properties should be animated to a single numeric value, except as noted below; most properties that are non-numeric cannot be animated using basic jQuery functionality (For example, width, height, or left can be animated but background-color cannot be, unless the jQuery.Color plugin is used). Property values are treated as a number of pixels unless otherwise specified. The units em and % can be specified where applicable.

background-color takes in either the name of a color (string), an rgb() value, an rgba() value or a hex value. It is not numeric.
What I would recommend is to use CSS3 animations with keyframes. Here is an example

#my-div {
  background-color: #000;
  height: 100px;
  width: 100px;
}

#my-div:hover {
  animation-name: changeColor;
  animation-duration: 0.4s;
}

@keyframes changeColor {
  from { background-color: #000; }
  to { background-color: #f5f5f5; }
}

Create a new animation with the @keyframes syntax. Inside the animation block declare properties for each step of the animation.

*

*Starting Step: Represented by from or 0%

*Ending Step: Represented by to or 100%
For each of the steps, we can declare multiple css rules separated by semicolons.
Now that we have our animation rule created, we need to apply it. Use the :hover pseudoselector to listen for when the mouse enters an element.
There are two properties to set here. The animation-name property should be set to the name of the rule we just created. The animation-duration property specifies how long the animation will run for, and in this case takes 0.4 seconds.
Alternatively, they can be converted to the short hand animation property.
animation: changeColor 0.4s


text:
Q: How to align text including hidden elements May I know how to make this align?
Line number 1 is hide the asterisk.
How to make the asterisk even hide will occupied width?
Sample code

    Required">*
    <input type="text" class="param" size="40" name="fullName" value=""/>

    Required">*
    <input type="text" class="param" size="40" name="fullName" value=""/>

Thank

A: Then use
$('selector').css('visibility','hidden');

It will hide the content and leave the space.

A: Try this
input{
    float:right
}
span{
    float:left
}

DEMO
OR
style="visibility:hidden;" instead of style="display:none"
DEMO 2

A: Instead of display:none, use visibility:hidden.
You don't need jQuery for it, just change it on the HTML

    Required">*
    <input type="text" class="param" size="40" name="fullName" value=""/>

    Required">*
    <input type="text" class="param" size="40" name="fullName" value=""/>

LIVING DEMO


text:
Q: Sampling with independent probabilities I'm looking for one specific sampling method that decides about inclusion probability of each item regardless of existence of other elements. As an example given 0.5 as the inclusion probability, it toss a coin for each element to decide about its inclusion.
This is different from fixed size sampling methods like sampling with replacement and without replacement as in this method only inclusion probability is provided and not the sample size.
Now I need more information about this method like the name of method, and the probability of having different sizes for the sample.

A: This method is called Poisson sampling (or sometimes Haje'k Poisson sampling after the statistician who first described it in detail). The name comes from the simple fact that the sample size is random, and for probability of selection invariant across units, the sample size is binomial (and hence for small probabilities of selection, which is often the case, is approximately Poisson). The first reference on Google does not seem too bad.


text:
Q: How to put an image in a progress bar programmatically (WPF) I'm completely new to WPF and I need some help putting an image in my progress bar (programmatically).
I found this (and it works):
<ProgressBar.Template>
    <ControlTemplate>
        <Grid>
            <Image Name="PART_Track" Source="MyImage" Stretch="Fill"/>
            <Rectangle Name="PART_Indicator" Fill="BlanchedAlmond" HorizontalAlignment="Left"/>
        </Grid>
    </ControlTemplate>
</ProgressBar.Template>

I just need some help converting that XAML code to C# code.

A: This will get you started :
FrameworkElementFactory grid = new FrameworkElementFactory(typeof(Grid));

FrameworkElementFactory image = new FrameworkElementFactory(typeof(Image));
image.Name = "PART_Track";
ImageSource source = new BitmapImage(...); // create it
image.SetValue(Image.SourceProperty, source);
image.SetValue(Image.StretchProperty, Stretch.Fill);

grid.AppendChild(image);

FrameworkElementFactory rectangle = new FrameworkElementFactory(typeof(Rectangle));
rectangle.Name = "PART_Indicator";
rectangle.SetValue(Rectangle.FillProperty, new SolidColorBrush(Colors.BlanchedAlmond));
rectangle.SetValue(Rectangle.HorizontalAlignmentProperty, HorizontalAlignment.Left);

grid.AppendChild(rectangle);

    ControlTemplate ct = new ControlTemplate(typeof(ProgressBar));
ct.VisualTree = grid;

MyProgressBar1.Template = ct;


text:
Q: Returning a pointer or reference to my current object from a insert_node function in a linked list program I'm a beginner in c++. and I was writing a link list in which I can call my function for inserting nodes like this:
(assuming a and b and c are data which I want to insert in link list.
list.insert(a)->insert(b)->insert(c);

and I did it like this:
#include <iostream>
using namespace std;

class Node {
public:
    char letter;
    Node* next;
};

class link_list {

private:
    Node* head;
public:

    link_list() {
        head = NULL;
    }
    link_list* insertNewNode(char item);
};

link_list* link_list::insertNewNode(char item) {
    Node* temp;
    temp = new Node;
    temp->letter = item;
    temp->next = head;
    head = temp;
    return this;
}

int main() {

    link_list list;
    list.insertNewNode('a')->insertNewNode('b')->insertNewNode('c');
    return 0;
}

in my insertNewNode function I'm returning a pointer to my current object.and it's working fine ,however I'm not sure if my method is right?
But I should also explain what happen , if instead of returning a pointer or reference to my current object ,I return my current object.
so I tried this:
class Node {
public:
    char letter;
    Node* next;
};

class link_list {

private:
    Node* head;
public:

    link_list() {
        head = NULL;
    }
    link_list insertNewNode(char item);
};

link_list link_list::insertNewNode(char item) {
    Node* temp;
    temp = new Node;
    temp->letter = item;
    temp->next = head;
    head = temp;
    return *this;
}
int main() {

    link_list list;
    list.insertNewNode('a')->insertNewNode('b')->insertNewNode('c');
    return 0;
}

and then I received an error which said list should be a pointer ,so I changed my main to:
int main() {

    link_list *list;
    list = new link_list;
    list->insertNewNode('a')->insertNewNode('b')->insertNewNode('c');
    return 0;
}

but I'm still receiving this error which said here list->insertNewNode('a')->insertNewNode('b')->insertNewNode('c'); expression must have a pointer type and these two errors:

1.type 'link_list' does not have an overloaded member 'operator ->'
2.'->link_list::insertNewNode': left operand has 'class' type, use '.'

so here is my questions for purpose of calling insert function like this list.insert(p1)->insert(p2)->insert(p3);, is my way in first program right ? and also is it even possible to return my current object for this purpose? and what would happen if I return current object?
PS:sorry for long question and also thanks in advance for your help.

A: *

*Well, there's nothing criminal in your current method returning a pointer. Not something done very often, still quite compilable.

*More idiomatic would be to return current object by-reference:
link_list &insert(char elem) {
    return *this;
}

*Your initial problem was that you changed method's return type, but retained -> in main(). If you change insert's return type to reference from pointer, then chained calls should be done via ., as you're working with objects and references to them, not with pointers.

*Returning a copy of current object from a setter is not something that should be done, especially if you manage private resources on your own and haven't defined a proper copy constructor yet. Rather return a reference.

A: Your method seems fine. You are doing
link_list* insertNewNode(char) {
  // ...
  return this;
}

so that you can chain the insertions like this
list.insertNewNode('a')->insertNewNode('b')->insertNewNode('c');

You could also return a reference to the link_list, like this
link_list& insertNewNode(char) {
  // ...
  return *this;
}

and now chaining the insertions looks like this
list.insertNewNode('a').insertNewNode('b').insertNewNode('c');

Note that you shouldn't do something like
link_list insertNewNode(char) {
  // ...
  return *this;
}

because this will compile, but you would be returning a copy of the linked list, and the chaining would simply not work.
If your nodes would be added to the tail, the default copy constructor would make it appear as if chaining works, because the original link_list would see all Nodes added to the copy.
In your implementation, you are adding Nodes at the head, so the original link_list doesn't see Nodes added to the copy, and so the chaining doesn't appear to work. This is good, because the copies would leak the memory they allocate, even if you write a proper destructor.


text:
Q: ICMP and traceroute , How does ICMP keep a counter while it passess hops When tracerouting a destination and going through all these hops, what happens during this process? Does ICMP have an initial counter and decrements this counter on each hop it passes? If the counter is initiated to be 30, how will this work on a RIP network? RIP has knowledge only about 15 hops and that's where it quits.
Thanks for your answers!

A: "Traceroute works by sending packets with gradually increasing TTL value, starting with TTL value = 1. The first router receives the packet, decrements the TTL value and drops the packet because it then has TTL value zero. The router sends an ICMP Time Exceeded message back to the source. The next set of packets are given a TTL value of 2, so the first router forwards the packets, but the second router drops them and replies with ICMP Time Exceeded. Proceeding in this way, traceroute uses the returned ICMP Time Exceeded messages to build a list of routers that packets traverse, until the destination is reached and returns an ICMP Echo Reply message."
Source.
http://en.wikipedia.org/wiki/Traceroute

A: You can define the maximum number of hops in an ICMP package. For each hop this counter is decremented and when 0 is reached an error is sent back.
Traceroute begins with a maximum number of 1 hop and increments after each error the value by one and determines by the collected error returns the route to the destination.