Q:

Git branch model critique: always derive from master

I am currently working on a large project involving at least 3 teams working on separate feature sets in the same codebase versioned on Git. Some features require back-end integration and stabilization and I've heard of features taking months from being ready to going live.
I've seen A successful Git branching model and found it unsuitable for this situation, especially because feature branches must derive only from the development branch.
I assume features should always be in sync with master which represents current production code. The process of taking code from master->release->develop->feature makes keeping features up-to-date more difficult.
Plus, when complex merge conflicts arise on a merge from release to develop, who should solve it? On a large project with distributed teams with non-overlapping responsibilities not a single person is best suited to resolve complex merge conflicts across a whole codebase. No one owns the develop branch, neither a person or a team.
Merging features to and from the development branch also brings to them not-yet-production-ready code from other features while trying to keep them up-to-date with master, making feature branches sort of infect one another in the process. Once I've pulled from development to update my feature with latest production code and be able to call it "finished", I've infected my branch with supposedly finished code from other features that have merged to development. If any features in development are found to be either hard to stabilize or de facto a bad idea, we've compromised the development branch and all its feature branches.
Instead of deriving from the development branch, I found deriving from master and merging into disposable "release-package" branches lead to less headaches.

When merge conflicts arise in master->feature merge, the person doing the merge is the one most suited to resolve them. She knows the code and what it should do, it's her feature.
Features are streamlined into disposable release branches that can be deleted and reformed at any time. If a feature is not ready to go live by the release deadline, we can delete and recreate the package without it.
Development is only done in feature branches. Release branches only receive merges. If features conflict in a meaningful way, we should question if they should be merged into one another or scheduled for sequential release, one after another. In the case we merge two features into one another, the scenario might look too similar to NVIE's branch model, but here we are given a choice to do it or reschedule the features and recreate the release package.
The disposable nature of release branches and the independence of feature branches makes it possible to stage fallback releases.

If all four features don't stabilize until the deadline, only 1 and 2 go live.
Is my proposal a suitable branch model?
PS: I've read this answer about branch models vs quality and CI, and I don't think it applies. This project does have a quality problem. This quality problem will be there tomorrow and the next month, and while this quality problem remains there must be a suitable branch model we can use, one that does not make life harder.

A:

