Q:

Reduce Resale Value to Avoid Theft? (Uglify)

"Uglify your bike" was mentioned here as a theft deterrent.
I have a 20102009 Canondale F3 and I'm thinking about locking it up in Manhattan from time to time. I think that Uglifying will help.

How should one best uglify a bike? How would you do this without disassembling the bike? Would spray paint stick to the current paintjob, or would I need to use paint remover or to sand the current paint off? What about the components? I don't want to ruin the bike in the process of trying to keep it, but I would prefer not to remove all components and cables, etc.
Note: I know that having another beater bike and other options are great, but I'm trying to figure out how to ride my bike and keep it from being stolen (or even looked at).
Edit: I've removed a part on "Does anyone have any evidence that uglyfying does or does not work..."  It's now here.

A:

The first thing is to note that vibrant, brightly-colored objects are by nature more attention-getting, so I hope your bike is not bright red, light orange, yellow or bright green. I have noted that gray bikes are less noticeable and even hard to see in some conditions. Dark blue, dark gray, pale or dusty white, and brown are also favorable colors to make a bike less noticeable.
I have seen many bikers disguising their machines by wrapping the frame, or parts of it using duct tape. Some types of duct tape are less shiny than others, and some have a rather weak adhesive that won't be too hard to remove. The advantage of duct tape is that being skillful, you don't need to take apart the bike.
With bikes that have straight tubes, you can find some PVC leftover piping that you can cut lengthwise in order to make a sleeve to be inserted around tubes. Depending on the pipe fitting it can even look very cool, but the point is, PVC is very easy to paint with spray paint or many other types, so you can "uglyfy" the pipe as much as you want, but you can remove it from your bike if you want. Having more patience you can make covers for the joints in the frame and make the PVC piping fit really well so it won't be obvious that it has a cover.
As for the components, you can cover then with a lot of materials, for example I use a sleeve made out of old inner tubes to wrap the crank arms, held in place with zip ties. I made that for protection actually, but it cleverly covers also the brand name tag. This very same technique can be used in chain stays, seat tube, handlebars hubs and even brake or shifter levers. Just make sure that the tube isn't "too black" nor shiny. This material can be almost invisible in twilight conditions and cluttered environments, so almost any other bike will drag more attention than yours.
For other components, like derailleurs, shifters, levers, I would recommend to partially cover them with "hot glue" and let the glue become dirty. The hot glue won't stick too hard on metal, so it will be easily removable. There are transparent and non transparent types, I recommend the latter as it disguises branding better. Use it wisely to cover badges and the like, but don't make it get into pivots or anything. You can stain the glue with black oil, grease or dirt making it look even uglier. You can add dirt and dust when the glue is still warm.
I give this advise based on experience and what I've seen other riders do in my city. I use some of these tricks, not all of them. I personally commute on a dark blue bike that is not so shiny, and most my components are matte black or matte gray and generic (so I don't have brand badges to cover). I have left the bike unlocked among a lot of motorcycles at my workplace and nothing has happened to it without making it look like trash ;) but I can assure you that this bike is hard to see, to the point that to myself, when I'm approaching the parking lot it's hard for me to find it from a distance, even knowing where it is!
Finally a note of advice on safety: Disguising your bike and making it less noticeable is dangerous in traffic, so make sure you use bright of reflecting clothes, reflective straps on ankles, elbows, wrists, etc, a bright helmet, a bright backpack or whatever you find useful, so you are easily seen by drivers and pedestrians! You can attach the blinking lights to your backpack instead of the bike, as long as they are correctly positioned and oriented, they will serve their purpose.
Good luck with your project!

A:

I did it in what I consider a "perfect" way: sticking LOTS of reflective stickers (home made) covering every logo on the bike. Of course it is just a part of the uglification program (others include never washing the paintjob, and strapping any new stuff on the bike with duct tape, tube rubber strips or bread bag ties).
It works three ways:

The logos get hidden, so anyone would look at a fancy bike and see just a regular bike;
You get extra-safety, because your bike is way more visible at night;
A bike looking too much as a vehicle, or as a bike that is seriously ridden, gives the impression that is beaten instead of "manicured", so thieves might not be so interested.

