Q:

Android Service: should it be declared as a process or not?

I have implemented a simple Android Service that, by default, is deployed within the same process as my app / apk.  I want the Service running concurrently with each Activity.  To make that happen, in each Activity.onStart() and Activity.onStop() implementation, I have logic that invokes Activity.bindService() and Activity.unbindService(), respectively.
Well, all of this works fine, but it feels awkward.  Is there any other way to make sure the Service is continuously running and bound to all Activities without having to re-invoke Activity.bindService() and Activity.unbindService() for each Activity?  Should the Service in this case be declared as a stand-alone process?
Also, my Service starts a separate thread, but never stops it.  Should my code stop the thread?  Is there a chance the thread could be orphaned?  Starting / stopping the thread with OnUnbind / OnRebind seems like overkill.

A:

Create a base Activity and call bindService in onStart, unbindService in onStop.
public class BaseActivity extends Activity {

    @Override
    public void onStart() {
        // ...
        bindService(intent, serviceConnection, flags);
    }

    @Override
    public void onStop() {
        // ....
        unbindService(serviceConnection);
    }
}

This will make sure every activity that extends base is bound to the service.
When last activity is unbound from the service, it will be stopped. If you want to avoid that, call startService first, and then bind to it. This will prevent service from stopping even if you don't have running activities.

Should the Service in this case be declared as a stand-alone process?

In your case, you don't need a separate process for your service.

Also, my Service starts a separate thread, but never stops it. Should my code stop the thread?

If you want to stop your service, you should stop your thread because thread is a GC root, and all objects accessible from it will remain in memory. So, infinite thread that is not used is a memory leak.
You can implement threading different ways depending on your requirements. You can either implement a regular thread in your Service, or a ThreadPoolExecutor or a Handler. Pick a solution that fits to your needs.


Q:

In Github, I want to prevent members from merging a pull request

In my workflow I have two default branches: master (production) and dev (staging). All members create their branches from the dev branch. However, I want require the members to do a pull request to merge back into the dev branch. Additionally, I want to prevent those members from approving the pull request. I want to be the only one to approve a pull request merge after a code review.
I've been looking at protecting branches but I'm not sure if I'm on the right track.

A:

If you enable branch restrictions on your master and dev as mentioned https://help.github.com/articles/enabling-branch-restrictions/, everyone who branches out from these 2 will have to create a pull request which only you can merge


Q:

How do I perform a multi-colum match in SQLite?