The main problem you are going to face is that when you are combining the feature branches to a release branch, you'll need to solve all the inter-branch conflicts. Merge conflicts are the easier ones, since they pop when you are merging specific branches and you can ask the branch owner to solve them(it's far from ideal though, since the branch is not fresh in the owner's memory). But not all conflicts pop us as merge conflicts - some create compilation errors or runtime bugs, and it's not as trivial to figure which feature branches have caused those.
A possible solution can be to shorten the release cycle - adding more rapid "sub-releases", e.g. twice a week. This will limit the number of feature branches you are merging on each sub-release, which in turn limit the conflict potential. This, of course, comes with it's own problems - a frequent release overhead, where the release master needs to choose which features to merge in each sub-release, and after the sub-release the developers need to merge/rebase their pending feature branches(and resolve conflicts).
At any rate, I think your fear of branching-from-develop is unjustified. You are portraying develop as some big playground where all developers push their unfinished scrabbles of untested code - and it's not true. The feature branches fulfill this role. develop, while it might not need to be as stable and as rigorously tested as master, should still have a certain level of stability - the primary rule is not to push to develop if it'll prevent the other developers from continuing to develop even if they merge/rebase develop to their feature branches.
This essentially means that you don't merge a feature branch to develop unless it passes automated tests(doesn't have to be the full suite - if you have a 10-minute suite that catches most bugs and a 5-hour suite that catches even the rarest of bugs, test the feature branches with the 10-minutes suite), so it should be OK to merge it to develop.
Note that master still needs to pass the 5-hour suite, and you have no guarantee a a merged feature branch won't break the 5-hour suite - but neither does your model provide such guarantee. The point is that even if a merged feature branch does break the 5-hour suite - it's still a branch you want in the next release(otherwise you wouldn't have merged it to develop), and the solution is rarely to exclude the feature from the next release.
Update
To answer the asker's first comment to this answer:

When runtime integration bugs arise, the affected feature-set team will be assigned to correct it. If it is caused by code from features created by any of the other teams, fixes are made into pull requests to the offending feature branch. Pull requests are then reviewed by the team that owns that feature, merged in and then merged into the release package. The team that knows how a feature should work makes the fix, the team who owns the offending code reviews it.

This method of solving bugs has several drawbacks compared to solving them as part of the preparation of a feature branch to be merged into develop:

The feature-set where the bug happens is usually easy in to figure in both methods. The actual changes that invoked the bug are trivial when branching from develop and very tricky when branching from master. The former only gives you a cue about you about who should be assigned to try solving the bug first, which is not as useful as the actual lead you get from the letter. At any rate, branching from develop allows you to have both hints.
The responsibility is backwards. If anything, the owner of the offending code is the one who should fix it, since they know best what they are trying to achieve, and the owner of the feature-set is the one who should review it, because they know best how the different parts of the feature-set should interact with each other.
But the branch-from-develop approach has an even better way to decide who will be the one to start solving the conflict - it's the one who tries to merge last!
Now, that claim might seem a little weird and arbitrary - it looks unfair to "punish" the developer who pushed last for being slow. But I believe they are the best choice for starting to solve the problem:

They are already in the context of the problem. This is the most important reason - being in context is crucial for solving problems, and entering context is hard. But the developer who pushes last is already in context, because that's the task they are working on. They have already build the mental model that can help them solve this problem.
They are available. They don't have something more urgent to do right now, because what they were doing was trying to merge their feature branch, and solving the conflict is required for merging the feature branch.
They don't have to actually solve the conflict entirely by themselves - just to be the first ones to look at it. When examining the problem they can decide some other developers need to be involved. Since they are in context, they are in the best position to tell who these other developers are. Also since they are in context, they can help bringing these other developers quickly into context.

That pull request into the offending feature branch will be a nightmare. The code in the feature branch works, because the other branch it was conflicting with is not part of it. So, you are sending a fix to a problem that's not yet there, that might have to relies on changes that come with the same code that introduced that problem. There is no sane way to do that without merging/rebasing the other branch(or the new release) into the feature branch - but if you do that you are just using branch-from-develop with develop having it's name replaced on each release.


Q:

DNS Policies are not properly resolving CNAMEs in Zone Scopes if the Query Resolution Policy includes the NE operator for Client Subnets

I'm fairly sure I've uncovered a bug, but I'm trying to make sense of it and maybe get a sanity check.
Scenario
A policy where if the request is looking for a specific record AND the client IP is not in a particular subnet, the policy matches and results in a CNAME record, the target of which is not covered by the policy and does not exist in a scope.
Example:

Zone = example.com
Records in example.com default scope:

testme IN A 10.1.2.3
testOther IN A 10.11.11.11

Zone Scope = TesterScope
Record in TesterScope:

testme IN CNAME testOther.example.com.

Client Subnet MySubnet contains 10.8.8.0/24

QRP with EQ for Client Subnet

Query Resolution Policy MyQRP with following config:

Condition = And
Content = TesterScope
Criteria:

FQDN = EQ,testme.example.com.
ClientSubnet = EQ,MySubnet

This will produce the expected results, that is:

If a request comes in for testme.example.com from an IP within MySubnet (should match), it will correctly return (and resolve) the CNAME record, even though the CNAME must be resolved in the default scope (the QRP specifically should only match when FQDN is testme.example.com not for testOther.example.com). Therefore, the result is 10.11.11.11, which is correct.
If a request comes in for testme.example.com from an IP outside MySubnet (should not match), it resolves to 10.1.2.3 as expected.

QRP with NE for Client Subnet

Query Resolution Policy MyQRP with following config:

Condition = And
Content = TesterScope
Criteria:

FQDN = EQ,testme.example.com.
ClientSubnet = NE,MySubnet <- change here

This will produces unexpected results:

If a request comes in for testme.example.com from an IP outside MySubnet (should match), it will correctly return the CNAME record, but it is unable to resolve it. Further testing revealed that if the target of the CNAME also exists within the zone scope, it will resolve, but it shouldn't be doing this because there is no QRP that matches requests for that target to make the queries use the scope.
If a request comes in for testme.example.com from an IP inside MySubnet (should not match), it resolves to 10.1.2.3 as expected.

Additional Notes

The ClientSubnet criteria can contain both EQ and NE operators in one (like EQ,ThisSubnet;NE,ThatSubnet). The behavior happens anytime the NE operator is included.
I am aware that these CNAME resolutions are being done internally on the DNS server; the client is not receiving the CNAME and then resolving it in a different request.
I contend that the EQ-only behavior is correct, because as previously mentioned the target of the CNAME has no QRP that should cause the zone scope to be used. Additionally, if a client were to directly request the target of the CNAME, it will not use the rule, so I feel that the results should be consistent between internal and external CNAME resolution.
Even if my contentions above are incorrect, the result of the internal CNAME resolution is still inconsistent with itself (different results with EQ vs NE).
If the record within the zone scope is an A record instead of a CNAME (doesn't require internal resolution) then everything works as planned (this is a possible but in my opinion undesirable workaround).

PowerShell to Demonstrate
(I've done my own tests, but not directly with this code, let me know if it's broken)
$myZone = 'example.com'
$myScope = 'MyScope'
$mySubnetName = 'MySubnet'
$mySubnetCIDR = '10.8.8.0/24'
$commonName = 'testme'
$commonValue = '10.1.2.3'
$otherName = 'testOther'
$otherValue = '10.11.11.11'
$myPolicy = 'MyQRP'

$myCommonFqdn = "${commonName}.${myZone}."
$myOtherFqdn = "${otherName}.${myZone}."

$myDC = 'My2016DC'

Import-Module DnsServer

$PSDefaultParameterValues = @{
    '*-DnsServer*:ComputerName' = $myDC
}

Add-DnsServerClientSubnet -Name $mySubnetName -IPv4Subnet $mySubnetCIDR

Add-DnsServerZoneScope -ZoneName $myZone -Name $myScope

Add-DnsServerResourceRecord -ZoneName $myZone -Name $commonName -A -IPv4Address $commonValue
Add-DnsServerResourceRecord -ZoneName $myZone -Name $otherName -A -IPv4Address $otherValue

Add-DnsServerResourceRecord -ZoneName $myZone -ZoneScope $myScope -Name $commonName -CName -HostNameAlias $myOtherFqdn

# Add the policy with EQ that works correctly
Add-DnsServerQueryResolutionPolicy -ZoneName $myZone -ZoneScope $myScope -Name $myPolicy -Fqdn "EQ,$myCommonFqdn" -ClientSubnet "EQ,$mySubnetName"

# Uncomment these to change it around

# Use NE instead of EQ
# Set-DnsServerQueryResolutionPolicy -ZoneName $myZone -ZoneScope $myScope -Name $myPolicy -Fqdn "EQ,$myCommonFqdn" -ClientSubnet "NE,$mySubnetName" -Action REPLACE
# Set it back to using EQ
# Set-DnsServerQueryResolutionPolicy -ZoneName $myZone -ZoneScope $myScope -Name $myPolicy -Fqdn "EQ,$myCommonFqdn" -ClientSubnet "EQ,$mySubnetName" -Action REPLACE

That should create a reproducible scenario in your environment (change the variables as needed). From there you can use nslookup or dig as needed to check the results. Note you must only check against the single DC that this is applied to if you're in an AD environment (the policies/subnets don't get replicated).
Update -- Wed 24 May
I have a case open with Microsoft for this issue. They claim they can not reproduce it.
Anyone out there willing to give this a try?
Update -- Wed 26 Jul
Microsoft is able to reproduce the issue, after repeated demonstrations. I am awaiting a deeper response from the internal team.

A:

So, here's how my case went with Microsoft.
Eventually, it made its way internally to the developer (who posted an answer on this question), and so the official response is "this is how it was designed."
I'm personally not at all satisfied with that answer, as this behavior is not documented, and makes no intuitive sense, but there it is.
I was told that to go any further with the issue, we would have to open a Premier support case (we don't have premier support). Given that this took many months, and my company no longer needs this feature, that won't be happening.


Q:

Method to detect a click on a text in LibGdx

How can I detect a click on a text using LibGdx? For example, I want the user to be able to click on the String Show Highscore. The problem I'm having is that I already implemented an if-statement, which states that if anything is clicked on, the game starts. What kind of method do I have to write now, so that the user can click on Show Highscore? I can change the if statement which uses the whole screen, if necessary. Thanks :)
public class MainMenuScreen implements Screen {

final FlappyWizardGame game;
OrthographicCamera camera;

String buttonHighscore = "Show Highscore";

public MainMenuScreen(FlappyWizardGame game) {
    this.game = game;

    camera = new OrthographicCamera();
    camera.setToOrtho(false, 1280, 720);
    screenHeight = Gdx.graphics.getHeight();
}

@Override
public void render(float delta) {

    Gdx.gl.glClearColor(0, 0, 0.2f, 1);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

    camera.update();
    game.batch.setProjectionMatrix(camera.combined);

    game.batch.begin();
    game.batch.draw(game.hermine, 0, 0, (int)(game.hermine.getWidth() * 0.25), (int)(game.hermine.getHeight() * 0.25));
    game.font.draw(game.batch, "Welcome to Flappy Wizard!!! ", camera.viewportWidth / 3, camera.viewportHeight - 100);
    game.font.draw(game.batch, "Tap anywhere to begin!", camera.viewportWidth / 3, camera.viewportHeight - 150);
    game.font.draw(game.batch, buttonHighscore, camera.viewportWidth / 3, camera.viewportHeight - 200);

    if (Gdx.input.isTouched()) {
        game.setScreen(new GameScreen(game));
        dispose();
    }
}

A:

You must create a Rectangle around the Text:
Rectangle rectangle = new Rectangle(x, y, width, height);

And then in your if statement check if the touch event is in the Rectangle:
if(Gdx.input.isTouched()){
    if(rectangle.contains(Gdx.input.getX(), Gdx.input.getY())){
        openHighscore();
    } else{
        game.setScreen(new GameScreen(game));
        dispose();
    }
}


Q:

Double.longBitsToDouble and Double.doubleToRawLongBits with NaN

Why is
Double.NaN != Double.longBitsToDouble(Double.doubleToRawLongBits(Double.NaN));

although the SE 6 documentation says the following:

In all cases, the result is a long integer that, when given to the
  longBitsToDouble(long) method, will produce a floating-point value the same as the
  argument to doubleToRawLongBits.

A:

But Double.NaN != Double.NaN...


Q:

App not showing network activity in Android Studio's Profiler

I am trying to analyze my app's network activity such as number of connections and total size of response and request per connection.
However, it won't register in my Profiler's Network section.
I am using Java sockets as explained in how to create Socket connection in Android?.
How do you show it in the tool?

A:

Apparently, the Android Studio's (Network) Profiler only captures connections made thru HttpURLConnection and OkHttp classes. This won't work if you are using Socket from the Java API.
Source: https://developer.android.com/studio/profile/network-profiler


Q:

Partitioning table based on first letter of a varchar field

I have a massive table (over 1B records) that have a specific requirement for table partitioning:
(1) Is it possible to partition a table in Postgres based on the first character of a varchar field?
For example:
For the following 3 records:
a-blah
a-blah2
b-blah

a-blah and a-blah2 would go in the "A" partition, b-blah would go into the "B" partition.
(2) If the above is not possible with Postgres, what is a good way to evenly partition a large growing table? (without partitioning by create date -- since that is not something these records have).

A:

You can use an expression in the partition by clause, e.g.:
create table my_table(name text)
partition by list (left(name, 1));

create table my_table_a
partition of my_table
for values in ('a');

create table my_table_b
partition of my_table
for values in ('b');

Results:
insert into my_table
values
    ('abba'), ('alfa'), ('beta');

select 'a' as partition, name from my_table_a
union all
select 'b' as partition, name from my_table_b;

 partition | name
-----------+------
 a         | abba
 a         | alfa
 b         | beta
(3 rows)

If the partitioning should be case insensitive you might use
create table my_table(name text)
partition by list (lower(left(name, 1)));

Read in the documentation:

Table Partitioning
CREATE TABLE


Q:

Swift UIlabels not showing properly in uistackview

I am trying to programatically add uilabels into a stackview but for some reason it is not showing up properly. Here is what I have:
let label = UILabel()
label.textColor = UIColor.black
label.text = "Text that goes before "

let matlabel = MTMathUILabel()
matlabel.labelMode = MTMathUILabelMode.text
matlabel.latex = "$\\frac{x}{y}$"
matlabel.textColor = UIColor.black

let endLabel = UILabel()
label.textColor = UIColor.black
label.text = "? after"

self.textStack.addArrangedSubview(label)
self.textStack.addArrangedSubview(matlabel)
self.textStack.addArrangedSubview(endLabel)

And here is what I get

A:

You create a "endLabel" but you didn't set text on it. You mistakenly set text on "label" so it just override your "label" text. try the following code:
let label = UILabel()
label.textColor = UIColor.black
label.text = "Text that goes before "

let matlabel = MTMathUILabel()
matlabel.labelMode = MTMathUILabelMode.text
matlabel.latex = "$\\frac{x}{y}$"
matlabel.textColor = UIColor.black

let endLabel = UILabel()
endLabel.textColor = UIColor.black
endLabel.text = "? after"

self.textStack.addArrangedSubview(label)
self.textStack.addArrangedSubview(matlabel)
self.textStack.addArrangedSubview(endLabel)


Q:

JSON parsing on server vs. parsing client side

I'm writing a node app and need to server a bunch of JSON map data. In order for the data to properly show up, it must be parsed.
Now I'm wondering if it's better to parse on the server (and send this parsed data object to the client) or send pure json and have it be parsed on the client side after the ajax call.
My biggest concern with doing it on the server is that many simultaneous queries could slow everything down for a whole bunch of people.
Server side code option:
var data = [];
db.simple_query([{ask: COMPLEX QUERY TO RETURN DATA AS JSON }], function(err, geo_data){
                        if (err) {
                            callback(err);
                        }
                        else{
                            data.push(JSON.parse(geo_data.rows[0].row_to_json));
                            callback();
                        }
                    });

Client side code option:
$.ajax({
                    type: 'GET',
                    url: url,
                    success: function(data){
                        if (data){
                            $.each(data, function(i, geo){
                                L.geoJson(JSON.parse(geo)).addTo(map);
                            });
                        }
                    },
                    error: function(data){
                        //Error Handling
                    }
                });

A:

It really doesn't matter. Compared to a database access (or basically anything that involves network or disk activity) serializing/deserializing JSON is blazingly fast. Don't over-optimize things that do not need optimization.
However, if you want to pass the data to the client without any server-side processing and already get a JSON string it would be pointless to deserialize it on the server and then serialize it again to transmit it to the client which will again have to deserialize it.


Q:

Get sum of all DOM nodes having same class with JavaScript or jQuery

My question is simple  let's say you have multiple  elements like this
 10,000
 20,000
 40,000
 500,000

How do you get each number content inside the span tag, strip the commas away and add the numbers get the answer and add commas, cause I can't seem to figure out a way to do this.
This is what I want to achieve
//data would be gotten from Span tag with class HI

A:

You can use spread syntax on querySelectorAll to get an array and then you can use reduce method to calculate sum.

const sum = [...document.querySelectorAll('span')].reduce((r, e) => {
  return r + parseInt(e.textContent.replace(',', ''))
}, 0)

console.log(sum)
10,000
20,000
40,000
500,000

A:

var total = 0;
$(".hi").each(function() {
    total += parseInt($(this).html().replace(",", ""));
});
$("#theans").html(total);


Q:

why __init__ is called before object created?

class Point(object):

    def __init__(self, x=0, y=0):
        self.__x = x
        self.__y = y
        print 'point ({x},{y}) created.'.format( x=self.__x, y=self.__y )

class Line(object):

    def __init__(self, start_point=Point(), end_point=Point()):
        print 'Line.__init__ called.'
        self.start = start_point
        self.end = end_point

def test_line():
    p1 = Point(1,1)
    p2 = Point(2,2)
    line1 = Line(p1, p2)

if __name__=='__main__':
    test_line()

When I run this script, it gives the result:
point (0,0) created.
point (0,0) created.
point (1,1) created.
point (2,2) created.
Line.__init__ called.

I don't know why Point.__init() is called before line1 is created.

A:

def __init__(self, start_point=Point(), end_point=Point())

Default function parameters are members of the function itself and are created when the function is defined, not at runtime. So each instance of Line uses the same start and end
The common way to work around this is set them by default to None:
def __init__(self, start_point=None, end_point=None):
    if start_point is None:
        self.start = Point()
    if end_point is None:
        self.end = Point()


Q:

Update tables when cannot modify a column which maps to a non key-preserved table

----- s.op_id= ------
| S |----------| OP |
----- op.op_id ------
                  |
                  | op.op_id = j.op_id
                  |
                -----
                | J |
                -----

An oracle database has three tables journey, op_profile and special.
journey has two columns journey_id (primary key) and op_id,
op_profile has primary key op_id and
special has a column op_id which is a foreign key on op_profile and a further column s_id which is the tables primary key.
I have tried to update all the op_id columns to equal the journey_id column of the journey table with the following sql usin sql developer:
UPDATE (SELECT special.op_id, journey.journey_id, op_profile.op_id AS op
        FROM special, journey, op_profile
        WHERE special.op_id = journey.op_id AND journey.op_id = op_profile.op_id)
SET op_id = journey_id, op = journey_id;

which gives the following error
SQL Error: ORA-01779: cannot modify a column which maps to a non key-preserved table
01779. 00000 -  "cannot modify a column which maps to a non key-preserved table"
*Cause:    An attempt was made to insert or update columns of a join view which
           map to a non-key-preserved table.
*Action:   Modify the underlying base tables directly.

which seems to say that this operation is failing because of the keys of each table.
Is this possible in this way, or another?

A:

Yes this is possible using two update statements:
update s
    set op_id = (select j.journey_id
                 from j
                 where j.op_id = s.op_id
                );

and:
update op
    set op_id = (select j.journey_id
                 from j
                 where j.op_id = op.op_id
                );


Q:

How to update a table in ORM "ActiveAndroid"?

I use in my project "ActiveAndroid". I have a model which I retain. here is a model:
@Table(name="Params")
public class Params extends Model {

    public Params() {
        super();
    }

    @Expose
    @Column(name="height")
    @SerializedName("heigth")
    public int heigth;

    @Expose
    @Column(name="weight")
    @SerializedName("weight")
    public int weight;
}

here all save:
public void success(User user, Response response) {
               user.params.save();
               user.save();
                ActiveAndroid.clearCache();
            }

Everything works fine! But if I want to add another field in the model:
@Expose
    @Column(name="strong")
    @SerializedName("strong")
    public int strong;

I get an error:
android.database.sqlite.SQLiteException: table Params has no column named strong (code 1): , while compiling: INSERT INTO Params(Id,weight,height,strong) VALUES (?,?,?,?)

of course I know why this error. Because the table is no such column. That's the question, how to add this column ???
Now that I've tried:

remove programs completely, again to compile, run, and everything works fine! because it creates a new table from this column.
Tried to change the version in the manifest database, but this has not led to success.

I know that with normal use of the database in the method of upgrade you can change the version of the database and restructure table. but how to do it in ORM "ActiveAndroid" ?

A:

There is a thing known as Migration, in Active Android you can do that like this

Add the field in your model (which you already did)
Change the database version the the AndroidManifest.xml's metadata
Write your migration script. Name your script [newDatabaseVersion].sql, and place it in the directory [YourApp’sName]/app/src/main/assets/migrations. In my specific example, I’ll create the file [MyAppName]/app/src/main/assets/migrations/2.sql.

E.G. ALTER TABLE Items ADD COLUMN Priority TEXT;


Q:

Equivalent matlab function mod in numpy or python

I was converting some codes from Matlab to Python.
In matlab there is the function mod which gives the modulo operation.
For example the following example shows different results between the matlab mod and the equivalent numpy remainder operation:
Matlab:
>> mod(6, 0.05)

ans =

     0

Numpy:
np.remainder(6, 0.05)
0.04999999999999967

np.mod(6, 0.05)
0.04999999999999967

Python modulus operator gives the same results as numpy.
6%0.05
0.04999999999999967

Is there anything in python which gives the same mod operation as the one in Matlab? preferably can be operated on numpy 2d/3d arrays.
numpy documentation says that numpy.mod is equivalent to matlab mod.

A:

This is the core of the problem, in python:
>>> 6/0.05 == 120
True

>>> 6//0.05 == 120  # this is 119 instead
False

The floating-point result of 6/0.05 is close enough to 120 (i.e. within the resolution of double precision) that it gets rounded to 120.0. However, it's ever so slightly smaller than 120, so explicit floor division will truncate that number to 119 before it could be normalized to 120.0.
Some proof:
>>> from decimal import Decimal
... print(6/Decimal(0.05))  # exactly approximate
... print(6/Decimal('0.05'))  # exact
119.9999999999999933386618522
1.2E+2

The first number is what you'd first get with 6/0.05, but the number 119.9999999999999933386618522 gets rounded to the nearest number representable with double precision, and this is 120. One can easily prove that these two numbers are indeed the same within double precision:
>>> print(6/Decimal('0.05') - 6/Decimal(0.05))
6.6613381478E-15

>>> 120 - 6.6613381478E-15 == 120
True

Now here's help mod from MATLAB:
    MOD(x,y) returns x - floor(x./y).*y if y ~= 0, carefully computed to
    avoid rounding error. If y is not an integer and the quotient x./y is
    within roundoff error of an integer, then n is that integer.

This suggests that when x/y is close to an integer then it's rounded first, rather than being truncated like in python. So MATLAB goes out of its way to do some magic with the floating-point results.
The simplest solution would be to round your numbers yourself (unless you can use something like decimal.Decimal, but this means you should forgo native doubles entirely, including literals) and reproduce MATLAB's mod that way, assuming that makes sense for your use cases.


Q:

Custom react dropdown menu not open close properly

Currently, I have a 3 rows in a table. Each row has two column: file name and a button

file name is just a dummy link.
button will hide show a menu.

My requirements are following:

Click a button, it will toggle the menu. i.e. if prev it is close, it should be open. If prev is open, close.
When you are click on this button, if other menus are open, they should be close.
Each time, only 1 menu is open.

github link
git clone, npm install, npm start
I have the following code
import React, {useState, useEffect} from 'react';

function Menu({buttonName, menuIndex, currRowInd, setCurrRowInd}) {
  // inside menu
  const [open, setOpen] = useState(false);
  const [showMenu, setShowMenu] = useState(false);
  const menuItems = {download: 'download', view: 'view', delete: 'delete'};

  useEffect(() => {
    if (open && menuIndex === currRowInd) {
      setShowMenu(true);
    } else {
      setShowMenu(false);
    }
  }, [open, currRowInd]);

  return (

      <button
        onClick={event => {
          // it is mouse click
          if (event.pageX !== 0 && event.pageY !== 0) {
            // toggle
            setOpen(!open);
            setCurrRowInd(menuIndex);
          }
        }}
      >
        {buttonName}
      </button>
      {showMenu && (

          {Object.keys(menuItems).map((item, itemIndex) => {
            return (

                {item}

            );
          })}

      )}

  );
}

function TableElement() {
  const [currRowInd, setCurrRowInd] = useState('');

  const items = [
    {
      file: 'file1',
      button: 'button1'
    },
    {
      file: 'file2',
      button: 'button2'
    },
    {
      file: 'file3',
      button: 'button3'
    }
  ];
  return (

        {items.map((item, index) => {
          return (

                {item.file}

                <Menu
                  buttonName={item.button}
                  menuIndex={index}
                  currRowInd={currRowInd}
                  setCurrRowInd={setCurrRowInd}
                />

          );
        })}

  );
}

function App() {
  return (
    <>
      <TableElement />
    </>
  );
}

export default App;

I have a bug:

Click button 1, it opens 1st menu (good)
Click button 2, it opens 2nd menu and close 1st menu (good)
Click button 1 again, 2nd menu close (good so far), but 1st menu is not open.

Any idea?

A:

You don't need all that state in the Menu component, it's just adding a lot of complexity. Your issue is solved simply by removing it, and changing some props around.
Link to working codesandbox
function Menu({buttonName, showMenu, handleClick}) {
  const menuItems = {download: 'download', view: 'view', delete: 'delete'};

  return (

      <button
        onClick={event => {
          // it is mouse click
          if (event.pageX !== 0 && event.pageY !== 0) {
            // toggle
            handleClick();
          }
        }}
      >
        {buttonName}
      </button>
      {showMenu && (

          {Object.keys(menuItems).map((item, itemIndex) => {
            return (

                {item}

            );
          })}

      )}

  );
}

function TableElement() {
  // number is a better default. -1 will never match
  const [currRowInd, setCurrRowInd] = useState(-1);

  const items = [
    {
      file: 'file1',
      button: 'button1'
    },
    {
      file: 'file2',
      button: 'button2'
    },
    {
      file: 'file3',
      button: 'button3'
    }
  ];
  return (

        {items.map((item, index) => {
          return (

                {item.file}

                <Menu
                  buttonName={item.button}
                  showMenu={index === currRowInd}
                  handleClick={() => {
                    // toggle
                    if (index !== currRowInd) setCurrRowInd(index)
                    else setCurrRowInd(-1)
                  }}
                />

          );
        })}

  );
}


Q:

UML diagram and VS2010 IDE

Is there any way by which we can generate UML diagrams automatically for my VS2010 project? Is there any free tool for it?  Manually generating UML diagrams is a very time consuming process.... Can anybody help me with an idea as to how I can easily generate UML diagrams for my .net project.

A:

Visual Studio 2010 Ultimate offers several types of UML diagrams. I think the reverse engineering of the code into diagrams is not part of Visual Studio 2010 Ultimate RTM but can be downloaded as separate feature pack 2 (offers generation of UML class diagram from code).
If you don't have VS 2010 Ultimate you should use some other Case tool (most probably commercial because of quality). Very popular is Enterprise Architect.


Q:

Selendroid won't start some apps

I got the average setup for starting an app on a device and sometimes it works perfectly fine (the app starts and can be controlled by selendroid) sometimes (in the case of the firefox.apk) this happens:
Aug 10, 2015 3:02:13 PM io.selendroid.standalone.io.ShellCommand exec
INFORMATION: Executing shell command: C:\Users\Dustin Altermann\AppData\Local\Android\sdk\platform-tools\adb.exe -s BX903DKMSR shell am instrument -e main_activity -e server_port 8080 io.selendroid.org.mozilla.firefox/io.selendroid.server.ServerInstrumentation
Aug 10, 2015 3:02:13 PM io.selendroid.standalone.io.ShellCommand exec
INFORMATION: Shell command output
-->
usage: am [subcommand] [options]
usage: am start [-D] [-W] [-P ] [--start-profiler ]
[--R COUNT] [-S] [--opengl-trace]
am startservice
am force-stop
am kill
am kill-all
am broadcast
am instrument [-r] [-e ] [-p ] [-w]
[--no-window-animation]
am profile start
am profile stop []
am dumpheap [flags]
am set-debug-app [-w] [--persistent]
am clear-debug-app
am monitor [--gdb ]
am screen-compat [on|off]
am display-size [reset|MxN]
am to-uri [INTENT]
am to-intent-uri [INTENT]

am start: start an Activity. Options are:
-D: enable debugging
-W: wait for launch to complete
--start-profiler : start profiler and send results to
-P : like above, but profiling stops when app goes idle
-R: repeat the activity launch times. Prior to each repeat,
the top activity will be finished.
-S: force stop the target app before starting the activity
--opengl-trace: enable tracing of OpenGL functions

am startservice: start a Service.

am force-stop: force stop everything associated with .

am kill: Kill all processes associated with . Only kills.
processes that are safe to kill -- that is, will not impact the user experience.

am kill-all: Kill all background processes.

am broadcast: send a broadcast Intent.

am instrument: start an Instrumentation. Typically this target is the form /. Options are:
-r: print raw results (otherwise decode REPORT_KEY_STREAMRESULT). Use with
[-e perf true] to generate raw output for performance measurements.
-e : set argument to . For test runners a
common form is [-e [,...]].
-p : write profiling data to
-w: wait for instrumentation to finish before returning. Required for test runners.
--no-window-animation: turn off window animations will running.

am profile: start and stop profiler on a process.

am dumpheap: dump the heap of a process. Options are:
-n: dump native heap instead of managed heap

am set-debug-app: set application to debug. Options are:
-w: wait for debugger when application starts
--persistent: retain this value

am clear-debug-app: clear the previously set-debug-app.

am monitor: start monitoring for crashes or ANRs.
--gdb: start gdbserv on the given port at crash/ANR

am screen-compat: control screen compatibility mode of .

am display-size: override display size.

am to-uri: print the given Intent specification as a URI.

am to-intent-uri: print the given Intent specification as an intent: URI.

specifications include these flags and arguments:
[-a ] [-d ] [-t ]
[-c [-c ] ...]
[-e|--es ...]
[--esn ...]
[--ez ...]
[--ei ...]
[--el ...]
[--ef ...]
[--eu ...]
[--ecn ]
[--eia [, [--ela [, [--efa [, [-n ] [-f ]
[--grant-read-uri-permission] [--grant-write-uri-permission]
[--debug-log-resolution] [--exclude-stopped-packages]
[--include-stopped-packages]
[--activity-brought-to-front] [--activity-clear-top]
[--activity-clear-when-task-reset] [--activity-exclude-from-recents]
[--activity-launched-from-history] [--activity-multiple-task]
[--activity-no-animation] [--activity-no-history]
[--activity-no-user-action] [--activity-previous-is-top]
[--activity-reorder-to-front] [--activity-reset-task-if-needed]
[--activity-single-top] [--activity-clear-task]
[--activity-task-on-home]
[--receiver-registered-only] [--receiver-replace-pending]
[--selector]
[ | | ]

Error: Bad component name: server_port
<--
Aug 10, 2015 3:02:13 PM io.selendroid.standalone.io.ShellCommand exec
INFORMATION: Executing shell command: C:\Users\Dustin Altermann\AppData\Local\Android\sdk\platform-tools\adb.exe -s BX903DKMSR forward tcp:8080 tcp:8080
Aug 10, 2015 3:02:13 PM io.selendroid.standalone.io.ShellCommand exec
INFORMATION: Shell command output
-->

<--
Aug 10, 2015 3:02:13 PM io.selendroid.standalone.android.impl.AbstractDevice startLogging
INFORMATION: starting logcat:
Aug 10, 2015 3:02:13 PM io.selendroid.standalone.server.model.SelendroidStandaloneDriver waitForServerStart
INFORMATION: Waiting for the Selendroid server to start.
Aug 10, 2015 3:02:13 PM io.selendroid.standalone.android.impl.AbstractDevice isSelendroidRunning
INFORMATION: Checking if the Selendroid server is running: http://localhost:8080/wd/hub/status
Aug 10, 2015 3:02:13 PM org.apache.http.impl.execchain.RetryExec execute
INFORMATION: I/O exception (java.net.SocketException) caught when processing request to {}->http://localhost:8080: Connection reset
Aug 10, 2015 3:02:13 PM org.apache.http.impl.execchain.RetryExec execute
INFORMATION: Retrying request to {}->http://localhost:8080
Aug 10, 2015 3:02:13 PM org.apache.http.impl.execchain.RetryExec execute
INFORMATION: I/O exception (java.net.SocketException) caught when processing request to {}->http://localhost:8080: Connection reset
Aug 10, 2015 3:02:13 PM org.apache.http.impl.execchain.RetryExec execute
INFORMATION: Retrying request to {}->http://localhost:8080
Aug 10, 2015 3:02:13 PM org.apache.http.impl.execchain.RetryExec execute
INFORMATION: I/O exception (java.net.SocketException) caught when processing request to {}->http://localhost:8080: Connection reset
Aug 10, 2015 3:02:13 PM org.apache.http.impl.execchain.RetryExec execute
INFORMATION: Retrying request to {}->http://localhost:8080
Aug 10, 2015 3:02:13 PM io.selendroid.standalone.android.impl.AbstractDevice isSelendroidRunning
INFORMATION: Can't connect to Selendroid server, assuming it is not running.

The app doesn't start and selendroid keeps trying but nothing happens. I can start the app manually without any problems.
I don't understand the difference or what to do to narrow down the problem.
BTW.: I used the firefox.apk from the Google Play Store if anyone wants to try themselves.

A:

Ok I finally did it:
The problem was that this particular app had an AndroidManifest.xml file (read it by using e.g. https://code.google.com/p/xml-apk-parser/) using the tag "activity-alias". Inside this tag there were the fields that Selendroid needs to determine the so called "main_activity":
<activity-alias android:label="Firefox" android:name=".App" android:targetActivity="org.mozilla.gecko.BrowserApp">
    <intent-filter android:priority="999">
        <action android:name="android.intent.action.MAIN">
        </action>
        <category android:name="android.intent.category.LAUNCHER">
        </category>
        <category android:name="android.intent.category.MULTIWINDOW_LAUNCHER">
        </category>
        <category android:name="android.intent.category.DEFAULT">
        </category>
    </intent-filter>

Unfortunately Selendroid doesn't understand this tag and therefore cant find the "main_activity".
Solution: I had to use the "SelendroidCapabilities.setLaunchActivity"-method to specifically tell Selendroid what activity to use:
SelendroidCapabilities caps = new SelendroidCapabilities("org.mozilla.firefox:39.0");
caps.setLaunchActivity("org.mozilla.gecko.BrowserApp");


Q:

java.lang.OutOfMemoryError: Java heap space on JSP Pages

I was getting out of memory error on a spring framework application. I disabled a few filters (like security filter). But now the error is coming on JSP Pages. My JSP pages are quite heavy and use Tile Framework.
Unfortunately the hosting I have is providing only 32 MB of heap space and I could not increase that.
I have added a few lines in my layout page:
final long  MEGABYTE = 1024L * 1024L;

// Get current size of heap in bytes
long heapSize = Runtime.getRuntime().totalMemory();
out.println("Total Memory (MB): "+(heapSize / MEGABYTE ));

// Get maximum size of heap in bytes. The heap cannot grow beyond this size.
// Any attempt will result in an OutOfMemoryException.
long heapMaxSize = Runtime.getRuntime().maxMemory();
out.println("
Heap Max Size (MB): "+(heapMaxSize / MEGABYTE ));

// Get amount of free memory within the heap in bytes. This size will increase
// after garbage collection and decrease as new objects are created.
long heapFreeSize = Runtime.getRuntime().freeMemory();
out.println("
Heap Free Size (MB): "+(heapFreeSize / MEGABYTE ));

The above prints following output at output (HTML Page)
Total Memory (MB): 29
Heap Max Size (MB): 29
Heap Free Size (MB): 3

Here is the stack trace:
javax.servlet.jsp.JspException: ServletException in '/jsp/fragments/account/newAccount.jsp': java.lang.OutOfMemoryError: Java heap space
at org.apache.struts.taglib.tiles.InsertTag$InsertHandler.doEndTag(InsertTag.java:921)
at org.apache.struts.taglib.tiles.InsertTag.doEndTag(InsertTag.java:460)
at org.apache.jsp.jsp.common.tiles.layout_jsp._jspx_meth_tiles_005finsert_005f3(layout_jsp.java:818)
at org.apache.jsp.jsp.common.tiles.layout_jsp._jspService(layout_jsp.java:428)
at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:803)
at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:393)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:320)
at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:266)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:803)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:654)
at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:445)
at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:379)
at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:292)
at org.springframework.web.servlet.view.InternalResourceView.renderMergedOutputModel(InternalResourceView.java:238)
at org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:250)
at org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1047)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:817)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:719)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:644)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:549)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:690)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:803)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:263)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:844)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:584)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447)
at java.lang.Thread.run(Thread.java:662)

