Q:

Keeping a LinkedList always sorted

I've been given a code as shown below for practice purpose, and my task is to modify it so that the linked list is always sorted. My main problem now is that I have no idea where to start or what methods are to be modified. Any hints are welcome.
import java.util.Iterator;
import java.util.NoSuchElementException;

/
 * This is a copy of the LinkedList class, which has been modified to only
 * accept elements that can be compared.
 *
 * Note that the elements accepted by this list must implement the Comparable
 * interface. This means that the elements can be compared as follows:
 *
 * x.compareTo(y) == 0 means x == y
 * x.compareTo(y) < 0 means x < y
 * x.compareTo(y) > 0 means x > y
 *
 * Your task is to modify this class so that the elements always are sorted.
 */
public class SortedLinkedList<T extends Comparable<T>> implements Iterable<T> {

/* Easy operations for a linked list

add(x): Searching for the place where the element x is to be added must
        take place in the calling routine. This must set previous to
        point to the node AFTER which the new element is to be inserted.
        curr is set to point to the new element.

remove(): The curr element is removed from the list. Searching for this
          element must take place in the calling routine. This must set
          curr to point to the element to be removed. After removal curr
          points to the element following the removed one.

isEmpty(): checks for an empty list

endOfList(): checks whether curr has reached and passed the end of the list

retrievecurr(): return the info part of the curr element.

reset(): resets the list so that curr points to the first element

succ(): an iterator, moves curr one step forward

Note that when a class implements the interface Iterable<T> then
it can be the target of the "foreach" statement. See IterationExample.java
 */

private Node start, curr, prev;

public SortedLinkedList() {

    curr = null;     // the curr position in the list
    start = null;    // the first element
    prev = null;     // the node before curr
}

public void add(T x) {

    if (start == null) {            // if start == null, insert a first element into an empty list
        Node newNode = new Node();  // create the new element, info and link are set to null.
        newNode.info = x;           // and assign the data given as parameter. The link is left as null
        start = newNode;            // start is updated to point to the new element
        curr = start;               // curr is updated to point to the new first (and only) element

    } else if (prev == null) { // a new first element is inserterd into a non-empty list

        Node newNode = new Node();  // a new node is created ...
        newNode.info = x;           // and assigned the data given as parameter
        newNode.link = start;       // and linked before the old first element
        start = newNode;            // start is updated to point to the new first element
        curr = newNode;             // curr is updated to point to the new first element

    } else { // a new element is inserted last (if prev.link == null) or between prev and curr

        Node newNode = new Node();  // create a new node
        newNode.info = x;           // assign it the data given as parameter
        newNode.link = prev.link;   // link it before curr ...
        prev.link = newNode;        // ... and after previous
        curr = newNode;             // update curr to point to newNode
    }

} // add

public void remove() {              // removes the current node

    if (isEmpty() || endOfList()) { // no node to be removed
        return;
    }
    else {                          // curr points to the element to be removed
        if (prev == null) {         // remove a first element: start is updated!
            start = start.link;     // "jump over" the first element (curr/start)
            curr = start;           // update curr to point to the new start
        }
        else {                      // the element to be removed is in the middle of the list/last
            prev.link = curr.link;  // "jump over it!"
            curr = curr.link;       // curr is updated to the element after the removed one
        }
    }
} // remove

public boolean isEmpty() { // checks if the list is empty
    return start == null;
}

public T retrieveCurr() { // return the curr element's data
    return curr.info;
}

public void reset() { // resets a list so that curr points to the first element

    curr = start;     // curr starts from the beginning of the list
    prev = null;      // there is no previous element for curr
}

public boolean endOfList() { // has curr reached and passed the end of the list?

    return curr == null;
}

public void succ() { // moves curr to the next element

    curr = curr.link;       // curr is set to the next node
    if (prev == null) {     // previous must follow; if it was null to begin with ...
        prev = start;       // ... it must now point to start
    }
    else {
        prev = prev.link;   // otherwise it is just moved one step forward
    }
}

public Iterator<T> iterator(){ //Needed to implement the iterable interface
    return new ListIterator();
}

private class Node {

    T info;
    Node link;

    Node() {
        info = null;
        link = null;
    }
}

/*
 * An example iterator class to walk through the list from
 * the start to the end. Note the similarity with the methods
 * above. They implement similar functionality, but here it
 * is hidden behind a standard interface.
 *
 * Note the class is private and the implementation of the iterator
 * is therefore not visible outside.
 *
 * See the java api documentation for more information on
 * how iterators should behave.
 */
private class ListIterator implements Iterator<T>{

    private Node curr;

    public ListIterator(){
        curr=start;
    }

    public boolean hasNext(){
        return curr!=null;
    }

    public T next(){
        if(curr==null){
            throw new NoSuchElementException();
        }
        T value=curr.info;
        curr=curr.link;
        return value;
    }
    public void remove(){
        throw new UnsupportedOperationException();

    }
}
}

A:

I think the only big change in implementation which you have to make is to keep the list sorted as you insert elements.  Note that the reverse operation, namely removing elements, doesn't need to change, because you are simply throwing things away which would not change any order in the list.
The add() method below walks down the list until it finds the appropriate position.  Then, it splices in the new node and updates the start, prev, and curr pointers where applicable.
public void add(T x) {
    Node newNode = new Node();
    newNode.info = x;

    // case: start is null; just assign start to the new node and return
    if (start == null) {
        start = newNode;
        curr = start;
        // prev is null, hence not formally assigned here
        return;
    }

    // case: new node to be inserted comes before the current start;
    //       in this case, point the new node to start, update pointers, and return
    if (x.compareTo(start.info) < 0) {
        newNode.link = start;
        start = newNode;
        curr = start;
        // again we leave prev undefined, as it is null
        return;
    }

    // otherwise walk down the list until reaching either the end of the list
    // or the first position whose element is greater than the node to be
    // inserted; then insert the node and update the pointers
    prev = start;
    curr = start;
    while (curr != null && x.compareTo(curr.info) >= 0) {
        prev = curr;
        curr = curr.link;
    }

    // splice in the new node and update the curr pointer (prev already correct)
    newNode.link = prev.link;
    prev.link = newNode;
    curr = newNode;
}


Q:

When did the MSDN search include SO results?

I was just using MSDN search, and discovered I could filter by source, and SO was one of the filter options.