And as a benefit, you keep the original stickers and paintjob protected under the reflective material (in the other hand, I could never get the refectives out, they are REALLY sticky...).
This photo shows some of this reflection. In really dark conditions, it makes a lot of difference. (I'm the guy on the left):

A:

I saw these stickers, and I like the idea. Makes your bike look beat up without doing any permanent damage. Should help if you plan on reselling you bike and upgrading in a few years.


Q:

How to achieve forward compatible string literals in python?

I've got a script which runs with python 3 except string literals.
Python 2.x force me to prefix string literals with u'' and python 3 dosen't understand it.
How to so solve that?

A:

try this when running it in python 2.x:
>>> from __future__ import unicode_literals
>>> s=['xx','yy','zz','aa']
>>> s
[u'xx', u'yy', u'zz', u'aa']

same thing when executed in python 3.x:
>>> from __future__ import unicode_literals
>>> s=['xx','yy','zz','aa']
>>> s
['xx', 'yy', 'zz', 'aa']


Q:

Disable Space key for WebBrowser

When the user focus on webBrowser Control and Press Space key the webBrowser Scrolls Down.
How can I disable this event?

A:

Finally this javascript code solve my problem:
onkeypress='if(event.keyCode=13) return false;'

because the false returning for spaceKey prevent the webBrowser from scrolling down!


Q:

What is the benefit of the MoSCoW technique?

I do not see how the MoSCoW Method's "Must, Should, Could, Would" prioritisation is better that simply 1,2,3,4? If I receive the requirements from the customer, they already are prioritised, usually using this range.
Also what is so interesting on this MoSCoW thing, why it is so 'famous'?

A:

It's not about using acronyms at all. It's about perception.
If you ask a business to rank everything 1, 2, 3, 4 or High, Medium, Low then everything becomes a high priority. You're not really explaining, in those systems, why you're asking.
If you ask businesses to rank things as must have, should have, could have, would have, then you are simultaneously selling the point that, in all likelihood, they're not getting everything by the set release time. So, what MUST they have, for the product to even be viable? What SHOULD they have for it to be truly useful? What COULD they have, if there's time to do it? And what WOULD just be nice to have? (ie. what seems like a good idea, but they'll probably never use it.)
And, if the business do this right, and give a balanced rating, it also manages the expectations of the developers.
Rather than "Ok, let's work through the 1s and see what time we have left," it becomes very real, it becomes "the business literally cannot use this product without this pile and it's not going to benefit them much unless we can do this pile here." A useful product is a strong driving force for many developers.


Q:

Automatically apply $scope changes (trigger digest) after a non-$q promise resolves in angularjs

Let's say you have:
function myPromise() {
  // using some promise lib other than $q, like Q or bluebird
  var defer = Q.defer();
  defer.resolve('John');
  return defer.promise;
}

and then you have something like:
function foo() {
  return myPromise().then(function (name) {
    return name + ' Smith';
  });
}

foo().then(function (name) {
  $scope.$apply(function () { // or can use $timeout
    console.log('after foo');
    $scope.text = 'Hey ' + name;
  });
});

Is there a way to modify foo so that the after foo block is automatically wrapped in $scope.$apply()? i.e. we can then just have:
foo().then(function (name) {
  console.log('after foo');
  $scope.text = 'Hey ' + name;
  // $scope.$apply() is automatically called after this block is executed
});

The reason I ask is that I am developing an API where the user will make several of these foo calls and it would greatly cut down on the user's code if the digest cycle was automatically triggered after the foo promise resolves. I know I can use a callback to accomplish this, but I'm hoping there is a cleaner way that just uses promises.
My hunch is that the solution lies in wrapping the non-$q promise in a $q promise...

A:

I was able to trigger the digest cycle just by wrapping my API functions in $timeout blocks, e.g.
function foo() {
  return $timeout(function () {
    return myPromise().then(function (name) {
      return name + ' Smith';
    });
  });
}


Q:

How to recode variables in SAS?

I tried to recode the missing values but instead lost all my other variables within a dataset

BEFORE:

AFTER:
        data work.newdataset;
        if (year =.) then year = 2000;
        run;

A:

You are missing the SET statement.
data want;
set have;
myvar=5;
run;

will create a new dataset, want, from have, with the new variable value applied (or the recode or whatever).  You could also do
data have;
set have;
myvar=5;
run;

That would replace have with itself plus the recode/whatever.  This is actually less common in SAS; it is often preferable to do all recodes in one step, but to create a new dataset (so that the code is reversible easily).


Q:

Complex query to count votes with a redistribution system

I've spent the last couple of evenings trying to build a system for redistribution of votes in a ranked voting system. I've finally come up with the model for redistributing surpluses from a candidate whose number of votes exceeds the threshold.
I'm at the beginning of my learning curve and I've used Stack Overflow extensively during this process to gain knowledge about how to produce each and every query within this system.
Finally I've reached the result I want as can be seen below on the expense of a really confusing set of queries:
 +-----------+-------+----------------+----------------------------+
 | CANDIDATE | VOTES | REDISTRIBUTION | VOTES_AFTER_REDISTRIBUTION |
 +-----------+-------+----------------+----------------------------+
 |         1 |     8 |             -1 |                          7 |
 |         2 |     1 |          0.125 |                      1.125 |
 |         3 |     2 |           0.25 |                       2.25 |
 |         4 |     4 |            0.5 |                        4.5 |
 |         5 |     2 |           0.25 |                       2.25 |
 |         6 |     3 |              0 |                          3 |
 +-----------+-------+----------------+----------------------------+

As mentioned - these queries are horrible. Absolutely and utterly HORRIBLE. Now I need to understand how this could be simplified and at the same time as effective or even more effective than this mess of queries.
Could anyone explain how to optimize this in a way that I can learn more about writing good queries?
This is my (awful) query:
SELECT vote_candidate candidate, original_votes votes, surplus_redistribution redistribution, (original_votes + surplus_redistribution) votes_after_redistribution
FROM (
    SELECT c.vote_candidate, (
        SELECT (
            (MAX(votes_above_the_threshold) - (
                SELECT FLOOR((COUNT(*) / (2 + 1)) + 1) threshold
                FROM votes
            )) / MAX(votes_above_the_threshold)
        ) ratio
        FROM (
            SELECT vote_candidate vote_candidate, COUNT(*) votes_above_the_threshold
            FROM vote_orders
            WHERE vote_order = 1
            GROUP BY vote_candidate
            HAVING votes_above_the_threshold >= (
                SELECT FLOOR((COUNT(*) / (2 + 1)) + 1) threshold
                FROM votes
            )
        ) t
        WHERE votes_above_the_threshold = (
            SELECT MAX(votes_above_the_threshold)
            FROM vote_orders
        )
    ) surplus_ratio, c.original_votes, LEAST(0,t.threshold - c.original_votes) surplus_redistribution
    FROM (
        SELECT o.vote_candidate, COUNT(*) original_votes
        FROM vote_orders o
        WHERE o.vote_order = 1
        GROUP BY o.vote_candidate
    ) c
    CROSS JOIN (
        SELECT FLOOR((COUNT(*) / (2 + 1)) + 1) AS threshold
        FROM votes
    ) t
    GROUP BY c.vote_candidate
    UNION
    SELECT vote_candidate, (
        SELECT (
            (MAX(votes_above_the_threshold) - (
                SELECT FLOOR((COUNT(*) / (2 + 1)) + 1) threshold
                FROM votes
            )) / MAX(votes_above_the_threshold)
        ) ratio
        FROM (
            SELECT vote_candidate vote_candidate, COUNT(*) votes_above_the_threshold
            FROM vote_orders
            WHERE vote_order = 1
            GROUP BY vote_candidate
            HAVING votes_above_the_threshold >= (
                SELECT FLOOR((COUNT(*) / (2 + 1)) + 1) threshold
                FROM votes
            )
        ) t
        WHERE votes_above_the_threshold = (
            SELECT MAX(votes_above_the_threshold)
            FROM vote_orders
        )
    ) surplus_ratio, COUNT(*) original_votes, (
        ROUND((COUNT(*) * (
            SELECT (
                (MAX(votes_above_the_threshold) - (
                    SELECT FLOOR((COUNT(*) / (2 + 1)) + 1) threshold
                    FROM votes
                )) / MAX(votes_above_the_threshold)
            ) ratio
            FROM (
                SELECT vote_candidate vote_candidate, COUNT(*) votes_above_the_threshold
                FROM vote_orders
                WHERE vote_order = 1
                GROUP BY vote_candidate
                HAVING votes_above_the_threshold >= (
                    SELECT FLOOR((COUNT(*) / (2 + 1)) + 1) threshold
                    FROM votes
                )
            ) t
            WHERE votes_above_the_threshold = (
                SELECT MAX(votes_above_the_threshold)
                FROM vote_orders
            )
        )), 3)
    ) surplus_redistribution
    FROM vote_orders
    WHERE vote_order = 1
    AND vote_candidate IN ((
        SELECT vote_candidate
        FROM vote_orders a
        INNER JOIN (
            SELECT vote_id, MIN(vote_order) AS min_vote_order
            FROM vote_orders
            WHERE vote_candidate NOT IN ((
                SELECT vote_candidate
                FROM (
                    SELECT vote_candidate vote_candidate, COUNT(*) votes_above_the_threshold
                    FROM vote_orders
                    WHERE vote_order = 1
                    GROUP BY vote_candidate
                    HAVING (
                        votes_above_the_threshold >= (
                            SELECT FLOOR((COUNT(*) / (2 + 1)) + 1) threshold
                            FROM votes
                        )
                        OR (
                            votes_above_the_threshold >= (
                                SELECT FLOOR((COUNT(*) / (2 + 1)) + 1) threshold
                                FROM votes
                            )
                            AND votes_above_the_threshold = 0
                        )
                        OR (
                            votes_above_the_threshold = 0
                        )
                    )
                ) t
            ))
            GROUP BY vote_id
        ) b
        ON a.vote_id = b.vote_id
        AND a.vote_order = b.min_vote_order
        INNER JOIN (
            SELECT vote_id
            FROM vote_orders
            WHERE vote_candidate = (
                SELECT vote_candidate
                FROM (
                    SELECT vote_candidate vote_candidate, COUNT(*) votes_above_the_threshold
                    FROM vote_orders
                    WHERE vote_order = 1
                    GROUP BY vote_candidate
                    HAVING votes_above_the_threshold >= (
                        SELECT FLOOR((COUNT(*) / (2 + 1)) + 1) threshold
                        FROM votes
                    )
                ) t
                WHERE votes_above_the_threshold >= (
                    SELECT MAX(votes_above_the_threshold)
                    FROM vote_orders
                )
            )
            AND vote_order = 1
        ) c
        ON a.vote_id = c.vote_id
        GROUP BY vote_candidate
    ))
    GROUP BY vote_candidate
    ORDER BY vote_candidate ASC
) y
GROUP BY vote_candidate;

This is the schema:
CREATE TABLE votes
(
    vote_id INT NOT NULL AUTO_INCREMENT,
    vote_candidate_a INT,
    vote_candidate_b INT,
    vote_candidate_c INT,
    vote_candidate_d INT,
    vote_candidate_e INT,
    vote_candidate_f INT,
    PRIMARY KEY vote_id(vote_id)
);

INSERT INTO votes
VALUES
(NULL, 1, 3, 2, 5, 4, 6),
(NULL, 1, 2, 4, 6, 3, 5),
(NULL, 5, 3, 2, 1, 4, 6),
(NULL, 6, 1, 5, 3, 4, 2),
(NULL, 2, 3, 5, 6, 1, 4),
(NULL, 4, 1, 6, 3, 2, 5),
(NULL, 3, 2, 6, 1, 5, 4),
(NULL, 4, 3, 1, 6, 2, 5),
(NULL, 1, 2, 4, 3, 6, 5),
(NULL, 1, 5, 3, 2, 4, 6),
(NULL, 4, 5, 6, 2, 3, 1),
(NULL, 1, 4, 2, 3, 5, 6),
(NULL, 1, 2, 3, 4, 5, 6),
(NULL, 3, 6, 5, 1, 4, 2),
(NULL, 1, 2, 3, 4, 5, 6),
(NULL, 6, 5, 4, 3, 2, 1),
(NULL, 4, 3, 1, 5, 6, 2),
(NULL, 6, 3, 1, 2, 5, 4),
(NULL, 1, 4, 6, 3, 2, 5),
(NULL, 5, 3, 6, 4, 2, 1);

CREATE TABLE vote_orders
(
    id INT NOT NULL AUTO_INCREMENT,
    vote_id INT,
    vote_order INT,
    vote_candidate INT,
    PRIMARY KEY id(id)
);

INSERT INTO vote_orders (id, vote_id, vote_order, vote_candidate)
SELECT NULL, vote_id, 1, vote_candidate_a FROM votes
UNION
SELECT NULL, vote_id, 2, vote_candidate_b FROM votes
UNION
SELECT NULL, vote_id, 3, vote_candidate_c FROM votes
UNION
SELECT NULL, vote_id, 4, vote_candidate_d FROM votes
UNION
SELECT NULL, vote_id, 5, vote_candidate_e FROM votes
UNION
SELECT NULL, vote_id, 6, vote_candidate_f FROM votes;

The rules for redistributing works like this:
If a candidate exceeds the threshold in the first round, his/hers surplus is redistributed proportionally to the candidate ranked as number two on the winners ballots.
The ratio is calculated like this:
The surplus of the winner is divided by the total max votes rounded down to the nearest full integer. Then the redistributed value is added to the candidates.

A:

Your query is simultaneously awful and awesome.  It is truly impressive, especially if you are self-taught.
Unfortunately, I don't believe it is correct.  (Or, I may have misunderstood how you intended for the vote redistribution scheme to work.)  For example, it reports that the redistribution in favour of Candidate 2 should be +0.125.  Of the 8 ballots that have Candidate 1 as the first choice, 4 of them have Candidate 2 as the second choice.  Shouldn't the redistribution be +0.5 then?
As further evidence, the redistribution column should sum to 0.  However, -1 + 0.125 + 0.25 + 0.5 + 0.25 + 0 = 0.125, which isn't neutral.
Schema
I would have changed the terminology of your votes table as
CREATE TABLE ballots
( id INT NOT NULL AUTO_INCREMENT PRIMARY KEY
, choice1 INT
, choice2 INT
, choice3 INT
, choice4 INT
, choice5 INT
, choice6 INT
);

However, it may have been better to do away with that table altogether, and go straight to the vote_orders table, because it's a bad idea to design your schema to support a fixed number of candidates.  (As the saying goes, there are only three numbers in computer science: zero, one, and many.  You want to support many.)  Consider the ballots table to be more of a data entry tool (possibly a TEMPORARY TABLE) than a storage format.
I would have used the name "votes" for what you called the vote_orders table:
CREATE TABLE votes
( ballot INT NOT NULL
, rank INT NOT NULL
, candidate INT NOT NULL
, UNIQUE (ballot, rank)
, UNIQUE (ballot, candidate)
);

For the rest of the review, I'll stick with your original names, so as to avoid confusion.
Choice of RDBMS
For a complex query like this, I recommend using a more capable database than MySQL.  For example, PostgreSQL (and others) offers several advantages:

Support for Common Table Expressions (WITH clauses), which help tremendously with managing the complexity.  MySQL does not support CTEs.  As a workaround, you can create views instead.  However, it's harder to edit all of your views at once as easily as a single query with CTEs, so development is more cumbersome.  Also, CTEs don't pollute the global namespace, and it's easier to see how subsequent CTEs depend on earlier CTEs.
I've written my solution below using CTEs, but it's trivial to rewrite each CTE as a CREATE VIEW statement instead, and I've verified that it does work with MySQL that way.
Support for recursive queries.  Using recursive CTEs, you should be able to write one query that processes multiple rounds of vote transfers.  With MySQL, your alternative would be to write a stored procedure that manipulates a temporary table, which is less elegant.
Stricter interpretation of SQL.  I often find that MySQL adheres loosely to the SQL standard, and makes sense of queries that shouldn't make sense.  For example, you have some rather suspect SQL such as
WHERE votes_above_the_threshold = (
    SELECT MAX(votes_above_the_threshold)
    FROM vote_orders
)

that PostgreSQL would have rejected (see discussion about this excerpt below).  You'll end up acquiring better habits developing on PostgreSQL than MySQL.

Overall impression
Unfortunately, your query is too complex for me to try to understand, especially since it yields wrong results.  However, I can say that you did some things well:

Indentation is consistent and logical (though using subqueries to select attributes results in messy indentation; see below).
Keywords are capitalized according to common practice.
Column names are pretty clear and meaningful.

Some problems are:

Repetition, such as the threshold calculation.
Cryptic table aliases, such as t, c, and y.
Many of your subqueries are to select an attribute (SELECT (SELECT …) AS attribute).  Try to formulate your subselects to appear in the FROM clause (SELECT subsel.attr FROM (SELECT attr FROM …)), which will make your indentation saner and the query generally more readable.
Convoluted reasoning that looks almost circular.  For example, in the first two dozen lines…
SELECT c.vote_candidate, (
    SELECT (
        (MAX(votes_above_the_threshold) - (
            SELECT FLOOR((COUNT(*) / (2 + 1)) + 1) threshold
            FROM votes
        )) / MAX(votes_above_the_threshold)
    ) ratio
    FROM (
        SELECT vote_candidate vote_candidate, COUNT(*) votes_above_the_threshold
        FROM vote_orders
        WHERE vote_order = 1
        GROUP BY vote_candidate
        HAVING votes_above_the_threshold >= (
            SELECT FLOOR((COUNT(*) / (2 + 1)) + 1) threshold
            FROM votes
        )
    ) t
    WHERE votes_above_the_threshold = (
        SELECT MAX(votes_above_the_threshold)
        FROM vote_orders
    )
) surplus_ratio,

votes_above_the_threshold is defined as a column of t. t is filtered through a HAVING clause.  It is further filtered by WHERE votes_about_the_threshold = (SELECT MAX(votes_above_the_threshold) FROM vote_orders), but there is no votes_above_the_threshold column in vote_orders!  I'd also try removing the HAVING condition in t favour of the WHERE condition of the surplus_ratio subquery.
What happens if there is a tie for first place after a round (multiple MAX(votes_above_the_threshold))?  Does it still work?
It's not obvious how to take your massive query apart for inspection and verification.

Solution
Here is my solution as SQL Fiddles for PostgreSQL and MS SQL Server, also ported to MySQL.
The second CTE, preferences, is worth explaining.  I've devised it as a way to capture all the votes in a useful aggregated format.
The last two CTEs (raw_next_round and redistributed_next_round) are actually superfluous.  I've left it in to show how you can do a SELECT *  FROM redistributed_next_round ORDER BY 1, 2, 3 to produce a data set that is self-similar to the original preferences CTE, thus serving as a proof-of-concept for recursion.
Rather than explain the code line by line, I think it would be instructive to follow along yourself.  Query each CTE in turn:

SELECT * FROM quota;
SELECT * FROM preferences ORDER BY 1, 2, 3;
SELECT * FROM electees ORDER BY 1, 2, 3;
etc.

The purpose of each CTE should be clear, and the intermediate results are all verifiable at each step.
WITH quota AS (
    SELECT FLOOR(COUNT(*) / (2 + 1)) + 1 AS threshold
        FROM votes
), preferences AS (
    SELECT 1 AS round
         , NULL AS preferred_candidate
         , vote_candidate AS candidate
         , COUNT(*) AS votes
         , CAST(NULL AS INTEGER) AS elected_in_round
        FROM vote_orders
        WHERE vote_order = 1
        GROUP BY vote_candidate
  UNION ALL
    SELECT fallback.vote_order AS round
         , preferred.vote_candidate AS preferred_candidate
         , fallback.vote_candidate AS candidate
         , COUNT(*) AS votes
         , NULL AS elected_in_round
        FROM vote_orders AS preferred
            JOIN vote_orders AS fallback
                ON preferred.vote_id = fallback.vote_id
                AND preferred.vote_order + 1 = fallback.vote_order
        GROUP BY fallback.vote_order, preferred.vote_candidate, fallback.vote_candidate
), electees AS (
    SELECT preferences.round
         , preferences.preferred_candidate
         , preferences.candidate
         , preferences.votes
         , round AS elected_in_round
         , votes - quota.threshold AS surplus
        FROM preferences, quota
        WHERE votes >= quota.threshold
            AND round = (SELECT MIN(round) FROM preferences)
), per_electee_redistribution AS (
    SELECT this_round.round AS round
         , this_round.candidate AS preferred_candidate
         , next_round.candidate AS candidate
         , this_round.votes AS preferred_votes
         , this_round.surplus AS surplus
         , next_round.votes AS fallback_votes
         , this_round.surplus * next_round.votes / (this_round.votes + 0.0) AS redistribution
        FROM electees AS this_round
            LEFT OUTER JOIN preferences AS next_round
                ON this_round.round + 1 = next_round.round
                AND this_round.candidate = next_round.preferred_candidate
        WHERE this_round.elected_in_round = this_round.round
), redistribution AS (
    SELECT round
         , candidate AS beneficiary
         , SUM(redistribution) AS redistribution
        FROM per_electee_redistribution
        GROUP BY round, candidate
  UNION ALL
    SELECT round
         , candidate AS beneficiary
         , -surplus
         FROM electees
         WHERE elected_in_round = round
), redistributed AS (
    SELECT preferences.round AS round
         , preferences.preferred_candidate
         , preferences.candidate
         , preferences.votes
         , COALESCE(redistribution.redistribution, 0) AS redistribution
         , preferences.votes + COALESCE(redistribution.redistribution, 0) AS votes_after_redistribution
        FROM preferences
            LEFT OUTER JOIN redistribution
                ON preferences.round = redistribution.round
                AND preferences.candidate = redistribution.beneficiary
), raw_next_round AS (
    SELECT round
         , NULL AS preferred_candidate
         , candidate
         , SUM(votes) AS votes
         , NULL AS elected_in_round
        FROM preferences
        WHERE round = 1 + (SELECT MIN(round) FROM redistributed)
            AND candidate NOT IN (SELECT candidate FROM electees)
        GROUP BY round, candidate
  UNION ALL
    SELECT *
        FROM preferences
        WHERE round > 1 + (SELECT MIN(round) FROM redistributed)
            AND preferred_candidate NOT IN (SELECT candidate FROM electees)
            AND candidate NOT IN (SELECT candidate FROM electees)
  UNION ALL
    SELECT 1 + (SELECT MIN(round) FROM redistributed) AS round
         , NULL
         , candidate
         , votes
         , elected_in_round
        FROM electees
), redistributed_next_round AS (
    SELECT raw_next_round.round
         , raw_next_round.preferred_candidate
         , raw_next_round.candidate
         , raw_next_round.votes + redistributed.redistribution AS votes
         , raw_next_round.elected_in_round
        FROM raw_next_round
            CROSS JOIN redistributed
        WHERE raw_next_round.round = redistributed.round + 1
            AND raw_next_round.candidate = redistributed.candidate
)
SELECT candidate
     , votes
     , redistribution
     , votes_after_redistribution
    FROM redistributed
    WHERE round = 1
    ORDER BY candidate;

A:

Disclaimer: I'm a SQL Server guy. I might get the particular syntax of MySQL wrong. I apologize if I do.
The first thing I notice is this that subquery shows up over and over again in your query.
SELECT FLOOR((COUNT(*) / (2 + 1)) + 1) threshold
FROM votes

You should use a variable to store the result of this at the beginning of your query and call it each time you would use it later. Something like:
DECLARE @threshold INT
SELECT @threshold := SELECT FLOOR((COUNT(*) / (2 + 1)) + 1) FROM votes

This simplifies your where statements later.
This:
    SELECT (
        (MAX(votes_above_the_threshold) - (
            SELECT FLOOR((COUNT(*) / (2 + 1)) + 1) threshold
            FROM votes
        )) / MAX(votes_above_the_threshold)
    ) ratio

Becomes this:
    SELECT (
        (MAX(votes_above_the_threshold) - threshold) / MAX(votes_above_the_threshold)
    ) ratio

You can apply that through out your query. (In SQL Server I had to leave it duplicated in your Cross Join.)
This subquery shows up a lot in your code too.
        SELECT vote_candidate vote_candidate, COUNT(*) votes_above_the_threshold
        FROM vote_orders
        WHERE vote_order = 1
        GROUP BY vote_candidate
        HAVING votes_above_the_threshold >= @threshold

This a good candidate for a temporary table. I don't know how to create and populate a table in MySQL, so you'll have to look it up. The query should flow something like this though.

Declare @threshold variable.
Set @threshold variable.
Create temporary table to store vote_candidate & votes_above_the_threshold.
Populate temporary table.
Use temporary table in place of subquery in all places the subquery is now.

That should give you a pretty good start. It might take a couple of iterations until you really have something manageable. It's completely possible that you'll find the variable is completely unnecessary once you've implemented the temporary table.


Q:

Document Management System

Is there any Document Management System in Ubuntu?
I tried Alfresco, RavenDB, Owl, Document Manager.
Alfresco, RavenDB are heavy. More than my requirements.
Owl having source issues.
Document Manager im trying to install.

Should keep data on the same machine as I am looking for more of internal purpose.
Should allow to upload Zip files as well. If it extracts Zip it will be a great +
Should allow to send email to preconfigured email addresses
Should allow to upload data of size around 100MB at one go
Should maintain history of documents also deleted documents
Should allow role based document access.
Should be Free :)
It should not do any spoofing on data. Documents are confidential.

Please share your knowledge. Thanks.

A:

LogicalDOC offers both Community(free) and Commercial editions. We used it for some customers and in comparison with Alfresco we can state that LogicalDOC is more easy and lightweight, moreover the support service on the Commercial edition is very fast.
It has a very well documented WebService we used to integrate LogicalDOC with ERP and CRM.


Q:

Logo sides smoothen

I'm about to create an intro video with a 3d font in center of the image.
Using Blender 2.8 and a svg graphic i started.. I extruded the whole graphic and now i see that the sides of the graphic are looking rough and unpolished.
Now i wanted to smoothen them but it always smoothes the whole graphic including the facing forward side wich is directly looking into the camera and the backside aswell..
How can i just smoothen the sides of the Logo without the face and back of the 3d object?
and, additional one object is unable to smoothen

A:

You're going to want to use Smooth Shading and Auto-Smooth Normals here.
To enable Smooth Shading, select the object, right-click, and select Shade Smooth near the top.
Smooth shading essentially takes the normals and averages them out, giving you a smooth look. However, you don't want that to happen on every edge. That results in hard edges being given a weird impossible shading (shown below).

To fix this issue, go to Object Data Properties > Normals  and enable Auto-Smooth. Changing the Auto-smooth angle will cause all the edges with faces at an angle less than or equal to the auto-smooth angle to be smoothed out. For example, if you set the angle to 90 degrees, You'll end up with the smooth shaded cylinder shown in the first image, as the angle between the vertical faces and the top face, is equal to 90 degrees.


Q:

a composite component inside panelgrid is not 'expanded'

Basically, i've been using this pattern again and again inside a panelgrid :
<h:panelGrid columns="2" >
    <h:outputLabel for="heroName" value="Hero Name : " />
    <h:panelGroup>
        <h:inputText label="Hero Name : "
            value="#{ccBean.data.map['heroName']}" id="heroName" />
        <p:message for="heroName" />
    </h:panelGroup>
    ...
</h:panelGrid>

I notice that i duplicate things so much, like the id in h:inputText, which will be duplicated again in for="idValue" for outputLabel, and then again in p:message. The same thing happens with the inputText's label value and h:outputLabel value.
So, i was thinking about making a simple composite component to wrap these up :
<composite:interface>
    <composite:attribute name="id" required="true" />
    <composite:attribute name="label" required="true" />
    <composite:attribute name="value" required="true" />
    <composite:attribute name="includeLabel" required="false" default="false"/>
</composite:interface>

<composite:implementation>
    <h:outputLabel for="#{cc.attrs.id}" value="#{cc.attrs.label}"
            render="#{cc.attrs.includeLabel}" />
    <h:panelGroup>
        <h:inputText label="#{cc.attrs.label}"
            value="#{cc.attrs.value}" id="#{cc.attrs.id}" />
        <p:message for="#{cc.attrs.id}" />
    </h:panelGroup>
</composite:implementation>

And then i make use of the composite components :
<h:panelGrid columns="2" >
    <s:inputText
        id="heroName"
        label="Hero Name : "
        value="#{ccBean.data.map['heroName']}"
            includeLabel="true"
    />
    <s:inputText
        id="heroName2"
        label="Hero Name 2 : "
        value="#{ccBean.data.map['heroName2']}"
            includeLabel="true"
    />
    ...
</h:panelGrid>

That composite component works fine, but the panelGrid now assumes that the s:inputText is one component. Before using the composite component, there are 2 components in one row, which is the outputLabel and the panelGroup.
Is it possible to hint the composite component to 'expand' itself in this case so that it takes up 2 columns instead of 1 column in my panelGrid ?
Thank you !

A:

No, unfortunately not. Your best bet is to create a simple tag file instead.
See also:

How to make a grid of JSF composite component?


Q:

Relationship between motor torque and acceleration

I am working on designing and building a small (1 1/2 lbs), 2-wheeled, differential drive Arduino-controlled autonomous robot. I have most of the electronics figured out, but I am having trouble understanding how much torque the motors will actually need to move the robot. I am trying to use the calculations shown here and the related calculator tool to determine what speed and torque I will need. I will be using wheels 32mm in diameter and one of Pololu's High-Power Micro Metal Gearmotors. I performed the calculations for a robot weight of 2 lbs to be safe and found that the 50:1 HP Micro Metal Gearmotors (625 RPM, 15 oz-in) should theoretically work fine, moving the robot at 3.43 ft/s with an acceleration of around 29 ft/s^2 up a 5-degree incline.
However, I have not found an explanation for several things that I think would be very important to know when choosing drive motors. When the robot is not moving and the motors are turned on at full power, they should need to deliver their full stall torque. Based on the calculations, it seems that any amount of torque can get the robot moving, but the more torque, the faster the robot's acceleration. Is this true? Also, if the power source cannot supply the full stall current of the motors, will the robot not be able to start moving? In my case, I am powering the robot through a 7.2V (6S) 2200mAh NiMH battery pack that can provide around 2.6A continuously, and when it does that the voltage drops to less than 1V. Will this be able to power my motors? Once the robot reaches full speed and is no longer accelerating, theoretically the motors will not be providing any torque, but I do not think this is the case. Is it, and if so, how will I know how much torque they will be providing? Will the motors I chose have enough torque to move my robot?

A:

1) but the more torque, the faster the robot's acceleration: YES
$$
F=\frac{Torque}{wheelradius}
$$
and robot's acceleration is
$$
a=\frac{F}{m}
$$
so, from that equation you can see that linear acceleration of the robot increases with the torque
2)Once the robot reaches full speed and is no longer accelerating, theoretically the motors will not be providing any torque:NO
According to the equation:
$$
T=\frac{P}{w}
$$
that appears in one of the tutorials that you sent us, it is not possible to have 0 torque except that when the power=0. When you are at top speed, angular speed is high and torque is just enough to overcome the different resistances to the motion (friction, air resistance, whatever). It represents a very small value, which makes that the acceleration is close to 0, according to my first and second formula.