A:

I have is providing only 32 MB of heap space and I could not increase that..

Sorry, but then that's the end of story. You have 2 options:

Rewrite your views to be more memory efficient. Perhaps you need to fall back to plain vanilla JSP/Servlet without any additional frameworks which each of course needs their own memory share.
Give the server more memory. Upgrade your existing hosting account or migrate to a different host.


Q:

Extra space (or missing) after a ref with a second digit in a bibitem

I create my bibliography as follows but after the 10nth Ref i have an extra space on the first line or a missing space on the following lines. Any idea on how to fix this?
Thank you!
\begin{thebibliography}{9}
.
.
.
\bibitem{hulu}
Hulu,
\emph{Hulu Bandwidth Recommendations},
URL: \url{http://www.hulu.com/support/article/197541},
January, 2014.

\bibitem{itu-t_p800_1}
ITU-T,
\emph{Mean Opinion Score (MOS) Terminology},
ITU-T Recommendation P.800.1,
November, 2006.
.
.
.
\end{thebibliography}

A:

The argument to \begin{thebibliography}{} should be the widest string ever used as a label. So you should change the 9 to 99, or even 999, to leave space.


Q:

How to insert a checkmark in emacs -nw/gui-less mode

I want to insert a tick mark, maybe this: ✔
Can I do it with C-x 8 or some other way?
My environment:
Latest MacOS, inside Terminal.app
I start with emacsclient -nw (No gui)

A:

Use C-x 8 RET followed by the name of the Unicode character or its hex code point.
In this case, you probably want character CHECK MARK, which has code point 2713. So either of these works:

C-x 8 RET check mark RET
C-x 8 RET 2713 RET


Q:

Do "Instant Approved" credit card inquires appear on credit report?

I have a very good credit score (just shy of excellent) and I wanted to purchase a fairly pricey item on Amazon. They have a couple of decent credit card offers, one with Chase that gives you $70 Amazon credit on approval and their store card that gives you $40. I applied for the Chase, and found out I wasn't immediately approved. So, I took the chance and applied for the store card and got instantly approved. Later that day, I got approved from Chase too.
Anyway, few weeks later I check my annual free credit report (one of them) and interestingly I have only a "hard" inquiry from chase registered. Which makes me wonder, is the other not a hard inquiry or is it delayed and will show up later? I've read online that being pre-approved for credit cards only leads to a soft inquiry and so won't effect the score. Was I "pre-approved" when I was instantly approved for the store card?

A:

It is not delayed and if it didn't show yet - will not show on that agency's credit report.
However, you may find it on another agency's report. There are three major agencies, and creditors don't always check all of them (each inquiry costs them money).


Q:

update matrix values in python

I need to update matrix values with elements in list. When i use for loop to iterate the index of matrix and include the elements in list. only the last value is updated as it is the last value of the iterator.
But i need the sequence of the list to be added in the matrix.
please let me know if there could be any possibilities to do this..
     >>> n
      [0, 1, 2, 3]
     >>> for i in range(len(m)):
            for j in range(len(m)):
              for k in range(len(n)):
                m[i][j]=n[k]

      >>> m
        array([[ 3.,  3.],
               [ 3.,  3.]])

A:

In the most inside loop:
          for k in range(len(n)):
            m[i][j]=n[k]

i and j doesn't changes, so you assign n[i][j]=n[0] and then n[i][j]=n[1], n[i][j]=n[2], n[i][j]=n[3] and just the last one holds.
A naive way to solve it is:
    k=0
    for i in range(len(m)):
        for j in range(len(m)):
            m[i][j]=n[k]
            k+=1


Q:

Search Bar in Table View Swift

im doing a simple project in Xcode 6 and i want to add search bar in tableviewcontroller but something is not working for me. Im doing it by this tutorial
http://www.raywenderlich.com/76519/add-table-view-search-swift
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    if tableView == self.searchDisplayController!.searchResultsTableView {
        return self.filteredProgramy.count
    } else {
        return self.programy.count
    }
}