I have never noticed this before (although, I don't use the MSDN search that often, Google tends to suffice), when was this nice little addition implemented, or did Microsoft just do it without any input from SE?

A:

Joel announced the integration on October 29th, 2010, which I roughly remember being a day or so after it being launched.


Q:

No such file or directory at /cgi-bin/upload.pl line 26. When trying to upload a file using AngularJS

This is my HTML Code.
<button class="button" ngf-select ng-model="files" ngf-multiple="multiple">Select File</button>

Files:

{{f.name}}

Upload Log:

{{log}}

This is controller code.
$scope.$watch('files', function () {
    $scope.upload($scope.files);
});
$scope.log = '';

$scope.upload = function (files) {
    if (files && files.length) {
        for (var i = 0; i < files.length; i++) {
            var file = files[i];
            Upload.upload({
                url: '/cgi-bin/upload.pl',
                fields: {
                    'username': $scope.username
                },
                file: file
            }).progress(function (evt) {
                var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
                $scope.log = 'progress: ' + progressPercentage + '% ' +
                            evt.config.file.name + '\n' + $scope.log;
            }).success(function (data, status, headers, config) {
                $timeout(function() {
                    $scope.log = 'file: ' + config.file.name + ', Response: ' + JSON.stringify(data) + '\n' + $scope.log;
                });
            })
            .error(function (data, status, headers, config) {
                alert ('Error');
            });

        }
    }
};

This is Perl script.
#!c:/perl64/bin/perl.exe

use strict;
use warnings;
use DBI;
use CGI::Carp qw(warningsToBrowser fatalsToBrowser);
use CGI;
use CGI qw(:standard);
use JSON;
use CGI::Carp qw ( fatalsToBrowser );
use File::Basename;

#send the obligatory Content-Type
print "Content-Type: text/html\n\n";

$CGI::POST_MAX = 1024 * 5000;
my $safe_filename_characters = "a-zA-Z0-9_.-";

my $cgi = new CGI();
my $upload_dir = "../images"; #location on our server
my $filename = "dummy.png";

my $upload_filehandle = $cgi->upload("file");
print $upload_filehandle;

open UPLOADFILE, ">../..$upload_dir$filename"  or die $!;
binmode UPLOADFILE;

while ( <$upload_filehandle> )
{
    print UPLOADFILE;
}
close UPLOADFILE;

When i trying to upload the file on local Apache server, seeing this error.
No such file or directory at C:/Program Files (x86)/Apache Group/Apache2/htdocs/admin/cgi-bin/upload.pl line 26.
This is line 26 in perl script.
open UPLOADFILE, ">../..$upload_dir$filename"  or die $!;

I have a folder named images already created. So why this error?
Can anyone help me what is wrong, and what chages are needed to that i can upload the file properly.

A:

$upload_dir is ../images, and
$filename is dummy.png, so
"../..$upload_dir$filename" is ../..../imagesdummy.png.
Need I say more?
That's why it's good to include the path in the error message.
my $qfn = "../..$upload_dir$filename";
open(my $UPLOADFILE, '>', $qfn)
   or die("Can't create \"$qfn\": $!\n");

(Note that I made other improvements, including switching from global glob UPLOADFILE to lexical scalar $UPLOADFILE for the file handle. You'll have to adjust the following code to use that scalar if you adopt this highly recommended practice.)


Q:

How to prepend HTML `` to `` using jQuery?

I need to append an
 element to multiple
 using a for-loop in jQuery.
Code Snippet:
JQuery:
var lists = $('ul.menu');

for(var i=0; i<lists.length; i++){
    var lnk = "
All
";
    lnk = $('
').html(lnk).text();
    lists[i].prepend(lnk);
}

HTML:

Graphics

Videos

Programming

Our Story

About Us

As per code
 inserts as the proper text, but is been formatted as plain text instead of an
.
What am I doing wrong? How to correct my mistakes?

A:

A slightly more jQuery-ish alternative to TJ Crowder's solution...

$('ul.menu').each(function() {
    $(this).prepend("
All
");
})

Graphics

Videos

Programming

Our Story

About Us

A:

You're calling the raw DOM prepend (which only exists on modern browsers), because lists[i] accesses the raw ul element. You're also just taking the text of what you want to prepend, rather than including any li markup. You probably want to:

Call jQuery's prepend, and
Include the li in what you're prepending

Example:

var lists = $('ul.menu');

for(var i=0; i<lists.length; i++){
 var lnk = "
All
";
 lists.eq(i).prepend(lnk);
}
/* No CSS */

Graphics

Videos

Programming

Our Story

About Us


Q:

getopts not working in bash script

#! bin/bash
# code for train.sh
   while getopts "f:" flag
    do
         case $flag in
             f)
               echo "Hi"
               STARTPOINT = $OPTARG
               ;;
         esac
    done

    echo Test range: $4
    echo Train range: $3

    #path of experiment folder and data folder:
    EXP_DIR="$1"
    DATA_DIR="$2"
    echo Experiment: $EXP_DIR
    echo DataSet: $DATA_DIR
    echo file: $STARTPOINT

I ran the command > ./train.sh test1  test2 test3 test4  -f testf

and got the output
Test range: test4
Train range: test3
Experiment: test1
DataSet: test2
file:

So getopts option does not seem to work for some reason as you can see the nothing is printed after file and also echo "Hi" command is not executed in the case statement. Can anyone please help me with this?

A:

You need to put any options before naked parameters
./train.sh -f testf test1  test2 test3 test4

with output
Hi
Test range: test4
Train range: test3
Experiment: test1
DataSet: test2
file: testf

You need a couple of changes too
while getopts "f:" flag
do
     case $flag in
         f)
           echo "Hi"
           STARTPOINT=$OPTARG
           shift
           ;;
     esac
     shift
done

To set the environment variable and shift the got option out of the way


Q:

Testing Ember Data

Anyone have any good examples of testing Ember data in your own app?
I'm starting to build an app using the Fixtures adapter, which is great. But I want to test my models and make sure everything works properly as I build.
I have QUnit setup and running, but I don't want to write the server side in order to verify that the Data Model makes a call. I'd like to mock out the Adapter and just see if the find method is called and return a new object from it. I'll worry about the server side implementation later.
Any ideas?
This is what I have so far (that doesn't work):
test('MyModel should call find', 1, function(){
  App.TestAdapter = DS.Adapter.extend({
    find: function(store, type, id){
      ok(true, 'calls the find method');
      console.log('find: ', type, id);
    }
  });

  App.Store = DS.Store.extend({
    adapter: 'App.TestAdapater'
  });

  myModel = App.MyModel.createRecord({
    name: 'Test',
    period: 0
  });

  // method that should call .find
  myModel.currentObject();

});

A:

I ended up going with Konacha.
The biggest part was:
before(function() {
  Ember.run(function() {
    App.initialize();
  });
});

afterEach(function() {
  Ember.run(function() {
    App.reset();
  });
});


Q:

Get array elements from HashMap in Java

I have a method that puts value in HashMap of type HashMap<String, Object[]> & returns the same HashMap.
Code for putting value in HashMap:
doc = Jsoup.connect(url).get();
for( org.jsoup.nodes.Element element : doc.getAllElements() )
{
    for( Attribute attribute : element.attributes() )
    {
        String option_ID=element.tagName()+"_"+attribute.getKey()+"_"+attribute.getValue();
        String HTMLText=element.text();
        int HTMLTextSize=HTMLText.length();
        if(!HTMLText.isEmpty())
            data.put("Test"+i,new Object[{"Test"+i,option_ID,HTMLText,HTMLTextSize});//adding value in HashMap.
            i++;
    }

 }

I tried iterating as below, which I think is not the correct way :
HashMap<String, Object[]>set=HTMLDocument.createHTMLSet("URL of website");
Iterator it = set.entrySet().iterator();
while (it.hasNext()) {
    Map.Entry pair = (Map.Entry)it.next();
    System.out.println(pair.getKey() + " = " + pair.getValue());
}

As I am getting output as :

Test79 = [Ljava.lang.Object;@14e1a0f
Test378 = [Ljava.lang.Object;@1a5f880

How should I iterate over this HashMap to get Object[] values such as option_ID, HTMLText?

A:

Since each object has toString() method, the default displays the class name representation, then adding @ sign and then the hashcode, that's why you're getting the output
[Ljava.lang.Object;@14e1a0f

that means the array contains a class or interface.
One solution would be looping on the array and print each part (or using Arrays.toString method), but I highly recommend you wrapping this to your own class and override the toString method.


Q:

How to call this curl API request to get the highest 'likelihood' json field name?

I'm trying to use this API from this site fullcontact for normalizing a number of possible names into 'likelihood values' for name extraction.
Tried the following code but it can't run Undefined offset: 2 error: $index_name = $possible_names[$n];. Moreover, I'm was stuck with the logic of extracting the name. Can someone help? Thanks
$possible_names = array("Jimmy Frank", "Wall Street"); // In this case Jimmy Frank should be the output person name

if (count($possible_names) > 1)
{
     for ($n = 0; $n <= count($possible_names); $n++)
     {
         $index_name = $possible_names[$n];
         $ch = curl_init();
         curl_setopt($ch, CURLOPT_URL, "https://api.fullcontact.com/v2/name/normalizer.json?q=$index_name");
         curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
         curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");

         $headers = array();
         $headers[] = "X-Fullcontact-Apikey: APIKEY";
         curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

         $namenormalizer_result = curl_exec($ch);

         if (curl_errno($ch)) {
            echo 'Error:' . curl_error($ch);
         }
         else
         {
            $namejson_result = json_decode($namenormalizer_result, true);
            $namejson_array[] = $namejson_result['likelihood'];
         }
         curl_close ($ch);
     }
}

A:

$possible_names is an array of size 2. Arrays are indexed from 0 so you need to remove the last index 2 which doesn't exist :
for ($n = 0; $n <= count($possible_names) - 1; $n++) {

}

or use strict condition :
for ($n = 0; $n < count($possible_names); $n++) {

}

For the extraction, you can use $namejson_result->nameDetails->fullName to extract fullName and $namejson_result->likelihood for likelihood :
$namejson_result = json_decode($result);

echo "likelihood for $index_name on " .
    $namejson_result->nameDetails->fullName . " : " .
    $namejson_result->likelihood . "\n";


Q:

Entangled Material

Recently I saw the case of creating two entangled electrons with opposite spins from the Higgs boson (which has no spin). The electron spins are always opposite to equal zero as a sum - conserving the Higgs zero spin. So we always create opposites. Why would anyone find that remarkable? People have expressed amazement about the fact that the result can be guaranteed - even before light would have a chance to travel the distance. I don’t understand. If the result is always AB or BA depending who measures which why would this be quirky in any way and why would anyone suspect communication between the electrons?

A:

The term "quantum entanglement exists" is a subset of the term "there exists a single quantum mechanical wavefunction describing the system".
If you know the wavefunction, i.e. have a mathematical description of it, the theory of quantum mechanics has constraints on quantum numbers and their conservation, so quantum numbers are "entangled" because there exists a single wavefunction describing the system, that is all.
Let us take a simple example, the pi0 decay. It decays into two photons/gammas. The pi0 has spin zero. From conservations of quantum numbers ( in this case angular momentum conservation) in the decay wavefunction, one of the photons must have spin +1 and the other -1 the direction being the direction of their motion.
Once the decay has happened and there are no interactions, the spins are unknown for the experimenter, but they are defined by the wavefunction.
If I measure one in the lab and the other reach Alpha Centauri, I know its spin by having measured the one in the lab and using angular momentum conservation.
What people get confused with is with who has the information.
The information is not shared by the photons, the information is in the head of the experimenter, who sits in the lab.
How do we know this is true? Because we have validated quantum mechanical theory with innumerable experiments, trust mathematics, and extrapolate, all the information here in the lab.


Q:

How can I create a dired buffer listing all open files?

I have a mechanism for burning items to disc from a dired buffer.  Unfortunately,  the file's I've patched are strewn accross the file system.  How can I create a dired buffer from all open files?

A:

The dired command accepts a list of file-names as argument. Just create one and pass to it:
(dired
 (cons
  "Open Files"
  (sort (remove nil (mapcar #'buffer-file-name (buffer-list)))
       #'string<)))


Q:

What should I look for in a ukulele amp

I bought an electric ukulele and now I need an amp for it. What should I be looking for? Is there any uke specific things that are particular to this kind of amp? Would a regular guitar amp work just as well? I am not looking to preform in front of a crowd. I am just looking to have some fun and play some AC/DC.

A:

Since your uke is solid-body, you need the rest of your setup -- the amp, speaker, cabinet to give character to the sound.
Fortunately the ukulele's pitch range is within that of a guitar's. A soprano uke is similar to the top strings of a guitar being played high up the fretboard. A baritone uke is similar to the top strings of a guitar being played nearer the nut. So amplifiers designed for an electric guitar will work well with the uke.
You might also fancy experimenting with pedals, to get even more distortion, reverb etc.
(I would note that the AC/DC sound is from cranking the gain high on the clean channel of an amp with no pedals)
A guitar does reach much lower pitches than a uke, so you'll never get that gutsy crunch a guitarist gets from power-chording on the bass strings. You can play with EQ to at least make the uke less piercing.
Since you're not looking to play in front of a crowd, go small. There are lots of very good small amps around nowadays, such as the tiny Danelectro Honeytone, Roland Microcube, and many others. They're not toys either - I've seen them mic'd up through the PA at major artists' gigs.

A:

Any guitar amp will be absolutely fine. The sounds and tonal range are well within those a guitar amp was designed for.
Enjoy.

A:

Most Uke players want a kind of "acoustic" sound. Most guitar amps color the sound and make the Uke sound distinctly more electric. I have a Marshall AS50D and it has a separate tweeter, which makes the tone more neutral. It also has an anti-feedback filter. I believe that's pretty much a notch filter that suppresses the band where most feedback occurs. With my standard guitar amp, it's a constant war to keep the uke from exploding from feedback. With the Marshall, it's no prob.
There are plenty of other amps out there (as well as PAs) that fill the bill nicely. I just provided one example. On the plus side, any of your acoustic instruments that have pickups will sound great through this kind of amp. On the minus side, it's more gear to buy and more gear to carry.
If you're really keen on playing AC/DC, then why not get a shredder guitar, a cheap used Crate amp, turn everything all the way up and wail away?


Q:

Why does my CSS stop working whenever I add "<!DOCTYPE html....."

I had some code that produced a table, and worked perfectly.

This is the code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

SCHED DATEAMOUNT

Aug 1, 2011	$100

Jul 27, 2011	$100

Jul 20, 2011	$100

Total:	$300

Then I added a line so that I could pass html validation at validator.w3.org
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

but that broke my CSS, the right format is gone, and my total line is gone

How can I fix that?

A:

The following portion of your code looks strange :

The {} arround the style's values doesn't seem quite standard (and as you specified, with the doctype declaration, that you want the browser to interpret your code using a well-defined standard...)

You should probably remove those {}, and use something like this -- which looks a bit more standard-compliant :

Also, as noted by @cthulhu, you are opening
 and  tags, but never closing them :

there is an opening
 at the beginning of each of the following lines (and others) :
and you have two opening  tags on the first line :

SCHED DATEAMOUNT

Aug 1, 2011	$100

Jul 27, 2011	$100

You should add closing 	 and
 tags where needed :

    SCHED DATE
    AMOUNT

    Aug 1, 2011
    $100

    Jul 27, 2011
    $100


Q:

Comparing and reducing difference between two numbers regardless of which is larger

I'm using the abs built-in function to measure the difference between two numbers regardless of whether x is bigger than y or vice versa.
For example, if y = 5 and x = 7, the result will be 2. If y = 7 and x = 5, result will still be 2.
But if I want iterate until the result is 0, is there a way I can use abs or a different built-in so that y or x can be incremented or decremented so that the result will be 0?
I like the abs function, but it seems a shame to write code that has to check whether y is bigger than x or vice versa so as to increment or decrement until the difference is 0.

A:

if x > y: x, y = y, x   # swap x and y if x > y
for x in range(x, y+1):
    diff = y-x

is pretty simple. Notice that one if-statement saves you N calls to abs (where N = abs(y-x)). So I think you should prefer the if-statement instead of trying to avoid it.

Since you didn't specify if you wished to increment (the smaller) or decrement
(the larger) presumably by one, you might be only interested in the difference. In that case, you
could use:
for diff range(abs(y-x), -1, -1):
    ...


Q:

Jquery .post serialize() not sending created input fields

I have a form that is posting a for when you hit add to cart. it will add the new input fields for the options and everything then .post the form to update the pricing at the top....however when it does the post which is after it creates the fields it does not count those fields within the post and it is only for the newly created ones....you can see the running script at https://www.presidentialuniversity.com/synergy-business-tools/order_new.php?cid=1#top if you need more info don't hesitate to ask. you can see the javascript that pertains to this action at the bottom of: https://www.presidentialuniversity.com/synergy-business-tools/js/order_functions.js
the portion that actually does the submitting is:
var form = $('#store');
url = form.attr('action');
$.post(url+'&a=updatecart', form.serialize(),function(data){
    alert(data);
    $('#top_totals').html(data);
});

currently it is alerting the post data. the fields go in with out a problem i can see them there they just aren't getting picked up when the form is posted

A:

the problem was that a fadeIn animation was showing the new fields and the .post was running before that fadeIn was complete so the fields were not completely rendered before the .post of serializing


Q:

What are the different approaches for deploying DB changes using TFS 2015?

Currently, we are manual running DB scripts (SQL Server 2012) outside of our CI/CD deployment. What are ways (including toolsets) can we automate deployment of DB changes using TFS 2015 Update 3?

A:

There are really two approaches here, both of which work with TFS. Really TFS just facilitates the execution of any scripting that you will use to update your database, including your custom, handcrafted scripts.
There is the state based approach, which uses a comparison technology to look at your VCS/dev/test/staging database and compare this to production. SQL Source Control and the DLM Automation Suite from Redgate Software does this, as do other comparison tools. What you would do is use a command line or programmatic interface to set your source and target, capture the output and then use this as an artifact in your release process. I might include a review of the artifact as a scripting choice in your flow.
Note, there are some problems that State based comparisons don't do well with. Renames, splits, merges, data movement, a few others. Some comparison tools have ways around this, some do not. Be aware this may be an issue. If you have a more mature database, perhaps not, but you should consider this. SQL Source Control allows custom migration scripts, which can handle these issues.
The other approach is a script runner or migration strategy where each change you make to a dev database is captured as an ordered script and a framework executes these in order, if they are needed. This is preferred by some people since you can see exactly what code will be executed at dev and deployment time. ReadyRoll from Redgate Software, Liquibase, Rails Migrations, DBUp, FlywayDB, all use this strategy.
Neither of these is better or worse. Both work, both have pros and cons, but really the choice comes down to your comfort level and preference.
Disclosure: I work for Redgate Software.


Q:

Issue when removing row from ComboBox model

I have an ComboBox in my QML file:
import QtQuick 2.4
import QtQuick.Controls 2.0
// ...
ComboBox {
    id: serailPortNameBox
    model: availableSerialPortsModel
    textRole: "display"
}

and model availableSerialPortsModel that contains serial port names currently available in system:
QStringListModel availableSerialPortsModel;
QList<QSerialPortInfo> portsList = QSerialPortInfo::availablePorts();
for (auto port : portsList) {
    int row = availableSerialPortsModel.rowCount();
    availableSerialPortsModel.insertRow(row);
    QModelIndex index = availableSerialPortsModel.index(row);
    availableSerialPortsModel.setData(index, port.portName(), Qt::DisplayRole);
}
// ...
engine.rootContext()->setContextProperty("availableSerialPortsModel", availableSerialPortsModel);

When I'm removing some serial port:
for (int row = availableSerialPortsModel.rowCount() - 1; row >= 0; --row) {
    QModelIndex index = availableSerialPortsModel.index(row);
    QString name = availableSerialPortsModel.data(index, Qt::DisplayRole).toString();

    if (portsToRemove.contains(name)) {
        availableSerialPortsModel.removeRow(row);
    }
}

ComboBox removes this port with some visual issue:

Is it just a bug og ComboBox or am I doing something wrong? My Qt version is 5.7.0 on a Apple device with Sierra 10.12.2.
Here a simple project that reproduces the issue.

A:

This is Qt 5.7.0 bug (bugreports.qt.io/browse/QTBUG-54573). Upgrading to Qt 5.7.1 id solved the problem.


Q:

Check if view model property has value in Javascript using MVC Razor syntax

How do I get value from view model in Javascript if the property is nullable like int?, bool? etc.
I easily managed to check if property has a value, it works until I return it's value.
<script type="text/javascript">

    // Works as expected
    var year = !!'@Model.Year' ? 1994 : 0;

    // Null reference exceptin thrown
    var year2 = !!'@Model.Year' ? @Model.Year.Value : 0;

</script>

For some reason the condition is ignored when returning property using razor syntax. The same happens if use if and else statements.

Edit:
The exception is thrown also if using @Model.Year.HasValue.ToString().ToLower() to check for null value.

A:

You can use the HasValue property on the nullable int variable to determine whether it has value or not, If yes, read the value, else set the default value you want. You can do this in one c# statement so that you do not need to worry about True and true inconsistencies between C# and javascript.
This should work fine.
<script>

    var year = @(Model.Year.HasValue ? Model.Year.Value : 0);
    alert(year);

</script>

Here we wrapped the entire expression as a single C# statement by wrapping it in @( and ). So when this page is loaded, razor will run the C# statement and set the resulting value to your javascript variable.


Q:

Disk brake caliper fit, inboard width of calipers

How can you tell if a disk caliper is going to fit on a given fork?  there is an inboard width of a caliper that determines how far into the wheel it is set, ie. make or brake compatibility with the wheel.

A:

I'm assuming the question is about physical interference between the caliper and the wheel, namely the spokes.
The fork isn't the determining piece here, because a given wheel and rotor is going to want the caliper to be located in a certain position relative to the wheel. In most (maybe all) cases where there is an interference problem, changing the fork wouldn't do anything about it.
The way this has played out for the most part is that some calipers have come out and been found to have issues with interfering with spokes on some or many wheels once in the wild. TRP Spyres were an example; when they come out in 2012-13ish they constantly had issues with running into the spokes of bikes people tried to put them on. I believe they fixed something in that design in a generational change because I haven't seen the problem in a while.
There are no measurements that brake manufacturers provide that let you predict the issue. It's become an unusual problem, even with large flange hubs. For the most part it's going to take a very wide design like the Spyres for a problem to even come close to being possible. The standard practice is to basically ignore the possibility of a wheel/caliper interference problem until it bites you.


Q:

Textbox output size

First of all i am searching for an answer on the web for my question, and i couldn't find anything besides input limiting which is MaxLength property. If there is an answer about this I apologize..
I am having trouble with limiting or formatting the "output" in a textbox - not input (textbox.MaxLength) - ..
For example I calculated some number double type 268,99894642 .. and i want to limit this display size as 5 digits at most, so it will look like 268,99 . How can i do this?
Thanks..

A:

If you're setting the value programatically you can set the string format:
textbox1.Text = someValue.ToString("0.00");

Another approach would be to use the NumericUpDown control (instead of textbox) and set its property DecimalPlaces


Q:

How to query for Time less than another Time object in Volt with volt-mongo?

I am working on a Volt app that needs to compare times. Using a model that looks like this:
class Punchcard < Volt::Model
  field :punchtime
end

I can save instances of the model with a Time object for punchtime and see that they are persisted into MongoDB as ISODate() objects. All well so far.
When I want to query from the database using a less than criteria, I can see that Volt and volt-mongo are turning this call:
store.punchcards.where({"punchtime" => {"$lt" => punchtime}}).then...

(where "punchtime" is a Time object) into this Mongo query:
db.punchcards.find({"punchtime": {"$lt": "2015-07-08T10:25:05-0700"}})

Which returns no results even though it should.
When I trace the insert call when saving an instance of the Punchcard model, I see that the Time object is not stringified:
[INFO] task StoreTasks#save in 11.557ms
with args: "punchcards", ["punchcards", "[]"], {"user_id"=>"925b0eb84bc3d2185d1c693a", "punchtime"=>2015-07-08 16:38:49 -0700, "punch_status"=>"Out", "id"=>"75c1a3c35016d30895d38d28"}

Therefore, I'm guessing since the Time object is stringified on the find call but not on the save call, Mongo is doing a string comparison on the find.
How can I query Mongo with $lt / $gt and Time objects in Volt?

A:

This should be fixed on master.  Try running from master and let me know if it works.
gem 'volt', github: 'voltrb/volt'


Q:

Is there plugins for mind mapping?

Are there jQuery or JavaScript libraries or plugins for writing something like mind-mapping?

A:

See if one of these is OK:
http://code.google.com/p/jsplumb/
http://www.mxgraph.com/mxgraph.html
I have two more, but it won't let me post more than two links. I'll see if it allows a second answer with the other two.  If not check my Twitter stream @roygrubb

A:

Try looking on this: http://www.headjump.de/article/arrows-and-boxes
It is jQuery library which transforms right syntax into mind-map-like graphs
More libraries you should like:
http://code.google.com/p/js-mindmap/
http://www.yworks.com/en/products_yfilesajax_about.html
http://www.kylescholz.com/blog/projects/jsviz/


Q:

Server solution, forwarding HTTP traffic

I'm looking for a solution to redirect GET/POST HTTP requests on a server.
The easy part would be port translation and hostname redirection (HTTP 3xx redirection):
When my server in a DMZ receives traffic on port 7070 (http://mydmz.server.com:7070), it would redirect the traffic to a public web server (http://liveupdate.symantecliveupdate.com on default port 80)
But It also needs to modify on the fly request headers:

/clu-prod should get stripped from the URI
Host: mydmz.server.com should be replaced by Host: liveupdate.symantecliveupdate.com

What tool, solutions could I use on a server to listen on port 7070 and do the following ? A load balancer, a HTTP proxy ?

A:

I think you can achieve this with HAProxy.

Set it to listen port 7070/tcp in httpd mode.
modify host header with haproxy replace-value. In your case it could be like:
http-request replace-value Host mydmz.server.com:(.*) liveupdate.symantecliveupdate.com:\1

strip URI with haproxy url rewriting. In you case this could be something like:
reqrep ^([^\ ]*\ /)clu-prod[/]?(.*)     \1\2

With those settings your HAProxy configuration could look something like this (this is quickly modified from HAProxy default config in CentOS 7, this is not tested thoroughly):
    global
   log         127.0.0.1 local2
    chroot      /var/lib/haproxy
    pidfile     /var/run/haproxy.pid
    maxconn     4000
    user        haproxy
    group       haproxy
    daemon
    stats socket /var/lib/haproxy/stats

defaults
    mode                    http
    log                     global
    option                  httplog
    option                  dontlognull
    option http-server-close
    option forwardfor       except 127.0.0.0/8
    option                  redispatch
    retries                 3
    timeout http-request    10s
    timeout queue           1m
    timeout connect         10s
    timeout client          1m
    timeout server          1m
    timeout http-keep-alive 10s
    timeout check           10s
    maxconn                 3000

frontend  main *:7070
    default_backend             app

backend app
    http-request replace-value Host mydmz.server.com:(.*) liveupdate.symantecliveupdate.com:\2
    reqrep ^(.*)/clu-prod(.*) \1/\2
    balance     roundrobin
    server  app1 liveupdate.symantecliveupdate.com:80 check

Other option you maybe could use is squid proxy http://www.squid-cache.org/


Q:

Out of range error when reading from vector

After reading integers from a txt file and push_back them to a vector for different txt files (all of same structure) i dont get the right result every time.
the first line (first number of the vector) show how many graphs are to be implemented from this file.
Then the first number of the second line (second number of the vector) gives the nodes and the second number of the second line (third number of the vector) the edges. After there are the edges number pairs, then again number of nodes and number of edges and so on.
For the first vector my code works. This is what i have written:
int main(int argc, char** argv)  {
vector<int> read_ints = {2,9,9,6,3,7,1,8,9,6,4,5,1,1,9,2,5,1,4,5,4,9,9,4,6,8,1,3,4,2,8,6,7,9,3,4,7,1,5,4,9};
vector<int> read_ints2 = {10,25, 18,5 ,19,4 ,23,13, 25,4 ,7,2 ,18,11, 4,15, 25,16, 12,2 ,23,5 ,23,24, 19,14, 11,2 ,24,19, 2,14, 16,20, 24,19, 8,18, 3,15, 15,14, 10,15, 4,8 ,10,2 ,3,6 ,11,13, 9,8 ,1,7 ,13,5 ,12,3 ,9,12, 7,1 ,5,15, 2,14, 11,4 ,6,17, 17,9 ,1,10, 17,5 ,11,5 ,14,14, 13,7 ,4,14, 4,10, 8,17, 4,9 ,3,5 ,16,6 ,16,10, 3,2 ,14,1 ,13,15, 17,16, 13,16, 16,6 ,1,13, 5,5 ,8,16, 1,7 ,13,13, 10,10, 3,8 ,14,3 ,2,7 ,5,11, 12,7 ,12,7 ,10,15, 4,13, 15,11, 16,22, 22,11, 13,17, 6,10, 7,8 ,10,10, 21,20, 5,2 ,20,14, 4,3 ,22,7 ,1,4 ,19,2 ,16,11, 8,15, 1,1 ,4,16, 19,9 ,16,11, 3,12, 5,6 ,22,9 ,2,17, 5,18, 18,10, 4,10, 13,3 ,10,17, 12,15, 6,11, 2,6 ,17,7 ,5,14, 16,8 ,2,7 ,8,3 ,1,16, 9,16, 1,14, 12,9 ,5,14, 9,18, 11,20, 20,11, 8,9 ,11,1 ,19,7 ,15,5 ,12,1 ,6,10, 4,2 ,19,20, 7,3 ,8,11, 13,5 ,9,20, 18,10, 16,4 ,6,17, 14,18, 19,17, 5,8 ,10,17, 15,12, 12,6 ,4,12, 2,12, 8,7 ,4,7 ,5,10, 8,1 ,5,1 ,2,10, 6,10, 3,8 ,9,9 ,11,8 ,8,5 ,3,7 ,8,6 ,4,7 ,1,2 ,6,8 ,2,3 ,4,5 ,1,20, 20,6 ,15,14, 7,4 ,17,13, 3,8 ,15,17, 8,12, 18,14, 18,18, 7,9 ,15,11, 5,9 ,8,2 ,20,16, 20,4 ,1,3 ,2,20, 3,14, 10,1 ,5,19, 13};
vector<int>::iterator ints_iter;
int counter = 0; // to count the edges, for testing purposes.
int num_of_graphs = read_ints.at(0);
int num_vertices = read_ints.at(1) + 1; // + 1 because of the code i wrote for implementing the graph's vertices
int num_edges = read_ints.at(2);
read_ints.erase(read_ints.begin(), read_ints.begin() + 3); // deleting the first line (number of graphs) and the first graph's info, so it is easier to add edge's pairs.
for (int i = 0; i < num_of_graphs; i++){
    Graph g(num_vertices); // Graph is the class i made
    for (int i = 0; i < num_edges * 2; i += 2) {
        cout << read_ints.at(i) << " " << read_ints.at(i + 1) << endl; // printing the pairs line by line
        counter++;
    }
    read_ints.erase(read_ints.begin(), read_ints.begin() + (num_edges * 2)); // delete the pairs of the i'th graph every time from the vector to add the new edges on the next graph
    if (read_ints.empty()) // error handling for the last graph (which doesnt work)
        break;
    else
        int num_vertices = read_ints.at(0) + 1; // after deleting the previous graph info and the previous graphs edges from the vector, i change the i values for next graph's nodes and edges
        int num_edges = read_ints.at(1);
        read_ints.erase(read_ints.begin(), read_ints.begin() + 2); // since the vector is not empty i erase the last elements
}
cout << counter;

return 0;

For the first vector it works but for a bigger one like the second it says "terminate called after throwing an instance of 'std::out_of_range'
what():  vector::_M_range_check: __n (which is 8) >= this->size() (which is 8)"
after printing out all the edges.

A:

This
    else
        int num_vertices = read_ints.at(0) + 1;
    int num_edges = read_ints.at(1);
    read_ints.erase(read_ints.begin(), read_ints.begin() + 2);

declares two local variables named num_vertices and num_edges.  These are different from the local variables of the same name declared earlier in main, so the values used on the next iteration of the loop are from the first block of data.
Note that I've also adjusted the indentation to show the how the statements interact with the else.  In this case it is harmless because the other branch of the if is a break but you need to be careful that you don't misread your code due to misleading indentation.


Q:

Can batteries be charged and discharged at the same time? And do they wear down faster when doing so?

Imagine batteries connected to a charge controller and a load at the same time. When the load asks for power, and the charge controller delivers power, there are three possible situations:

P_in > P_out: there is netto power going into the battery: charging
P_in < P_out: there is netto power going out of the battery: discharging
P_in = P_out: battery keeps unchanged

The power that the battery loses/gains is |P_in - P_out|, but in the system as a whole there's flowing a lot more current than that. Does all the current go through the batteries in this system? Or is there no current flow through the battery in situation 3 (such that the current is flowing directly from the charge controller to the load).
Do the batteries wear down in situation 3? Or are they just completely unused then?
EDIT: I think my question is different than the so-called duplicate, since it's more about the physical working of the battery. I made a basic diagram about my question as asked by Olin Lathrop:

So the question boils down to: are the light green and pink currents present (comparable to a dynamic equilibrium state in a PN-junction at rest due to drift and diffusion, when there's also a lot of electrical current flowing throught the component but no net measurable current), which would make the battery wear down? And if they're not, why? Is "path of least resistance" a sufficient reasoning to state this?
Also I am not completely satisfied with the answer given in the other topic, since he tells it depends on the kind of charge controller. If the charge controller delivers e.g. 24W at 24V (so 1A) and the load asks 12W, why wouldn't that current go to the load? Or would the charge controller then deliver only .5A due to the applied resistance (the load), and neglegt the battery? And what will happen with the rest of the energy that the charge controller receives from its source (which is thus 24W-12W=12W)? Will it be dissipated somewhere?
I am talking about a system where charge controller, battery and load are always connected (a stand-alone solar electric system).

A:

Your confusion is not about batteries but a basic issue with current.
No, a battery can't be charged and discharged at the same time.  If a battery is connected to a charger delivering 1 A and a load drawing 3 A, then the battery will be discharged at 2 A.  There is no simultaneous charging and discharging going on.
Draw out the circuit and follow the currents.  You can conceptualize the above example as 1 A charging the battery and 3 A discharging it, but the battery sees the sum.  Again, draw a diagram and it should be more clear.  Handwaving makes everything difficult to understand.
Added:
Your diagram should make it clear.  You can't have current going thru the battery both directions simultaneously.  You can think of it conceptually as being two currents, but the battery will see the sum of the pink and green currents in your diagram.


Q:

My Google Cloud SQL instance connection and/or queries are too slow

In my job we have the task to see if we can migrate our App database from our current server to a Google Cloud SQL instance. I created my GCP, configured the instance and imported the database.
The issue is that I have already connected from my project (a CakePHP localhost App) to the database in gcloud and after ran some queries I noticed that they are taking a lot of time and the render of the view is very slow. I have already upgraded the storage of the instance (to have a better read/write speed) and the cores/memory with no results.
Here are some queries and the time they took:
Query.                                             Time.    Affected.

GCloud
SELECT * FROM clients WHERE company_id = 3711;     50ms.    3rows.

Localhost
SELECT * FROM clients WHERE company_id = 3711;     1ms.     3rows.

And also the CakePHP DebugKit timer response in one of my views:
GCloud    - Controller Action ---- 317.55 ms.
Localhost - Controller Action ---- 7.44   ms.

Another view took 3+ seconds using GCloud and 164 ms from my localhost.
I used the us-central1 zone, already upgraded the SSD, cores, RAM, and used small queries like this one to no avail. I think that maybe it has something to do with the latency, but I don't have the slightiest idea.
Im querying from Mexico, to be specific from Jalisco.
My instance is a 2 core with 13gb  of ram db-n1-highmem-2
in my localhost SELECT @@log_binreturns a 0.
Files:
php.ini
my.cnf
SHOW GLOBAL STATUS
SHOW GLOBAL VARIABLES
SHOW FULL PROCESSLIST
EXPLAIN SELECT SQL_NO_CACHE * FROM clients WHERE company_id = 3711;

1   SIMPLE  clients NULL    ref find_by_id,clients_modified,company_id_3,clients_by_creator,clients_by_owner    find_by_id  4   const   3   100.00  Using where

SHOW INDEX FROM clients;

Table   non_unique  key_name            seq_in_index    column_name         collation   cardinality sub_part    packed  null    index_type
clients 0           PRIMARY             1               id                  A           685571      NULL        NULL            BTREE
clients 0           PRIMARY             2               user_id             A           685571      NULL        NULL            BTREE
clients 0           PRIMARY             3               company_id          A           685571      NULL        NULL            BTREE
clients 0           find_by_id          1               company_id          A           1159        NULL        NULL            BTREE
clients 0           find_by_id          2               id                  A           685571      NULL        NULL            BTREE
clients 1           clients_modified    1               company_id          A           1587        NULL        NULL            BTREE
clients 1           clients_modified    2               modified            A           512088      NULL        NULL    YES     BTREE
clients 1           company_id_3        1               company_id          A           1254        NULL        NULL            BTREE
clients 1           company_id_3        2               prospectus          A           3642        NULL        NULL            BTREE
clients 1           company_id_3        3               last_update         A           303012      NULL        NULL    YES     BTREE
clients 1           clients_by_creator  1               company_id          A           1503        NULL        NULL            BTREE
clients 1           clients_by_creator  2               user_id             A           3577        NULL        NULL            BTREE
clients 1           clients_by_owner    1               company_id          A           1423        NULL        NULL            BTREE
clients 1           clients_by_owner    2               user_assigned_id    A           3949        NULL        NULL            BTREE
clients 1           company_id_3        3               last_update         A           303012      NULL        NULL    YES     BTREE
clients 1           clients_by_creator  1               company_id          A           1503        NULL        NULL            BTREE
clients 1           clients_by_creator  2               user_id             A           3577        NULL        NULL            BTREE
clients 1           clients_by_owner    1               company_id          A           1423        NULL        NULL            BTREE
clients 1           clients_by_owner    2               user_assigned_id    A           3949        NULL        NULL            BTREE

A:

Rate Per Second=RPS - Suggestions to consider for your Google Cloud Database flags - my.cnf [mysdld] section
innodb_lru_scan_depth=100  # from 2048 to conserve 95% CPU cycles used for function
innodb_flush_neighbors=0  # from 2 with SSD storage no need to look for neighbors
innodb_buffer_pool_size=4G  # from ~ 10G to support less than 1G of data, reduce mgmt cycles
innodb_old_blocks_time=20000  # from 1000 to reduce select_scan RPhr of 1,395

Provide feedback, please after implementation + 24 hours of use.


Q:

ASP.NET MVC 2 Html.actionline : Making it act like a postback, or passing in all current form values into controller action

Hey, is it possible to do either:
1) Get the html.actionlink to act like a post back and post all the current form values into a specific controller action? eg.
Index()
{
    Blah
}
[HttpPost]
Index(FormCollection)
{
    Blah
}

OtherMethod(FormCollection)

2) Or can i pass in all the current values for a form into the parameters for a controller action, besides the obvious having all values as a seperate parameter in the method header?
e.g.
OtherMethod(Model m)
{
     Blah
}

A:

By default anchor tags send GET requests only. If you want to send all the values inside a form I would recommend you using a submit button instead of an ActionLink. You could even make it look like a link using image button if this is your concern.
If you really insist on using ActionLink you could have some javascript to subscribe for the click event, submit the form and cancel the redirect. The question is why would you want to go through all this pain when you have the first option.
As far as passing values to a controller action are concerned you can pass them in the request (GET, POST, PUT, DELETE) or route => in this case the model binder will automatically bind them to action parameters.


Q:

XSLT code to convert one xml to another xml

Hi Guyz I am new to XSLT. Please help to create the XSLT to get the below output.
input XML
<ProjectedMonthlyIncomeList>
  <ProjectedMonthlyIncome>
      <StartDate>2014-09-11T00:00:00-04:00</StartDate>
      <EndDate>2014-09-30T00:00:00-04:00</EndDate>
      <Month>Sep</Month>
      <Income>372.00</Income>
  </ProjectedMonthlyIncome>
  <ProjectedMonthlyIncome>
      <StartDate>2014-10-01T00:00:00-04:00</StartDate>
      <EndDate>2014-10-31T00:00:00-04:00</EndDate>
      <Month>Oct</Month>
      <Income>222.00</Income>
  </ProjectedMonthlyIncome>
  <ProjectedMonthlyIncome>
      <StartDate>2014-11-01T00:00:00-04:00</StartDate>
      <EndDate>2014-11-29T23:00:00-05:00</EndDate>
      <Month>Nov</Month>
      <Income>379.00</Income>
  </ProjectedMonthlyIncome>

XSLT:
<xsl:stylesheet version="1.0" xmlns:xsl="w3.org/1999/XSL/Transform">
<xsl:template match="/">
    <xsl:apply-templates match = "ProjectedMonthlyIncomeList/ProjectedMonthlyIncome">
        <xsl:with-param name="sequence" select="1" />
    </xsl:apply-templates>
</xsl:template>

<xsl:template match="ProjectedMonthlyIncomeList/ProjectedMonthlyIncome">
    <xsl:param name="sequence" />
        <xsl:if test = "$sequence = '1'">
            <mon1><xsl:value-of select="Income"/></mon1>
        </xsl:if>
</xsl:template>
</xsl:stylesheet>

Output XML
<Mon1>372.00</Mon1>
<Mon2>222.00</Mon2>
<Mon3>379.00</Mon3>

I want Income tag to be mapped to Mon1, Mon2, Mon3 from each ProjectedMonthlyIncome tag

A:

Try this:
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:template match="ProjectedMonthlyIncomeList">
    <xsl:for-each select="ProjectedMonthlyIncome/Income">
        <xsl:element name="Mon{position()}">
            <xsl:value-of select="."/>
        </xsl:element>
    </xsl:for-each>
</xsl:template>
</xsl:stylesheet>


Q:

What's wrong with this change of variable in calculating definite integral?

Suppose we want to calculate $S=\int_{0}^{1}(-x^2+x)dx$ and somehow make the change of variable $x=-t$, so
$S=\int_{-1}^{0}(-t^2-t)(-dt)=\int_{-1}^{0}(t^2+t)dt=(\frac{t^3}{3}+\frac{t^2}{2})\big|_{-1}^{0}=0-(-\frac{1}{3}+\frac{1}{2})=-\frac{1}{6}$. This is obviously incorrect because the original integral $\int_{0}^{1}(-x^2+x)dx=(-\frac{x^3}{3}+\frac{x^2}{2})\big|_{0}^{1}=\frac{1}{6}$.  Which step is wrong in this change of variable procedure, and why? Thanks!

A:

The limits are wrong.
When $~x~$ is $~0~$, $~t~$ is still $~0~$.
When $~x~$ is $~1~$, $~t=-1~$
So integral is from $~0~$ to $~-1~$ and not form $~-1~$ to $~0~$.


Q:

 Injection between non-isomorphic irreducible Hilbert space reps?

I must be missing something trivial here.
Let $G$ be, say, a reductive Lie group (or more generally any locally compact Hausdorff unimodular topological group). A unitary Hilbert space representation of $G$ is a group homomorphism from $G$ to the group of unitary endomorphisms $U(H)$ of a Hilbert space $H$, with the property that for all $v\in H$ the map $G\to H$, defined by sending $g$ to $gv$, is continuous. A unitary Hilbert space representation is irreducible if $H\not=0$ and $0,H$ are the only closed $G$-invariant subspaces of $H$.
I am ploughing through the book by Jacquet and Langlands and have made it to the all-important last chapter. On page 497 they make an assertion which seems to me to be the following:
if $V$ and $W$ are irreducible Hilbert space reps of $G$, and $i:V\to W$ is a continuous $G$-equivariant map, then either $i=0$ or $V$ and $W$ are isomorphic.
But I cannot rule out the possibility that $V$ and $W$ are not isomorphic and yet $i$ is an injection with dense image.
What am I missing? Of course I might have misunderstood the assumptions being made---they are in an explicit situation with $G$ equal to $GL(2,A)$ for $A$ some adele ring---but I cannot imagine that this can make much difference. Another assumption I think one can make is that any $f\in C_c(G)$ acts on $V$ and $W$ via Hilbert-Schmidt operators. But my gut feeling is that there's a one-line observation that kills this.
I am supposed to be lecturing on this in about 14 hours so I had intended offering a big bounty! But I see from the FAQ that I have to wait 2 days before I can do so. grr

A:

No conditions are needed on the group $G$, or on the continuity of the representation, you do need the assumption that $i$ is continuous however.  Since $i:V \to W$ is continuous (equivalent to being bounded) it has a continuous adjoint $i^* : W \to V$ which is also $G$ equivariant, hence $i^* i:V \to V$ is $G$ equivariant and since $G$ acts on $V$ irreducibly must be a scalar multiple of the identity (if not the spectrum would contain more than one point and you could take a spectral projection of $i^* i$ and obtain a closed non-trivial $G$-invariant subspace).  This shows that $i$ is a scalar multiple of an isometry and hence the image must be closed.  If $G$ also acts irreducible on $W$ then $ii^*$ is also a scalar multiple of the identity and hence if $i \not= 0$ it must be a non-zero scalar multiple of a unitary between $V$ and $W$.


Q:

What is the Y-intercept?

In class, my math teacher was teaching us how to draw functions on a coordinate plane, and he mentioned something about the Y-Intercept being an important step in creating/solving a function. But, what exactly is a Y-Intercept?

A:

The $y$-intercept of a function $f(x)$ is the point where the function intersects the $y$-axis (if in fact it does intersect the $y$-axis) and it is found by evaluating $f(0)$, i.e., finding the value of $f(x)$ when $x = 0$.
For example,

the line $f(x) = y = 3x + 2$ intersects the $x$-axis at when $x = 0$: when $\;y = 3\cdot 0 + 2 = 2$. This is the function's y-intercept.
The parabola $f(x) = y = 2x^2 + 8$ intersects the $y$-axis when $x = 0:\;$ when $\;y = 2(0)^2 + 8 = 8$. This is the function's y-intercept.


Q:

Can we use static method in an abstract class?

In Java Programming, Can we call a static method of an abstract class?
Yes I know we can't use static with a method of an abstract class. but I want to know why.. ?

A:

In Java you can have a static method in an abstract class:
abstract class Foo {
   static void bar() { }
}

This is allowed because that method can be called directly, even if you do not have an instance of the abstract class:
Foo.bar();

However, for the same reason, you can't declare a static method to be abstract. Normally, the compiler can guarantee that an abstract method will have a real implementation any time that it is called, because you can't create an instance of an abstract class. But since a static method can be called directly, making it abstract would make it possible to call an undefined method.
abstract class Foo {
   abstract static void bar();
}

// Calling a method with no body!
Foo.bar();

In an interface, all methods are implicitly abstract. This is why an interface cannot declare a static method. (There's no architectural reason why an interface couldn't have a static method, but I suspect the writers of the JLS felt that that would encourage misuse of interfaces)

A:

If you are talking about java, answer is Yes But you need to define the static method. You cannot create an abstract static method. What you can create is non abstract static method.
Reason is you do not need a object instance to access a static method, so you need the method to be defined with a certain functionality.
so you cannot have,
  abstract class AbstractClassExample{
     abstract static void method();

}

But you can have,
abstract class AbstractClassExample{

     static void method(){}
}

Hope this helps...

A:

Here is a simple explanation.Abstract methods must be implemented later.We know that static methods cannot be overridden because static methods do not belong to any particular instance, rather it belongs to the class.Then different implementation of abstract method,which is static, in different classes is counter-intuitive.


Q:

Toggle button checked status on activity startup

Here's my code
public class Abc(){
Public void onCreate(){
Textview ustatus;
ustatus=(Textview)findviewbyid(R.id.status);
    statusButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    if (isChecked) {
                        statusOnline();
                        // The toggle is enabled
                    } else {
                        statusOffline();
                        // The toggle is disabled
                    }
                }
            });
}

      public void statusOnline(){
               ustatus.setText("Online");
}
public void statusOffline(){
               ustatus.setText("Offline");
}
}

I want to know what toggle state would be at the initial on startup suppose in statusOnline and statusOffline method i am doing alot more so i just want that at initial this toggle is intialized with "ON" state.
I don't how to achieve it please bring some light into my code.

A:

 <CheckBox
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:checked="true"
        android:gravity="bottom"/>

This will create a checkbox that is already ticked. U can change the checked to false if u want an unchecked box. The listner will only call when u interact with the checkbox.
For listener outside onCreate u can do as follows
  @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //other statements here
        CheckBox checkBox = (CheckBox)findViewById(R.id.checkbox);
        checkBox.setOnCheckedChangeListener(checkedChangeListener);
    }

    CompoundButton.OnCheckedChangeListener checkedChangeListener = new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
         //process logic here

        }
    };

SharedPreferences preferences = getSharedPreferences("PREFERENCE", 0);
SharedPreferences.Editor editor = preferences.edit();
editor.clear();
editor.commit();


Q:

Array from flash to php/mysql

How can I save to my mysql db an array from flash? I pass the array as a parameter to a php script. What I have to do next?

A:

Many options here, simplist is as follows:

Connect to db
searialize array and store in db

http://php.net/manual/en/function.serialize.php - This will convert the array in a string, which can be unserialized later.


Q:

Do you know whether employers can or will accept other evidence of eligibility to work, or is the residence card the only document they can consider?

I hope you can guide me on this one.
I was wondering if I can work as fast as possible in the UK just by showing I'm married to an EEA national. Basically, my question is the following: do you know whether employers can or will accept other evidence of eligibility to work, or is the residence card the only document they can consider?
I wonder if I can start working in the mean time as a baby sitter or waitress just by showing I am married to an EEA national. Can you guive me some guidance please? I really don't want to be out of work for a long time.

A:

The magic search term you want is "right to work". You'll likely want the employers guides, rather than the employee ones, as that'll help you work out the options better.
For the full details, you can read the Right to work checks: an employer's guide and Acceptable right to work documents: an employer's guide. For a quick summary, there's the Check a job applicant's 'right to work' documents page.
You'll really need to read through those, and work out what (if any) of the things you have are the ones that Employers are legally protected from fines if they see + record. Based on page 16 of the Acceptable right to work documents: an employer's guide, it looks like biometric residency cards are the normal way for non-EEA family members of EEA-citizens, but I haven't checked the list fully and I don't know what else you have!


Q:

Kotlin object expressions: Comparator example

This code basically sorts the array in a descending order:
val arrayList = arrayListOf(1, 5, 2)

Collections.sort(arrayList, object : Comparator<Int> {
   override fun compare(x : Int, y: Int) = y - x
})

How in the world does overriding the compare method with y - x works? How does Kotlin know what y - x means to put y before x if y < x?

A:

This actually has nothing to do with Kotlin. It's related to the Java API's Comparator interface, and how Collections.sort uses it.
From the documentation:

Compares its two arguments for order. Returns a negative integer,
  zero, or a positive integer as the first argument is less than, equal
  to, or greater than the second.

Now let's try this out for the arguments you gave:

1 - 5 = -4 (a negative integer), so 1 is less than 5.
5 - 2 = 3 (a positive integer), so 5 is greater than 2.
etc...

Collections.sort doesn't know anything about what y - x means. It simply respects the defined contract of the Comparator interface that any implementor also needs to respect (if it wants to work).
It just so happens that y - x is an implementation that does respect that contract, because Math.

A:

Since Comparator is a SAM interface you can write this code more concise using a lambda:
Collections.sort(arrayList, {x : Int, y: Int -> y - x})

Or even
Collections.sort(arrayList) {
    x, y -> y - x
}

since the lambda is the last parameter of the sort function and the datatype of x and y can be inferred.

Taking two objects and having to define a single integer for them is an abstraction of a sort definition. You basically specify in which order those elements would be layed out if sorted.
For sorting integers it might seem like an overkill, but consider having to sort more complex objects for example instances of a class Car.
This class has a colorCode and you want to sort by that:
Collections.sort(cars) {
    car1, car2 -> car1.colorCode - car2.colorCode
}

That is how you would define an order for those objects in an abstract way.


Q:

Scala 2.10 + Json serialization and deserialization

Scala 2.10 seems to have broken some of the old libraries (at least for the time being) like Jerkson and lift-json.
The target usability is as follows:
case class Person(name: String, height: String, attributes: Map[String, String], friends: List[String])

//to serialize
val person = Person("Name", ....)
val json = serialize(person)

//to deserialize
val sameperson = deserialize[Person](json)

But I'm having trouble finding good existing ways of generating and deserializing Json that work with Scala 2.10.
Are there best practice ways of doing this in Scala 2.10?

A:

Jackson is a Java library to process JSON fast. The Jerkson project wraps Jackson, but appears to be abandoned. I've switched to Jackson's Scala Module for serialization and deserialization to native Scala data structures.
To get it, include the following in your build.sbt:
libraryDependencies ++= Seq(
  "com.fasterxml.jackson.module" %% "jackson-module-scala" % "2.1.3",
   ...
)

Then your examples will work verbatim with the following Jackson wrapper (I extracted it from jackson-module-scala test files):
import java.lang.reflect.{Type, ParameterizedType}
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.module.scala.DefaultScalaModule
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.`type`.TypeReference;

object JacksonWrapper {
  val mapper = new ObjectMapper()
  mapper.registerModule(DefaultScalaModule)

  def serialize(value: Any): String = {
    import java.io.StringWriter
    val writer = new StringWriter()
    mapper.writeValue(writer, value)
    writer.toString
  }

  def deserialize[T: Manifest](value: String) : T =
    mapper.readValue(value, typeReference[T])

  private [this] def typeReference[T: Manifest] = new TypeReference[T] {
    override def getType = typeFromManifest(manifest[T])
  }

  private [this] def typeFromManifest(m: Manifest[_]): Type = {
    if (m.typeArguments.isEmpty) { m.erasure }
    else new ParameterizedType {
      def getRawType = m.erasure
      def getActualTypeArguments = m.typeArguments.map(typeFromManifest).toArray
      def getOwnerType = null
    }
  }
}

Other Scala 2.10 JSON options include Twitter's scala-json based on the Programming Scala book--it's simple, at the cost of performance. There is also spray-json, which uses parboiled for parsing. Finally, Play's JSON handling looks nice, but it does not easily decouple from the Play project.

A:

Mentioning json4s that wraps jackson, lift-json or its own native implementation as a long term solution:

code
website

A:

I can heartily recommend argonaut for json support in scala. All you need to configure it to serialize your Customer object is one line:
implicit lazy val CodecCustomer: CodecJson[Customer] =
casecodec6(Customer.apply, Customer.unapply)("id","name","address","city","state","user_id")

That will pimp your class to give it an .asJson method which turns it into a string. It will also pimp the string class to give it a method .decodeOption[List[Customer]] to parse strings. It handles the options in your class fine. Here is a working class with a passing test and a running main method which you can drop into a git clone of argonaut to see it all working fine:
package argonaut.example

import org.specs2.{ScalaCheck, Specification}
import argonaut.CodecJson
import argonaut.Argonaut._

case class Customer(id: Int, name: String, address: Option[String],
                    city: Option[String], state: Option[String], user_id: Int)

class CustomerExample extends Specification with ScalaCheck {

  import CustomerExample.CodecCustomer
  import CustomerExample.customers

  def is = "Stackoverflow question 12591457 example" ^
    "round trip customers to and from json strings " ! {
      customers.asJson.as[List[Customer]].toOption must beSome(customers)
    }
}

object CustomerExample {

  implicit lazy val CodecCustomer: CodecJson[Customer] =
    casecodec6(Customer.apply, Customer.unapply)("id","name","address","city","state","user_id")

  val customers = List(
    Customer(1,"one",Some("one street"),Some("one city"),Some("one state"),1)
    , Customer(2,"two",None,Some("two city"),Some("two state"),2)
    , Customer(3,"three",Some("three address"),None,Some("three state"),3)
    , Customer(4,"four",Some("four address"),Some("four city"),None,4)
  )

  def main(args: Array[String]): Unit = {

    println(s"Customers converted into json string:\n ${customers.asJson}")

    val jsonString =
      """[
        |   {"city":"one city","name":"one","state":"one state","user_id":1,"id":1,"address":"one street"}
        |   ,{"city":"two city","name":"two","state":"two state","user_id":2,"id":2}
        |   ,{"name":"three","state":"three state","user_id":3,"id":3,"address":"three address"}
        |   ,{"city":"four city","name":"four","user_id":4,"id":4,"address":"four address"}
        |]""".stripMargin

    var parsed: Option[List[Customer]] = jsonString.decodeOption[List[Customer]]

    println(s"Json string turned back into customers:\n ${parsed.get}")

  }
}

The developers are also helpful and responsive to folks getting started.


Q:

accepting input using check_box in rails

I'm a beginner working my way through a rails tutorial. An assignment consists of adding questions to a page (which can be edited and updated/deleted). I'm trying to get my Question form to accept input from a check_box as to whether the question was answered (to include in the Update section).
I have read documentation on check_box here and and here, and see that I would need check_box(object_name, method, options = {}, checked_value = "1", unchecked_value = "0"). However, I am unsure as to where I would use that in my form, and what I would pass as object_name, method and options. Any pointers will be much appreciated!
Controllers:
class QuestionsController < ApplicationController
  def index
    @questions = Question.all
  end

  def new
    @question = Question.new
  end

  def create
    @question = Question.new(params.require(:question).permit(:title, :body))
    if @question.save
      flash[:notice] = "Question was saved."
      redirect_to @question
    else
      flash[:error] = "There was an error saving the post. Please try again."
      render :new
    end
  end

  def show
    @question = Question.find(params[:id])
  end

  def edit
    @question = Question.find(params[:id])
  end

  def update
    @question = Question.find(params[:id])
    if @question.update_attributes(params.require(:question).permit(:title, :body))
      flash[:notice] = "Question was updated"
      redirect_to @question
    else
      flash[:error] = "There was an error saving your post. Please try again."
      render :edit
    end
  end

  def destroy
    @question = Question.find(params[:id])
    @question.destroy
    redirect_to questions_path
    flash[:notice] = "The question has been deleted."
  end
end

show view:

<%= @question.title %>

<%= link_to "Edit", edit_question_path(@question), class: 'btn btn-success' %>

<%= link_to "Delete", @question, method: :delete, data: { confirm: "Are you sure?" }, class: 'btn btn-success' %>

<%= @question.body %>

edit view:

Edit and Update Question

Guidelines for questions

Stay on topic.

    <%= form_for @question do |f| %>

        <%= f.label :title %>
        <%= f.text_field :title, class: 'form-control', placeholder: "Enter post title" %>

        <%= f.label :body %>
        <%= f.text_area :body, rows: 8, class: 'form-control', placeholder: "Enter post body" %>

        <%= f.submit "Save", class: 'btn btn-success' %>
        <%= link_to "Delete", @question, method: :delete, data: { confirm: "Are you sure?" }, class: 'btn btn-success' %>

    <% end %>

A:

If, for instance, you have an answered attribute on your Question model that is a boolean, then all you have to do within your form_for block is say <%= f.check_box :answered %>. It'll evaluate to a true value if it's checked, false otherwise.


Q:

How to prove that the space $ \omega_1\times R $ has countable extent?

How to proof that the space $ \omega_1\times R $  has countable extent? The topological space $\omega_1$ is the first uncountable ordinal with order topology.

A space $X$ has countable extent if every uncountable subset of $X$ has a limit point in $X$.

Thanks for any help:)

A:

By $R$ I assume you are denoting the real line.
(Oh, dear; the question seems to have been substantially altered.  Please ignore the now silly sounding striked-out paragraph.)
Suppose that $A \subseteq (\omega + 1 ) \times R$ is uncountable.  Note that there must be a $i \leq \omega$ such that $A_i = \{ x \in R : (i,x) \in A \}$ is uncountable.  But as $R$ has countable extent it follows that $A_i$ has a limit point $x$ in $R$.  It easily follows that $(i,x)$ is a limit point of $A$ in $(\omega +1 ) \times R$.
Let $A \subseteq \omega_1 \times R$ be uncountable.  If there is an $\alpha < \omega_1$ such that $A_\alpha = \{ x \in R : (\alpha , x ) \in A \}$ is uncountable, then $A_\alpha$ has a limit point $x$ (as $R$ has countable extent), and it is easy to show that $(\alpha , x )$ is a limit point of $A$.
So assume that $A_\alpha$ is countable for each $\alpha < \omega_1$.  We may then recursively construct a sequence $\langle (\alpha_i , x_i ) \rangle_{i \in \omega}$ in $A$ such that:

$\alpha _i < \alpha_{i+1}$ for all $i \in \omega$; and
$\langle x_i \rangle_{i \in \omega}$ is a convergent sequence in $R$.

Let $\alpha = \sup_{i \in \omega} \alpha_i < \omega_1$ (and note that $\alpha$ is a limit ordinal).  Let $x = \lim_{i \in \omega} x_i$.  It is easy to show that $( \alpha , x )$ is a limit point of $A$ in $\omega_1 \times R$.


Q:

show route between multiple Annotations

I need to show route (path) between multiple annotations.they are located at different locations but in a range of say 10 km.

A:

I think this may be helpful for you as i have done this for drawing rout between cities.
CLLocationCoordinate2D firstCoords;
    firstCoords.latitude = lat1;
    firstCoords.longitude = lng1;

CLLocationCoordinate2D secondCoords;
    secondCoords.latitude=lat2;
    secondCoords.longitude=lng2;

NSLog(@" %f", lat1);
NSLog(@" %f", lng1);
NSLog(@" %f", lat2);
NSLog(@" %f", lng2);
routeCoordinates[0] = CLLocationCoordinate2DMake(lat1, lng1);
routeCoordinates[1] = CLLocationCoordinate2DMake(lat2, lng2);
MKPolyline *routeLine = [MKPolyline polylineWithCoordinates:routeCoordinates count:2];
[mapView addOverlay:routeLine];

A:

try out with this tutorial link, it shows only single route between two points. you need to change as per your requirement. for 10km distance. you have to calculate distance using both point's (latitude, longitude).


Q:

Issue when trying to display data from MySQL Database

I have a database on PHPMyAdmin, named mydb, then a table named myguests. Its supposed to access the information on the database and display it. Here is my code:
<?php
$connection = mysql_connect('localhost', 'root', '');
mysql_select_db('mydb');

$query = "SELECT * FROM myguests";
$result = mysql_query($query);

while($row = mysql_fetch_array($result)){
echo "Name: " . $row["firstname"]. " " . $row["lastname"].;
}

mysql_close();
?>

When I go to display the webpage it says
Parse error: syntax error, unexpected ';' in C:\xampp\htdocs\printback.php on line 10

Anyone have a solution?
Thanks for helping me!

A:

This line:
echo "Name: " . $row["firstname"]. " " . $row["lastname"].;

Has a dot right before the semicolon. Remove it and it'll work.


Q:

Sum the Column based on another column

i have a file with 2 columns, 1st column is time with HH:MM:SS  format and 2nd column is count.
I want to sum the 2nd column based 1st coulmn. with respect to Hour and minute of 1st column.
Input:
00:00:00,2.00,
00:00:10,1.00,
00:00:20,2.00,
00:00:30,6.00,
00:00:40,1.00,
00:00:50,7.00,
00:01:00,8.00,
00:01:10,7.00,
00:01:20,8.00,
00:01:30,11.00,

For Hour: the below awk works,
 awk -F, '{ a[substr($1,0,2)]+=$2 } END{ for (i in a) print i "," a[i] }' file

output:
00,53

For Minute:
unable sum the column based on the Minute filed, please suggesst the way to get the expected result.
Excepted Output:
00:00,19
00:01,34

A:

Using `awk:
awk -F '[:,]' -v OFS=, '{s[$1 ":" $2]+=$(NF-1)} END{for (i in s) print i, s[i]}' file
00:00,19
00:01,34

EDIT: If ordering of original timestamps is important then use:
awk -F '[:,]' -v OFS=, '{k=$1":"$2} !s[k]{b[++n]=k} {s[k]+=$(NF-1)}
     END {for (i=1; i<=n; i++) print b[i], s[b[i]]}' file
00:00,19
00:01,34


Q:

Modifiquei sem querer a branch do Git de meu projeto no android studio

Gente, eu estava trabalhando no meu projeto, quando cliquei em algo sem querer, e aparentemente "perdi" as versões mais novas.
Me apareceu esta mensagem em meu console do android studio:
Warning: you are leaving 19 commits behind, not connected to
any of your branches:
  d78081a App cliente Versão 1.5.7
  9d19da0 App cliente Versão 1.5.6
  861890d App cliente Versão 1.5.5
  15ff813 App cliente Versão 1.5.4
 ... and 15 more.
If you want to keep them by creating a new branch, this may be a good time
to do so with:
 git branch <new-branch-name> d78081a
Switched to branch 'master'

E, não sei o que deve ser feito

A:

Consegui resolver o problema, aparentemente quando as versões somem fica um histórico:
Cole isso no terminal
git reflog

então você precisa criar um novo branch e fazer referência ao que sumiu
git branch new-branch ba5a739

onde o new-branch é o nome do branch e o número ao lado é o número de referência
e então você volta o código ao branch antigo com o seguinte código:
git reset --hard ba5a739

e então todo o código vai voltar ao normal


Q:

Extract overlapping names from different data sets (character)

Is there any easy way to find overlapping names from different data sets ?
> class(list1)
[1] "character"

So let's say that I have a data like that:
list1 <- c("Mark", "Greg", "Max", "Gregor", "Paul", "JAck", "Marcus")
list2 <- c("Chris", "Jackson", "Mark", "Michael", "Gena", "Greg")
list3 <- c("Susane", "Mark", "Monica", "Chistopher", "Henry", "Atos", "Greg")
list4 <- c("Peter", "Marie", "Mark", "Greg", "Denice", "Daryl", "Maros", "Gert", "Suar")

The only names which are in all data are:
Mark and Greg

How to find such overlapping using R ? My data is much bigger so that's why I use an example.

A:

You can use:
Reduce(intersect, list(list1, list2, list3, list4))


Q:

Why admin menu and some styles working after modifying class Symlink -> Copy?

I have installed Magento ver. 2.1.2, Admin menu is not working and some of the front end styles are not coming properly.
After I replace (app/etc/di.xml) as in the below code, everything is working fine. I have been facing this issue with all Magento 2 versions.
Magento\Framework\App\View\Asset\MaterializationStrategy\Symlink

To
Magento\Framework\App\View\Asset\MaterializationStrategy\Copy

I got followed Solution for Inactive Admin Links in Magento 2 (Windows)
Can anybody tell me

Why the class replacement is necessary ?
Is this an internal bug ?
Am I missing something ?

A:

Officially Magento 2, as well as many other web application, is supposed to be installed and run in the native environment. The native environment means LAMP or LEMP + Unix compatible filesystem. On Windows you can easily have LAMP or LEMP but not fully Unix compatible filesystem (sure, you can try to emulate it in different ways but the emulation does not guarantee the system will work properly).
You need to change the Symlink materialisation strategy to the Copy statagy (Magento 2 using both for different cases) because your XAMPP installation does not support UNIX symlinks properly.
The symlinks in Windows (and XAMPP as well) are not the same as in the Unix based system. That's why you might have troubles using symlinks in Windows system.
No, it's not a bug since Magento is being developed and tested using the native (Unix) environment. Obviously, there's no reason to make the system compatible with different kinds of emulations. So, in order to be sure your system works correctly, it's strongly recommended to perform all development processes in the native environment as well (until you are going to run Magento 2 using Windows in production). It's achievable by using VirtualBox, Vagrant, Docker or other tools that allow you to run your web applications in Unix environment.


Q:

Using string staged in Textbox in MapPath method

I am working on a project to take data from a Word document and save it into an SQL database. I have everything working other than I currently have to hard code the path to where the image files have been stored (temporarily).
So this works:
using (Stream Image11 = File.OpenRead(Server.MapPath(@"\Temp\636794392003594492_files\image001.jpg")))

But I need to use something like this instead:
using (Stream Image11 = File.OpenRead(Server.MapPath("/" + Image1Up.ToString())))

unfortunately what I get when I try to use the value in the Image1up textbox is a string that ends with System.Web.UI.webcontrols.Textbox.

A:

Thank you RichardMc, that did it. Something simple that I should have seen, but a bit brain dead from fighting the overall project for days now.
using (Stream Image11 = File.OpenRead(Server.MapPath("/" + Image1Up.Text)))


Q:

Replace HTTPS to HTTPS of XML

I need to get an image url from a XML file, but my server got some errors because this url uses https. How can I read the https link and relace it to http? Please help me, I don't understand programming...
function api_lastfm( $artist, $api_key ) {
        $data = xml2array( get( "http://ws.audioscrobbler.com/2.0/?method=artist.getinfo&artist=" . urlencode( $artist ) . "&api_key={$api_key}", false, false, false, 6 ) );
        return ( isset( $data[ 'artist' ][ 'image' ][ 4 ] ) && !empty( $data[ 'artist' ][ 'image' ][ 4 ] ) ) ? $data[ 'artist' ][ 'image' ][ 4 ] : $data[ 'artist' ][ 'image' ][ 3 ];
    }

Thanks!

A:

Like I mentioned in my comment, use  str_replace() for this.
My example assumes that the get() method returns a string with the xml:
function api_lastfm( $artist, $api_key )
{
    $data = get( "http://ws.audioscrobbler.com/2.0/?method=artist.getinfo&artist=" . urlencode( $artist ) . "&api_key={$api_key}", false, false, false, 6 );

    // Replace all image urls using https to http
    $data = str_replace('https://lastfm-img2', 'http://lastfm-img2', $data);

    $data = xml2array($data);
    return ( isset( $data[ 'artist' ][ 'image' ][ 4 ] ) && !empty( $data[ 'artist' ][ 'image' ][ 4 ] ) ) ? $data[ 'artist' ][ 'image' ][ 4 ] : $data[ 'artist' ][ 'image' ][ 3 ];
}

This should change all image URL's from https to http. It does mean that the images must be available without https as well, though.


Q:

How to free memory from a list of classes

Say I have two classes created work and workItem.
        CWorker *work = new CWorker();
        CWorkItem *workItem = new CWorkItem();

The work class has a public list m_WorkList and I add the work item to it.
work->m_WorkList.push_back(workItem);

If I just delete work
if(work != NULL)
delete work;

Do I need to loop through the list in the destructor like the following? Any better way to do this? Could I use clear instead?
while(m_WorkList.size())
{
    CWorkItem *workItem = m_WorkList.front();
    m_WorkList.pop_front();
    if(workItem)
        delete workItem;
}

A:

Yes you need to delete each item.  If you call new N times, then you need to call delete exactly N times as well.  There is no shortcut for bulk deleting items.
Also when you're done with it you need to call delete on work.
You can use new[] and delete[] if you want to create an array of items on the heap and release the items on the heap respectively at once.   But in your case this isn't what you're looking for.
You can look to boost::shared_ptr if you don't want to manually do these delete calls.

A:

as said in the other responses, you need to loop over your list and delete each elements. if you call clear, it will just remove pointers from the list not pointed objects.
if you need a list with the notion of ownership you can use boost pointer container. it will ensure that your objects are destroyed when you destroy your list


Q:

What does "AF AX p" mean in CTL?

Both Logic in Computer Science (Huth and Ryan, 2004) and Branching vs. Linear Time: Final Showdown (Vardi, 2002), state something to this effect (paraphrased):

In LTL, X F p and F X p are equivalent, meaning "p is eventually true in some state that is not the current state". In CTL, AX AF p and AF AX p are not equivalent. AX AF p does mean the same as the above LTL formulas, but AF AX p means something different, which we leave as an exercise to the reader.

Both works emphasize that the meaning of AF AX p is something very strange.
From what I understand of CTL, AF AX p would mean "all paths from this state eventually reach a state where p is true in all next states", but that doesn't seem particularly strange. Am I correct in that understanding?

A:

Your understanding of $AF AX p$ is correct (in my opinion). But whether it seems particularly strange or hard to understand is rather subjective. The argument you quote compares the expressiveness or usability of LTL and CTL, and tries to convince readers that LTL is easier to understand (especially for engineers in practice).
In my experience, it indeed takes more time for me to figure out and confirm the meaning of $AF\,AX\,p$ than that of $AX\,AF\,p$, which is in turn more than that of $X\,F\,p$ or $F\,X\,p$. By the way, if $AF\,AX\,p$ were easier to understand than the other three formulas, you  would probably not bother asking for confirmations here.


Q:

change class of a cloned div with a button

I am cloning a div with a table in it. This div has a BLOCK class so it is visible. I would like to be able to have a button inside the div before the table, that gives the oportunity to hide this cloned div by changing it's class to a hidden class
var num = $('.class_of_div').length;
var newNum = num + 1;

Each cloned div has a new id. DIV_1 DIV_2 DIV_3.... each button also has new id's corresponding t it's div. So button_1 button_2 button_3....
The numbers after the tags are taken from the number of elements in another class.
these are my classes
.hidden{
     display: none;
 }

 .visible{
     display: block;
     margin-left: 20px;
 }

I would need to create a function with
.removeClass('.visible').addClass('.hidden')

but how can the button know that it must change the class of the current div in which is in? without changing classes of other old or new divs?
Hope all this was clear ;).

A:

If your button is inside the div that you want to edit it shouldn't be a problem to target that element using jQuery's .closest() function.
Additionally, you are going to want to use event delegation when you declare your event handlers, so they are triggered in all clones.
$("body").on("click", "button", function() {
  $(this).closest("div").removeClass('.visible').addClass('.hidden');
});

See the runnable snippet below for an example.

$("#wrapper").on("click", ".hide", function() {
  $(this).closest("div").hide("slow");
});
$("#wrapper").on("click", ".clone", function() {
  $(this).closest("div").clone().appendTo("#wrapper");
});
.cloneable {
  margin: 5px;
  outline: 1px solid;
  background-color: #CCC;
}

    <button class="hide">Hide</button>
    <button class="clone">Clone</button>


Q:

Where to find what commands/properties are available for AppleScript in Microsoft Outlook 2011

Does anyone know where I can find a list of available applescript commands/properties for Microsoft Outlook 2011?
I am trying to copy subject of the opened message into the clipboard and save the message as PDF to my desktop with subject as the file name.
Thanks.

A:

All applications that are apple-scriptable have a "dictionary" of terms as part of the application itself. To access a dictionary open AppleScript Editor, under the File menu choose "open dictionary", and then choose the application.
A second way would be to drag/drop the application onto the AppleScript Editor icon in the dock or applications folder.
A third way... under the Window menu in AppleScript Editor choose "Library". That window is a quick-access tool to access the dictionaries of various applications. You can click the "+" button to add applications not in that list. Double-click an application in the list to access its dictionary.
A 4th way... if AppleScript Editor and the application you are interested in are both in the dock, you can command-drag the application's dock icon onto the AppleScript Editor's dock icon.


Q:

Paging/Sorting not working on web grid used in Partial View

I have a partial view where I am showing a web grid depending upon a value selected from a page.
For drop down I have used
 @Html.DropDownListFor(
x => x.ItemId,
new SelectList(Model.Items, "Value", "Text"),
new {
    id = "myddl",
    data_url = Url.Action("Foo", "SomeController")
}
)

For drop down item select I have used
$(function() {
$('#myddl').change(function() {
   var url = $(this).data('url');
   var value = $(this).val();
   $('#result').load(url, { value: value })
});
});

and below is my action
public ActionResult Foo(string value)
 {
  SomeModel model = ...
return PartialView(model);
 }

everything works good, but when I try doing a paging or sorting on my webgrid which is on my partial view I am showing a new window with the web grid.
I wanted to be able to sort and page on the same page without postback
Please help

A:

The following example works fine for me.
Model:
public class MyViewModel
{
    public string Bar { get; set; }
}

Controller:
public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View();
    }

    public ActionResult Foo(string value)
    {
        var model = Enumerable.Range(1, 45).Select(x => new MyViewModel
        {
            Bar = "bar " + value + " " + x
        });
        return PartialView(model);
    }
}

Index.cshtml view:
<script type="text/javascript">
    $(function () {
        $('#myddl').change(function () {
            var url = $(this).data('url');
            var value = $(this).val();
            $.ajax({
                url: url,
                type: 'GET',
                cache: false,
                data: { value: value },
                success: function (result) {
                    $('#result').html(result);
                }
            });
        });
    });
</script>

@Html.DropDownList(
    "id",
    new[] {
        new SelectListItem { Value = "val1", Text = "value 1" },
        new SelectListItem { Value = "val2", Text = "value 2" },
        new SelectListItem { Value = "val3", Text = "value 3" },
    },
    new {
        id = "myddl",
        data_url = Url.Action("Foo", "Home")
    }
)

<div id="result">
    @Html.Action("Foo")
</div>

Foo.cshtml partial:
@model IEnumerable<MyViewModel>
@{
    var grid = new WebGrid(
        canPage: true,
        rowsPerPage: 10,
        canSort: true,
        ajaxUpdateContainerId: "grid"
    );
    grid.Bind(Model, rowCount: Model.Count());
    grid.Pager(WebGridPagerModes.All);
}

@grid.GetHtml(
    htmlAttributes: new { id = "grid" },
    columns: grid.Columns(
        grid.Column("Bar")
    )
)

Notice that I have used a GET request to refresh the grid instead of POST because this way the value query string parameter selected in the dropdown is preserved for future sorting and paging.


Q:

Catching LoadLibrary() errors gracefully

I'm working on a piece of C++ software which runs on all Windows versions between Windows XP and Windows Vista. In my code, I developed a DLL which links against a standard library (the Qt library). Once my software is deployed, it's not unusual that the user doesn't have the exact same Qt build on his system but a slightly different configuration. There might be features disabled (so their Qt build doesn't export the same set of symbols) or the library might even be changed in ways which make the library binary incompatible to the original.
At some point, I'm loading my DLL via a LoadLibrary() call. This pulls in whatever Qt library is on the user's system. If I'm lucky, their Qt build is compatible with what I used while developing my DLLs, so LoadLibrary() succeeds. However, depending on the changes they did to their Qt build, the LoadLibrary() call sometimes fails with

"The specified Module could not be found."; this usually happens if their Qt build consists of less DLLs than my Qt build. So my DLL attempts to load e.g. QtFoo.dll but since this dll is not part of their Qt build, loading my DLL fails.
"The specified Procedure could not be found."; this usually happens if they changes their Qt build so that certain features are disabled, which results in less exported symbols.

My question is: how can I catch these errors gracefully? Right I'm simply using GetLastError() and then print either of the above two messages. However, it would be much more useful if I knew which module could not be found, or which procedure is missing. I noticed that when running an application in the explorer which links against a missing DLL, explorer manages to yield a nice 'The application foo could not be loaded since the required library blah.dll is missing'. Is there maybe some API available to get more information about why a LoadLibrary() call failed exactly?

A:

Can MapAndLoad from ImageHLP.DLL may help. It returns a LOADED_IMAGE structure.