A:

Based on the calculations, it seems that any amount of torque can get
  the robot moving

That is true only for a theoretical robot moving in vacuum without any friction in its mechanisms. Normally if you limit a current too much, you won't even get the motor moving without any load, not to mention a whole robot.

the more torque, the faster the robot's acceleration

Yes, the acceleration is directly proportional to the force you apply $$
a=\frac{F}{m}
$$,
which in turn is directly proportianl to the torque
$$F=\frac{T}{R}$$
Both mass and wheel radius are constant, so when you increase torque, the acceleration increses also.

if the power source cannot supply the full stall current of the motors, will the robot not be able to start moving

The torque is proportional to the current you supply, so in the worst case scenario (depleated, undersized battery ant too weak motor) this may happen. However, for your robot and motors you should be fine. Your robot will just accelerate more slowly.

Once the robot reaches full speed and is no longer accelerating, theoretically the motors will not be providing any torque, but I do not think this is the case. Is it, and if so, how will I know how much torque they will be providing?

Again, you forget about the friction. Your robot will stop accelerating when friction will be equal to the torque. For Pololu motors this happens usually at 70-90% of motors no load speed, depending on robot's weight and mechanics.
Generally, in my calculations I usually choose 50% safety margin, and I have never had any trouble. You have some 30%, but that should be fine too.