here im getting error "fatal error: unexpectedly found nil while unwrapping an Optional value". idk why. whole code is here
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    if tableView == self.searchDisplayController!.searchResultsTableView {
        return self.filteredProgramy.count
    } else {
        return self.programy.count
    }
}

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = self.tableView.dequeueReusableCellWithIdentifier("cell") as UITableViewCell

    var program : Program

    if tableView == self.searchDisplayController!.searchResultsTableView {
        program = filteredProgramy[indexPath.row]
    } else {
        program = programy[indexPath.row]
    }

func filterContentForSearchText(searchText: String) {
    // Filter the array using the filter method
    var scope = String()
    self.filteredProgramy = self.programy.filter({( program: Program) -> Bool in
        let categoryMatch = (scope == "All") || (program.category == scope)
        let stringMatch = program.name.rangeOfString(searchText)
        return categoryMatch && (stringMatch != nil)
    })
}

func searchDisplayController(controller: UISearchDisplayController!, shouldReloadTableForSearchString searchString: String!) -> Bool {
    self.filterContentForSearchText(searchString)
    return true
}

func searchDisplayController(controller: UISearchDisplayController!, shouldReloadTableForSearchScope searchOption: Int) -> Bool {
    self.filterContentForSearchText(self.searchDisplayController!.searchBar.text)
    return true
}

}