Given two tables T1 and T2 with overlapping column definitions (B and C), how can I select rows in T1 where B and C cannot be found in T2 (in the same row?

Here is the setup:
create table T1('A' TEXT, 'B' TEXT, 'C' TEXT);
insert into T1 values
  ('a1', 'b1', 'c1'),
  ('a2', 'b2', 'c2'),
  ('a3', 'b3', 'c3');
create table T2('B' TEXT, 'C' TEXT, 'D' TEXT);
insert into T2 values
  ('b1', 'c1', 'd1'),
  ('b2', 'c2', 'd2'),
  ('b4', 'c4', 'd4');

With the following query, I can select the right rows. However this is limited to columns B and C so A is missing:
select B, C from T1
intersect
select * from (select B, C from T1
               except
               select B, C from T2);
-- this yields:
-- b3|c3

What I would like to do is something like:
select * from T1
intersect
select * from (select B, C from T1
               except
               select B, C from T2);
-- this yields:
-- Error: SELECTs to the left and right of INTERSECT do not have the same number of result columns

(Note the * in the first select statement.) I can't seem to grasp the concept of selecting rows with a subquery and returning full rows.
How do I have to change the query so that the result is a3|b3|c3?
By the way, this is a real life example where I have a dump of filenames from a restoration of a file system and I want to know which files are missing from the restoration.

A:

Perhaps not the best/most elegant solution but the following appears to work :-
SELECT A, X1B AS B, X1C AS C FROM
    (select X1.B AS X1B, X1.C AS X1C from T1 AS X1
       except
       select T2.B, T2.C from T2)
JOIN T1 ON B = X1B AND C = X1C

or :-
SELECT A, B, C FROM
    (select X1.B AS X1B, X1.C AS X1C from T1 AS X1
        except
        select T2.B, T2.C from T2)
JOIN T1 ON B = X1B AND C = X1C

Resulting in :-


Q:

Distribute elements evenly using CSS

A method to distribute elements evenly in a container using CSS appeared on Smashing Magazine today.
I recently had to use Javascript to achieve the same effect for elements of variable width, but the method presented on SM made me wonder if it was possible to do this without Javascript.
There's this question, where gargantaun says:

IMHO, and you probably don't want to hear this, but the design is probably flawed. It's common knowledge that distributing items evenly across a layout with CSS is a pain, so designers should avoid it.

But I can't tell the designer to change his design, and I don't agree that the shortcomings of CSS should limit designers.
Anyway, here's what I have in HTML (translated and simplified):

Home

News

Theme

Activities

Contact

in CSS (irrelevant properties removed and simplified):
#menu li { float: left; margin-right: 20px; }
#menu a  { display: block; padding: 0 1em; }

and in Javascript:
function justifyMenu() {
    var menuItems  = $$("#menu li");
    var menuWidth  = $("menu").getWidth();
    var totalWidth = 0;

    menuItems.each(function(e) {
        totalWidth += e.getWidth();
    });

    var margin = (menuWidth - 4 - totalWidth) / (menuItems.length - 1);
    margin = parseInt(margin);

    menuItems.each(function(e) {
        e.setStyle({ marginRight: margin + 'px' });
    });

    menuItems[menuItems.length - 1].setStyle({ marginRight: '0' });
}

And here's a scaled-down screenshot (see how the menu aligns with the header image):

Any idea how I can achieve this without Javascript?

A:

Of course this is exactly what the table element is for. It's sad and hilarious at the same time to see people twist themselves into a gordian knot with CSS, most of them not even knowing why they're avoiding tables.
Whatever reason you might have dreamed up to reject tables, it can't possibly be worse than depending on Javascript to layout your page.
Yes, I know this is not the answer you were looking for, but golly, it's so obvious.

A:

There have been casual claims that tables are the obvious solution, however, there hasn't been any real discussion of how to implement it. I'll show you that displaying divs as a table is the right way to do this, but it is not as easy as centering all of the cells and setting an automatic width. The problem with this is that you have no control of the outer margins of the further-most left and right cell-contents. They both are inset from its containing box an arbitrary amount you cannot control. Here's a work around:
First, a slight modification of Guder's html:

Home

News

Theme

Activities

Contact

Now the css:
#menu {display:table; width:// some width in px //}
#menu ul {display:table-row; width: 100%}
#menu li.left {display: table-cell; text-align: left; width: 20px; white-space:nowrap;}
#menu li {display: table-cell; text-align: right; width: auto;}

Now, we have full control of the outer-most sides of the menu, which align with the far-left and far-right sides of the containing box, and the distance between each element is consistent. You'll notice that I used a trick to get the furthest left cell to be the exact-width of it's content. I set the width property to a small size obviously below what its contents would normally be. I then set the white-space to no-wrap, which stretches the cell the least amount to fit the text of the cell. You can see here an image which shows the effect of this (using different html elements):

The beauty of this code is that it can accept however many cells and text-widths, without any knowledge of their actual widths, and distribute them evenly across the page. All the while, left and right elements reaching their perimeters, and ofcourse we have all our html in divs, no browser or internet geek is mislead to believe we're presenting tabular data. No known compromises here!

A:

This is what display:table-cell is supposed to achieve - however, the IE's just don't do it, and FF<3 has problems with it too, I believe.
These styles work in FF3, Chrome, Safari, and (I think) Opera 9:
#menu ul {display:table;padding:0;}
#menu li {display:table-cell;text-align:center;}

But you'll need a fair few hacks to get them working in the usual, commercial set of browsers.


Q:

Link ADSL modem together

Is it possible to connect two (not more) ADSL modem together by using RJ11 in a local environment (ie: in a lab) ?
 +-------+ RJ45 +--------------+   RJ-11   +--------------+ RJ45 +-------+
 | LAN 1 |======| ADSL MODEM 1 |- - - - - -| ADSL MODEM 2 |======| LAN 2 |
 +-------+      +--------------+   PPPoE   +--------------+      +-------+

A:

No. ADSL uses different upstream and downstream frequency ranges. As such, a modem is designed to transmit only in a narrow, low frequency range for which is has no receive capability.
(The much older, SDSL, does work head-to-head.)


Q:

What's the equivalent for C#'s goto statement in Java?

Is there a way I could adopt the C#'s goto statement in Java?

A:

There is no direct equivalent to the goto concept in Java. You can use break and continue .
Look at here for labelled statements with break and continue.

A:

There is no goto statement in Java:

Unlike C and C++, the Java programming language has no goto statement.

The closest you have are continue and break statements, which can be used in combination with labels, to exit from a loop.

A:

There are named blocks, and you can have a labeled break statement:
loop:
  for (int i = 0; i < 10; ++i)
      break loop;

Or
label: {
       if(something)
          break label;
}

More information can be found in Branching Statements. But other than that, you don't have a real goto statement.


Q:

Reinstall PHP Pear

I used to have MAMP (http://www.mamp.info/en/index.html). Uninstalled that and installed "MAMP" via Macports.
I completely removed /Applications/MAMP/ folders. I would now like to install PHPUnit via pear.
Pear is installed:
> which pear
/opt/local/bin/pear

> pear config-show
Configuration (channel pear.php.net):
=====================================
Auto-discover new Channels     auto_discover    <not set>
Default Channel                default_channel  pear.php.net
HTTP Proxy Server Address      http_proxy       <not set>
PEAR server [DEPRECATED]       master_server    pear.php.net
Default Channel Mirror         preferred_mirror pear.php.net
Remote Configuration File      remote_config    <not set>
PEAR executables directory     bin_dir          /Applications/MAMP/bin/php/php5.3.6/bin/
PEAR documentation directory   doc_dir          /Applications/MAMP/bin/php5.3/docs
PHP extension directory        ext_dir          /opt/local/lib/php/extensions/no-debug-non-zts-20090626
PEAR directory                 php_dir          /Applications/MAMP/bin/php5.3/share/pear
PEAR Installer cache directory cache_dir        /private/tmp/pear/cache
PEAR configuration file        cfg_dir          /Applications/MAMP/bin/php5.3/cfg
directory
PEAR data directory            data_dir         /Applications/MAMP/htdocs/pear
PEAR Installer download        download_dir     /tmp/pear/install
directory
PHP CLI/CGI binary             php_bin          /opt/local/bin/php
php.ini location               php_ini          <not set>
--program-prefix passed to     php_prefix       <not set>
PHP's ./configure
--program-suffix passed to     php_suffix       <not set>
PHP's ./configure
PEAR Installer temp directory  temp_dir         /tmp/pear/install
PEAR test directory            test_dir         /Applications/MAMP/bin/php5.3/tests
PEAR www files directory       www_dir          /Applications/MAMP/bin/php5.3/www
Cache TimeToLive               cache_ttl        3600
Preferred Package State        preferred_state  stable
Unix file mask                 umask            22
Debug Log Level                verbose          1
PEAR password (for             password         <not set>
maintainers)
Signature Handling Program     sig_bin          /usr/local/bin/gpg
Signature Key Directory        sig_keydir       /opt/local/etc/pearkeys
Signature Key Id               sig_keyid        <not set>
Package Signature Type         sig_type         gpg
PEAR username (for             username         <not set>
maintainers)
User Configuration File        Filename         /Users/*removed*/.pearrc
System Configuration File      Filename         /opt/local/etc/pear.conf

There are lots of references to /Applications/MAMP/ folder structure which I had deleted (and mysteriously keeps regenerating). I would like to remove all these references but not sure what substitute values should be. I cannot seem to uninstall pear or upgrade pear.
Ideally I would like a situation where pear remains installed and PHPUnit is installed so that I can run some tests.

A:

You can adjust those config values with pear config-set, for example
$ pear config-set php_dir /usr/share/pear/php
$ pear config-set data_dir /usr/share/pear/data

Do that for all config values with "broken" paths.
After that, either manually move the files from the old to the new directories, or reinstall all packages.


Q:

Use Android device as a simple server

I need a very simple server that listens for connections, retrieves a question and simply answers yes or no. Then the connection is broken.
As my Android device is the only device that is powered on and connected to the internet 24/7, I'm thinking of using it as the server.
Is this possible, and how could I achieve this? The biggest problems that I'm facing is the ip-address, as it could be changing a lot. I'm thinking of storing it in a public dropbox file, so the client can retrieve the address from that

A:

There's a whole slew of reasons why you shouldn't use your android device as a server, but I won't go into those. I'll just assume you have a good reason for doing what you want to do.
Since your question is very general, the best I can do is give you a very general answer. You'd implement a server on android like you would any other server using java using sockets. For a simple java implementation of a socket based server, checkout this tutorial. The tricky part is going to be getting your IP address to share with clients so that they can connect to your device. As nick suggested, dyndns might be an option here, but I'm not sure if they have a mobile client.


Q:

Clickable and automatic image slider

I created a slider that fades images automatically but you can also click to see the next or previous image. It already works how it should. But I think my code is really heavy. I am not experienced with JavaScript / jQuery so it would be nice if someone could help me to tidy up my code.
// helper to change the slider background image
var changeImage = function(id, image){
  $(id).css('background-image', 'url('+image+')');
};

// auto change slider elements over time
$(window).load(function() {
    var images = [  'http://mysite.com/image1',
                    'http://mysite.com/image2',
                    'http://mysite.com/image3',
                    'http://mysite.com/image4',
                    'http://mysite.com/image5',
                    'http://mysite.com/image6'
                ];
    var texts = [
                    '
Text 1
',
                    '
Text 2
',
                    '
Text 3
',
                    '
Text 4
',
                    '
Text 5
',
                    '
Text 6
'
                ];
    var hrefs = [   'http://mysite.com/link1',
                    'http://mysite.com/link2',
                    'http://mysite.com/link3',
                    'http://mysite.com/link4',
                    'http://mysite.com/link5',
                    'http://mysite.com/link6'
                ];
    var srcs = [    'http://mysite.com/image1',
                    'http://mysite.com/image2',
                    'http://mysite.com/image3',
                    'http://mysite.com/image4',
                    'http://mysite.com/image5',
                    'http://mysite.com/image6'
                ];
    // counter variables for images, texts and links
    var i = 0;
    var t = 0;
    var h = 0;
    var s = 0;

    var x = 0;
    var inter = "";
    var again = "";

    var hrefChange = document.getElementById('theHref');

    // register next slide click
    document.getElementById("clickablen").onclick = function() {
        clearInterval(inter);
        changeBackgroundNext();
    }

    // register previous slide click
    document.getElementById("clickablep").onclick = function() {
        clearInterval(inter);
        changeBackgroundPrev();
    }

    // Init sequence, loading the first image
    $("#wrapper_bottom").css("opacity", 0);
    changeImage('#wrapper_bottom', images[i]);
    changeBackground();

    // slider functionality - general function
    function changeBackground() {
        if ( i >= 6 ) { i = 0; }
        if ( t >= 6 ) { t = 0; }
        if ( h >= 6 ) { h = 0; }
        if ( s >= 6 ) { s = 0; }

        x = 0;

        $("#wrapper_bottom").css("opacity", 0);
        changeImage('#wrapper_bottom', images[i]);
        document.getElementById("myspan").innerHTML=texts[t];

        $('#wrapper_bottom').animate({"opacity": 1}, 1000, function(){
            hrefChange.setAttribute('href', hrefs[h]);
            changeImage('#wrapper_top', images[i], 1);
            if (++i >= images.length) { i = 0; x = 1}
            $("#wrapper_bottom").css("opacity", 0);
            changeImage('#wrapper_bottom', images[i]);
            if (++t >= texts.length) { t = 0; }
            if (++h >= hrefs.length) { h = 0; }
            if (++s >= srcs.length) { s = 0; }
        });

        // fade content background image
        if (srcs[s]) {
            $('#thesrc').fadeOut(300, function(){
                $(this).attr('src',srcs[s]).bind('onreadystatechange load', function(){
                   if (this.complete) $(this).fadeIn(300);
                });
            });
        }
    }
    // repeat this function every 10 seconds
    inter = setInterval(changeBackground, 10000);

    // slider functionality - click next function
    function changeBackgroundNext() {
        clearInterval(again);
        again = setInterval(changeBackground, 10000);

        if ( i == 6 ) { i = 0; }
        if ( t == 6 ) { t = 0; }
        if ( h == 6 ) { h = 0; }
        if ( s == 6 ) { s = 0; }

        x = 0;

        document.getElementById("myspan").innerHTML=texts[t];

        $('#wrapper_bottom').animate({"opacity": 1}, 0, function(){
            hrefChange.setAttribute('href', hrefs[h]);
            changeImage('#wrapper_top', images[i], 1);
            $("#wrapper_bottom").css("opacity", 0);
            if (++i >= images.length) { i = 0; x = 1;}
            changeImage('#wrapper_bottom', images[i]);
            if (++t >= texts.length) { t = 0; }
            if (++h >= hrefs.length) { h = 0; }

            if (srcs[s]) {
                $('#thesrc').fadeOut(0, function(){
                    $(this).attr('src',srcs[s]).bind('onreadystatechange load', function(){
                        if (this.complete) $(this).fadeIn(0);
                    });
                });
                if (++s >= srcs.length) { s = 0; }
            }
        });
    }

    // slider functionality - click previous function
    function changeBackgroundPrev() {
        clearInterval(again);
        again = setInterval(changeBackground, 10000);

        i=i-2;
        t=t-2;
        h=t-2;
        s=s-2;

        if ( i <= -1 ) { i = 5; }
        if ( t <= -1 ) { t = 5; }
        if ( h <= -1 ) { h = 5; }
        if ( s <= -1 ) { s = 5; }

        if (x == 1) { i = 4; t = 4; h = 4; s = 4; }

        document.getElementById("myspan").innerHTML=texts[t];
        $('#wrapper_bottom').animate({"opacity": 1}, 0, function(){
            hrefChange.setAttribute('href', hrefs[h]);
            changeImage('#wrapper_top', images[i], 1);
            $("#wrapper_bottom").css("opacity", 0);
            changeImage('#wrapper_bottom', images[i]);

            if (srcs[s]) {
                $('#thesrc').fadeOut(0, function(){
                    $(this).attr('src',srcs[s]).bind('onreadystatechange load', function(){
                        if (this.complete) $(this).fadeIn(0);
                    });
                });
            }

            x = 0;

            ++i;
            ++t;
            ++h;
            ++s;
        });
    }
});

A:

A few thoughts :

It's hard to see why you need four congruant arrays. Why not one array containing objects, each with properties .image, .text, .href, .src?
Probably better to increment/decrement the indices "on demand" not in advance. That way you only ever need to adjust by +1 or -1. Currently, -2 is only necessary because +1 was previously predicted.
Use the module operator % to acheve the "wrap-around" effect. Javascript doesn't naturally do modulo of negative numbers properly, but a simple solution is available.
Don't hard-code 6. Use images.length etc all through.
jQuery's .bind() is deprecated in favour of .on(), but you should probably be using .one() to prevent the build-up of event handlers.

Also :

Similar functions changeBackground(), changeBackgroundNext() and changeBackgroundPrev() could be combined into one, with the detailed behaviour determined by parameters; it seems that direction 1|-1 and a boolean indicating manual|auto will suffice.
Two interval vars, inter and again seem unnecessary. One should suffice.

Without seeing a demo, it's hard to visualise the interplay between #wrapper_top and #wrapper_bottom and the differences betweeen a manual and auto so those aspects may be wrong, but the general pattern might be as follows :
// Auto change slider elements over time
$(window).load(function() {
    // *** Outer vars ***
    var data = [
        {
            'image': 'http://p5.focus.de/img/fotos/crop3167630/6282711837-w1200-h627-o-q75-p5/Google.jpg',
            'text': '
Text 1

...
',
            'href': 'http://google.de/',
            'src': 'http://p5.focus.de/img/fotos/crop3167630/6282711837-w1200-h627-o-q75-p5/Google.jpg'
        },
        {
            'image': 'http://www.heise.de/imgs/18/1/4/9/2/9/0/1/urn-newsml-dpa-com-20090101-150420-99-02936_large_4_3-fc997534cde9c449.jpeg',
            'text': '
Text 2

...
',
            'href': 'http://google.de/',
            'src': 'http://www.heise.de/imgs/18/1/4/9/2/9/0/1/urn-newsml-dpa-com-20090101-150420-99-02936_large_4_3-fc997534cde9c449.jpeg'
        },
        {
            'image': 'http://p5.focus.de/img/fotos/crop3167630/6282711837-w1200-h627-o-q75-p5/Google.jpg',
            'text': '
Text 3

...
',
            'href': 'http://google.de/',
            'src': 'http://p5.focus.de/img/fotos/crop3167630/6282711837-w1200-h627-o-q75-p5/Google.jpg'
        },
        {
            'image': 'http://www.heise.de/imgs/18/1/4/9/2/9/0/1/urn-newsml-dpa-com-20090101-150420-99-02936_large_4_3-fc997534cde9c449.jpeg',
            'text': '
Text 4

...
',
            'href': 'http://google.de/',
            'src': 'http://www.heise.de/imgs/18/1/4/9/2/9/0/1/urn-newsml-dpa-com-20090101-150420-99-02936_large_4_3-fc997534cde9c449.jpeg'
        },
        {
            'image': 'http://p5.focus.de/img/fotos/crop3167630/6282711837-w1200-h627-o-q75-p5/Google.jpg',
            'text': '
Text 5

...
',
            'href': 'http://google.de/',
            'src': 'http://p5.focus.de/img/fotos/crop3167630/6282711837-w1200-h627-o-q75-p5/Google.jpg'
        },
        {
            'image': 'http://www.heise.de/imgs/18/1/4/9/2/9/0/1/urn-newsml-dpa-com-20090101-150420-99-02936_large_4_3-fc997534cde9c449.jpeg',
            'text': '
Text 6

...
',
            'href': 'http://google.de/',
            'src': 'http://www.heise.de/imgs/18/1/4/9/2/9/0/1/urn-newsml-dpa-com-20090101-150420-99-02936_large_4_3-fc997534cde9c449.jpeg',
        },
        {
            'image': 'http://p5.focus.de/img/fotos/crop3167630/6282711837-w1200-h627-o-q75-p5/Google.jpg',
            'text': '
Text 7

...
',
            'href': 'http://google.de/',
            'src': 'http://p5.focus.de/img/fotos/crop3167630/6282711837-w1200-h627-o-q75-p5/Google.jpg'
        }
    ];
    var i = data.length - 1; // counter variable for images, texts, links and srcs
    var inter;
    var hrefChange = document.getElementById('theHref');
    var title = document.getElementById("myspan");

    // *** Worker functions ***
    // Change an element's bg image
    function changeImage(id, image) {
        return $(id).css('background-image', 'url(' + image + ')');
    }
    // Initiate auto-play
    function auto() {
        inter = setInterval(function() {
            changeBackground(1, true);
        }, 10000);
    }
    // Slider functionality - general function
    function changeBackground(dir, isAuto) {
        var t1 = isAuto ? 1000 : 0;
        var t2 = isAuto ? 300 : 0;
        var ii = i; // remember index before incrementing/decrementing

        i = (((i + dir) % data.length) + data.length) % data.length; // increment/decrement index, with wrap-around in both directions.

        title.innerHTML = data[i].text;

        if(isAuto) {
            changeImage('#wrapper_bottom', data[ii].image).css('opacity', 1);
        }

        $('#wrapper_bottom').animate({'opacity': 1}, t1, function() {
            hrefChange.setAttribute('href', data[i].href);
            changeImage('#wrapper_top', data[ii].image);
            changeImage('#wrapper_bottom', data[i].image).css('opacity', 1);
        });

        // fade content background image
        if (data[i].src) {
            $('#thesrc').fadeOut(t2, function() {
                $(this).attr('src', data[i].src).off('onreadystatechange load').one('onreadystatechange load', function() {
                    if (this.complete) $(this).fadeIn(t2);
                });
            });
        }
    }

    // *** Attach event handlers ***
    document.getElementById("clickablen").onclick = function() {
        clearInterval(inter);
        changeBackground(1, false);
        auto();
    };
    document.getElementById("clickablep").onclick = function() {
        clearInterval(inter);
        changeBackground(-1, false);
        auto();
    };

    // *** Initialize ***
    changeBackground(1, true); // Load first image
    auto(); // Start auto play
});

Auto-play is assumed always to go forward. If it should go in reverse after clickablep, then simple change - auto() will need to accept 1|-1, which it can pass on to changeBackground(1, true);.


Q:

Sync Local Folder to FTP

I'm looking for an app I can put on my local server that will take files from C:\Source to a folder on my remote FTP Server every hour.
I was looking at rsync and it looked perfect until it told me I cant use my own FTP server. Any recommendations?
I'm going to have around 50,000 small files. nothing over 20kb, in the source folder, so the faster the ftp the better. Allway Sync is just too slow as well.

A:

I know two programs:

If you are willing to pay a little you have the FTP Synchronizer
Also there is a free version of a similar program that is called BestSync

I just found another one that looks good, however i've never used this: BatchSync FTP
I hope this helps :)


Q:

Show a logarithmic sequence converging almost surely and compute its limit

Given i.i.d $X_1, X_2,\cdots, X_n$ with their values belong to $\left\{1,\cdots, l\right\}$ such that $p_k = P(X_i=k) > 0$ for each $k$. Let $N_n(k)$ be the number of $X_1, X_2,\cdots$ whose value equals to $k$, and $\prod_n = \prod_{k=1}^{l} (p_k)^{N_n(k)}$. Show that the sequence $\left\{\frac{\log{\prod_n}}{n}\right\}$ converges almost surely and compute its limit.
My attempt: First, for proving a sequence converging almost surely, we need to show: for every $\epsilon > 0$, $\lim_{n\rightarrow \infty} \ P(\sup_{k\geq 1} |\frac{\log{\prod_{n+k}}}{n+k} -\frac{\log{\prod_n}}{n}| > \epsilon) = 0$.
Using property of logarithmic function, we have: $|\frac{\log{\prod_{n+k}}}{n+k} - \frac{\log{\prod_{n}}}{n}| = |\sum_{i=1}^{l} (\frac{N_{n+k}(i)\log(p_i)}{n+k} - \frac{N_n(i)\log(p_i)}{n})|\leq \frac{2\max_{i=1,2,...,l}|\log(p_i)|nk}{n(n+k)}$
(this is due to $4$ facts: $n(N_{n+k}(i) - N_n(i))\leq kn$, the triangle inequality, $\sum_{i=1}^{l} N_{n}(i) = n$, and $max_{i=1,2,...,l} |\log(p_i)|$ exists, as $p_is$ are all fixed numbers).
Now, since $p_{i}$ is given, dividing both the numerator and denominator by $k\geq 1$, we easily see that the $RHS\leq \frac{2n\max_{i=1,2,...,l}|\log(p_i)|}{n(n+1)}$. Let $n\rightarrow \infty$, $\frac{2\max_{i=1,2,...,l}|\log(p_i)|}{n+1}\rightarrow 0$, which implies $\lim_{n\rightarrow \infty} (\sup_{k\geq 1}|\frac{\log{\prod_{n+k}}}{n+k} - \frac{\log{\prod_{n}}}{n}|)\rightarrow 0$. Done!
For the limit, we could use this inequality: $\frac{l[\max_{i=1,2,...,l}\log(p_i)]}{n}\geq \frac{\log{\prod_n}}{n}\geq \frac{l[\min_{i=1,2,...,l} \log(p_i)]}{n}$. Let $n\rightarrow \infty$, both the upper and lower bound go to $0$, so by Squeeze's theorem, we conclude that our limit is $\fbox{0}$.
My question: Is my solution above correct? It's quite a technical proof for the a.s convergent, so I'm not sure if I accidentally made a mistake (as far as my review goes, nothing was found yet). Any thoughts would really be appreciated.

A:

Note that $N_n(k)=\sum_{i=1}^n 1_{X_i=k}$. Therefore, by SLLN, $\dfrac{N_n(k)}{n}=\dfrac{\sum_{i=1}^n 1_{X_i=k}}{n}\to E(1_{X_1=k})=P(X_1=k)=p(k)$ almost surely.
Therefore, $\dfrac{\log \prod_n}{n}=\dfrac{\sum_{k=1}^l N_n(k)\log(p_k)}{n}=\sum_{k=1}^l (\log p_k) \dfrac{N_n(k)}{n}\to\sum_{k=1}^l (\log p_k)p_k =\sum_{k=1}^l p_k\log p_k$ almost surely.
NB: See the importance of finite support. It enables you to interchange limit and sum.


Q:

Deserializing SQL table to object collection

I'm trying to deserialize an SQL table to a collection of objects in PHP and I'm lost as to how I can do so.
In C#, the equivalent would be:
public class Object
{
    public string objectProperty { get; set; }
    public string anotherProperty { get; set; }
}

public void Deserialize()
{
    List<Object> collection = new List<Object>();

    // Assuming that we have an SQL statement returning a row

    foreach (Row row in returnedSqlRow)
    {
        collection.Add(new Object
        {
            objectProperty = row["objectProperty"],
            anotherProperty = row["anotherProperty"]
        });
    }
}

which would give me a nice collection of Objects to work with.
In my PHP I have the following:
class Book {
    public $CN; // cataloguenumber
    public $title;
    public $author;
    public $description;
    public $price;
    public $enteredby;
}

with my SQL statement being:
$books = pg_query($conn, 'SELECT cataloguenumber, title, author, description, price, enteredby FROM CSBooks');
I can easily access each value from the row like so:
    while($row = pg_fetch_row($books)) {

        echo $row[0] . '
';
        echo $row[1] . '
';
        echo $row[2] . '
';
        echo $row[3] . '
';
        echo $row[4] . '
';
        echo $row[5] . '
';
    }

But I'm lost as to how I can create an object collection and deserialize the row to a Book object and store it.  Is there a PHP equivalent? I've taken a look at pg_fetch_object() but it doesn't quite seem to be what I'm looking for.

A:

I think the solution is to use PDO and PDOStatement::fetchObject which will abstract all the pg_* functions and make your db interaction easier to manage.
It will return a stdObject instead of an array by default, but you can make it map your object.
There would be a dirty solution if you really need to use pg_* functions instead of PDO... (I am ashamed to suggest it)
$a = ['a'=>'bla', 'b'=>1];
$shame = (object) $a;

Then on your class, you just write a constructor to bind the columns to the object fields...


Q:

Trouble with speed and vectors

I'm working on adding bullets to my game.  Right now I can shoot bullets in the direction that I would like from a ship by getting the ship's angle:
int speed = 5;
int dx = -(cos(degreesToRadians(ship.angle)) * speed); // rate of change in the x direction
int dy = -(sin(degreesToRadians(ship.angle)) * speed); // rate of change in the y direction

bulletPosition.addX(dx); // addX(dx) is simply bulletPosition.x += dx
bulletPosition.addY(dy);

The ship is pretty much the exact same thing, except I use the += operator:
int dx += -(cos(degreesToRadians(angle)) * 0.15)
int dy += -(sin(degreesToRadians(angle)) * 0.15);

shipPosition.addX(dx);
shipPosition.addY(dy);

I would like to be able to add the ship's velocity to the bullet's velocity, but I'm a little confused as to how should get the speed from the ship's vector.  I thought that adding the ship's dx to the bullet's dx like int dx = -(cos(degreesToRadians(ship.angle)) * speed * dx) would work because I'm adding the rate of change of the ship to the rate of change of the bullet, but that doesn't work.  So here's the final question: How can I get the speed of my ship and apply it to my bullet's speed?
Thanks in advance for all help :)