Q:

How to get the name of child in Firebase with Kotlin

I can`t get the only child-name on the firebase.
  mDatabase = FirebaseDatabase.getInstance().getReference("Diary_Subject")
    if (user != null) {
        mDatabase.child(user.uid).addValueEventListener( object :
            ValueEventListener {
            override fun onCancelled(p0: DatabaseError) {
                TODO("not implemented") //To change body of created functions use File ]| Settings | File Templates.
            }

            override fun onDataChange(snapshot: DataSnapshot) {

                if (snapshot!!.exists()){
                    diarylist.clear()
                val subject = snapshot.toString()
                }
})

This is my firebase

I want my program show only the child name like be
cgnyft

deveg

but it shows

A:

You can use snapshot key:
override fun onDataChange(snapshot: DataSnapshot) {
    for (postSnapshot in snapshot.children) {
        val name = postSnapshot.getKey()
        Log.d("Name",name)
    }
}

If you want to use "Diary_Subject" you can do it like this:
override fun onDataChange(snapshot: DataSnapshot) {
    for (postSnapshot in snapshot.children) {
        val name = postSnapshot.child("Diary_Subject").getValue(String.class)
        Log.d("Name",name)
    }
}


Q:

Apply temperature to specified nodes in Abaqus with Python script

I have a file that contains temperature values for specific coordinates. The format of file is as follows:
X Y Z Temp
The goal is to read this information from a file and apply it, then Abaqus does its magic. I have been given a Python script that builds the model (I suspect this script was generated automatically using the Abaqus GUI). In this file methods such as edges.findAt, faces.findAt and vertices.findAt are used to select the desired location and apply the temperature. Now, I am looking for a way to tell Abaqus to apply temperature at a certain nodal locations. It seems it is possible since when I look at the inp file I see such pattern. Even, if you could give me one example that reads load, temperature, or anything from a file and apply it at specific location it could be really helpful.
--Edit--
The file I have been working with can be found at this link. It contains two files, heat_aba.py and input.txt. My problem is concerned with lines 58-102, to be substituted with a routine in python to read temperatures from input.txt and initialize the model in Abaqus. The coordinates in the input.txt are nodal coordinates.

A:

I'll focus my answer on the Abaqus/Python details, since resources for learning how to open/read files with Python are already widely available.
The findAt method is used for geometric features. For example, to return a Face object at a specified location, use:
f = mdb.models[NAME].rootAssembly.instances[NAME].faces.findAt((x,y,z))

The command is similar for Cell, Edge, and Vertex objects. Note that there may be some ambiguity if more than one object could possibly be associated with the specified coordinates. For example, if the point specified lies on the boundary of multiple Faces (say, it's on an edge), you are responsible to ensure the correct face is returned from findAt. (Also, in one of your comments above you mention that you have a node stored in the variable tmp_node, but that is actually a Vertex object).
Now, once you have a geometric object reference, such as f shown above, you may use that to determine the nodes associated with that geometric region:
node_objects = f.getNodes()

Again, similar methods are available for other geometric entities. Note that getNodes returns a list of Node objects, each of which has various attributes. To get the label or coordinates of the ith Node, you can use:
n = node_object[i].label
c = node_object[i].coordinates

Now, if you are familiar with Python, matching this Node to an entry in the external data file should be easy. If not, that should probably be a separate question here on SO.
To apply the desired temperature to the node, you must use a Temperature object (seeing a pattern of object usage here?). You have an example of that in the (auto-generated?) Python script you linked to, in the lines you mentioned. Simply substitute the correct magnitude and region. For example assuming m and a are the model and root assembly:
# ...various module imports.
myregion = a.Set(name=NAME, nodes=(node_objects[100:101],) )
m.Temperature(name=NAME, createStepName=NAME, magnitudes=(NUMBER,), region=myregion)
a.regenerate()

Notice that both myregion.nodes and magnitudes are ordered, so if you are clever you can define the temperatures for all nodes with a single command.


Q:

why -1 to the power of e is undefined

I'm currently just playing with the number e, I have tried
$$ (-1)^e $$
But my calculator return undefined
I am a bit confused by why undefined is returned. What is the logic/theory behind it? Can this observation be extended to other function as well?

A:

Over the real numbers, the expression $x^y$ (for real $x$ and $y$) is defined to be $e^{y\ln(x)}$. Substituting for $x$ and $y$, the expression you're trying to compute is $e^{e \ln(-1)}$. The expression $\ln(-1)$ is ill-defined, however, because $\ln$ is defined as a function on only the positive reals.
Depending on your background, you might find this interesting: https://en.wikipedia.org/wiki/Complex_logarithm.


Q:

Don't want page to refresh upon viewing - Ionic 2+

When the user views the home screen for the first time - they are being sent there via this.nav.setRoot(Page). This presents an issue when I have three other pages settings root to a page. For example - I go to the home page, which is set root, so that home page data is loaded initially for the first time. Then the user navigates to the message page. Then the user goes back to the home page, the data is reloaded again. I don't want that to happen. I would like to only call it once, but due to setRoot, it refreshes the page. Just like how navCtrl.push(Page) and .pop, the data is not refreshed. I have a hamburger navigation style and that's why I have the set roots for each page in the hamburger navigation.
app.comp.ts
openPage() {
    this.nav.setRoot(Page);
  }
  openPageTwo() {
    this.nav.setRoot(MessagesPage);
  }

How do I override the nav.setRoot refresh? Or use something else entirely?
Thanks

A:

By setting a rootpage using navCtrl.setRoot(), you tell Ionic this page is the begin of the navigation tree of your application. For example, after a login, you should .setRoot(HomePage);
When you want to navigate from HomePage to MessagesPage, you should use navCtrl.push(), to pop the MessagesPage on top of the HomePage. eg; navCtrl.push(MessagesPage);


Q:

Kirchhoff's Law and Highest Potential Node

I'm quite confused on how does Kirchhoff's law work in a closed network (seen as a graph), if current could only flow from a higher potential node to a lower potential node.
In my linear algebra textbook there is a section about applying matrix operations to matrices that represent electrical circuits. The graph representing the current flows between nodes is directed and has directions going from the higher to lower potential node. Then after grounding a node it is possible to solve for the magnitude of the current flows.
What's surprising is that it's possible for the current flows to be negative, which means that it will be in the opposite direction as stated, and the current would be flowing in the wrong direction.
I also don't quite understand how could Kirchhoff's law hold if current could only flow from high potential to low potential nodes. If this is so, then the highest potential node will have no in/out current since current can only flow out and the sum of all current flows must be 0, then inducting we get that all nodes must have no current.

A:

Kirchhoffs current law (KCL) states that the sum of all currents flowing into a node equals zero. KCL deals with the sum of currents at a node and not potential. KVL deals with potential and says that the total voltage around a loop equals zero. Matrix operations are used to solve for system variables.


Q:

In which controller should I place elements that persist throughout the application?

Everything after @posts should persist throughout the application (Like the left sidebar you find on Facebook).
  def index
    @title = "Posts"
    default_order = "content_changed_at DESC"
    params[:order_by] ||= default_order
    @posts = current_user.subscribed_posts.paginate(:page => params[:page],
                                                    :per_page => 5,
                                                    :order => params[:order_by])
    @subscribed_tags = current_user.subscribed_tags
    @recent_posts = current_user.posts.limit(5).order("created_at DESC")
    @tags= Tag.limit(20).order("ID asc")
    @user = current_user
  end

views/layout/_sidebar.html.erb:

      <% avatar = image_tag(current_user.avatar.url(:thumb), :class => "authenticated-avatar") %>
      <%= link_to avatar, "/users/#{current_user.id}" %>
      <%= link_to "#{current_user.username}", "/users/#{current_user.id}", :class => "authenticated-username" %>

    <%= form_for(@user, :remote => true) do |f| %>

        <%= f.label :subscribed_tag_names %>

        <%= f.autocomplete_field :subscribed_tag_names, autocomplete_tag_name_posts_path, :"data-delimiter" => ' ', :class => "autocomplete_field" %>

        <%= f.submit :class => "user_subscribed_tag_names_submit" %>

    <% end %>

      <% @subscribed_tags.each do |subscribed_tag| %>
        <%= link_to "#{subscribed_tag.name}(#{subscribed_tag.posts.count})", unsubscribe_tags_path(:unsubscribed_tag_name => subscribed_tag.name) %>
      <% end %>

Recent Posts

        <% @recent_posts.each do |recent_post| %>

<%= link_to recent_post.title, recent_post %>

        <% end %>

      <% @tags.each do |tag| %>
        <%= tag.name %>
        <%= tag.posts.count %>
      <% end %>

  <% end %>

Where should I place the code in the controller if I want them to persist throughout the application? (I would like to see some example code if possible).

A:

If it persists throughout the application, i.e. for every actions of all controllers, you might place it in a before_filter in the application controller.
Add a before_filter to the application controller as :
before_filter :find_recent_posts_and_tags

And define it (as private) :
private
def find_recent_posts_and_tags
  # define your instance variables
end

More about filters here and here.


Q:

How get a collection of models with no tags assigned - Laravel

I am using rtconner/laravel-tagging package to get tags functionality to my app.
I can count attached tags  by $o->tags->count()
I can loop the tags by a foreach: @foreach($o->tags as $t).
print attached tags by
the problem
Now I want to get a collection of random 10 Quotation with no tags attached.
While I can print a random 10 pieces with a given attribute:
$object = Quotation::where('deepness', null)->get()->random(10);

(Note: I have a random scope defined in the model, irrelevant for  my issue)
... but this code, cloned from another model doesn't work:
$object = Quotation::whereHas('tags','>',0)->get()->random(10);

It produces this error message:

FatalThrowableError in Builder.php line 880:
Type error: Argument 2 passed to Illuminate\Database\Eloquent\Builder::whereHas() must be an instance of Closure, string given

I have also tried to execute this query
$object = Quotation::has('tags')->get()->random(10);

but I got this:
```
BadMethodCallException in Builder.php line 2431:
Call to undefined method Illuminate\Database\Query\Builder::tags()
```
Note 2: In the source model (the one I cloned from) the relation was counting a hasMany relation.
to do
Please help me to create the collection of Quotations with no tags assigned

A:

Had the same problem and solved it this way:
$objects = Quotation::all();

$objects = $objects->filter(
                function ($object, $key) {
                    return $object->tags->count() > 0;
                }
            )->random(10);

Hope issues still relevant :)


Q:

How can I determine the trim level on my 2015 Kia Optima?

I know the question is kinda stupid but yesterday I bought a Kia Optima 2015, there's no initials on the back of the car like (EX, LX, SX, SXL). It's a used car and I'm from Iraq. I checked all the VIN decoders websites the only thing I got is that:
Manufacturer: Kia Korea
Brand: Kia
Model: Optima III
Engine: N/A
Region/Plant: Hwa-Sung Korea
Check: B
Year: 2015

And I checked some videos on Youtube, All the models have phone dialer  buttons on the steering wheel but my car don't have these buttons there's only radio control and the service control buttons on the steering wheel?
And I checked the VIN on Kia website didn't recognize the VIN? So I don't know what is the model and where it made for (USA, Canada, Europe, Asia)?
UPDATE:
the first eleven characters of the VIM is KNAGN418BFA. and these are some specs of the car:
for the engine I'm not sure about it but I think it's 2.0 LT turbo. for the wheels it's 18. and for the lights it's not LED but it has a LED tool over the fog lights. for the interior, the steering wheel half leather and half wooden, and for the seats are all black leather. and the door trims are wooden.

A:

There's a few things you can use to try and work it out if you can't get hold of a Kia dealer to decode the VIN.
Assuming the specs match the US versions then you can probably puzzle it out from the  options:
Engine:
If it's the 2.4 then that narrows it down to LX, EX or SX spec, the 2.0T means it's SX Turbo or SXL Turbo.
Wheels:
If it's 16" Wheels then it's an LX, 18" means it's SX or SX Turbo, 18" Chrome wheels means SXL Turbo
Lights:
If the car has LED front fog lights then it's an SXL Turbo
Interior:
If the steering wheel and seats are NOT leather and it has manual air-con then the it's an LX spec.
If the door trim inserts are wooden then it's an EX


Q:

Getting my Post's ID to be random (but unique) string

Instead of just seeings my posts page as /posts/1 and so on, I'd prefer to have a random string thats more something like this /posts/299432. I did some research and found this answer on S.O.
How to make model IDs in Rails unpredictable and random
It does work, but I don't think it created a unique ID for the post, so there's a small probability that the post's id will get duplicated I would think.
My question here is will that method create unique strings to use? or should I be doing something differently to generate these unique random ID's for my posts??
Thanks

A:

Here's a better method. You can use Hashids.

A:

Yes it will create a unique ID. From the highest voted answer:
while Model.where(:id => self.id).exists?

Meaning it will keep generating a new random number until it finds one that doesn't exist yet. (Which is most likely the first time around.)


Q:

Flutter localisations : Auto generate key - value in intl_en.arb as we type code in dart file

Is there a shortcut, extension that lets me add Keys and values into ARB files (default and other languages) as I type my code in dart file?
For ex: In my build method, I want to introduce/add a new Text widget and instead of following process of first adding the key-value in default ARB then copying into all other languages and finally coming to dart file and adding it as S.of(context).key, do it reverse and save time?

A:

You can try to use Flutter Intl extension for VS Code and Android Studio that can generate keys and values in your intl arb files. Take a look at the "Extract to ARB files" section of their documentation.


Q:

Point-free lens creation does not type check

In the function test, I traverse over a list, generate lenses from it's members, and then print some data. This works when I use a pointful call style. It fails to typecheck when I make it point-free.
Why is this the case, and how can I solve this problem?
It looks like to me that GHC is not retaining the information that the higher-ranked f (in the lens) is a Functor when using point-free style, but I'm not too sure.
I'm using GHC 7.8.3
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE TemplateHaskell #-}

import Control.Lens
import Control.Monad
import Data.List
import Data.Maybe

type PlayerHandle = String

data Player = Player { _playerHandle :: PlayerHandle }
makeLenses ''Player

data GameState = GameState { _gamePlayers :: [Player] }
makeLenses ''GameState

type PlayerLens = Lens' GameState Player

getPlayerLens :: PlayerHandle -> PlayerLens
getPlayerLens handle f st = fmap put' get'
    where
        players = st^.gamePlayers
        put' player = let
            g p = case p^.playerHandle == handle of
                True -> player
                False -> p
            in set gamePlayers (map g players) st
        get' = f $ fromJust $ find (\p -> p^.playerHandle == handle) players

printHandle :: GameState -> PlayerLens -> IO ()
printHandle st playerLens = do
    let player = st^.playerLens
    print $ player^.playerHandle

test :: GameState -> IO ()
test st = do
    let handles = toListOf (gamePlayers.traversed.playerHandle) st
    --
    -- Works: Pointful
    --forM_ handles $ \handle -> printHandle st $ getPlayerLens handle
    --
    -- Does not work: Point-free
    forM_ handles $ printHandle st . getPlayerLens

main :: IO ()
main = test $ GameState [Player "Bob", Player "Joe"]

Test.hs:45:38:
    Couldn't match type `(Player -> f0 Player)
                         -> GameState -> f0 GameState'
                  with `forall (f :: * -> *).
                        Functor f =>
                        (Player -> f Player) -> GameState -> f GameState'
    Expected type: PlayerHandle -> PlayerLens
      Actual type: PlayerHandle
                   -> (Player -> f0 Player) -> GameState -> f0 GameState
    In the second argument of `(.)', namely `getPlayerLens'
    In the second argument of `($)', namely
      `printHandle st . getPlayerLens'