A:

self.searchDisplayController is nil.
I just downloaded the tutorial's sample code (which you should do as well) and I see that the author has a "Search Display Controller" in their nib file. Check your nib file and be sure that the Candy Search controller is hooked up properly.
It's supposed to look like this:

To get to that image right click on the Search Display Controller object in the .xib file. Notice in my image that "Referencing Outlets" has a connection between searchDisplayController and CandySearch. That's what you are missing.
To create the connection ctrl drag from the CandySearch controller to the `Search Display Controller" when you let go of the mouse you will see:

Click searchDisplayController and you should be good to go.
Lastly, you should read up on how optionals work in Swift to help you understand issues like this in the future:
https://developer.apple.com/librarY/prerelease/mac/documentation/Swift/Conceptual/Swift_Programming_Language/TheBasics.html#//apple_ref/doc/uid/TP40014097-CH5-XID_456


Q:

How to get the return code of make in a shell script?

If I have a shell script which include a 'make' command, which make a C++ project. How can I get the return code of the make command? Just like?
RETURN_CODE=`make`

Anyone got experience here?

A:

The special variable $? contains the return code of the last command. You can save it to a variable like this:
make
exit_code=$?

RETURN_CODE=`make` is a command substitution, and results in standard output of make being saved to the variable RETURN_CODE.
PS: You should use $(foo) command substitution rather than backticks, and uppercase variable names are by convention only those which are exported to other scripts.


Q:

Using css in svg

I'm trying to figure out how to make svgs without giving every element a style attribute.
Two problems:
When referencing an external css file, the style appears correctly in a browser, but not in an image viewer.  Is this normal/avoidable?
Most of my elements have class and id attributes, and the following css doesnt provide the desired effect, i.e., county 21015 doesnt have its fill overridden
.county
{
font-size:12px;
fill:#d0d0d0;
fill-rule:nonzero;
stroke:#000000;
stroke-opacity:1;
stroke-width:0.1;
stroke-miterlimit:4;
stroke-dasharray:none;
stroke-linecap:butt;
marker-start:none;
stroke-linejoin:bevel;
}

path#21015
{
fill:red;
}

A:

If the fill isn't the one you want then there probably is something with higher specificity overriding the stylerule you want, such as an inline style attribute on that element, or some other rule affecting that element. You can also admit defeat by writing "fill: red !important" - that will work in the majority of cases.
Anyway, this is more of a css question than an svg question.


Q:

Is XAMPP safe for use inside a firewall?

This is partly related to this question.
I am deploying a PHP/MySQL application in my office, for my LAN.  It will not be accessible to the outside world unless they can enter my wireless network (which is not broadcasting the SSID so only we know about it).  This application will be hosting sensitive data that cannot be compromised.  So my question is, is it safe to use an XAMPP installation with it being behind a firewall and an encrypted, invisible wifi connection, or should i take further precautions?

A:

Not broadcasting the SSID is not really effective. However, if your Wifi network is WPA2 encrypted, then you should be relatively okay. You might want to use non standard ports for the XAMPP stuff and block them in your router's firewall.
Keep in mind that XAMPP isn't meant for production. Remember to make passwords for everything, as XAMPP comes with no passwords. For a really secure system, the best option is to install everything (Apache, PHP, MySQL, etc) manually and make sure they are properly secured.


Q:

Sketch app exporting in different sizes

I often need to export my assets in multiple sizes. The '1x' and '2x' option in Sketch simply isn't enough, as I sometimes need the same icon in let's say 200x200, 300x300 and 400x400 while the original artboard might be 800x800.
Is there a way to export the contents of an artboard at a certain size?
Scaling isn't always easy in Sketch as things like text etc don't scale.

A:

You can also use notation with h or w.  So if you want it 400 by 400, and it's square.  You can put 400w in the size field of export.

A:

You can use fractions in export dialog.

And since you can export slices (which are like bounding boxes of sorts, for export purposes), which size you can define as you want, it's easy to define a slice - based on your example - on 1000x1000 dimensions, and export it as 0.2x, 0.3x, 0.4x and 0.8x.


Q:

How to get correct size of OGRE::RenderWindow after its resize?

My program changes the size of OGRE::RenderWindow at some time and later I want to get the current size of the window. But, when I use getWidth() or getHeight() on the window, they return the original size of the window.
Example code:
OGRE::RenderWindow* win;

// ... OGRE is initialized
// Window is drawn 1024x768 using size from ogre.cfg

// ... lots of code ...

// Window size is changed and it works
win->resize(800, 600);

// ... lots of code ...

// Window is still visibly 800x600, but this call
// returns 1024x768 (the original size)
int w = win->getWidth();  // Returns 1024
int h = win->getHeight(); // Returns 768

How to get correct size of the window?

A:

There is getActualWidth() and getActualHeight() methods in Ogre::Viewport class, so you code would look like:
Ogre::WindowEventUtilities::messagePump();

int w = win->getViewport(0)->getActualWidth();
int h = win->getViewport(0)->getActualHeight();

Here we assume that there is only 1 viewport (indexed by 0).
When you use Ogre's rendering loop, you don't have to call this messagePump() as far as I know.


Q:

Why was this question closed?

Any plans to ban body scanner opt out after Brexit? I asked a very specific question: whether plans exist or not. I did not ask what will happen. How on earth can the existence of these plans be a matter of opinion? We have seen people here (Gayot , especially ) who had excellent sources of materials ordinary people would be very hard pressed to find. This is why I asked what I asked. It's just people can't be bothered to read.

A:

The problem with all the Brexit travel questions is that no certainty exists anywhere in the process, starting from very basic questions such as whether or not the UK and the EU will allow unrestricted flights between each other. Yes, there might be a policy document somewhere deep on Gov.UK which mentions the possibility of removing the body scanners opt out, but what good does it do at this point? Britain might end up staying in the EU eventually or end up accepting EU's policies in body scanners to align airport security between the two regions.
Feel free to reopen this question a few weeks after Brexit actually happens (if it ever does) and I'm sure we could dig up a proper answer then.


Q:

Get the variables set in 'this' by a function in another function

I have a function which adds some variables in this, for example:
this.a = "hello";
this.b = "bye";

The this of this function is an image,
$('#image').function1();

Now I want to access these variables in another function. I am calling this function the same way:
$('#image').function2();

but when I try to access this.a and this.b, undefined is thrown.
How can I access these variables from function2?

A:

You can use $.fn.functionName to extend prototype with new method that will add new properties in your case a and b to object that you call this method on, and then in another method you can access those properties.
$ or jQuery is a constructor function and fn is same as prototype

$.fn.function1 = function() {
  this.a = 'hello';
  this.b = 'bye';
  return this;
}

$.fn.function2 = function() {
  console.log(this.a)
}

$('img').function1().function2()
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img src="" alt="">


Q:

using Get for ajax calls gives me 500 error

I was calling a [web method] using POST but as I am 'getting' data back I am trying to use GET instead.
Using Post works.
Using GET gives me a 500 error.
This is the main jquery call to my [web method]:
        $.ajax({
            type: 'GET',
            contentType: 'application/json',
            dataType: 'json',
            url: 'Cloud/Feed.aspx/GetNextFrames2',
            data: '{ test: "hime"}',

~
This is my test [web method].
[WebMethod]
[ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
public static string GetNextFrames2(string test)
{
    return 'test'
}

If I do not pass any parameters I will get no error using GET.
As soon as add a parameter I get 500 internal error.
I have used wireshark and Fiddler but I cannot see anything useful.
This is obviously down to using parameters.  So, at least I have pinpointed where the error is.
I have tried passing the parameters directly appended to the url:
myurl?par=testme...
but still same error.
What else can I try?
Thanks

A:

The problem is with the value in the query string. The value should be within quote. The below code is working.
$.ajax({
            type: 'GET',
            contentType:'application/json',
            dataType: 'json',
            cache:false,
            url: "TestWebMathod.aspx/GetNextFrames2?test='hime'",
            error: function (error) {
                alert(error.responseText)
            },
            success: function (result) {
                alert(result.d)

            }

        });

Also look at the error.responseText to know the exact exception message. This will help to resolve the error.


Q:

Passing a complex Struct (with inner array of struct) from C# to C++

I'm working on a driver for a scanner. Got dll and header files from provider, aside of a manual in PDF, written in native C++ (dont have source code). Need to use it within a C# project but I'm having problems with the structs (either trying to read or send them).
I got the dll methods using the Command Prompt, demangling them in a website (since it has +100). Of course, I wont use all of them, just the ones I need. Didn't have problems with the ones using primitive data types, in fact, made the scanner turn on/off, scan and such.
My main problem is the following: I need to set some parameters, because with the default ones I'm not getting the needed info (and that's the MOST important thing I need, actually). The only way to do it is with a method that include 2 params: the ID (just an int) and the setting (an struct). That struct has internally not one, but 2 different structs instances (and one of them is an array, within another kind of struct as one of the params). In other words, gonna need to work with 4 different structs.
I declared all my structs, following the template provided in the .h file, and inmported the method. When I try to do a test it keeps giving me an error. I believe the problem is the array of structs. I tried with a normal passing, Marshaling, using a pin to array, changing data type, adding a "MarshalAs" with all bool vars... nothing seems to work.
Been trying to solve this for days already. Dont know what am I doing wrong (because this is my first time importing methods). I read about the C++/Cli thing but never worked with that either.
See code below (I kinda modified a little because of confidentiality of the information)
This is how is defined in the .h file (C++)
// The structs (won't add all parameters, but are basically the same type)
typedef struct _ImParam
{
  UINT Format;
  UINT Resolution;
  UINT ColorDepth;
} IM_PARAM;

typedef struct _sValues
{
  UINT Xpos;
  UINT Ypos;
  UINT Width;
  UINT Height;
  BOOL Milli;
} S_VALUES;

typedef struct _sProperties
{
  BOOL Enable;
  S_VALUES Properties;
} S_PROPERTIES;

typedef struct _DevParam
{
  BOOL Enable;
  UINT Font;
  char Symbol;
  IM_PARAM Image1;
  IM_PARAM Image2;
  S_PROPERTIES Properties[10];
  UINT FeedMode;
} DevParam;

// more code, comments, etc. etc.

// This is how is defined
BOOL SetParameters( DWORD ID, DevParams DParam )

This is how I build the structs in C#
[StructLayout(LayoutKind.Sequential)]
public struct ImParam
{
   public uint Format;
   public uint Resolution;
   public uint ColorDepth;

   public ImParam(uint n)
   {
       Format = n;
       Resolution = 300;
       ColorDepth = 256;
   }
};

[StructLayout(LayoutKind.Sequential)]
public struct sValues
{
   public uint Xpos;
   public uint Ypos;
   public uint Width;
   public uint Height;
   public bool Milli;

   public sValues(uint n)
   {
       Xpos = n;
       Ypos = n;
       Width = n;
       Height = n;
       Milli = false;
   }
};

[StructLayout(LayoutKind.Sequential)]
public struct sProperties
{
   public bool Enable;
   public sValues Properties;

   public sProperties(int n)
   {
       Enable = false;
       Front = false;
       Properties = new sValues(n);
   }
};

// Commented code is from another attemp
[StructLayout(LayoutKind.Sequential)]
public struct DevParam
{
   public bool Enable;
   public uint Font;
   public char Symbol;
   public ImParam Image1;
   public ImParam Image2;
   public IntPtr Properties;
   //public sProperties[] Properties;
   public uint FeedMode;

   public DeviceParameters(IntPtr SnP) //(int n)
   {
       Enable = true;
       Font = 0;
       Symbol = '?';
       Image1 = new ImParam(3);
       Image2 = new ImParam(3);
       Properties = SnP;
       /*Properties = new sProperties[n];
        *for(int i = 0; i < n; i++)
        *   Properties[i] = new sProperties(0);*/
       FeedMode = 1;
   }
};

// .dll file path definition, some methods imported, etc. etc.
[DllImport(path, EntryPoint = "?SetParameters@@YGHKU_DevParam@@@Z")]
public static extern bool SetParameters(int ID, DevParam dParam);

And this is when I do call it (added commented code to show you my attemps)
static void Main(string[] args)
{
    bool res = false;
    int ID;
    sProperties[] SnP = new sProperties[10];
    for (int i = 0; i < 10; i++)
        SnP[i] = new sProperties(0);

    try
    {
        // Some code to turn on scanner, get ID value and such

        /* Attemp1: Passing the struct normaly.
         * Result: ArgumentException [HRESULT: 0x80070057 (E_INVALIDARG))]
         * try
         * {
         *     DevParam dParam = new DevParam(10);
         *     res = Class1.SetParameters(ID, dParam);
         *     Console.WriteLine(res);
         * }
         * catch (Exception e) { Console.WriteLine(e); }*/

        /* Attemp2: Marshaling each element of the array.
         * Result: The managed PInvoke signature doesnt mach the destination one
         * int S = Marshal.SizeOf(typeof(sProperties));
         * DevParam dParam = new DevParam(Marshal.AllocHGlobal(SnP.Length*S));
         * IntPtr ptr = dParam.Properties;
         * for (int i = 0; i < SnP.Length; i++)
         * {
         *     Marshal.StructureToPtr(SnP[i], ptr, false);
         *     ptr += S;
         * }
         * try
         * {
         *     res = Class1.SetDevParam(ID, dParam);
         *     Console.WriteLine(res);
         * }
         * finally { Marshal.FreeHGlobal(dParam.sProperties); }*/

         /* Attemp3: Adding a Pin Pointer to struct
          * Result: Exception (Object has no primitive data and it can't
          *     be transfered into bits blocks) */
         GCHandle SpHandle = GCHandle.Alloc(SnP, GCHandleType.Pinned);
         try
         {
             DevParam dParam = new DevParam(SpHandle.AddrOfPinnedObject());
             res = Class1.SetParameters(ID, dParam);
             Console.WriteLine(res);
         }
         catch (Exception e) { Console.WriteLine(e); }
         finally { SpHandle.Free(); }

         // More code for testing other methods and blahblahblah
     }
     catch (Exception e) { Console.WriteLine(e); }
     Console.WriteLine("Finished");
     Console.ReadKey();
}

What do I expect? Getting just a boolean result to see if method executed sucessfully (and of course, if true, scanner should have defined the new parameters)
What do I get? A bunch of exceptions.
Please, any help would be great. Thanks in advance.
PD: Sorry for that long post.
PD2: I'm quite rockie, so please try to explain it "for dummies"

A:

Thanks Hans. Seems it worked!
Just modiffied the struct as suggested:
[StructLayout(LayoutKind.Sequential)]
public struct DevParam
{
   public bool Enable;
   public uint Font;
   public char Symbol;
   public ImParam Image1;
   public ImParam Image2;
   //public IntPtr Properties;
   [MarshalAs(UnmanagedType.ByValArray, SizeConst = 10)]
   public sProperties[] Properties;
   public uint FeedMode;

   public DeviceParameters(int n) //(IntPtr SnP)
   {
       Enable = true;
       Font = 0;
       Symbol = '?';
       Image1 = new ImParam(3);
       Image2 = new ImParam(3);
       //Properties = SnP;
       Properties = new sProperties[n];
        for(int i = 0; i < n; i++)
           Properties[i] = new sProperties(0);
       FeedMode = 1;
   }
};

And used the "Attemp1" code.


Q:

Tab bar and Mapview issues

I'm really confused about this issue. I have recently been having issues with my mapview tab in my application. Even to the point of starting over again. I'm just wondering if I am the only one having this issue or am I doing something wrong here.
I am fairly new to iOS but I know how to define a mapview's center and span in order to center on the user's location.
I've built this in its own view and it seems to work but when I put it in a tab controller...I have an issue. The map stays zoomed out while showing the user's location.  It's supposed to show the user's location zoomed in.
My MapViewController:
- (void)viewDidLoad
{
    [super viewDidLoad];
    [self.mapView.delegate self];
    [self.mapView setShowsUserLocation:YES];
    // Do any additional setup after loading the view from its nib.
}

-(void)mapView:(MKMapView *)mapView
didUpdateUserLocation:(MKUserLocation *)userLocation
{
    CLLocationCoordinate2D loc = [userLocation coordinate];
    MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance(loc, 500, 500);
    [self.mapView setRegion:region animated:YES];
}

I also thought it could have something to do with the way I created the tab controller in the delegate.
My app delegate:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    // Override point for customization after application launch.
    UIViewController *viewController1 = [[NWSWelcomeViewController alloc] initWithNibName:@"NWSWelcomeViewController" bundle:nil];
    UIViewController *viewController2 = [[NWSMapViewViewController alloc] initWithNibName:@"NWSMapViewViewController" bundle:nil];
  //  UIViewController *viewController3 = [[NWSSettingsViewController alloc] initWithNibName:@"NWSSettingsViewController" bundle:nil];
    self.tabBarController = [[UITabBarController alloc] init];
    self.tabBarController.viewControllers = @[viewController1, viewController2, /* viewController3 */];
    self.window.rootViewController = self.tabBarController;
    [self.window makeKeyAndVisible];
    return YES;
}

I am writing for iOS 5.1 and I am using the latest Xcode.
Yes, I have the settings for zooming enabled on the mapView.
I just want to get the user location to zoom in the mapview to the user's location.

A:

This line in viewDidLoad:
[self.mapView.delegate self];

does nothing (it is trying to send the message self to self.mapView.delegate).
It doesn't actually set the map view's delegate and so the didUpdateUserLocation never gets called.
What you probably meant was:
[self.mapView setDelegate:self];

or this:
self.mapView.delegate = self;


Q:

How to add a tag where there isn't one yet?

If I have this HTML code for example:
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat.

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat.

How can I add tag

 for every text where I do not have any tags, like this untagged lorem ipsum text?

A:

Assuming your full text/lipsum is wrapped in some div or other html tag:

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

You can find the paragraphs, split by new lines, then re-insert it with surrounding p tags.
const element = $('.text')
const content = element.html()
const lines = content.split('\n')
const paragraphs = lines.filter(x => x)
const html = paragraphs.map(x => '
' + x + '
').join()
element.html(html)

If you're unfamiliar with fat arrows (x => ...) let me know and I'll change it to JS5
https://jsfiddle.net/wtLs7ef6/2/


Q:

How to display the value of a variable using remix debugger and emit

pragma solidity ^0.5.1;

contract test {
    event test_value(uint256 indexed value1);
    uint256 value_test;

     function test_f() public {

        //value_test processing
        emit test_value(value_test); // log the current value
    }
}

Can some body please guide me how to display the value of "value_test" using Remix debugger or emit?

A:

Deploy and Run Transactions
Deploy Contract
test_f
Debug
logs
value1: 0

Hope it helps.


Q:

How to read from csv to a ListMap

I have been assigned with the task of reading from csv, and creating a ListMap variable. The reason to use this specific class is that for some other use cases they were already using a number of methods with ListMap as input parameter, and they want one more.
What I have done so far is: read from the csv, and create a rdd.
The format of the csv is
"field1,field2"
"value1,value2"
"value3,value4"

In this rdd I have tuples of strings. What I would like is to now convert this to a ListMap class. So what I have is a variable with the type Array[(value1,value2),(value3,value4)].
I did this because I find it easy to go from a csv to tuples. The problem is I do not find any way to go from here to a ListMap. It seems easier to get a normal Map class, but as I said, it is required for the final result to be a ListMap type of object.
I have been reading but I do not really understand this answer nor this one

A:

Depending on the sample data you provided, you can use collectAsMap api to get the final ListMap
val rdd  = sparkSession.sparkContext.textFile("path to the text file")
  .map(line => line.split(","))
  .map(array => array(0) -> array(1))
  .collectAsMap()

Thats it.
Now if you want to go a step further you can do additional step as
  var listMap : ListMap[String, String] = ListMap.empty[String, String]
  for(map <- rdd) {
    listMap += map
  }


Q:

intellij- cannot resolve symbol 'support'

I am new to intellij13 and just imported my Android project into it. however get the following errors and tried adding dependencies but cannot work.
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.TextView;

those are my imports

A:

Going out on the limb here, but you probably need to add android-support-v4.jar to your project dependencies (in the /libs folder). If you are using Gradle, then add:
dependencies {
    compile 'com.android.support:support-v4:19.1.+'
    compile 'com.android.support:appcompat-v7:19.+'
}

in your build.gradle file


Q:

SQL postgresql insert statement

I have a following question, for example I have a following table:
CREATE TABLE "regions" (gid serial PRIMARY KEY,
"__gid" int8,
"name" varchar(20),
"language" varchar(7),
"population" int8);

And I want to insert some records, say one of the values for "name" is - 'B', what sort of code would I have to write to change 'B' to 'English-Speaking'? Is that done with some sort of trigger? So would I have to write a trigger to change the values automatically on insert? Any help greatly appriciated!!!

A:

It's an UPDATE statement which will do what you wish, in this case:
UPDATE regions set name = 'English-Speaking' where name = 'B';

To put this in a function use something like:
CREATE OR REPLACE FUNCTION  insert_into_wgs()
RETURNS void AS
$$
BEGIN
UPDATE regions SET name = 'English-Speaking' WHERE name = 'B';
END
$$
LANGUAGE 'pgpsql';

Then you create a trigger to run this function:
CREATE TRIGGER log_update
    AFTER UPDATE ON accounts
    FOR EACH ROW
    WHEN (OLD.* IS DISTINCT FROM NEW.*)
    EXECUTE PROCEDURE
    insert_into_wgs();


Q:

Is the V-T movement possible in English?

To clarify: V-T movement would be a type of movement of the V head (verb phrase) to I (or T) head (inflection phrase). Some languages, like French, allow for this movement. But during my syntax classes I've been told that such movement is illicit in English.
However, in a book on syntax (A. Witkos 'Movement Rules. Foundations of GB syntax of English' p. 252) I came across this sentence:

There is a student outside the classroom

it's bracketed derivation looked like this:

[IP There is [VP t(is) [PP a student [P' outside the classroom]]]

which shows an instance of such a movement. The 'is' trace sits in [head, VP] and then moves to [head, IP].

A:

Under the standard XP-Internal Subject Hypothesis, the derivation above is correct, and is does indeed exceptionally raise from V to T in cases like this.
It is true, though, that V-T movement (and further raising of finite main verbs into higher heads like Focus and C) was available in English until well after Shakespeare's time, and that, whereas in languages like Spanish, French, Italian or German it still remains generally available, in English it has since become restricted to a) auxiliaries (i.e., modals, aspectual have and be, passive be and 'dummy' do), b) the main verb be (in all its existential, identificational, or copular uses), and, to the extent the construction survives, in the speech of old-fashioned British English speakers, mainly, c) possessive uses of the main verb have, as in You haven't money, Have you money? (instead of the much more common You don't have money, Do you have money?).
The standard explanation for why V-T Raising has remained possible for just auxiliary verbs and main verb be used to be that none of them theta-marks its complements (and none projects a subject argument, either), which would leave them free to raise from the VP in order to check their inflectional features.
That may well be right for auxiliaries, certainly, copular uses of main verb be (e.g., She is brilliant, She is an engineer, She is in London, etc. in which the subject receives its theta-role from A, P or N), and for existential uses of be like the one you mention in your question, where be selects a PP complement but it is the P outside that theta-marks a student and the classroom.
However, that 'explanation' gets much more dubious, or plainly unacceptable, for a) existential uses of be in which be is not followed by any theta-marker (as in, e.g., There is a cafeteria, unless some hidden/ellipted PP structure is assumed, of course), b) 'identificational' uses of main verb be, as in That tall man is my brother, where is must be a two-place predicate and theta-mark the two NPs/DPs, and c), to the extent the construction survives, possessive uses of the main verb have, which is also a two-place predicate and must theta-mark its two arguments, the subject as 'Possessor' and the object as`Theme', or whatever the right role-label is for the entity 'possessed'.
Thus, what used to be the standard explanation for the exceptional survival of V-T raising in the above-mentioned cases is far from satisfactory, and, to my knowledge, please correct me if I am mistaken, it has not been replaced with any other, but the facts are solid enough: finite auxiliaries, finite main verb be, and, marginally, finite main verb have can still raise to T/Infl and higher, whereas no other English verbs can.