A:

You do want to add the ship's dx/dy to the bullet's dx/dy, but you want addition, not multiplication.
bulletDx = -(cos(degreesToRadians(bulletHeading)) * speed) + shipDx;


Q:

UITableView section with cells

I am trying to make something like this but I am having trouble adding the date to my tableview. I have a Realm database with dates(Date), names(String) and numbers(Int).
I have successfully added the date to each section, but I am having trouble finding out how to add the names and numbers to the cells. There are multiple rows with the same date, but with different names and numbers.
This is my code so far:
import UIKit
import RealmSwift

class myViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    @IBOutlet weak var tableView: UITableView!

    var data:Results<Objects>!
    var result:[Objects] = []

    let cellSpacingHeight: CGFloat = 5

    override func viewDidLoad() {
        super.viewDidLoad()

        tableView.delegate = self
        tableView.dataSource = self

        retreiveData()
    }

    func retreiveData() {
        let realm = try! Realm()

        // Retreive data
        self.data = realm.objects(Objects.self).sorted(byKeyPath: "date",ascending: false)
        self.result = Array(self.data)

        print(result)

        tableView.reloadData()
    }

    // MARK: - Table View delegate methods

    func numberOfSections(in tableView: UITableView) -> Int {
        return self.result.count
    }

    // Set the spacing between sections
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return cellSpacingHeight
    }

    /*func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }*/

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return result.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)

        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "EEEE - dd.MM.yyyy"

        let stringGivenDate = dateFormatter.string(from: result[indexPath.section].date!)

        cell.textLabel?.text = "\(stringGivenDate)"
        cell.detailTextLabel?.text = "\(result[indexPath.section].name!)"

        return cell
    }
}