Failed, modules loaded: none.

A:

Lens' is a higher ranked type, and type inference is very brittle with those, and basically only works when all functions that take higher-rank arguments have explicit signatures to do so.  This works very badly with point-free code using . and the like, which don't have such signatures. (Only $ has a special hack to sometimes work with this.)
The lens library itself gets around this by making sure that all functions that use a lens argument don't have a fully general lens type for it, but only a type which indicates the precise lens feature they use.
In your case, it's the printHandle function which is the culprit for this.  Your code will compile if you change its signature to the more precise
printHandle :: s -> Getting Player s Player -> IO ()

I found this signature by deleting the original one and using :t printHandle.
EDIT (and EDIT again to add ALens'): If you think the "cure is worse than the illness", then depending on your needs another option, which doesn't require you to change your function signatures, but which does require you to do some explicit conversion, is to use the ALens' type instead.  You then need to change two lines:
type PlayerLens = ALens' GameState Player
...
printHandle st playerLens = do
    let player = st^.cloneLens playerLens
...

ALens' is a non-higher rank type that has been cleverly constructed so that it contains all the information needed to extract a general lens from it with cloneLens.  But it still is a special subtype of a lens (the Functor has just been particularly cleverly chosen) so you only need explicit conversion from ALens' to Lens', not the other way.
A third option, which may not be the best for lenses, but which usually works for higher-rank types in general, is to turn your PlayerLens into a newtype:
newtype PlayerLens = PL (Lens' GameState Player)

Of course this now needs both wrapping and unwrapping in several places in your code. getPlayerLens was particularly disrupted:
getPlayerLens :: PlayerHandle -> PlayerLens
getPlayerLens handle = PL playerLens
    where
        playerLens f st = fmap put' get'
            where
                players = st^.gamePlayers
                put' player = let
                    g p = case p^.playerHandle == handle of
                        True -> player
                        False -> p
                    in set gamePlayers (map g players) st
                get' = f $ fromJust $ find (\p -> p^.playerHandle == handle) players


Q:

Unable to build PlusClient

    import com.google.android.gms.common.ConnectionResult;
    import com.google.android.gms.common.GooglePlayServicesClient.ConnectionCallbacks;
    import com.google.android.gms.common.GooglePlayServicesClient.OnConnectionFailedListener;
    import com.google.android.gms.plus.GooglePlusUtil;
    import com.google.android.gms.plus.PlusClient;
    import android.os.Bundle;
    import android.app.Activity;
    import android.app.ProgressDialog;
    import android.content.Intent;
    import android.content.IntentSender.SendIntentException;
    import android.util.Log;
    import android.view.Menu;
    import android.view.View;
    import android.widget.Button;
    import android.widget.Toast;

    public class MainActivity extends Activity implements ConnectionCallbacks,
            OnConnectionFailedListener {

        private static final int REQUEST_CODE_RESOLVE_ERR = 7;
        private ProgressDialog mConnectionProgressDialog;
        private PlusClient mPlusClient;
        private ConnectionResult mConnectionResult;
        private String TAG = "GmailLogin";

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);

            int errorCode = GooglePlusUtil.checkGooglePlusApp(this);
            if (errorCode != GooglePlusUtil.SUCCESS) {
                GooglePlusUtil.getErrorDialog(errorCode, this, 0).show();
            } else {

                 mPlusClient = new PlusClient.Builder(this, this, this)
                 .setVisibleActivities( "http://schemas.google.com/AddActivity",
                 "http://schemas.google.com/BuyActivity").build();

                mConnectionProgressDialog = new ProgressDialog(this);
                mConnectionProgressDialog.setMessage("Signing in...");

                Button signInButton = (Button) findViewById(R.id.sign_in_button);
                signInButton.setOnClickListener(new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {

                        if (mConnectionResult == null) {
                            mConnectionProgressDialog.show();
                        } else {
                            try {
                                mConnectionResult
                                        .startResolutionForResult(
                                                MainActivity.this,
                                                REQUEST_CODE_RESOLVE_ERR);
                            } catch (SendIntentException e) {
                                // Try connecting again.
                                mConnectionResult = null;
                                mPlusClient.connect();
                            }
                        }
                    }
                });
            }

        }

        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            // Inflate the menu; this adds items to the action bar if it is present.
            getMenuInflater().inflate(R.menu.main, menu);
            return true;
        }

        @Override
        public void onConnectionFailed(ConnectionResult result) {
            if (result.hasResolution()) {
                try {
                    result.startResolutionForResult(this, REQUEST_CODE_RESOLVE_ERR);
                } catch (SendIntentException e) {
                    mPlusClient.connect();
                }
            }
            // Save the result and resolve the connection failure upon a user click.
            mConnectionResult = result;
        }

        @Override
        protected void onActivityResult(int requestCode, int responseCode,
                Intent intent) {
            if (requestCode == REQUEST_CODE_RESOLVE_ERR
                    && responseCode == RESULT_OK) {
                mConnectionResult = null;
                mPlusClient.connect();
            }
        }

        @Override
        public void onConnected() {
            String accountName = mPlusClient.getAccountName();
            Toast.makeText(this, accountName + " is connected.", Toast.LENGTH_LONG)
                    .show();
        }

        @Override
        public void onDisconnected() {
            Log.d(TAG, "disconnected");
        }

        @Override
        protected void onStart() {
            super.onStart();
            mPlusClient.connect();
        }

        @Override
        protected void onStop() {
            super.onStop();
            mPlusClient.disconnect();
        }

        }