Q:

(int)Math.random prints random line of numbers outside of set range for first line

Trying to make an array of random numbers. Here is what I have so far:
    public static void main(String[] args) {
randomArray(5);
    }
    public static int randomInt(int low, int high){
        int x=0;
        for (int i=0;i<10;i++){
           x= (int)(Math.random ()*high)+low;
             System.out.print(x);
        }
     return x;
    }
    public static int[] randomArray(int n){
        int[] a = new int [n];
        for (int i = 0;i<a.length;i++){
            a[i]=randomInt (0,100);}
        printArray(a);
        return a;
    }
    public static void printArray (int[]a) {
        for (int i = 0; i<a.length;i++){
            System.out.println(a[i]);
    }

    }
}

this  returns something along the lines of
9265956792478464547638861753937389642303686408882492318499964845942725987325868511898811389
42
49
73
72

Which is way, way out of range. Any ideas?

A:

Because you have a: System.out.print(x) inside randomInt.


Q:

Student's t-test with a covariate?

I am testing the different between some variables $X$ and $Y$ using the Student's t-test. I suspect that there might be a latent variable $Z$ that has an effect on both $X$ and $Y$. How could I control $Z$?
I am using Python for the data analysis.

A:

One common means of controlling for some other covariate would be via regression. Put the X and Y values into the response (DV), and a Y-group indicator (0 if in X, 1 if in Y) as a DV, along with your covariate (or some suitable proxy for it if the variable can't be measured directly) as another DV.
You regress on your covariate and the group-indicator. If there's a difference between X and Y based on the covariate, this will be "adjusted" for by the regession, and significance of the coefficient of the group-indicator will then be a test of a mean-shift between the two groups after accounting for the covariate.

This is sometimes called ANCOVA (unless Z is a factor, in which case it would usually be called ANOVA; you can still do it using regression).
Some people would formally test parallelism of the two group-lines (by including an interaction between covariate and group-indicator). I think that's wrong-headed (do we believe the hypothesis of no-interaction is exactly true? I don't -- in which case the hypothesis test is a noisy answer to a question we already know the answer to -- surely they're never going to be exactly parallel) ... but don't especially care about. The better question here is "are they close enough to parallel that it doesn't badly impact the properties of the inferences we wish to make?'. Answering that is nearer to measuring an effect size, so a residual display - e.g. residuals vs covariate that distinguishes the groups with symbols or colors - might come closer to addressing that.

However, depending on what you mean by 'latent' in your question, it's possible that you may actually be after something more like an instrumental variable. (There are numerous questions on site on the topic.)

A:

By means of t-test you are assessing whether there is a significant difference between two sets of data --- e.g. the realizations of two random variables $X$ and $Y$. When using t-test you are doing a hypothesis test, and you can't control for any variable. To be more specific, when doing hypothesis tests you are not establishing any causal relationship between random variables.
If you want to investigate the effect of a latent variable $Z$ on both $X$ and $Y$, you should rely on a regression analysis. For a deeper analysis on the role and effects of some variables (which can cause a bias in your analysis), you can apply some methods of graphical models.
Here you find a nice IPython Notebook on regression.


Q:

Using a lemon's energy

Some simple exercises i need some confirmations on.
Let's say a lemon has U = 1V and an average current of 0.1mA for about an hour.
Q1. How much lemons do you need to light a 100W bulb.
Is the answer 1 million lemons ?
Q2.The Atmega1284P processor has an average energy consumption of 0.18nJ/instruction. How much instructions can be executed from a single lemon.
Is the answer (6*10^6)/0.18 ?
And a bonus one i haven't figured :
A battery that functions at 1Ah is draining with 4C on a resistance of 2W. How much time till the battery is fully drained.

A:

Since $P=UI$, for Q1 $100W=1V\cdot 0.1mA\cdot N\Rightarrow N=10^6$, so your answer is right.
For single lemon we have $A=1V\cdot 0.1mA\cdot 3600 s=360mJ$. Thus we can execute $A/q=360mJ/(0.18nJ/instruction)=2\cdot 10^9$ instructions.


Q:

What is "Dummy for Loop" in C?

One of my friend asked me this question while we were travelling back to home. And he got to know about this from his teacher. First he told me its something like the infinite loop with no body. Hence I posted this question here asking whether infinite loop is called as dummy for loop.
I haven't seen anything like Dummy For in any of the books I read and not from the internet as well. Later he told me that those for loops which contains blank body are known as dummy loop. One like this :
for (int i=0; i<10; ++i);

Such loops are quite helpful in some cases. I was more eager to know if there is something really exists in software development field or it's just a name given by an individual.
Sorry for the delay in editing the details.

A:

It is an infinite loop with no body. The purpose would be to make sure the program doesn't end, yet does nothing. It is also known as an idle loop.
That doesn't mean nothing will ever happen. There could still be interrupts occurring, which make the cpu jump out of the loop, and return to the loop after the interrupt service routine has finished.
Often this technique is used in embedded programming, where inputs and timers trigger interrupts, in which all of the activity occurs. When no interrupt is being serviced, we want to ensure the program doesn't just run off the end of the code.


Q:

How to use http Response method Read in go?

It's been a while since I dealt with go and I seem to have forgotten how to read the docs.
If I do a get request like this...
resp, err := http.Get("https://example.com")

I then see that the response has a Body that is of an io.ReadCloser type (https://golang.org/pkg/io/#ReadCloser). I see the ReadCloser is an interface to Reader and Closer.
When I look at the Reader interface I see it has a Read method that reads bytes into p (https://golang.org/pkg/io/#Reader).
To recap, the http Response has a body which is a io.ReadCloser Interface which itself contains a Reader interface which has a Read method.
When I try this I would expect to Read the response bytes into HTML, but I see nothing...
var html []byte
num, err := resp.Body.Read(html)
fmt.Println("\n\thtml: ", html)
fmt.Printf("\n\tnum: %v, err: %v\n", num, err)

Output:
html:  []
num: 0, err: <nil>

What am I missing here?

A:

short answer: You are passing a slice html where its len would be '0' and Read reads up to len(html) bytes into html
Here is snippet from https://golang.org/pkg/io/#Reader

Read reads up to len(p) bytes into p. It returns the number of bytes
read (0 <= n <= len(p)) and any error encountered. Even if Read
returns n < len(p), it may use all of p as scratch space during the
call. If some data is available but not len(p) bytes, Read
conventionally returns what is available instead of waiting for more.

Now what you may do  use ioutil and update the code as
body, err := ioutil.ReadAll(resp.Body)

Code
package main

import (
    "fmt"
    "io/ioutil"
    "net/http"
)

func main() {
    resp, err := http.Get("http://httpbin.org/ip")
    if err != nil {
        fmt.Println("Error making request", err.Error())
        return
    }
    defer resp.Body.Close()
    body, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        fmt.Println("Error reading response", err.Error())
        return
    }
    fmt.Println("Response\n", string(body))
}

Here is play link, in go playground HTTP requests won't work it is a security precaution so you may test this in your machine


Q:

Dropbox API uploading mp3 file

I am making a Python script to upload mp3 files in my Music folder to Dropbox, but I cannot figure out how to do so. I am using Dropbox API and here's my code
import dropbox
dbx = dropbox.Dropbox('*******')
dbx.users_get_current_account()

f = open('Channa Mereya.mp3', 'rb')
dbx.files_upload(bytes(f.read()), 'Channa Mereya.mp3')

but I get the error
dropbox.stone_validators.ValidationError: 'Channa Mereya.mp3' did not match pattern '(/(.|[\r\n])*)|(ns:[0-9]+(/.*)?)'

I don't know much about regex patterns.
Also while reading API documentation, files_upload takes first argument as bytes, I don't why it takes bytes.
I also tried to just pass the path of mp3 file instead of opening and passing the file like
dbx.files_upload("/home/username/python projects/Channa Mereya.mp3", 'Channa Mereya.mp3')

Here Channa Mereya.mp3 is a mp3 file stored in the same directory as the
script

A:

When specifying a file path to upload to in Dropbox API v2, the path should have a leading "/" to identify root. So, the second parameter to files_upload should look like '/Channa Mereya.mp3'.
The error is indicating that your path value 'Channa Mereya.mp3' doesn't match the allowed pattern, i.e., it doesn't have that leading slash.


Q:

How are DNS name-servers for a TLD updated when a new domain is registered?

Let's say I have registered new domain mydomain.com with a domain registrar like Godaddy.
When I dig for my domain, I see the following section:
;; AUTHORITY SECTION:
mydomain.com.       3079    IN  NS  nsXX.domaincontrol.com.
mydomain.com.       3079    IN  NS  nsXX.domaincontrol.com.

This indicates that the authoritative servers for mydomain.com are the nsXX.domaincontrol.com servers, which (according to info out there) are godaddy-owned name servers.
I would like to better understand how the .com TLD servers are updated to know the authoritative name-servers for a newly registered domain? Specifically:

Does this involve a zone file update for the .com TLD? If so what
kind of entry is made there?
Is there only one zone file for the .com TLD?
What is the mechanism by which the update is made? Is there any API integration between a registrar like Godaddy and the TLD server
to make such entries? Or does the registrar publish such updates by
some other mechanism?
At the registrar end, is a separate zone file created and maintained for mydomain.com?

A:

Yes, the TLD updates their zone to include your name servers, so that a resolver knows where to go next. When a recursive resolver looks up a record, it first goes to the root . to get the name servers for com., then it asks those servers for the name servers for mydomain.com. which it then asks for the record, for example www.mydomain.com.. Or if it's a delegated subdomain, it might get another set of name servers, and so and so forth.
Yes, in theory there's only one single zone file, it's however replicated to a lot of different servers globally.
Larger TLDs and registrars use an API call to notify the TLD operator of any new registrations and changes. In fact almost every TLD has some sort of API, but smaller registrars still do manage things manually (usually smaller outfits that don't mainly deal in domains, but offer it as a part of their services)
If the registrar offers DNS services, they might automatically create a zone for your domain so you can get started (this is what GoDaddy seems to have done), and as such they've registered their servers as the name servers for mydomain.com. with the .com. TLD. However, some registrars don't offer these services, so they'll just register whatever name servers you specify.

There are some TLDs that let the end customer register with them directly, for example the .fi. TLD used to allow this, but has since demanded that end customers go through a registrar for some reason.


Q:

Identifying best method for solving a $1^{st}$ order O.D.E

I am faced with this d.e:
$$y' = \frac{2xy+3y^2}{2xy +x^2}$$
I know these methods for solving a $1^{st}$ order, o.d.e:
*Integrating factor
*Separation of variables
*Exact d.e
*Using intgrating factor to transform a d.e to exact d.e
I could try each of these methods in a brute force way until i manage to find a solution for my d.e.
But this is not optimal.
So how do I know which method to use?
In this example and/or in general.

A:

$$y' = \frac{2xy+3y^2}{2xy +x^2}$$ is a homogeneous equation.
The change of variable $$y=ux$$ will transform the equation into a separable one.
$$ u+xu'=\frac {2u+3u^2}{2u+1} $$
which simplifies to $$ \frac{dx}{x}=\frac{(2u+1)du}{u^2+u}$$


Q:

is my JSON response correct? and why i see this exception when i try to retrieve it?

my problem is that i have an asp. web service .. and it gives me the following result when i invoke it :
[
  {
    "_OrderDetails": [
      {
        "ProductName": "FUCHS SUPER GT SAE 10W30 6X5 / FP10100010102",
        "TotalAfterDiscount_Lc": "7500",
        "MeasureUnitName": "كرتونة",
        "TotalPrice_Lc": "7500",
        "PricePerUnit_Lc": "75",
        "Quantity": "100"
      }
    ],
    "Id": "274",
    "OrderDate": "4/10/2014 12:00:00 AM",
    "Number": "16",
    "CustomerName": "الأسد",
    "Note": ""
  }
]

and in the main activity i do the following :
 Gson gson = new Gson();
            Log.e("Response", responseJSON);

            if (responseJSON != null) {
                try {
                    JSONObject jsonObj = new JSONObject(responseJSON);

                     //JSONArray jsonarr =new JSONArray();
                    // details=jsonObj.getJSONObject(0);
                    // Getting JSON Array node
                    details = jsonObj.getJSONArray(TAG_CONTACTS);

                    // looping through All Contacts
                    for (int i = 0; i < details.length(); i++) {
                        JSONObject c = details.getJSONObject(i);

                        String product = c.getString(TAG_PRODUCT);
                        Log.e("prodeuct",product+"");
                    }

i see the response in the logcat correctly but when i try to get any object  from the array i see a JSON exception it says :
JSON array can't be converted to JSON object !!!
please can anyone help me??

A:

Because your json return jsonarray and you are try to access jsonobject.
Change your code:
if (responseJSON != null) {
                try {
                    JSONArray jsonObj = new JSONArray(responseJSON);

                          // looping through All Contacts
                    for (int i = 0; i < jsonObj.length(); i++) {
                        // your code
                    }


Q:

Disable input fields within iFrame without Javascript

I know that you can disable an input field like this:
<input disabled></input>

But is there a simple way to disable all the inputs within an iFrame a similar way?  Like this:
<iframe src="/foo" disabled></iframe>

A:

Unfortunately no answers have been satisfactory (or they just didn't answer the correct question), so I am answering my own.
The answer I've found from the documentation on the properties/attributes has led me to believe it is impossible.  Since I was using an iframe from a source I could modify, I fixed what I needed to there, but it would have been a much cleaner and DRYer solution if this were possible.


Q:

How can I take immediate payment plus recurring via PayPal?

I'm using Express Checkout, and I would like to set up a scenario as follows:

$10 is charged right now
A monthly payment of $15 is set up

So if today is day 0, on day 0 they'd be billed $10, on day 1, they'd be billed $15, and then on day 61 they'd be billed $15 again (and so on).
I'm doing this using the trialamt, trialtotalbillingcycles, trialbillingperiod and trialbillingfrequency parameters. This sets up a payments profile like in this screenshot:

As you can see, this was set up on May 6th. No money has been taken out, not even the initial amount there, and it says that the next payment due is May 6th, and the profile start date was then too. Is there some gigantic delay on the sandbox? It's been 3 days now.
Alternatively is there another way to do this? I could make a standard Express Checkout payment for the today amount and then use the profilestartdate to start it tomorrow. However, I believe that if you set a future date using profilestartdate, the profile is marked as 'suspended' and you nor the customer can cancel it until it's activated.

A:

There does appear to be a delay, especially on the sandbox, of anything up to several days. This makes testing difficult sometimes. An alternative might be to use both a one-off Express Checkout payment instead of using the initamt field, since you can get the user to confirm both the subscription and payment for an item at the same time.