A:

What you need to do is group the data by date
let grouped: [Data: [Objects]]!

//...
self.result = Array(self.data)
grouped = Dictionary(grouping: result) { (element) -> Date in
    return element.date
}

This will produce a dictionary grouping all the elements with the same Date.  Now, you might need to do some additional decision making, for example, grouping them only by month and year instead.
Once you have this, you basically have the structure of your table (sections are the dictionary keys and the rows data behind the keys.
For convince, I might also include...
sections = grouped.keys.sorted()

to make it faster to access the keys in a specified order.
Then you just need to apply the appropriate data to your delegate...
  func numberOfSections(in tableView: UITableView) -> Int {
    return sections.count
  }

  // Set the spacing between sections
  func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
    return cellSpacingHeight
  }

  func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return grouped[sections[section]]!.count
  }

  func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)

    let rows = grouped[sections[indexPath.section]]!
    let row = rows[indexPath.row]

    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "EEEE - dd.MM.yyyy"

    let stringGivenDate = dateFormatter.string(from: row.date!)

    cell.textLabel?.text = "\(stringGivenDate)"
    cell.detailTextLabel?.text = "\(row.name!)"

    return cell
  }

  func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
    let date = sections[section]

    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "EEEE - dd.MM.yyyy"

    return dateFormatter.string(from: date)
  }

As a side note, DateFormatter is expensive, so you might consider making this a instance property instead
Runnable example....

//
//  ViewController.swift
//  QuickTest
//
//  Created by Shane Whitehead on 10/2/19.
//  Copyright © 2019 Swann Communications. All rights reserved.
//

import UIKit

struct Stuff: CustomDebugStringConvertible {
  let date: Date
  let name: String

  var debugDescription: String {
    return "\(date) = \(name)"
  }
}

extension Date {
  static func random(daysBack: Int)-> Date {
    let day = arc4random_uniform(UInt32(daysBack))+1
    let hour = arc4random_uniform(23)
    let minute = arc4random_uniform(59)

    let today = Date(timeIntervalSinceNow: 0)
    let calendar  = Calendar.current
    var offsetComponents = DateComponents()
    offsetComponents.day = -Int(day)
    offsetComponents.hour = Int(hour)
    offsetComponents.minute = Int(minute)

    let randomDate = calendar.date(byAdding: offsetComponents, to: today)
    return randomDate!
  }

  var startOfDay: Date {
    let calendar  = Calendar.current
    return calendar.startOfDay(for: self)
  }
}

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

  @IBOutlet weak var tableView: UITableView!

  let cellSpacingHeight: CGFloat = 5

  var grouped: [Date: [Stuff]] = [:]
  var sections: [Date] = []

  var headerDateFormatter: DateFormatter = {
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "MMM yyyy"
    return dateFormatter
  }()

  var cellDateFormatter: DateFormatter = {
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "EEEE - dd.MM.yyyy"
    return dateFormatter
  }()

  override func viewDidLoad() {
    super.viewDidLoad()

    retreiveData()

    tableView.delegate = self
    tableView.dataSource = self

    tableView.rowHeight = UITableView.automaticDimension
    tableView.sectionHeaderHeight = UITableView.automaticDimension
    tableView.estimatedRowHeight = 44
    tableView.estimatedSectionHeaderHeight = 44

    tableView.reloadData()
  }

  func retreiveData() {
    var data: [Stuff] = []
    for index in 0..<100 {
      let stuff = Stuff(date: Date.random(daysBack: 10), name: "\(index)")
      data.append(stuff)
    }

    grouped = Dictionary(grouping: data) { (element) -> Date in
      return element.date.startOfDay
    }
    sections = grouped.keys.sorted()

  }

  // MARK: - Table View delegate methods

  func numberOfSections(in tableView: UITableView) -> Int {
    return grouped.count
  }

  // Set the spacing between sections
//  func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
//    return cellSpacingHeight
//  }

  /*func numberOfSections(in tableView: UITableView) -> Int {
   return 1
   }*/

  func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return grouped[sections[section]]!.count
  }

  func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)

    let rows = grouped[sections[indexPath.section]]!
    let row = rows[indexPath.row]

    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "EEEE - dd.MM.yyyy"

    let stringGivenDate = dateFormatter.string(from: row.date)

    cell.textLabel?.text = "\(stringGivenDate)"
    cell.detailTextLabel?.text = "\(row.name)"

    return cell
  }

  func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
    let date = sections[section]
    return headerDateFormatter.string(from: date)
  }
}


Q:

Getting center of screen

Note: using c# windows form in visual studio 2017
The below code is now correct for future use.
I am trying to develop code that will help me detect in which quadrant the mouse is each 0.5 second. I first tried with 0 but I discovered that there is no negative value for the mouse position in c#. So instead I thought I would use the width and the height that I calculated with:
 public void setScreenSize()
 {
    int W = Screen.PrimaryScreen.Bounds.Width;
    int H = Screen.PrimaryScreen.Bounds.Height;
    Console.WriteLine("Height is: " + H + "width is: " + W);
 }

full code here:
public partial class Recording : Form
{

    private System.Timers.Timer mousePositionTimer;

    int W, H;

    public Recording()
    {
        InitializeComponent();
    }

    private void Recording_Load(object sender, EventArgs e)
    {
        setScreenSize();
        SetTimer(mousePositionTimer, 250,OnTimedMousePositionEvent);

    }

    public void setScreenSize()
    {
        W = Screen.PrimaryScreen.Bounds.Width;
        H = Screen.PrimaryScreen.Bounds.Height;
        Console.WriteLine("Height is: " + H + "width is: " + W);

    }

    private void SetTimer(System.Timers.Timer t, int millis, ElapsedEventHandler f)
    {
        t = new System.Timers.Timer(millis);
        t.Elapsed += f;
        t.AutoReset = true;
        t.Enabled = true;
    }

    private void OnTimedMousePositionEvent(Object source, ElapsedEventArgs e)
    {

        record.addMousePosition(W,H,MousePosition.X,MousePosition.Y);
    }

}

Then, I used the following to detect the quadrant:
//getting position of mouse in a given quadrant
public static class record
{
     public static void addMousePosition(int w, int h, int x, int y)
     {
         if (x > w/2 && y > h/2)
             mousePositions.Add(1);
         else if (x > w/2 && y <= h/2)
             mousePositions.Add(2);
         else if (x <= w/2 && y <= h/2)
             mousePositions.Add(3);
         else if (x <= w/2 && y > h/2)
             mousePositions.Add(4);
     }
}

However, when I print my list I always get Quadrant 1 . Is there a better way to get the center of the screen so I can do my conditions in a correct manner?
Please remember that I am trying to do this outside the form and not necessarily on it.

A:

Scope issue?
public void setScreenSize()
{
    int W = Screen.PrimaryScreen.Bounds.Width;
    int H = Screen.PrimaryScreen.Bounds.Height;
    Console.WriteLine("Height is: " + H + "width is: " + W);
}

to
public void setScreenSize()
{
    W = Screen.PrimaryScreen.Bounds.Width;
    H = Screen.PrimaryScreen.Bounds.Height;
    Console.WriteLine("Height is: " + H + "width is: " + W);
}


Q:

A pejorative term for "unreasonably gregarious"

I am looking for a pejorative term to describe someone who constantly needs social interaction regardless of quality.
Something along the lines of "social nymphomaniac", but not necessarily gender-specific, and preferably in a single word. I would also prefer it if it were not colloquial.

A:

I would call such a person intrusive, if I were limited to a single word. Some of the synonyms my thesaurus gives for intrusive are presumptuous, pushy, impertinent, officious, and forward. They're all pejorative. An officious person offers help, advice, or service where none is wanted. A presumptuous person presumes on a degree of familiarity or intimacy that isn't warranted by the actual relationship. Another word for forward in this sense is brash.


Q:

Is it plagiarism to copy the form and structure of an article?

As an undergraduate student, I wrote a science paper. Because I was learning to write, I used the form and structure of a paper on a completely different topic; in fact, it was a slightly different discipline all together. So my paper has a similar layout, transitions, and structure as said paper, though the information, content, subject matter, and topic are different.
Is this plagiarism? I later contacted the original author, upon discovering the similarities, and he said that it was okay, that he learned the form from others, and that I should go on with life.

A:

You've done nothing wrong; most manuscripts follow the same structure.
Consider the following recommendations for structure: (1) Introduction, (2) Materials and Methods, (3) Results, and (4) Discussion. Would it be wrong to adopt that structure? No. It's a very common style and is widely adopted.

The OP added:

It's not just the [structure] that I followed, but the language - i.e. transition words.

Transition words, e.g., https://msu.edu/~jdowell/135/transw.html, are standard, so they shouldn't create an issue.

The order of the introduction is the same, for example.

That's just a different form of structural issue, hence, this isn't a problem.

I said why the world needs the paper in a similar language even though there was two totally different topics and subject matters.

Such a style is advocated by many, e.g., Simon Peyton Jones, so that shouldn't create an issue.

Note: Without seeing the texts, we cannot comment on specific issues.

A:

Academic writing is fairly standardized. Most disciplines follow a standard template, usually a variety of the following:

Introduction

Why the world needs this paper
What the literature already says on the topic and what this paper contributes
How this paper is organized

Background: An elaboration in roughly five paragraphs on the first paragraph of the introduction, setting the stage for the analysis and making the reader aware of the context needed to understand the paper
Theory: An inventory and perhaps formalization of the theoretical concept(s) or model(s) used in the subsequent analysis in roughly five paragraphs
Methods

How the theory was operationalized
How the data was generated
How the data was analyzed

Analysis: Two or three subsections, each making one major claim that relates to the overall research question. Explains how the data/observations inform the theory and/or vice versa.
Conclusion

Restatement of the main thesis and argument in theoretical terms
Discussion of the contribution to the literature
Implications for future research

If you used a format similar to this one, you didn't plagiarize; you just followed academic writing convention, which is good. And so did the paper that you used as a template.

A:

This is something that has come up in comments, but not yet in answers: you should not have written that paper that way. You copied parts of the other professor's wording (perhaps at long stretches) and plugged in your own material. The content and the quality of writing (e.g. persuasive style, apt wording) are both important in academia. In fields like philosophy or literature, both may be equally important, whereas in experimental sciences many authors and readers would be happier if articles just consisted of figures, tables, citations, and bullet points. In all fields, though, there are people who put extra effort into writing well and would be particularly annoyed at having their structure and unique wording copied.
This is in the realm of plagiarism, but it does not make the top 28 guidelines for avoiding plagiarism offered by the U.S. Department of Health and Human Services' Office of Research Integrity. Because you appropriated the peripheral wording and not the content, this is more of a gray area (depending on exactly how much was borrowed), and it does not impact whether the scientific record should be corrected: your results still stand, and your ideas are still yours. This is one of the reasons no one so far seems to be in favor of retraction.
I've even heard writing advice that you SHOULD copy the argumentation structure of other papers, but usually there are caveats about not taking everything from the same place. In creative writing classes, there are often assignments to write in the style of some other author, as practice, but the goal is to help the writer pick up different tools of expression, and in the final work for public consumption it shouldn't be obvious that the writer was mimicking someone else.
This issue probably still feels unresolved. The first time I misjudged a traffic light and essentially ran a red light, I was shaken and pulled over and expected the police to immediately find me and ticket me. But I realized that mistakes happen, and sometimes the correct way to rectify them is not to seek out appropriate punishment for yourself but to be vigilant about not making the same mistake again.
You did a good thing by reaching out to the original author, and because they do not want a retraction, you can consider this matter resolved. (You may want to save a copy of that correspondence, on the exceedingly remote chance that someone raises this as an issue later, after discovering it through a natural language processing exercise or something. Plus, if this article ends up in your "Collected Works" someday, as GEdgar suggested in a comment, you can then quote that author's kind correspondence in your commentary.)


Q:

App custom notification light color

I am programming my own app and I have some issues with my notifications.
Is it possible to have custom notification light color in android?
Because when I try to set the color to #FF64B5F6 I didn't gte this color.
Or can I only set the color to these Color.RED, Color.MAGENTA?
And when I can set custom colors, is this the right way?
Java:
NotificationCompat.Builder(this.context).setLights(ContextCompat.getColor(this.context, R.color.c_account), 500, 500)

xml:
<color name="c_account">#FF512DA8</color>

Hope you guys can help me.

A:

Is it possible to have custom notification light color in android?

Well, you can try. It may not work.
First, some devices do not have an LED.
Of those that do, some devices do not use the LED for showing notifications.
Of those that do, some devices do not support different colors.
Of those that do, some devices will not support arbitrary colors (though ideally they map your requested color to one that they do support).
So, you are welcome to request a specific color. Just bear in mind that it is quite likely that you will not get the color that you want, and that there is no guarantee that you will get any sort of LED effect.


Q:

how to display and image using external jquery in my html file

i am new to jquery, can anyone tell me how to display and image using external jquery in my html file.
i want my html to be clean and load the image where the image path is mentioned in the external jquery file.
my jquery file will be like this testjquery.js
 // url to load the image (which i dont know ,whats the code for it)

and in my html file.

Thanks in advance!

A:

You can simply use:
HTML

JQUERY
$('#divWhereYouWantAddImage').append("");

You can read more about jquery .append() function here.


Q:

How did Skarpi know Kvothe's name in "The Name of the Wind"?

Skarpi is mentioned many times before appearing in the first Kingkiller book.  He's mentioned as friend of Kvothe and as a companion of the Chronicler.  But his only interactions with Kvothe in Wind are in chapters 26 and 28.  In neither (as far as I can find) does Kvothe give his name to Skarpi.  Yet at the end of chapter 28 when Skarpi is being arrested on trumped up charges of heresy, he uses Kvothe's name when telling him to run.  How did he know it?

A:

He has called him by his True Name.
In the universe of "The Kingkiller Chronicles", everything has a true name, and if you know how, you can command everything you know the true name of. That concept is explained in depth as part of the story Skarpi is telling before he calls Kvothe by his name:

In the midst of silence Lyra stood by Lanre's body and spoke his name [...] But Landre heard her calling. Lanre turned at the sound of her voice and came to her. From beyond the doors of death Lanre returned.

(The Name of the Wind, Chapter 26: Lanre Turned)
We do know that commanding something by using its true name, it simply sounds as the calling name of the thing. In other words, if you command the fire to do something, it sounds like you are simply saying "Fire", even though you said something else:

Dal hesitated for a moment, then smiled. He looked intently into the brazier between us, closed his eyes, then gestured to the unlit brazier across the room. "Fire." He spoke the word like a commandment and the distant brazier roared up in a pillar of flame.
  "Fire?" I said. "That's it? The name of fire is 'fire'?"

(The Wise Man's Fear, Chapter 22: Slipping)
It's worth looking at what happens when Skarpi calls Kvothe by his name:

"You should run, Kvothe. [...] Head to the rooftops. Stay where they won't see you for a while. [...] There is nothing you can do here. Go."
  Since he wasn't looking at me when he spoke, there was a moment of confusion. The Justice gestured again and one of the guards struck Skarpi a blow to the back of his head. [...] I slipped out the door, onto the street.
  I took Skarpi's advice and was on the rooftop before they left the bar.

(The Name of the Wind, Chapter 28: Tehlu's Watchful Eye)
What is odd is that Skarpi told Kvothe to hide on the rooftops, in front of the very people he is hiding from. This makes more sense if Skarpi was talking to Kvothe in a language the others could not understand, the same as when Dal was talking to the fire in the other passage. The confusion was not because Skarpi was adressing some unknown person, but because he was saying something they could not understand.
Then if Skarpi did indeed talk to Kvothe using his true name, then how did he know it?
Though we see Kvothe calling the name of the wind with much difficulty and emotions involved, there are a few hints that getting the true name of something can be as easy as simply knowing it:

How can I say this so you understand? Saicere was a fine name.[...] It fit the sword like a glove fits a hand.
  But it wasn't the perfect name. This sword's name was Caesura. [...] The name didn't fit like a glove. It fit like skin.

(The Wise Man's Fear, Chapter 125, Caesura)
This does not only apply to objects or elements, but also people:

Elodin looked back and forth between the two of us. "Auri?"
  I waited for him to finish his question, but that sreemed to be all of it.
  Auri understood before I did. "It's my name", she said, grinning proudly.
  "Is it now?" Elodin said curiously.
  Auri nodded. "Kvothe gave it to me." She beamed in my direction. "Isn't it  marvelous?"
  Eloin nodded. "It is a lovely name," he said politely. "And it suits you."

Later in the same chapter:

"Why did you pick that name for her?"
  "Ah", I said, embarassed. "Because she's so bright and sweet. She doesn't have any reason to be, but she is. Auri means sunny."
  "In what language?" he asked.
  I hesitated. "Siaru, I think."
  Elodin shook his head. "Sunny is leviriet in Siaru."

(The Wise Man's Fear, Chapter 11: Haven)
The implication is that Auri is not simply a nickname of sorts, but might her true name, or at least part of it. In case of Auri, it seems that something has happened to her that
changed her nature in such a way that her old name no longer fits. She even says: "If your name is getting too heavy, you should have Kvothe give you a new one". We have seen a name change like this once before, with the change from Lanre to Haliax.
To sum it up, Skarpi is a skilled namer who knew Kvothes name by looking at him. He commanded him to leave and go to the rooftops, which he promptly did.

A:

At that point in the story, Kvothe is an orphan running free in the city of Tarbean. The place where he often sleeps and helps around, though, is at the home of the priestly man called Trapis.
Kvothe suspects that Trapis might be Tehlin Priest. Scarpi is Tehlin Priest.
More importantly, both characters tell stories to children and Scarpi is later arrested as a heretic during one of the storytelling sessions. Trapis is confirmed by Rothfuss in this interview  to be a disciple of a schism of Tehlinism referred to as the Mender Heresies.
Basically, Trapis practically knows all the beggar children of Tarbean. He occasionally tells them stories and tells them when Scarpi is in town and telling stories to children.
It is never explained in the books how Scarpi knows Kvothe's name, but my guess is that he just asked Trapis. Their names are quite similar and I guess they might either be brothers by blood or brothers by faith. Both seem to be members of the same schism of Tehlinism.
Other theories are that Skarpi is really Selitos, the famous Namer and that he actually saw Kvothe's true name and so called him by it. The other theory is that Skarpi is really Taborlin The Great, another great Namer, and that he knows and sees true names of everyone.
Truth be told, we don't have confirmation of any of that and Kvothe is somewhat of an unreliable narrator.


Q:

Aggregate or join strings in linq to sql query (SQL Server)

Given a table like
ID | Name | City
1  | X    | Y
2  | Z    | Y
3  | W    | K

I want to produce a result like
ID | Description
1  | Y (X, Z)
3  | K (W)

I tried something like
From C In Clients Group C By C.ID, C.City _
Into G = Group Select New With {.ID = ID, .Description = City & _
" (" & (From C In Clients Select C.Name).Aggregate(Function(X, Y) X & ", " & Y) & ")"}

Which gave me an error "The query operator 'Aggregate' is not supported."
Also tried
From C In Clients Group C By C.ID, C.City _
Into G = Group Select New With {.ID = ID, .Description = City & _
" (" & String.Join((From C In Clients Select C.Name).ToArray, ", ") & ")"}

Which gave me the error "no supported translation to SQL"
So, how can i do this?

A:

I hacked this in C# and it seems to give what you want. I'll leave the translation to VB up to you.
var clients = from c in context.Clients
              group c by c.City into cities
              select new {
                  ID = cities.First().ID,
                  City = cities.Key,
                  Names = string.Join(",", (from n in cities select n.Name).ToArray())
              };

foreach (var c in clients) {
    Console.WriteLine(string.Format("{0}| {1} ({2})", c.ID, c.City, c.Names));
}


Q:

Make Html.CheckBoxFor return an integer

I want to bind a checkbox to an integer (the ISACTIVE value shown below) in ASP.net MVC.
@Html.CheckBoxFor(model => model.ISACTIVE, new { htmlAttributes = new { @class = "form-control" } })

I know that Html.CheckBoxFor only accepts bool as input and I could add a new property on my Model, but I'm using an already existing database and every time it updates, the Model gets refreshed.
Is there a way to create a new method for CheckBoxFor that would return an integer based on if the box is checked or not?

A:

You could also try using simple HTML input control for checkbox type. That way, you can assign some value or name to it and return it to the controller as well.
This might not be the exact thing that you are trying to achieve. It would give you an idea though.
In your view :
<input type="checkbox" id="yourId" name="selectedIds" value="@menu.Id"/>

In your controller, you can try accessing this particular control's value like this :
value = Request.Form["selectedIds"];

Hope this helps.


Q:

Populate Drop Down List from IEnumerable in the Model, Set Selected Value

This is the model:
public class PolicyDetail
{
    public Policy Policy { get; set; }
    public IEnumerable<Insured> Insured { get; set; }
    public IEnumerable<Risk> Risk { get; set; }
    public IEnumerable<Construction> Construction { get; set; }
}

Construction just looks like this:
public class Construction
{
    public int ConstructionID { get; set; }
    public string ConstructionType { get; set; }
}

And in the DB, there are only 4 rows.  It's basically an enum.
And within Risk is this property:
public int ConstructionID { get; set; }

Before sending the model to the view, we fill up each object within PolicyDetail, where Insured and Risk are children of Policy.  Construction is loaded up every time with all four of it's rows.
So, in the model, we are listing off all the Risks.  And as we display them, we want to show Constructions as a dropdown list, and set the selected value to whatever is the value in Risk.ConstructionID.
It's amazing how much heart burn these simple dropdowns can be in MVC.
@foreach (var item in Model.Risk)
{
    ... Other items in Risk

        @Html.Label("Construction Type", new { @class = "control-label col-md-2" })

            @Html.DropDownList(?????????)

    ... Other items in Risk
}

How do I fill up that drop down with all of the items from
Model.Constrution

and set the selected item to what's in
item.ConstrucitonID

?
Thanks!
EDIT:
Here's the working solution:
@Html.DropDownList("ConstructionType", new SelectList(Model.Construction.Distinct().ToList(), "ConstructionID", "ConstructionType", item.ConstructionID))

A:

You need to convert the IEnumerable<Construction> to SelectList and specify the selected value.
Something like the following (note: I did not code this in VS, so syntax or parameters are probably not correct, but you'll get the idea)
@Html.DropDownList("ddlConstructionId", new SelectList(Model.Constrution, "ConstructionID" , "ConstructionType", item.ConstrucitonID))

You'll need to specify the selected value when creating the SelectList. I think this is the best constructor for you:
public SelectList(
    IEnumerable items,
    string dataValueField,
    string dataTextField,
    object selectedValue
)

So, in your case, it would be:
@Html.DropDownList("CompanyName",
               new SelectList(Model.Construction.Distinct().ToList(), "ConstructionID", "ConstructionType", item.ConstrucitonID));


Q:

How to make a simple audio equalizer for the iPhone?

I want to make a simple audio equalizer for the iPhone, but I don't know how to start. The equalizer should be really simple and just change bass, high, distortion and maybe echo and chorus.
How can I start? Maybe a sample code would be helpful.

A:

Firstly you're getting confused in your terminology.
An equalizer just changes the frequency response of an audio channel. It usually has a fixed number of frequency bands, whose individual gains can be controlled by the user.
Distortion, echo, chorus, etc are effects - in the digital domain they are simply algorithms that are applied to an audio channel to modify the data passing through it.
So you need to decide what it is that you are designing: an equalizer, some kind of effects processing gizmo, or maybe some combination of these.
Once you have a rough design for what you want to implement, then you can start work on the various algorithms that are going to be used to implement this design. For the equalizer you can consider either doing frequency domain filtering or implement a time domain filter bank. For the effects part you will need to do some research into the various different effects and how they are implemented, e.g. distortion usually uses some non-linear transfer function to introduce additional harmonic content.


Q:

Change field name in django admin

I am customizing django admin and I would like to change the display name of my fields.
I think the answer is here but I can't find it.
I already change the table name thanks to Meta class. I have also ordered fields, gathered them, collapsed them...

A:

What I was looking for is :
name = models.CharField(max_length=200, verbose_name="Nom")

Thanks anyway for your help !

A:

Look at Field.label.
See this: https://docs.djangoproject.com/en/dev/ref/forms/fields/#label
Basically, it's
class MyForm(forms.Form):
    name = forms.CharField(label='My Name')

But that requires extending the admin, which may be more than you want to do.


Q:

Checking condition before starting an activity

I want to check some condtiton before the main activity starts and based on test result i have to either start a new activity or continue the same activity. How to do this?

A:

you can check it in your OnCreate() method. It is called when your activity start.
onCreate(...){
....
if(want this){
//continue;
}else{
// start new activity
}

}


Q:

Laravel- VerifyCsrfToken exclude not working

I'm having an issue with excluding a route from verifying CSRF token.
I'm trying to exclude all requests on an endpoint which I call mydomain.com/example so I do like this in the VerifyCsrfToken.php file.
class VerifyCsrfToken extends Middleware
{
    /**
     * Indicates whether the XSRF-TOKEN cookie should be set on the response.
     *
     * @var bool
     */
    protected $addHttpCookie = true;

    /**
     * The URIs that should be excluded from CSRF verification.
     *
     * @var array
     */
    protected $except = [
        'example/*',
    ];
}

But it does not solve the issue. If I do this in the app/Http/Kernel.php file everything works as it should.
Does anyone know why I can't exclude specific routes?
protected $middlewareGroups = [
        'web' => [
            \App\Http\Middleware\EncryptCookies::class,
            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
            \Illuminate\Session\Middleware\StartSession::class,
            // \Illuminate\Session\Middleware\AuthenticateSession::class,
            \Illuminate\View\Middleware\ShareErrorsFromSession::class,
            //\App\Http\Middleware\VerifyCsrfToken::class,
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
            \Barryvdh\Cors\HandleCors::class,
        ],

        'api' => [
            'throttle:60,1',
            'bindings',
        ],
    ];

A:

You're excluding every route AFTER "/example" by using the wildcard and the middleware isn't registered in the kernel and therefore not even running
protected $except = [
    '/example'
];

And don't forget to uncomment the middleware
'web' => [
    \App\Http\Middleware\EncryptCookies::class,
    \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
    \Illuminate\Session\Middleware\StartSession::class,
    // \Illuminate\Session\Middleware\AuthenticateSession::class,
    \Illuminate\View\Middleware\ShareErrorsFromSession::class,
    \App\Http\Middleware\VerifyCsrfToken::class, // <--- HERE
    \Illuminate\Routing\Middleware\SubstituteBindings::class,
    \Barryvdh\Cors\HandleCors::class,
],


Q:

how to fire event from native module

CLI version 3.2.3, Titanium SDK version 3.2.2.GA
I am using a external jar file and trying to make it work into the native module so that native module can be used with titanium
i am not able to fire an event from the handler
i have two classes in native module
clsModule  and Handler
clsModule.java
import ext.Extclient;

@Kroll.module(name="extclient", id="ti.extclient")
public class clsModule extends KrollModule{

private Handler h ;
Extclient ext ;

public clsModule()
    {
    super();
    ext = new Extclient();
     h = new Handler(this);
    im.addHandler(h);
    }
}

Handler.java
import ext.ResponseHandler;

public class Handler implements ResponseHandler
    {

public void OnConnected(String arg0, String arg1) {
HashMap<String, Object> event = new HashMap<String, Object>();
    event.put("u1", arg0);
    event.put("u2", arg1);

    //How do i fire a event here ?

    }
}

i tried with fireEvent but that did not work it gives a error that it is not defined.

A:

Your module (as do all modules) extends KrollModule which extends KrollProxy, which handles events. Your Handler class does not have access to this object so it cannot fire the event itself, however you are already passing that reference (new Handler(this)) so just use it!
import ext.ResponseHandler;

public class Handler implements ResponseHandler {
    private KrollModule proxy; // Hold onto this reference
    public Handler(KrollModule proxy) {
        this.proxy = proxy;
    }

    public void OnConnected(String arg0, String arg1) {
        // Fire event if anyone is listening
        if (proxy.hasListeners("colorChange")) {
            HashMap<String, Object> event = new HashMap<String, Object>();
            event.put("u1", arg0);
            event.put("u2", arg1);
            proxy.fireEvent("colorChange", hm);
        }
    }
}

This is the general idea, pass the proxy to fire an event to the class itself, an alternative would be to inline an anonymous implementation of ResponseHandler inside your module instead. I'm not sure if you are implementing ResponseHandler right, or if OnConnected is even firing, you need to check that first.


Q:

Graph API to get all AAD Properties

Is there a Graph API which can be used to get a list of all properties which AAD supports. I dont need these properties to be user specific. All I need is the name of the properties (ex - firstname, lastname, phoneNo etc).I dont need to hard code these properties in my code I want to know if there is any API to get all the properties name. I only have tenant related data like tenant Id.

A:

The closest thing that you might be looking for is probably the EDM metadata available here: https://graph.microsoft.com/v1.0/$metadata.
It's in XML, but if you parse it and find the EntityType element with Name="user" attribute, you can see what properties it has:
<EntityType Name="user" BaseType="graph.directoryObject" OpenType="true">
  <Property Name="accountEnabled" Type="Edm.Boolean"/>
  <Property Name="ageGroup" Type="Edm.String"/>
  <Property Name="assignedLicenses" Type="Collection(graph.assignedLicense)" Nullable="false"/>
  <Property Name="assignedPlans" Type="Collection(graph.assignedPlan)" Nullable="false"/>
  <Property Name="businessPhones" Type="Collection(Edm.String)" Nullable="false"/>
  <Property Name="city" Type="Edm.String"/>
  <Property Name="companyName" Type="Edm.String"/>
  <Property Name="consentProvidedForMinor" Type="Edm.String"/>
  <Property Name="country" Type="Edm.String"/>
  <Property Name="creationType" Type="Edm.String"/>
  <Property Name="department" Type="Edm.String"/>
  <Property Name="displayName" Type="Edm.String"/>
  <!-- Lot of other properties... -->
</EntityType>

The OpenAPI documents are also available in GitHub: https://github.com/microsoftgraph/microsoft-graph-openapi.
They aren't available through a URL like the EDM metadata, but seems that is future plan:

Our plans are to expose the OpenAPI descriptions for Microsoft Graph as part of the service itself


Q:

What are the relative permeability and electrical conductivity of $\rm GaAs$?

I am doing some simulations in COMSOL with the material $\rm GaAs$. The COMSOL built-in models require me to input the relative permeability and electrical conductivity of $\rm GaAs$. I have tried hard to search for these two electrical properties online, but no luck.
Could anyone tell me these?

A:

GaAs is not a magnetic material, so you can probably just use μr=1, depending just exactly how accurate you need your simulation to be.
As for the conductivity, it will depend on how the material is doped, the temperature, and the  frequency of the signals you are interested in.
If you know the doping, you can estimate the conductivity from
$\sigma=ne\mu_c$,
where σ is conductivity, n is carrier density, e is the elementary charge, and $\mu_c$ is the carrier mobility. You can get estimates of carrier mobility over temperature from, for example, the Ioffe Institute. Unfortunately, depending on exactly what kind of simulation you are doing, coming up with an accurate value for the mobility can be quite complicated.
Note that n might also depend on temperature, particularly for near-intrinsic material or for very low temperatures.


Q:

How to get month name from prompt by using Date object and then calculate next birthday

In my javascript program I am trying to calculate birth years. I have created prompt dialogue boxes which accept different values and I am displaying these values but month values given by user is not showing correct in second line. user has entered 8 and it's showing October. Can anyone help me to identify an issue ? How should I get values all three values from prompt to calculate birth year ?
code:

var today = new Date();

var monthNames = ["January", "February", "March", "April", "May", "June",
  "July", "August", "September", "October", "November", "December"
];

var birth = new Date();

var myMonth = prompt("What month were you born in?");
var myDay = prompt("What day were you born on?");
var myYear = prompt("What year were you born in?");

var days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
var dateLoc = document.getElementById("dateField").innerHTML = "Today is " + today;

var birthField = document.getElementById("birthField")
  .innerHTML = "I was born on " + monthNames[birth.getMonth()] + ' ' + myDay + ',' + myYear + '.' +
  '(' + myMonth + '/' + myDay + '/' + myYear + ')';

var secondsBetween = (endDate.getTime() - startDate.getTime()) / 1000
endDate = new Date(today.getFullYear() + 1, myMonth, myDay);
var nextBirth = document.getElementById("nextBirth").innerHTML = "I am" + endDate + "Years old, and will turn"+  +"in" ;

output:

A:

You have a problem with monthNames[birth.getMonth()], try monthNames[myMonth - 1] instead:
    var birthField = document.getElementById("birthField")
    .innerHTML = "I was born on " + monthNames[myMonth - 1] + ' ' + myDay + ',' + myYear + '.'
    + '(' + myMonth + '/' + myDay + '/' + myYear + ')';

October is current month name, it's so due to birth = new Date()
Your next birthday could be obtained by (myMonth - 1) / myDay / (today's year + 1). Then to calculate seconds between two dates you may use
var secondsBetween = (endDate.getTime() - startDate.getTime()) / 1000

It means that you have to covert input date to the javascript Date. In your case (just following specification) it is pretty simple:
endDate = new Date(today.getFullYear() + 1, myMonth - 1, myDay);

A:

The problem is that birth.getMonth() simply returns the current month, as birth is simply set to new Date(). As it's October at the moment, you'll always get October as a result.
Instead, you're looking to access the index provide by the user with monthNames[myMonth - 1]. The subtraction of 1 is needed because the index starts at zero, and months start at one. To have the correct month show up, simply enter the month number in the following example:

var today = new Date();

var monthNames = ["January", "February", "March", "April", "May", "June",
  "July", "August", "September", "October", "November", "December"
];

var birth = new Date();

var myMonth = prompt("What month were you born in?");
var myDay = prompt("What day were you born on?");
var myYear = prompt("What year were you born in?");

var days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
var dateLoc = document.getElementById("dateField").innerHTML = "Today is " + today;

var birthField = document.getElementById("birthField")
  .innerHTML = "I was born on " + monthNames[myMonth - 1] + ' ' + myDay + ',' + myYear + '.' +
  '(' + myMonth + '/' + myDay + '/' + myYear + ')';
p {
  text-align: center;
  font-family: monospace;
  font-size: 20px;
}

Hope this helps! :)


Q:

Can I declare a view composer for a Form or HTML macro in Laravel 4?

I have a partial view that I am using to provide a pair of form select fields, and both sets of options depend on some variables set by a view composer for this view.
I would like to implement this view as a Form::macro instead so that I can parameterize some parts of it.  However, I'm not sure how I can point the view composer at a macro instead of a partial view.  Is this even possible?
I could go the route of pointing the composer at any view that I'm using the macro in, but I'd much rather have the option data load automatically any time I use the macro as it is a common component in my web app.

A:

I use partials for some Bootstrap UI components, and create a macro to connect data into the template, so I only use HTML::macro or Form::macro to access them:
Form::macro('myMacro', function($data) {
   return View::make('myPartial', $data);
};


Q:

ListBox that loads/unloads items when needed

I have a ListBox bound to a large collection of a custom objects that, among other things, hold a Bitmap.
Currently I'm having problems with the memory because all the bitmaps are loaded even if they aren't visible.
I would like the ListBox to notify my model in some way so I could load/unload the bitmaps on demand as they are needed, in order to avoid having all of them loaded. Thus, only but only load the bitmaps that are visible within the bounds of the ListBox.
How could I do it?

A:

If you check ItemContainerGenerator.ContainerFromItem for every item in your collection, it should return null if item is out of view and Virtualizing is enabled.
Or
From Get ListView Visible items:

Get the ScrollViewer of the ListView (with a FindDescendant method,    that you can do yourself with the VisualTreeHelper ).
Read its ScrollViewer.VerticalOffset : it is the number of the first    item shown
Read its ScrollViewer.ViewportHeight : it is the count of    items shown.

Rq : CanContentScroll must be true.


Q:

How to combine the use of Lazy Loding and parameterized routes in Angular

I currently have a working Angular 4 application with parameterized route with variables placeholders i.e. :zoneId :schemaId :id . I do not want to get rid of these but now that we are converting our app to use lazy loading, I cannot figure out where these parameterized routes go.
Currently
app-routing.module.ts(which is imported into app-module.ts) has
const ROUTES: Routes = [
 {
        path: 'zones/:zoneId/schemas/:schemaId/errands/:id',
        component: ErrandDetailComponent

but all the examples I'm following such as these
https://toddmotto.com/lazy-loading-angular-code-splitting-webpack
https://medium.com/@kouipheng.lee/lazy-loading-with-angular-4-29c23792b7f4
seemed to make me wipe away this path and give a generic name and use the loadChildren router which requires the path of the module #SomeModuleName This would make my code look something like this:
    const ROUTES: Routes = [
     {
            path: 'errandDetailComponent',
            loadChildren: './items/errands/errand-routing.module#ErrandRoutingModule',
            component: ErrandDetailComponent

Here is my issue because I don't know where I can use my parameterized routes now.
Just for completeness, my child router looks like this:
const errandRoutes: Routes = [
    {
        path: '', // APPARENTLY THIS MUST BE EMPTY FOR LAZY LOADING TO WORK SO CAN'T PUT PARAMETERIZED PATH IN HERE EITHER
        component: ErrandDetailComponent,
        resolve: { errand: ErrandResolver },
    }
];

@NgModule({
    imports: [
        RouterModule.forChild(errandRoutes)
    ],
    declarations: [ErrandRoutingModule],
    exports: [
        RouterModule
    ],
})
export class ErrandRoutingModule { }

A:

For this setup you can use child routes to add the parameters back in.
app-routing.module.ts
const ROUTES: Routes = [
 {
      path: 'zones',
      loadChildren: './items/errands/errand-routing.module#ErrandRoutingModule',

errands-routing.module.ts
const errandRoutes: Routes = [
    {
        path: '',
        component: ErrandsComponent,
        children: [{
            path: ':zoneId/schemas/:schemaId/errands/:id',
            component: ErrandDetailComponent,
            resolve: { errand: ErrandResolver },
        }]
    }
];

And you will just need a very thin ErrandsComponent for displaying the detail component.
errands.component.ts
@Component({
  selector: 'app-errands',
  template: '<router-outlet></router-outlet>',
})
export class ErrandsComponent{}


Q:

More than one call at a time at Softlayer API

I am using Node.js to call the Softlayer API. The problem is, when I make two API call at softlayer client, only the first call gets response objects. Rest face an error. Can anyone help me with the information about how many requests can be processed at a time over SoftLayer API?

A:

The limit is 50 request for second for each user. See:
Is there a rate limit on Softlayer API
What is the 'rate limit' exceeded of SoftLayer API endpoint?
I recommend to post the error you got and/or part of your code in order to get more further help from node.js or softlayer community.


Q:

How to set default value for inherited property in custom control - Style vs DefaultInitializer vs OverrideMetadata

As I researched ways to specify default values for inherited dependency properties on a custom control, I ended up being more confused than enlightened.
What I found is basically:

Using the Style in Generic.xaml: WPF ControlTemplate: How to provide a default value for TemplateBinding?
Using OverrideMetadata in the static constructor: How can I change the default value of an inherited dependency property?
Using an initializer based on DefaultInitializer: How to set default value to CustomControl inherited?

I guess I'd be happy if I knew only one of the possibilities, but now I wonder which approach is the best fit under normal circumstances / whether there are significant drawbacks to any of the approaches.

A:

When building Custom Controls there's a clear separation between the abstract model (class) and its representation (Generic.xaml). As always we should keep the view as dumb as possible, but likewise it pays to keep the implementation in the representation layer (and not clutter the model).
The only reason I can think of for overriding the default value in the class, would be when the order of initialization matters. For example, in case the inherited default value would throw an exception during the initialization of your class (before the Generic style would be able to "override" it).

Generic XAML: the preferred method, this offers most flexibility. Provides a clear picture of the default implementation (see edit).
Method override: As mentioned, when the order of initialization matters. Leads to less clean code.
DefaultInitializer: Is used to provide default values for VS designer.

The DefaultInitializer extension is invoked when the user adds an object from the Toolbox to the design surface.
  Derive from the DefaultInitializer class to configure default initial values for your object.

EDIT - Subclassing Custom Controls
This is another area where separation of concerns pays off, giving you a clear overview.
<Style TargetType="{x:Type local:MyButtonBase}">
    <Setter Property="FontSize" Value="12"/>
    <Setter Property="HorizontalContentAlignment" Value="Center"/>
    <Setter Property="VerticalContentAlignment" Value="Center"/>
</Style>

<Style BasedOn="{StaticResource {x:Type local:MyButtonBase}}"
       TargetType="{x:Type local:MyButton}">
    <!--Override inherited default value-->
    <Setter Property="FontSize" Value="18"/>
    <!--Add default values-->
    <Setter Property="IsDefault" Value="True"/>
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type local:MyButton}">

                ...

            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>


Q:

Should I register every time before uploading to pypi?

I know this is what it needs to publish your project to pypi
$ python setup.py register -r pypi
$ python setup.py sdist upload -r pypi
$ python setup.py bdist_wheel upload -r pypi

Should I register every time before uploading to pypi? Or just the first time? Thank you.

A:

Now I can confirm the answer is: Yes, always
If you don't register, pypi will not allow you to upload. And you can't register with the same version number, this is not allowed either, which means you should modify version number in setup.py before registering and uploading.
What if I don't want to change version but need to modify code?
Here's a solution:
Suppose the previous version is 0.0.1, then you can use 0.0.1.post1 and pypi will happily accept this.
Here's 0.0.1.post1 version of my ezcf package on pypi, as you can see it is a valid version number.
https://pypi.python.org/pypi/ezcf/0.0.1.post1


Q:

Listing off players in a tournament such that each player won against the next?

Given a class with N people(This is represented by an array int[] a), where each person plays a game with all other people. Each game will involve only 2 players. So for N people there will be total NC2 games.
Results are with you for all the games. You have to arrange each and every person in a queue with a condition that, a[i] should have won game with a[i-1]. THis is true for all values of i.
We don’t need to care about the result between a[i] and a[i-2] . a[i] may win or lose the game with a[i-2].
My Approach( I used backtracking to solve this problem) :

For each person we will maintain a list of people who won the game with that person.
A new result array will be created(Length equal to the total players).
1st position is filled up iteratively with each person.
Next position in the result array is filled up with the person who won game with previous person. This person will be picked up from corresponding winning list of previous person by iterating over that array.

Above solution will try each and every path using recursive approach. Isn't there any better algorithm ?

A:

Mathematically what you have is something called a tournament graph and you are trying to find a Hamiltonian path inside of that tournament graph. Although in an arbitrary graph the problem of finding a Hamiltonian path is NP-hard, it's known that every tournament graph must have a Hamiltonian path and fortunately they're not that hard to find.
One simple approach is to use recursion. If there's only one node in the graph, it's pretty simple to solve this problem: just list off the one person in the graph. Otherwise, choose some node arbitrarily. Split the tournament into to sub-tournaments: one of all the people who beat that person and one of all the people that person lost to. Recursively get a Hamiltonian path in each of those sub-tournaments. Then, concatenate the Hamiltonian paths together, putting the person you singled out in the first step in the proper place in between them.
So just how efficient is this algorithm? Like quicksort, the efficiency of the algorithm depends on how you split the tournament a smaller pieces. Suppose that when you choose a person to split the tournament into smaller pieces, you choose the person whose number of wins is as close to n/2 to as possible. This will produce two smaller tournament of size roughly n/2. Determining which person to pick takes quadratic time, because you have to look at the outcome of each game to count of how many wins and losses player has. This gives us the following recurrence relation:

T(n) = 2T(n/2) + O(n2)

Using the master theorem, we get that this recurrence solves to O(n2), which is considerably faster than your initial idea.
Hope this helps!


Q:

How to transform rows into column in SQL Server?

Using MS SQL Server and I have below table:
+-----------+------------------+------------------+---------------------+-------------------------+
| SrNo      |    ApprCode      |  ApprName        |     ApprStatus      |      ApprDate           |
+-----------+------------------+------------------+---------------------+-------------------------+
| SR_176    |   X001           |   James          |   APR               | 2019-10-03              |
| SR_176    |   X002           |   Sam            |   APR               | 2019-10-03              |
+-----------+------------------+------------------+---------------------+-------------------------+

Tried with PIVOT but its showing james and X001 as a column heading:
Expected Result:
+-----------+-------------- +---------------+---------------------+-------------------------+------------------+
    SrNo    | ApprCode_1    | ApprName_1    | ApprDate_2               ApprCode_2     ApprName_2     ApprDate_2
+-----------+---------------+---------------+---------------------+-------------------------+------------------+
    SR_176     X001             James         2019-10-03               X002           Sam            2019-10-03
+-----------+---------------+---------------+---------------------+---- ---------------------+------------------+

Query to generate data:
CREATE TABLE #Temp
(
    SrNo NVARCHAR(200),
    ApprCode NVARCHAR(200),
    ApprName NVARCHAR(200),
    ApprDate Date
)

INSERT INTO #Temp VALUES ('SR_176','X001','James', '2019-10-03')
INSERT INTO #Temp VALUES ('SR_176','X002','Sam', '2019-10-03')

Query that I tried:
declare @sql nvarchar(max)
declare @name_concat nvarchar(max)
declare @name1_concat nvarchar(max)
declare @select_aggs nvarchar(max)
select @name_concat = STUFF((select distinct ',' + quotename(ApprCode) from #Temp order by 1 for xml path('')), 1, 1, '')
select @name1_concat = STUFF((select distinct ',' + quotename(ApprName) from #Temp order by 1 for xml path('')), 1, 1, '')

select @sql = '
;with cte2 as
(
    SELECT SrNo,' + @name_concat + ',' + @name1_concat + '
    FROM #Temp
    PIVOT(MAX(ApprCode)
          FOR ApprCode IN (' + @name_concat + ')) AS PVTTable PIVOT
          (
          MAX(ApprName)
          FOR ApprName IN (' + @name1_concat + ')) AS PVTTable1
)
select * from cte2
'
exec sp_executesql @sql

A:

I solved it by using ROW_NUMBER() and Case Expression:
Here is the query:
 SELECT *,
       Row_number()
         OVER(
           partition BY srno
           ORDER BY apprdate) AS RN
INTO   #temptable
FROM   #temp

SELECT srno,
       CASE rn
         WHEN 1 THEN Max(apprname)
       END AS [1 Approver],
       CASE rn
         WHEN 2 THEN Max(apprname)
       END AS [2 Approver],
       CASE rn
         WHEN 1 THEN Max(apprcode)
       END AS [1 ApproverCode],
       CASE rn
         WHEN 2 THEN Max(apprcode)
       END AS [2 ApproverCode],
       CASE rn
         WHEN 1 THEN Max(apprdate)
       END AS [1 Date],
       CASE rn
         WHEN 2 THEN Max(apprdate)
       END AS [2 Date]
INTO   #james
FROM   #temptable
GROUP  BY srno,
          rn

SELECT srno,
       Max([1 approver])     AS ApproverName_1,
       Max([1 approvercode]) AS ApproverCode_1,
       Max([1 date])         AS ApproverDate_1,
       Max([2 approver])     AS ApproverName_2,
       Max([2 approvercode]) AS ApproverCode_2,
       Max([2 date])         AS ApproverDate_2
FROM   #james
GROUP  BY srno


Q:

How can I know if the airbags have expired and what are the consequences?

How do I know if the airbags have expired? Is it the same years for every airbag? Maybe they can be checked?
Then, if I have the airbags expired, what would be the consequences of using the car? Would the airbags get activated without a crash? Or if I have a crash, would they still protect me?
I know that replacing the airbags is something expensive and I want to know what the risks are. I am about to buy a Golf GTI '99 so that means that the airbags are 17 years old (if never changed, of course).

A:

In general airbags don't have an expiration date.  The airbags in a modern vehicle are designed to last for life.
Some manufacturers have service intervals for the airbags, but it's normally a visual check and making sure the SRS (airbag) diagnostic systems is functioning correctly.
Mercedes put expiration date stickers on the door sill with an expiration date of 10 years out, but even then they retroactively decided that all air bags installed after 1992 did not have a meaningful expiration date so most of those stickers are meaningless.
If airbags did expire I think most people would just disable/uninstall them because for a 15 year old car, replacing all the airbags can potentially cost more than the vehicle is worth.  I'm not suggesting this, I'm just pointing it out as a logic exercise.  If there was a 15yr time-bomb on the value of the vehicle, you'd hear about it a lot more.

A:

You should check to see if your car is under the current Takata Air Bag recall

Does an Airbag Expire?
  While some automakers have set time limits on when to replace an airbag, the actual components are extremely durable. The key difference is the type of seal used to house the airbag igniter, also known as the squib.
"Almost all squibs since Day One have used what is called 'glass-to-metal' sealing, which is the best for moisture protection," says Douglas Campbell, who is president of the Automotive Safety Council and has worked in the airbag industry for more than 25 years.
"Some earlier non-North American models may have used 'plastic-to-metal' seals, which would have passed the vehicle life tests, but are considered to be potentially not as robust in extreme testing," Campbell says.
Leo Knowlden, a field performance assessment engineer for General Motors, said that GM has used glass-to-metal seals on all its airbags since the very beginning. A plastic-to-metal seal is more likely to accumulate moisture over the years, Knowlden says. This can lead to corrosion of the electrical pins in the igniter and potentially lead to a less responsive airbag.
As proof of the lifetime durability of GM airbags, Knowlden pointed to a 1992 Insurance Institute for Highway Safety study, where a rusty 1972 Chevrolet Impala was crash-tested and both the driver's airbag and passenger airbag successfully deployed. That Impala was one of the first 1,000 airbag-equipped cars made by GM.
And similarly, "airbags from 1990s vehicles are operating correctly in today's accidents," says Campbell.
The National Highway Traffic Safety Administration (NHTSA) knows of successful deployments of airbags more than 30 years after production, says Jose Ucles, a NHTSA spokesperson.

Source


Q:

How do I bypass the ac rectifier in a guitar amp so I can power it directly with DC power source instead of mains?

I have a guitar amp that died recently, the primary coil of the transformer lacks continuity when tested with a multi-meter. I am trying to power it with a 9V power source instead of AC power outlet. I am intending to bypass the rectifier but I'm not sure where to hook up the 9V source on the circuit board.
The transformer outputs 10.5 volts and I figured 9V should do the trick if I don't pass it through the diodes. The fuse is rated at 1 Amp and the 9V source is also 1 Amp.
I diagrammed out the power source circuit. Hopefully that is enough information. Pretty new to all this stuff. Thanks in advance.

simulate this circuit – Schematic created using CircuitLab
--Update--
Looks like I'm going to need something like this to create a power supply that is split into +9V and -9V with a ground at 0V:

Found this and more here

A:

The diode bridge is used together with a center tapped secondary to create plus and minus supplies.  You can't just replace that with a single-output supply.  What you show won't work.
You can get your own ±9 V supply, then connect its three leads to the three nets you show going into the dashed block at right.  Since the diodes would be reverse-biased if you connect the external supply correctly, there is no need to remove them.  In fact, they give you some protection against connecting the external supply in reverse.


Q:

pandas - return column of exponential values

Starting from a sample dataframe df like:
a,b
0,0.71
1,0.75
2,0.80
3,0.90

I would add a new column with exponential values of column b. So far I tried:
df['exp'] = math.exp(df['b'])

but this method returns:
"cannot convert the series to {0}".format(str(converter)"
TypeError: cannot convert the series to <type 'float'>

Is there a way to apply a math function to a whole column?

A:

Well math.exp doesn't understand Series datatype, use numpy np.exp which does and is vectorised so operates on the entire column:
In [24]:
df['exp'] = np.exp(df['b'])
df

Out[24]:
   a     b       exp
0  0  0.71  2.033991
1  1  0.75  2.117000
2  2  0.80  2.225541
3  3  0.90  2.459603


Q:

What's the isospin of photons?

What's the isospin of photons? Why PDG book says $0, 1(1^{--})$ for its $I(J^{PC})$? What does $0, 1$ mean here? Is it that the isospins aren't determined and can be 0 or 1?

A:

It's a (known) linear combination of 0 and 1. The electromagnetic field operator can be written as something like
$$A_\mu = B_\mu\cos\theta_W + W_\mu^3\sin\theta_W$$
where $B_\mu$ is the $U(1)$ hypercharge operator and $W_\mu^3$ is the measured component of the weak isospin operator. $B_\mu$ is not associated with any weak isospin, so that's where the 0 comes from, but $W_\mu^3$ is, so that's the 1.
By the way, it's worth mentioning (as Ron pointed out) that weak isospin is not the same thing as just isospin. The latter corresponds to a particular $SU(2)$ subgroup of the $SU(6)$ flavor "symmetry," but weak isospin corresponds to its own completely separate $SU(2)$ symmetry group. Basically they are completely different physical properties that just happen to share the same group structure. Some physicists have developed an unfortunate habit of calling any property that follows this group structure "isospin" (unless it is actual spin).
Since the photon does not have any up/down flavor, it exists in the trivial representation of non-weak isopsin $SU(2)$, and thus its actual isospin is zero.