I cannot compile this code because it says:

PlusClient.Builder cannot be resolved to a type

at
mPlusClient = new PlusClient.Builder(this, this, this)
        .setVisibleActivities( "http://schemas.google.com/AddActivity",
        "http://schemas.google.com/BuyActivity").build();

also in onConnected()
I get null for accountName
String accountName = mPlusClient.getAccountName();

A:

If anybody still has this problem: the PlayClient is deprecated now.
The "new" way to go is described here: http://android-developers.blogspot.com/2014/02/new-client-api-model-in-google-play.html
mClient = new GoogleApiClient.Builder(this)
        .addApi(Drive.API)
        .addScope(Drive.SCOPE_FILE)
        .addApi(Plus.API, plusOptions)
        .addScope(Plus.SCOPE_PLUS_LOGIN)
        .addConnectionCallbacks(this)
        .addOnConnectionFailedListener(this)
        .build();

A:

The error is because PlayClient is deprecated now, as Luigi04 states.
As a work around, I got this working by downgrading the play services version in the gradle dependencies to 'com.google.android.gms:play-services:6.1.71', as stated here:
https://stackoverflow.com/a/27637059/2161698


Q:

How to use .hasClass with $(this)?

I have a header on my page, and block with boxes. That boxes represents my projects. When I click on one of them it is suppose to change my header background.

First

Second

And my function:
function headerProjBackground(){
 if($(this).hasClass('job-one')){
  console.log('Hi!');
  $('header').css('background-image': 'url(css/images/first-thing.png)');
 }
 if($(this).hasClass('job-one')){
   console.log('Hello!');
  $('header').css('background-image': 'url(css/images/second-thing.png)');
 }
}

But it is not working. It can't understand my (this). There are no errors in the console. So this is logical mistake.

A:

Outside of the onclick attribute, this is no longer defined. You can fix this in (at least) two ways.
Alt 1: Pass this as a parameter:

function headerProjBackground(clicked) {
    //Replace this with clicked in the code of the function.

Alt 2: Do the event binding with jQuery instead of with HTML attributes:

$(".backgroundchanger").click(function() {
    //Put the same code as for headerProjBackground() in your question.
    //Here you can use the this keyword.
});

And some further thoughts: The way you have coded this is not very good if you want it compact (and clear). So lets try to improve it some! If you go with Alt 2 you could use a custom data- attribute to shorten the code:

//If something that has the data-background attribute is clicked.
$('[data-background]').click(function() {
    //Get the value from the data-background attribute, and use that as background image.
    var background = $(this).attr('data-background');
    $('header').css('background-image': 'url(' + background + ')');
});

Or, if you use Alt 1, you could just pass the desired background url as a parameter instead of this.


Q:

How to NOT overload the std::map::at member function in the case where the two template types are the same?

I have a here a bidirectional map. I make it form 0. I defined member functions like insert count size and others and of course a function at which returns a reference to the mapped value of the element identified with the given key. Until type A is not the same with type B everything works fine, but when type A is the same with type B i get an error that i try to overload this function at, which is correct :( But my mind can`t help me with a method to solve this error. Maybe you can give me an example or tell me what i can do in this case :)
template <class A,class B>

class BidirectionalMap
{
public:
    void insert(A a,B b)
    {
        m1.insert(std::pair<A,B> (a,b));
        m2.insert(std::pair<B,A> (b,a));
    }
    BidirectionalMap& operator =(BidirectionalMap &a)
    {
        m1=a.m1;
        m2=a.m2;
        return *this;
    }
    A& at(const A& a)
    {
        if(m1.find(a)!=m1.end()) return m1.at(a);
        else return m2.at(a);
    }
    const B& at(const A& b) const
    {
        return m1.at(b);
    }
    const A& at(const B& a) const
    {
        return m2.at(a);
    }
    int size() const
    {
        return m1.size();
    }
    int count(const A& a) const
    {
        return m1.count(a);
    }
    int count(const B& b) const
    {
        return m2.count(b);
    }
    B& operator[](const A& a)
    {
        return m1[a];
    }
    A& operator[](const B& b)
    {
        return m2[b];
    }
private:
    std::map<A,B> m1;
    std::map<B,A> m2;
};

And what if i cannot modify this sequence in main()?
  BidirectionalMap<int, int> f;
  f.insert(3, 18);
  f.insert(8, 2);
  f.insert(7, 5);
  f.insert(9, 1);
  const BidirectionalMap<int, int> cf = f;

  if( f.at(5) == 7 &&
      f.count(12) == 0 &&
      f.at(8) == 2)
  {
    yourMark = cf[18] + cf[9];
  }

A:

Implement at in a CRTP base class.
template<class D, class A, class B>
struct crtp_at {
  D* self() { return static_cast<D*>(this); }
  D const* self() const { return static_cast<D const*>(this); }
  const B& at(const A& b) const {
    return self()->m1.at(b);
  }
  const A& at(const B& a) const {
    return self()->m2.at(a);
  }
  B& at(const A& b) {
    return self()->m1.at(b);
  }
  A& at(const B& a) {
    return self()->m2.at(a);
  }
};
template<class D, class A>
struct crtp_at<D,A,A> {
  D* self() { return static_cast<D*>(this); }
  D const* self() const { return static_cast<D const*>(this); }
  A& at(const A& a) {
    if(self()->m1.find(a)!=self()->m1.end()) return self()->m1.at(a);
    else return self()->m2.at(a);
  }
  A const& at(const A& a) const {
    if(self()->m1.find(a)!=self()->m1.end()) return self()->m1.at(a);
    else return self()->m2.at(a);
  }
};

Then your class uses the above like:
template <class A,class B>
class BidirectionalMap:public crtp_at< BiDirectionalMap<A,B>, A, B >
{
  // rest of your code
};

however, I would advise actually blocking at in that case, and any other method where it is not clear which way you are going.
You should have methods that clearly go one way or the other in your code for cases like short <-> double anyhow.


Q:

Converting month name in given date into month number

Possible Duplicate:
PHP date format converting

I have a date like 2012-september-09. How to convert this into 2012-09-09 using PHP?

A:

Try this
Change

<?php echo date('Y-m-d',strtotime('2012-september-09'));?>

 To

<?php echo date('Y-m-d',strtotime('09-september-2012'));?>


Q:

IC which can drive an RGB input to two outputs

Is there a way to duplicate a wire from an RGB source without degrading the signal. I wish to take a wire and split it into two wires without the current halving. (edit) 75 ohms and one RGB signal wire i.e just the blue line.

A:

It depends on what you want to do with the signals once you separate them. It also depends on the specific type of "RGB" interface you are dealing with: 3-wire, 4-wire, or 5-wire.
The 3-wire interface has only the R,G & B signals and carries the sync information (usually) on the G wire. Aka: sync-on-green. The 4-wire interface has an additional wire which carries both H-Sync (horizontal sync) and V-Sync (vertical sync) OR'ed together into one electrical signal. The 5-wire interface has two additional wires - one for H-Sync and one for V-Sync.
The R,G, & B signals are almost always "75 Ohm signals", meaning they have a source impedance of 75 Ohms and they must be terminated with 75 Ohms at the receiving end (generally a video monitor, but possibly a repeater input, splitter input, and similar). The connecting cable must have a characteristic impedance of 75 Ohms as well, and is usually co-axial cable.
On the other hand the sync signals in a 4 or 5-wire hook-up are typically NOT 75 Ohms, they are essentially TTL logic levels, most typically 0-5 volts. That's typical, there are systems where these signals are also "75 Ohm signals" and are therefore carried by coax cable. If you are dealing with a PC, laptop, TV-set with auxiliary "VGA" or "RGB" input, these are almost universally TTL signals. Sometimes these signals are terminated at the receiving end, sometimes not. If terminated you will find anywhere from 470 to 2,000 Ohms as terminators.
Now, to split the RGB signal passively (not using a powered splitter, but a simple "Y" connection) you have several problems to overcome. The first is not losing signal amplitude when you connect the receiving ends to two 75 Ohm loads simultaneously. This will halve the signal amplitude and cause various problems, primarily loss of contrast in the image. In a 3-wire system the sync-on-green signal may be so adversely affected that the connected monitor(s) will not be able to acquire sync. Depends on the actual monitors you are connecting and how much internal gain they use to recover the RGB signals. There is one cheap trick fix I describe below for this situation which will work in some instances.
The sync signals present less of a problem if they are the TTL type (very typical in PC and Laptop environments). These you can usually split with no ill effects because of the way they are usually lightly terminated at the receiving end. If the syncs are 75-Ohm, you have more of a problem. The cheap trick described next might even work for these.
Cheap Trick: Remove the 75-Ohm termination resistors from one of the monitors. If the connecting cables are "short enough" and the signals you are sending are low-resolution (e.g. 800x600 @ 60 Hz), you might get a suitable image. There are lots of variants possible with this trick. If you have two monitors, leave the termination resistors in the far monitor and remove them from the close monitor. Daisy chain the monitors together, remove the termination from the first monitor and run the signals to the second monitor right from the connector of the first monitor, but leave the terminators in the second monitor. Don't worry about the sync termination resistors unless all else fails. Leave them intact in both monitors.
Your best bet is to try both monitors first with their original 75-Ohm termination resistors intact, and adjust the contrast on each monitor to see if you can get a decent enough picture on the screen. The "Contrast" control is actually the video gain control. Depending on the specific monitor this gain might have enough high-end margin to squeak you by. (The "Brightness" control is actually video offset and will have much less of an effect on weak signals.)
If all else fails, buy a splitter. They are actually pretty cheap these days.


Q:

Fazer handle do jQuery-Tools acompanhar um time

Utilizo o jQuery-Tools pra criar um efeito personalizado de scroll em uma div como no exemplo a seguir:

"use strict";

var id_label_ms = document.getElementById("count_label_ms");
var range = document.getElementById("area");
var cronometro = {};
var countms = 0;
var counterms;
var cronometroAtivo = false;

window.onload = function () {
  areaMusica();

  var scroll = $(".area");

  $(":range").rangeinput({
    onSlide: function(ev, step)  {
      scroll.css({left: -step});
    },
    progress: true,
    change: function(e, i) {
      scroll.animate({left: -i}, "fast");
    },
    speed: 0
  });
};

function areaMusica(){
  var k = 1; var tabela = '';
  tabela = '
';
  for (var i = 0; i < 2; i++) {
    if(i < 1){
      tabela += '
';
      for (var j = 1; j < 62; j++) {
        if(j == 1){
          tabela += 'start	';
        }else{
          tabela += '	';
          k++;
        }
      }
      tabela += '
';
    }else{
      tabela += '
	';
      for(var j = 1; j < 61; j++) {
        if(j % 5 == 0){
          tabela += ''+seconds2time((j*2)-10) +"min - "+seconds2time(j*2)+'min	';
        }
      }
      tabela += '
'
    }
  }
  tabela += '
';
  document.getElementById('area').innerHTML = tabela;
}

function seconds2time(seconds){
  var minutes = Math.floor((seconds ) / 60);
  var seconds = seconds - (minutes * 60);
  var time = "";

  if(minutes < 10){
    minutes = "0"+minutes;
  }
  if(seconds == 0){
    seconds = "0"+seconds;
  }

  time = minutes+":"+seconds;
  return time;
}

function iniciar(elemento){
  var icon = elemento.dataset.option;
  range.style.left = 0;
  if(icon === "play"){
    start();
    elemento.src = "http://cdn.flaticon.com/svg/70/70419.svg";
    elemento.title = "Pausar";
    elemento.dataset.option = "pause";
  }else{
    stop();
    elemento.src = "http://cdn.flaticon.com/svg/70/70409.svg";
    elemento.title = "Tocar";
    elemento.dataset.option = "play";
  }
}

function start() {
  if (cronometroAtivo) return;
  cronometroAtivo = true;
  counterms = setInterval(function () {
    range.style.left = range.style.left.substring(0, range.style.left.length-2) - 1;
    countms = countms + 1;
    id_label_ms.innerHTML = countms / 100 + " s";
  }, 10);
};

function stop(){
  range.style.left = 0;
  cronometroAtivo = false;
  countms = 0;
  id_label_ms.innerHTML = countms + " s";

  clearInterval(counterms);
  cronometroAtivo = false;
};
.containerArea{
  height: auto;
  width: 1030px;
  border: 1px rgb(89,89,89) solid;
  margin-top: 30px;
  background: rgb(173,234,234);
}

.slider {
  position:absolute;
  cursor:pointer;
  height:1px;
  border:2px solid rgb(179,179,179);
  width:1000px;
  -moz-border-radius:2px;
  -webkit-border-radius:2px;
}

#scrollwrap {
  margin-top:30px;
  margin-left:10px;
  overflow:hidden;
  width: 1000px;
  margin-left:5px;
  height:auto;
}

.container{
  min-width: 23px;
  height: 26px;
  border: 1px rgb(140, 173, 188) double;
}

.containerFaixa{
  width: 1000px;
  height: 26px;
  border: 1px rgb(140, 173, 188) double;
  background: rgb(216,216,191);
  border-radius: 7px;
}

.faixa{
  color: rgb(0, 0, 0);
  text-align: center;
  font-size: 12px;
  font-weight: bold;
  font-family: inherit;
  font-style: inherit;
  text-decoration: inherit;
  text-align: center;
  line-height: 1.85em;
}

.tempo{
  color: rgb(0, 0, 0);
  font-size: 10px;
  font-weight: inherit;
  font-family: 'Courier New', Courier, monospace;
  font-style: inherit;
  text-decoration: inherit;
}

.progress {
  background-color:rgb(179,179,179);
  height:3px;
  position:absolute;
  width:0;
}

.handle {
  position: absolute;
  z-index:4;
  width: 28px;
  height: 115px;
  background-position: top center;
  background-size: 25px 30px;
  background-image: url(http://cdn.flaticon.com/svg/17/17736.svg);
  background-repeat: no-repeat;
}

.area {
  position:relative;
  font:bold 90px  sans-serif;
  height:auto;
}

.range {
  display:none;
}

  <input id="range" type="range" max="795" value="0" />

    Count:

A intenção é criar um player de áudio personalizado, quando clicar em play, o handle começar a se movimentar junto com o count. Cada coluna da tabela representa 2 segundos.
Problema 1: Esse meu exemplo funciona localmente, mas não consegui fazer funcionar online, tanto aqui no Stack Snippets, quanto no jsFiddle e tanto quanto no codeOpen. A contagem inicia mas o handle não começa a se mover, criei um zip pra quem quiser testar localmente.
Essa nem é a questão principal, mas gostaria de entender o que há de errado pra que nessas ferramentas online ele não funcione corretamente?
Problema 2: Sei que a velocidade constante do handle deveria ser:  ou seja 2/24 = 0,0834. Então, teoricamente na função start o calculo deveria ser:
range.style.left = range.style.left.substring(0, range.style.left.length-2) - 0,0834;

Porém não está se movimentando corretamente, está se movimentando muito devagar, tentei ajustar para mais e para menos, mas sempre parece ficar ou muito lento, ou muito rápido, isso também afeta o problema 3.
Problema 3: Desejo fazer um handle que possa ser personalizado, localmente se eu altero o estilo do handle, como no exemplo a seguir:

"use strict";

var id_label_ms = document.getElementById("count_label_ms");
var range = document.getElementById("area");
var cronometro = {};
var countms = 0;
var counterms;
var cronometroAtivo = false;

window.onload = function () {
  areaMusica();

  var scroll = $(".area");

  $(":range").rangeinput({
    onSlide: function(ev, step)  {
      scroll.css({left: -step});
    },
    progress: true,
    change: function(e, i) {
      scroll.animate({left: -i}, "fast");
    },
    speed: 0
  });
};

function areaMusica(){
  var k = 1; var tabela = '';
  tabela = '
';
  for (var i = 0; i < 2; i++) {
    if(i < 1){
      tabela += '
';
      for (var j = 1; j < 62; j++) {
        if(j == 1){
          tabela += 'start	';
        }else{
          tabela += '	';
          k++;
        }
      }
      tabela += '
';
    }else{
      tabela += '
	';
      for(var j = 1; j < 61; j++) {
        if(j % 5 == 0){
          tabela += ''+seconds2time((j*2)-10) +"min - "+seconds2time(j*2)+'min	';
        }
      }
      tabela += '
'
    }
  }
  tabela += '
';
  document.getElementById('area').innerHTML = tabela;
}

function seconds2time(seconds){
  var minutes = Math.floor((seconds ) / 60);
  var seconds = seconds - (minutes * 60);
  var time = "";

  if(minutes < 10){
    minutes = "0"+minutes;
  }
  if(seconds == 0){
    seconds = "0"+seconds;
  }

  time = minutes+":"+seconds;
  return time;
}

function iniciar(elemento){
  var icon = elemento.dataset.option;
  range.style.left = 0;
  if(icon === "play"){
    start();
    elemento.src = "http://cdn.flaticon.com/svg/70/70419.svg";
    elemento.title = "Pausar";
    elemento.dataset.option = "pause";
  }else{
    stop();
    elemento.src = "http://cdn.flaticon.com/svg/70/70409.svg";
    elemento.title = "Tocar";
    elemento.dataset.option = "play";
  }
}

function start() {
  if (cronometroAtivo) return;
  cronometroAtivo = true;
  counterms = setInterval(function () {
    range.style.left = range.style.left.substring(0, range.style.left.length-2) - 1;
    countms = countms + 1;
    id_label_ms.innerHTML = countms / 100 + " s";
  }, 10);
};

function stop(){
  range.style.left = 0;
  cronometroAtivo = false;
  countms = 0;
  id_label_ms.innerHTML = countms + " s";

  clearInterval(counterms);
  cronometroAtivo = false;
};
.containerArea{
  height: auto;
  width: 1030px;
  border: 1px rgb(89,89,89) solid;
  margin-top: 30px;
  background: rgb(173,234,234);
}

.slider {
  position:absolute;
  cursor:pointer;
  height:1px;
  border:2px solid rgb(179,179,179);
  width:1000px;
  -moz-border-radius:2px;
  -webkit-border-radius:2px;
}

#scrollwrap {
  margin-top:30px;
  margin-left:10px;
  overflow:hidden;
  width: 1000px;
  margin-left:5px;
  height:auto;
}

.container{
  min-width: 23px;
  height: 26px;
  border: 1px rgb(140, 173, 188) double;
}

.containerFaixa{
  width: 1000px;
  height: 26px;
  border: 1px rgb(140, 173, 188) double;
  background: rgb(216,216,191);
  border-radius: 7px;
}

.faixa{
  color: rgb(0, 0, 0);
  text-align: center;
  font-size: 12px;
  font-weight: bold;
  font-family: inherit;
  font-style: inherit;
  text-decoration: inherit;
  text-align: center;
  line-height: 1.85em;
}

.tempo{
  color: rgb(0, 0, 0);
  font-size: 10px;
  font-weight: inherit;
  font-family: 'Courier New', Courier, monospace;
  font-style: inherit;
  text-decoration: inherit;
}

.progress {
  background-color:rgb(179,179,179);
  height:3px;
  position:absolute;
  width:0;
}

.handle {
  position: absolute;
  z-index:4;
  width: 28px;
  height: 55px;
  border: rgb(161, 233, 240) solid;
  background-position: top center;
  background-size: 25px 30px;
  background-image: url(http://cdn.flaticon.com/svg/17/17736.svg);
  background-repeat: no-repeat;
  box-shadow:  0px 0px 0px 1px rgb(0, 0, 0),inset 0px 0px 0px 1px rgb(0, 0, 0);
}

.area {
  position:relative;
  font:bold 90px  sans-serif;
  height:auto;
}

.range {
  display:none;
}

  <input id="range" type="range" max="795" value="0" />

    Count:

O tempo do movimento do handle ao clicar no botão start fica estranho e aparentemente fica mais rápido sendo que não há alteração nenhuma na função:
function start() {
  if (cronometroAtivo) return;
  cronometroAtivo = true;
  counterms = setInterval(function () {
    range.style.left = range.style.left.substring(0, range.style.left.length-2) - 1;
    countms = countms + 1;
    id_label_ms.innerHTML = countms / 100 + " s";
  }, 10);
};

A:

Referente ao problema 1:
seu teste https://jsfiddle.net/xjyofffu/
meu teste
https://jsfiddle.net/nq72w31a/
Ambos não funcionando porém da p/ ter uma idéia que a ordem de execução dos scripts faz diferença, e o jsfiddle esta arbitrando isso.
Outro ponto importante, dentro desse plugin jquery.tools.min.js tem implementado IFRAME  coisa que o JSFiddle não aceita.
Referente ao Problema 2:
Temos os blocos com 23px + 1px de padding + 1 px de borda, da 25px, mas eles estão espaçados por causa do table então tens que tirar o cellspacing deixa ele zerado, então teremos 25px por bloco, ai podemos começar a fazer uma formula e alguns testes ficaria assim:

"use strict";

var id_label_ms = document.getElementById("count_label_ms");
var range = document.getElementById("area");
var cronometro = {};
var countms = 0;
var counterms;
var cronometroAtivo = false;

window.onload = function () {
  areaMusica();

  var scroll = $(".area");

  $(":range").rangeinput({
    onSlide: function(ev, step)  {
      scroll.css({left: -step});
    },
    progress: true,
    change: function(e, i) {
      scroll.animate({left: -i}, "fast");
    },
    speed: 0
  });
  //iniciar( document.getElementById("teste") );
};

function areaMusica(){
  var k = 1; var tabela = '';
  tabela = '
';
  for (var i = 0; i < 2; i++) {
    if(i < 1){
      tabela += '
';
      for (var j = 1; j < 62; j++) {
        if(j == 1){
          tabela += '	';
        }else{
          tabela += '	';
          k++;
        }
      }
      tabela += '
';
    }else{
      tabela += '
	';
      for(var j = 1; j < 61; j++) {
        if(j % 5 == 0){
          tabela += ''+seconds2time((j*2)-10) +"min - "+seconds2time(j*2)+'min	';
        }
      }
      tabela += '
'
    }
  }
  tabela += '
';
  document.getElementById('area').innerHTML = tabela;
}

function seconds2time(seconds){
  var minutes = Math.floor((seconds ) / 60);
  var seconds = seconds - (minutes * 60);
  var time = "";

  if(minutes < 10){
    minutes = "0"+minutes;
  }
  if(seconds == 0){
    seconds = "0"+seconds;
  }

  time = minutes+":"+seconds;
  return time;
}

function iniciar(elemento){
  var icon = elemento.dataset.option;
  range.style.left = 0;
  if(icon === "play"){
    start();
    elemento.src = "http://cdn.flaticon.com/svg/70/70419.svg";
    elemento.title = "Pausar";
    elemento.dataset.option = "pause";
  }else{
    stop();
    elemento.src = "http://cdn.flaticon.com/svg/70/70409.svg";
    elemento.title = "Tocar";
    elemento.dataset.option = "play";
  }
}

function start() {
  if (cronometroAtivo) return;
  cronometroAtivo = true;
  counterms = setInterval(function () {
    range.style.left = range.style.left.substring(0, range.style.left.length-2) - 0.129;
    countms = countms + 1;
    id_label_ms.innerHTML = countms / 100 + " s";
  }, 10);
};

function stop(){
  range.style.left = 0;
  cronometroAtivo = false;
  countms = 0;
  id_label_ms.innerHTML = countms + " s";

  clearInterval(counterms);
  cronometroAtivo = false;
};
.containerArea{
  height: auto;
  width: 1030px;
  border: 1px rgb(89,89,89) solid;
  margin-top: 30px;
  background: rgb(173,234,234);
}

.slider {
  position:absolute;
  cursor:pointer;
  height:1px;
  border:2px solid rgb(179,179,179);
  width:1000px;
  -moz-border-radius:2px;
  -webkit-border-radius:2px;
}

#scrollwrap {
  margin-top:30px;
  overflow:hidden;
  width: 1000px;
  height:auto;
}

.container{
  min-width: 23px;
  height: 26px;
  border: 1px rgb(140, 173, 188) double;
}

.containerFaixa{
  width: 1000px;
  height: 26px;
  border: 1px rgb(140, 173, 188) double;
  background: rgb(216,216,191);
  border-radius: 7px;
}

.faixa{
  color: rgb(0, 0, 0);
  text-align: center;
  font-size: 12px;
  font-weight: bold;
  font-family: inherit;
  font-style: inherit;
  text-decoration: inherit;
  text-align: center;
  line-height: 1.85em;
}

.tempo{
  color: rgb(0, 0, 0);
  font-size: 10px;
  font-weight: inherit;
  font-family: 'Courier New', Courier, monospace;
  font-style: inherit;
  text-decoration: inherit;
}

.progress {
  background-color:rgb(179,179,179);
  height:3px;
  position:absolute;
  width:0;
}

.handle {
  position: absolute;
  z-index:4;
  width: 28px;
  height: 115px;
  background-position: top center;
  background-size: 25px 30px;
  background-image: url(http://cdn.flaticon.com/svg/17/17736.svg);
  background-repeat: no-repeat;
  left: 13px;
}

.area {
  position:relative;
  font:bold 90px  sans-serif;
  height:auto;
}

.range {
  display:none;
}

<link type="text/css" rel="stylesheet" href="style-teste.css" />

  <input id="range" type="range" max="795" value="0" />

    Count:

eu testei e ficou quase lá com um tempo em torno de 0.12 a 0.13 lá na parte range.style.left.substring(0, range.style.left.length-2) - 0.13; // por exemplo agora sou ruim de matemática ao meu ver teria que ser uma formula tipo 2/25 = 0.08, talvez seja esse setInterval=10 que esteja bugando sua formula a cada 10 mms tanto para mais quanto para menos, minha contribuição sobre o problema seria isso, os tamanhos dos blocos e o espaçamentos estava equivocado sobre eles.
Obs: Seu marcador esta mal posicionado no Start, ele tem que ficar encostado no primeiro bloco, fiz uma gambi ai removendo a palavra Start e mexi para posicionar ele ali rente ao primeiro bloco, vai de você ou deixar a palavra Start e posicionar ele, ou remover como eu fiz...


Q:

White Box Obscures View When Keyboard Appears

For some reason after updating flutter, one of the sections of my app has been broken. I have a list of text form widgets set in a SingleChildScrollView. Whenever I press one of the text forms, the keyboard appears and an empty white box pushes itself up into the field of view, obscuring the text entry boxes.

After having some trouble with text entry in a list view before I followed the advice of this link: https://www.didierboelens.com/2018/04/hint-4-ensure-a-textfield-or-textformfield-is-visible-in-the-viewport-when-has-the-focus/
It effectively solved the problems I had beforehand where the text entry boxes were not remaining visible when the keyboard appears. But now the while box is appearing and obscuring the view. I also made sure to use:
resizeToAvoidBottomPadding: false

as is regularly advised.
Here is the code in question with one of the text field widget's code too:
  @override
Widget build(BuildContext context) {

return new Scaffold(

  body: new SafeArea(
      child: new Form(

          key: _formKey,

          child: new SingleChildScrollView(

            padding: const EdgeInsets.all(16.0),

            child: new Column(
              crossAxisAlignment: CrossAxisAlignment.stretch,

              children: <Widget>[

                circumstances(),
                divider(),
                description(),
                divider(),
                externalHappenings(),
                divider(),
                internalHappenings(),
                divider(),
                reflectionsAndCorrections(),
                divider(),
                abatement(),
                divider(),
                footerButtons()

              ],

            ),

          )

      )
  ),

  resizeToAvoidBottomPadding: false,
);

}

Widget circumstances() {

  return new EnsureVisibleWhenFocused(
  focusNode: _focusNodeCircumstances,
  child: new TextFormField(

    controller: _circumstancesController,
    maxLines: maxLines,

    decoration: const InputDecoration(
      border: const OutlineInputBorder(
          borderRadius: const BorderRadius.all(const Radius.circular(0.0)),
          borderSide: const BorderSide(color: Colors.black, width: 1.0)
      ),

      filled: true,

      labelText: "Circumstances",
      hintText: "Who was there? Where were you?",
    ),

    autofocus: true,

    validator: (value) {

      _activeJournalEntry.setCircumstances(value);

      if(value == null || value.isEmpty) {
        return "Please enter some circumstances.";
      }

    },

    focusNode: _focusNodeCircumstances,

  ),
);

}

A:

The replies to this thread pointed me in the right direction to solve the issue.
I had three deep nested scaffolds where the innermost two had this set:
resizeToAvoidBottomPadding: false

However, my outermost Scaffold did not, causing this issue. So it turns out that it is fine to have nested Scaffolds but you must ensure that each of them have that property set to avoid this issue.
See also,
https://github.com/flutter/flutter/issues/7036


Q:

Grease or anti-seize for alloy thru-axle-to-QR adapter?

I've got a 26" front wheel with HB-M758 15x100mm thru-axle hub that I'll be using on a QRx100mm front fork. Going to install my alloy 15mm-to-QR axle adapter, it's a tight fit, which is good. Since the adapter is aluminum and the hub shaft is steel (I think), I'm just wondering if I should use anti-seize to lubricate it rather than standard grease.

A:

Anti-seize is the best from the standpoint of corrosion resistance and it has washout resistance that surpasses the greases usually used on bikes. The reasons it's not used on bikes more are that it's messy, another thing to have, and it takes a pretty extreme or specific situation for grease to not be enough. Tradition plays a role too. You can use it here and in all other metal-on-metal assembly prep spots where you'd use grease otherwise. The parts won't mind, but it's up to you whether the messiness is worth it. I would never use it on thru-axle or QR shafts because of the mess factor when the wheel is out.


Q:

WIA Scanning issues on XP

I have a WPF application that I am using to scan documents to a users mailbox etc.
When debugging the application on my 32bit Windows 7 professional machine all goes according to plan, as well as the deployed version on another 32bit Windows 7 machine.
When I deploy to a XP machine and try to start a scan I get the following error:

Retrieving the COM class factory for component with CLSID
  {850D1D11-70F3-4BE5-9A11-77AA6B2BB201} failed due to the following
  error: 80040154 Class not registered (Exception from HRESULT:
  0x80040154 (REGDB_E_CLASSNOTREG)).

Any suggestions?

A:

The win 7 version does not work on xp - you could try downloading this version for XP.
download here