Q:

What's in a druid's grove?

I've started a D&D 5e campaign in Oerik (Greyhawk) with a druid in the party. I want to allow her to use the druid groves on the Anna B Meyer maps, but I can't find any info on their benefits, if any. I'm envisioning maybe some healing properties, and possibly some type of communication with other groves.
Has anyone used druid groves?

A:

This is not lore, but is instead focused on D&D 5E mechanics.
In Xanathar's Guide to Everything, there is a Spell called Druid Grove which magically creates a warded area--and if you repeat the spell in the same location for a year, the magic becomes permanent (until dispelled).
As for size

The area can be as small as a 30-foot cube or as large as a 90-foot cube.

As for what the warded area does...

The spell creates the following effects within the area. When you cast this spell, you can specify creatures as friends who are immune to the effects. You can also specify a password that, when spoken aloud, makes the speaker immune to these effects.

You get the following protections over the area...

Solid Fog. You can fill any number of 5-foot squares on the ground with thick fog, making them heavily obscured. The fog reaches 10 feet high. In addition, every foot of movement through the fog costs 2 extra feet. To a creature immune to this effect, the fog obscures nothing and looks like soft mist, with motes of green light floating in the air.
Grasping Undergrowth. You can fill any number of 5-foot squares on the ground that aren’t filled with fog with grasping weeds and vines,
  as if they were affected by an entangle spell. To a creature immune to
  this effect, the weeds and vines feel soft and reshape themselves to
  serve as temporary seats or beds.
Grove Guardians. You can animate up to four trees in the area, causing them to uproot themselves from the ground. These trees have
  the same statistics as an awakened tree, which appears in the Monster
  Manual, except they can’t speak, and their bark is covered with
  druidic symbols. If any creature not immune to this effect enters the
  warded area, the grove guardians fight until they have driven off or
  slain the intruders. The grove guardians also obey your spoken
  commands (no action required by you) that you issue while in the area.
  If you don’t give them commands and no intruders are present, the
  grove guardians do nothing. The grove guardians can’t leave the warded
  area. When the spell ends, the magic animating them disappears, and
  the trees take root again if possible.
Additional Spell Effect. You can place your choice of one of the following magical effects within the warded area:

A constant gust of wind in two locations of your choice
Spike growth in one location of your choice
Wind wall in two locations of your choice

To a creature immune to this effect, the winds are a fragrant, gentle
  breeze, and the area of spike growth is harmless.

So, in short, it would be easy to make the assumption that mapped Druid Groves are simply places where a powerful Druids has made a Druid Grove spell permanent. Anything else that may be within them is up to the druids who live near there and use the Grove.
If you'd like further info on Druidism in Greyhawk, and of the spiritual significance of a Grove...

Sacred Groves: The sacred groves act as centers of worship for the Old Faith. They are the lesser of the two worship sites and are much more common than megalithic circles. Oak groves are the most prevalent, but other trees are used, such as the massive deklo or the fruit-bearing usk. The choice of trees in a grove is crucial as every tree has symbolism to the Old Faith.

As taken from an old D&D 3.5E article on WotC's website.
Note that as I am not Anna B Meyer, I cannot say for absolute certain that this was their intent with the groves placed on their maps.

A:

Masters of the Wild web enhancement - Druids Grove (3.5e), which was a pdf addon to the corebook Masters of the Wild, contains the following info:
Must haves:

First, there must be a place for the druid to sleep. This can be a natural shelter, such as a cave, or one built from natural materials, such as a sod hut or tree house.
Next, there must be a good supply of food and clean, fresh water. The food supply can include nuts and berries, tree fruit, and a diverse population of animals.
In addition, most druids maintain at least one herb garden, and many also cultivate a patch of vegetables.
The next vital feature is a system of protection for the druid and her charges, both plant and animal. This often takes the form of natural barriers, such as briar
hedges or dense forest.
Warmth is another vital issue. If the climate where the druid lives is temperate or cooler, she requires a good source of firewood, coal, or other fuel.  In addition, druids use natural materials to make warm clothing and blankets. Each generally has a cache of tools stashed away for sewing hides and weaving cloth from plant fibers or animal hair.
Druids like to be prepared for emergencies, so most keep a supply of important magical and nonmagical items secreted about their groves—in hollow trees, under stones, and in unused animal lairs. Stashed magical items usually include goodberries and infusions of
useful spells (see Masters of the Wild, Chapter 3). Other useful items include small amounts of money (in case they need to visit a town), tools for starting a fire, knife and extra weapons.
A typical druidic grove features some means for scrying—most often a pool of still, mirrorlike water. A large, highly polished rock also might make a good
scrying device. In a pinch, a druid can use the create water spell to produce still water for scrying in a large container or natural crevice.

Those are the main points, slightly edited for brevity. The rest of the pdf is devoted to outlining a sample druid's grove for a 12th level Half Elf Druid named Thyme. The pdf is freely available for download at the link above.
In addition, if you have access to the 2e rulebook The Complete Druid's Handbook, there are details on lesser and greater magical groves, which would add the benefits you are seeking, among which are the following (Lesser Grove):

Druids entering the grove feel a watching presence and a sense of power. For every three rounds they spend within its boundaries they learn one power of the sacred grove, through a vision or intuition.
All druids receive a +1 bonus to saving throws vs. spell, death magic, and wands
while within a lesser magical grove. The grove’s steward receives a +2 bonus.
All in the grove are rendered immune to magical fear while within it.
Dig spells never work within a grove.
Natural (nonmagical) lightning never strikes trees or beings in the grove.
Evil enchanted creatures cannot enter the grove unless it has been defiled. (See ”Defiled and Cursed Groves” in this chapter).

There are tables to determine random benefits for lesser and greater magical groves (Of which not all groves are magical to begin with.)


Q:

Handling object deserialisation after changing namespace

I'm wondering is there any way to handle deserialisation after changing a classes, namespace?
At the moment I'm having to do an edit replace on the text value of the XML replacing old namespace with new namespace.
Is there a better way to do this?

A:

Always a tricky one. Unless you can guarantee that the class won't change, then it's probably best to find another approach to serializing.
However, to answer the question, you could have a Version property of the class (or put it in a base class if you have many). You'll need to remember to increment this whenever you change the class.
Then you could have a series of "migrations", which would know how to transform the XML from one version to the next. When you want to deserialize, first load the file as XML, apply the migrations in turn (as there may have been several changes since the file was created), and then deserialize the now transformed XML.


Q:

How do I bind the right value of this in javascript class callbacks?

class SomeClass {
  constructor() {
     this.x = 0;
  }
  getSomething(inputVal) {
   let self = this;
   return new Promise((resolve, reject) => {
    setTimeout(function(){
     if(inputVal){
       self.x = 1;
       resolve();
     }
     else{
       self.x = -1;
       reject();
     }

   }, 10);
 });
}

I am having to use a variable called self to refer to this. Is this wrong to do? if not, how else do I do it?

A:

Is this wrong to do?

No, obviously that method it's not wrong, it's just a way to keep a reference to this object.
But there are some alternative ways for this problem:
1. Use bind method.

The bind() method creates a new function that, when called, has its
  this keyword set to the provided value, with a given sequence of
  arguments preceding any provided when the new function is called.

getSomething(inputVal) {
        return new Promise((resolve, reject) => {
            setTimeout(function(){
                if(inputVal){
                    this.x = 1;
                    resolve();
                }
                else{
                    this.x = -1;
                    reject();
                }

            }.bind(this), 10);
        });
 }

2. Use arrow functions.
Until arrow functions, every new function defined its own this value.
For instance, this can be a new object in the case of a constructor.

function Person(age){
  this.age=age;
  console.log(this);
}
let person=new Person(22);

Or this can points to the base object if the function created can be accessed like obj.getAge().

let obj={
  getAge:function(){
    console.log(this);
    return 22;
  }
}
console.log(obj.getAge());

An arrow function does not create its own this, it's just used the this value of the enclosing execution context. In the other hand, arrow function uses this of parent scope.
getSomething(inputVal) {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            if (inputVal) {
                this.x = 1;
                resolve();
            }
            else {
                this.x = -1;
                reject();
            }

        }, 10);
    });
}


Q:

Force page to load even when landing by navigating back (by back-button)

I'm quite desperate due to the following issue:
How the hell :-) .. can I force my page to be reloaded everytime so lands on it?
I have a input which is automatically filled with text from localStorage if this value is set. And I have links on my page to other pages. So (just an example) maybe the user clicks on pagexyz.com and then decides to navigate back to my site by clicking the backbutton. I tried a whole lot of things but am not able to force my piece of javascript to be executed.
The solution given here did not help me around.
These did not help.
So what else to do? I tried setting all cache-related meta tags - there must be a way to execute js when the page is called!?
So thankful for any kind of hint!
hos

A:

The problem is that by navigating back with the back button of the browser, the onload event of the page usually does not fire, neither will the JS code in the global scope be executed.
One possible solution that is widely used for the so-called "hash history hack": Start an interval with setInterval() that checks every (let's say) 500 msec for a hash change and refresh the content according to the hash.
On a usual content refresh you'll have to set the hash manually (window.location.hash="..."). And on initial page load (perhaps from a bookmark) you'll have to check the window.location.hash and load content accordingly.


Q:

Spring JdbcTemplate: how to limit selected rows?

I'm using Spring JdbcTemplate interface for fetching data from a MS SqlServer DB.
In the documentation I see there is the setMaxRows() method to set a limit for all the queries, but what if I want to limit only a select?
Is there a way to set a limit only for a specific invoked query in a "configurable" way?

A:

Some SQL based query languages(derby) doesn't support LIMIT keyword. So you can't use LIMIT in query directly. Using Spring JDBC Template we can set maximum number of rows needed through setMaxRows(Integer intvalue)
jdbcTemplate.setMaxRows(1);

A:

Limiting the result set of a specific query can be done by putting the limit directly into the query. Consult your DB vendor documentation to see if it supports for example LIMIT.
Example on MySQL: SELECT * FROM EMPLOYEE LIMIT 10


Q:

Given a nxn matrix $A$, show that if $A^3 = 0$ then $A-I_n$ is invertible. (Closed)

So if we have $$A^3 = 0$$ we can say that $$A^3-I_n = -I_n$$ where $I_n$ is a n x n identity matrix. We know that to be invertible as all the columns of $I_n$ are linearly independent.
I know we can factorize that to $$(A-I_n)(A^2+A+I_n)=-I_n$$
This is where I get stuck and am not sure on how to proceed.

A:

Another proof: suppose that $A-I_n$ is not invertible. Then $0$ is an eigenvalue of $A-I_n$. Hence $1$ is an eigenvalue of $A$. It follows that $1=1^3$ is an eigenvalue of $A^3=0$, contradiction !


Q:

Possible to query by key instead of value in Hazelcast (using Predicates)?

In Hazelcast, is it possible to query an IMap based on attributes of a key instead of the values?  All the Hazelcast examples show querying by value.  E.g., for a map of employees with keys that are strings:
IMap<String, Employee> employees;

The typical search predicates then search based on employee attributes (name, salary, etc).  But my case uses more complex keys, such as:
IMap<DataAttributes, DataValue> myData;

So if DataAttributes has fields such as:
 class DataAttributes {
     String theDescription;
     Date   theStartTime;
     public String getDescription() { return theDescription; }
     // etc....
 }

I want to write a predicate that can query by the keys, to return an appropriate DataValue object.  This does not work:
Predicate pred = Predicates.equal("description", "myDescription");
myData.keySet(pred);  // Throws IllegalArgumentException: "There is no suitable accessor for..."

I could roll-my-own as suggested in this answer, but I'd rather use an out-of-the-box solution if I can.
It doesn't matter if I wind up using the Criteria API, or the Distributed SQL Query API.  Any working query would be great.  Bonus points for a solution that works on nested attributes (i.e.: DataAttributes theStartTime.getYear()).

A:

It is possible using PredicateBuilder (com.hazelcast.query.PredicateBuilder).  The PredicateBuilder paradigm allows you to query based on keys, like so:
EntryObject eo = new PredicateBuilder().getEntryObject();
Predicate fredWithStartTimeThisYear = eo.key().get("Description").equal("Fred")
  .and(eo.key().get("theStartTime.Year").equal(2015));

Note that you can refer to class members by accessor method ("getter") or field name, as you can see in the above example code.  I found this information in the "Mastering Hazelcast" online book, available at hazelcast.org (but you have to fill out a registration form to gain access to it).


Q:

How configure multiple cassandra nodes as storage.backend in Rexster config?

I have Titan/Rexter running on machine and a 3-node cluster of Cassandra as storage.backend for the Titan graph DB. I want to configure Rexster, so as to connect to all 3 nodes of Cassandra cluster. I have listed ip-addresses of all nodes of cassandra as comma-separated, as given below.
<graph>
    <graph-name>graph</graph-name>
    ...
    <properties>
        <storage.backend>cassandrathrift</storage.backend>
        <storage.hostname>10.240.182.197,10.240.166.40,10.240.78.153</storage.hostname>
        ...
        </properties>
</graph>

But it seems like, Rexster is connecting to only the first node only "10.240.182.197", means if I shutdown node - 10.240.182.197, Rexster is unable to connect to other nodes and which throws an exception
Rexster startup log
[INFO] RexsterApplicationGraph - Graph [graph] - configured with allowable namespace [tp:gremlin]
**[INFO] GraphConfigurationContainer - Graph graph - titangraph**[cassandrathrift:10.240.182.197]** loaded**
[INFO] RexsterApplicationGraph - Graph [tinkergraph] - configured with allowable namespace [tp:gremlin]
[INFO] GraphConfigurationContainer - Graph tinkergraph - tinkergraph[vertices:0 edges:0 directory:data/graph-example-1] loaded

[update]
I changed the  config  from "cassandrathrift" to "cassandra" and now its able to connect to all nodes.
Now my question is why "cassandrathrift" API is not able to connect to other nodes?
What is difference in using "cassandrathrift" and "cassandra" ? pros & cons?
which one is faster in loading and retrieving data into graph?

A:

"Cassandrathrift" adapter do not have the intelligence to load balance or node-discovery by itself. It always try to connect to the first listed host-ip, there's no load balancing, and when ip1 goes down Rexster stops.
With the astyanax adapter, will get automatic ring discovery and fault detection. Set storage.backend as "cassandra" as given below.
modified config (rexster.xml) :-
<graph>
    <graph-name>graph</graph-name>
    ...
    <properties>
        <storage.backend>cassandra</storage.backend>
        <storage.hostname>10.240.182.197,10.240.166.40,10.240.78.153</storage.hostname>
        ...
        </properties>
</graph>

After this bounce the titan/rexster and it connected to all the nodes.
Ref : Aurelius › Rexster/Titan-Cassandra high availability


Q:

Trigger keeps failing to compile. Claims table not found when table exists

All the tables that are called definitely exist. I double checked the spelling as well.
The errors sqldeveloper gives are not very helpful and I can't seem to figure out why this is failing. I am attempting to make a trigger which updates the top5restaurants table when a new review comes in. I have a procedure which parses the review and adds them to the rating table. The top5restaurant table maintains the restaurants with the 5 highest ratings.
drop view bestratings_rest;
create view bestratings_rest(rid, rate) as
(select distinct rid, max(stars) from rating
group by rid);

drop table top5restaurants;
create table top5restaurants(rid int);

insert into top5restaurants rid
    select rid from
            (select rid, rate from bestratings_rest r
            order by r.rate asc)
        where rownum <=5;
drop view top5rest;

create view top5rest as
select rid, best from(
    select t.rid, best from top5restaurants t
    inner join (select distinct rid, max(stars) as best from rating
    group by rid) b
    on t.rid = b.rid);

create or replace trigger top5_trigger
    after insert on rating
    for each row
    declare
    minrow top5rest%rowtype;
    restrid restaurant.rid%type;
    restname restaurant.name%type;
    begin

    insert into minrow
    select rid, min(best) from top5rest;

    insert into restname
    select rid from restaurant
    where :new.rid = restaurant.rid;

    if :new.stars > minrow.best  then
    DELETE FROM top5restaurants
    where top5restaurants.rid = :new.rid;
    insert into top5restaurants values(rid);
    end if;

    end;
    /
--
--
begin
update_reviews('Jade Court','Sarah M.', 4, '08/17/2017');

update_reviews('Shanghai Terrace','Cameron J.', 5, '08/17/2017');

update_reviews('Rangoli','Vivek T.',5,'09/17/2017');

update_reviews('Shanghai Inn','Audrey M.',2,'07/08/2017');

update_reviews('Cumin','Cameron J.', 2, '09/17/2017');

end;
/
select * from top5restaurants;

sqldeveloper outputs:
View BESTRATINGS_REST dropped.
View BESTRATINGS_REST created.
Table TOP5RESTAURANTS dropped.
Table TOP5RESTAURANTS created.
5 rows inserted.
View TOP5REST dropped.
View TOP5REST created.
Trigger TOP5_TRIGGER compiled
LINE/COL  ERROR

7/5       PL/SQL: SQL Statement ignored
7/17      PL/SQL: ORA-00942: table or view does not exist
11/5      PL/SQL: SQL Statement ignored
11/17     PL/SQL: ORA-00942: table or view does not exist
18/5      PL/SQL: SQL Statement ignored
18/40     PL/SQL: ORA-00984: column not allowed here
Errors: check compiler log

A:

You don't insert into a scalar variable.  You can do a select into.  The statement
select rid
  into restname
  from restaurant
 where :new.rid = restaurant.rid;

is syntactically valid.  But it is almost certainly incorrect.  Presumably, you want to select the restaurant name not the rid
select name
  into restname
  from restaurant
 where :new.rid = restaurant.rid;

If you declare a %rowtype variable, then you want to do a select * into that variable.  Otherwise you'll get a compilation error in the future if anyone adds or removes a column.  You'd have to add a predicate that specified which row you wanted to select.  My guess is that you want something like this to give the row with the lowest best score (or the row with the lowest rid if there are two with the same low score
 select *
  into minrow
  from top5rest low
 where not exists( select 1
                     from top5rest high
                    where low.best > high.best )
   and not exists( select 1
                     from top5rest same
                    where low.best = same.best
                      and low.rid > same.rid )

More fundamentally, though, even if you get your syntax errors corrected, you're going to get a runtime mutating table error if you try to query the rating table (which your view does) from inside a row-level trigger on the rating table.  That's not allowed.  It almost guarantees that you have a problem in your logic.  In this case, there seems to be no need for a separate table to store the top 5 restaurants.  Realistically, your view should just do that calculation if you need the results in real-time or you should create a materialized view that refreshes periodically if you don't need to see a restaurant's overall rating change instantly when new ratings are added.  So you probably don't want a trigger at all.


Q:

How to distinguish routing to the same POST method with TModel and IEnumerable in ASP.NET Core

I have a controller at .Net Core 2.2 Web API.
There is a POST method which is responsible for creation of an entity.
A current need is to add another POST method to be able to create many.
Here is the sample code I have (no other routing is used):
[Route("api/[controller]")]
public class SampleController: BaseController
{
    [HttpPost]
    public Task<IActionResult> Create([FromBody] SampleModel model) {...}

    [HttpPost]
    public Task<IActionResult> CreateMany([FromBody] IEnumerable<SampleModel> models) {...}
}

As far as exception message says these two are ambiguous routes. But for me it seems not quiet clear. In fact actions' arguments are different types. Might be I am missing something or it is a natural restriction?

A:

In HTTP there are no "actions" and "arguments".
When your app receives POST request to api/Sample, app infrastructure must dispatch request somewhere. Create and CreateMany serves the same route, so it's impossible to choose one of them.
You can either modify route for one of these actions, e.g. using HttpPost("CreateMany")], or remove the first action, since it is superfluous.


Q:

save error :unknown property 'DataInsert.fields'

Here is my apex class:
global class DataInsert {

     // property declarations

     Set<String> fields ;

     global PageReference doInsert() {

        // other logic

        Schema.DescribeSObjectResult objSchema = Incident__c.sObjectType.getDescribe();
        Map<String, Schema.SObjectField> fieldMap = objSchema.fields.getMap();

        fields = new Set<String>();
        for (String fieldName : fieldMap.keySet()){

            SObjectField sfield = fieldMap.get(fieldName);

            schema.describefieldresult dfield = sfield.getDescribe();
            if(objdlt.get(fieldName) == true) {
                if(dfield.isCustom() && String.valueOf(dfield.getSoapType()) == 'Boolean') {
                    system.debug(objdlt.get(fieldName));
                    fields.add(fieldName);
                    System.debug('All Fields are selected ::::'+fields);
                }
            }
        }

This is my vf page :
<apex:page sidebar="false" controller="DataInsert">
 <apex:form >

         <apex:pageBlock title="All Selected Fields ">
           <apex:repeat value="{!fields}" var="key">
                <apex:outputText value="{!key}"/> <br/>
           </apex:repeat>
         </apex:pageBlock>

 </apex:form>
</apex:page>

But I got this error:

save error :unknown property 'DataInsert.fields'

How to resolve this error?

A:

If you want your page to be able to iterate the collection, you need to give it a public getter. One way to do so would be:
public Set<String> getFields() { return fields; }

However, I would hesitate to use a Set for this functionality, since the order would not be very predictable. A better method might be to alphabetically sort them:
public List<String> getFields()
{
    List<String> sortedFields = new List<String>(fields);
    sortedFields.sort();
    return sortedFields();
}

There is also a syntactic alternative to the above, which is similar to how you've declared your other properties:
public Set<String> fields { get; private set; }

If you change your declaration of the fields variable to the above, then it will become a property and be accessible by the page. Note that you do not need a public setter, and I use private set everywhere possible to clearly indicate properties which cannot be written by the page.


Q:

How can I make this effect by using css3?

This is an amazing effect like PPT. Link is here :
http://udc.weibo.com/builder2011/data.html
I know single part was made by css3-animation effects but I don't know
1.how to play all these effects in a timeline?
2.how to make position change and local to whole effect?
Where can I find a tutorial like this?
Thanks cordially.

A:

You could actually make the whole thing out of CSS3.
Keyframes is how you'd be able to time the different functions: http://www.leemunroe.com/css3-animations/
You would need something like an entire CSS3 powered page page, and then just place a window over that with overflow hidden. Use keyframe to move the page around but the window will only show a portion of it.
Just realized, that actually happens to be exactly what they did.


Q:

Is $\mathbb{R^2}$ Hausdorff? Give an example of a non-Hausdorff topology on $\mathbb{R}$

these are two questions on Hausdorff topological spaces. The bit I am having particular difficulty with is finding an 'example of a non-Hausdorff topology on $\mathbb{R}$'

A Hausdorff topological space $(X, \tau)$ is such that any distinct points $a, v \in X$ have disjoint open neighbourhoods. i.e. there are open neighbourhoods $U_a, V_b \in \tau$ such that $ a \in U_a  $ and $b \in V_b $ and $U_a \cap V_b = \emptyset$

Is $\mathbb{R^2}$ Hausdorff?

I believe so. Take $a, b \in \mathbb{R^2}$. Take open neighbourhoods:
$U_a=B_{r_a}(a)=\{(x, y) : |(x, y)-a|<r_a\}$
$V_b=B_{r_b}(b)=\{(x, y) : |(x, y)-b|<r_b\}$
Let $r=d(a,b)$. Take $r_a=r_b=\frac{r}{2}$
So $\mathbb{R^2}$ is Hausdorff.
Is this correct?

Give an example of a non-Hausdorff topology on the set of real numbers

$\mathbb{R}$ is clearly Hausdorff. What is another example of a topology on $\mathbb{R}$ ?
Please could you help me with this one?

A:

Recall that a topology on a set E (here $\mathbb R^2$) is defined by a subset of $\mathcal P(E)$ with special properties (contains $\emptyset$ and E, stable by union and finite intersection) called the set of open sets of E.
Now it appears the simplest possible topology on $\mathbb R^2$, namely $\{\mathbb R^2,\emptyset\}$ (called the trivial topology) perfectly fits your needs, the only neighborhood of any point is $\mathbb R^2$ itself!
To say it with your words, in this topology, given $a,b\in\mathbb R^2$, the only neighborhood $U_a$ of $a$ and $U_b$ of $b$ you can find is $U_a=U_b=\mathbb R^2$ and in this case you definitely don't have $U_a\cap U_b=\emptyset$ ! So it's impossible to separate any two points given this topology.


Q:

cycle or swim without injury while training hard for a race

So I was a great swimmer (2k), cyclist (100+ milers) okish runner. (10k max)
After the brain tumor like diagnosis and hospitalization, things went cold. Started running again in a few months and Nike+ Running App recommended the advanced program for my first ever 5k race. (That was top on my bucket list)
I loved the program, it's all about distance, so just for a 5k race the "advanced" program had me run 16K! on one of the days!
Signed up for a 10k next, got a bicycle and there's a swimming pool nearby. Next on my bucket list is a triathlon.
Unfortunately for the 10k one week I ran a lot (Advanced program has you running 5-6 times per week), on the ONE rest day I had I bloody cycled. Kinda really injured my quads.
So I figured I need to meld my swimming and cycling somehow without injuring myself, and that is my question.
How do I somehow cycle and swim occasionally when I run about 4/5/6 times a week and not injure myself?
Replacing the run for cycling on any day isn't too good right? Since the goal is to run a 10k race now. Is there a way to balance them without compromising on the running?

A:

I would presume that you are falling into the same trap that many recreational runners and triathletes fall into, in that you are going too hard on your easy days, and not hard enough on your hard days. So, you're in a perpetual state of "almost" recovered, and then busted out a cycle day that thrashed you for a while.
Just like your advanced couch to 5k, there are many (quite a few of them free) training plans for triathlons. Perfectly fine to even stack multiple workouts in a day, as long as you are paying attention and really sticking to the easy/medium/hard levels for workouts. That is the biggest key, because the key to endurance sports is being able to get up every day and get the work in. Does no good to put in three killer days and then need 5 days of rest.
I have found that the beginner programs on Beginner Triathlete are very well put together and have different emphases if you are a good runner already, or cyclist, etc. In addition they have mentor groups, some of them affiliated to certain plans that give you a group to talk with and a couple of experienced triathletes as mentors/sounding boards. Really a great resource.


Q:

Add GameObject on position of a mesh in Unity

I'm using an FBX 3d model with about 100 meshes. I want to select one of this meshes and place a GameObject (cube) on the same position to use it later in the code to focus the camera on it. The cube has been added but is not on the right position - it's out off the viewport instead of. Don't know how to determine the correct coordinates of the meshes in Unity.
Object prefab = Resources.Load("my_prefab"); // Assets/Resources/Prefabs/prefab1.FBX
var obj = (GameObject)Instantiate(prefab, new Vector3(370, 105, 100), Quaternion.identity);
obj.transform.localScale = new Vector3(150, 150, 150);

GameObject cube = GameObject.CreatePrimitive(PrimitiveType.Cube);
cube.name = "my_cube";
cube.GetComponent<Renderer>().material.SetColor("_Color", Color.red);
cube.transform.localScale = new Vector3(100, 100, 100);
cube.transform.parent = obj.transform;

var meshFilter = FindMesh(obj.GetComponentsInChildren<MeshFilter>(), "head");

List<Vector3> vector3List = new List<Vector3>();

for (int i = 0; i < meshFilter.mesh.vertices.Length; ++i)
{
    vector3List.Add(obj.transform.TransformPoint(meshFilter.mesh.vertices[i]));
}

cube.transform.localPosition = vector3List[0];
Camera.main.transform.LookAt(obj.transform);

public MeshFilter FindMesh(MeshFilter[] mesh, string name)
{
    foreach (MeshFilter meshFilter in mesh)
    {
        if (meshFilter.name == name)
        {
            return meshFilter;
        }
    }
        return null;
}

Any idea what is wrong with my code? I think it has something to do with the scaling of the prefab.
THX for your help!!
Edit:
Updated code and implemented changes suggested by Anis Brachemi but it's still not working. The cube is now child of the head component but when the camera looks at the cube the head isn't visible in the viewport.
Object prefab = Resources.Load("ironman"); // Assets/Resources/Prefabs/prefab1.FBX
var obj = (GameObject)Instantiate(prefab, new Vector3(370, 105, 100), Quaternion.identity);
obj.transform.localScale = new Vector3(150, 150, 150);

GameObject cube = GameObject.CreatePrimitive(PrimitiveType.Cube);
cube.name = "my_cube";
cube.GetComponent<Renderer>().material.SetColor("_Color", Color.red);
cube.transform.localScale = new Vector3(10, 10, 10);

var components = obj.GetComponentsInChildren<Component>();
foreach (Component c in components)
{
    if (c.name == "head")
    {
        cube.transform.parent = c.transform;
        break;
    }
}

cube.GetComponent<Collider>().isTrigger = true;
Camera.main.transform.LookAt(cube.transform);

this is the fbx I'm using: https://free3d.com/de/3d-model/iron-man-2-11174.html
I'm new in Unity. So I don't know the best way to focus the camera to child compontents of a gameobject. Maybe  there is better way to do it...

A:

The position of the GameObject I've added was wrong. I changed the localPosition of the cube to the vector of the head and it works
        var head = GameObject.Find("head");
        var vertex = head.GetComponent<MeshFilter>().mesh.vertices[0];

        GameObject cube = GameObject.CreatePrimitive(PrimitiveType.Cube);
        cube.transform.localScale = new Vector3(10, 10, 10);
        cube.transform.parent = GameObject.Find("my_parent").transform;
        cube.GetComponent<Collider>().isTrigger = true;
        cube.transform.localPosition = vertex;

        Camera.main.transform.LookAt(cube.transform);


Q:

Issue printing out objects from arraylist

First i have a class called card with this code
public class Card
{
private int value;
private String suit;
// private int value;
//private String rank;
public Card (int v, String s)
{
    value=v;
suit=s;
}

public int random()
{
    int randomNum = ((int)(Math.random() * 100) % 13 +1);
    return randomNum;
}

public void displayCard()
{
    System.out.println(value + " of " + suit);
}

}

then i have a class called deck with this code
import java.util.*;

public class Deck
{
public ArrayList<Card> card;
private ArrayList<String> suits;
private ArrayList<Card> hand;

public Deck()// time to build a deck
{

    card=new ArrayList<>();
    suits=new ArrayList<>();

    suits.add("Hearts");
    suits.add("Spades");
    suits.add("Clubs");
    suits.add("Diamonds");

    for (int y=2; y<15; y++)
        {
            card.add(new Card(y,suits.get(0)));
        }

    for (int y=2; y<15; y++)
        {
            card.add(new Card((y),suits.get(1)));
        }

    for (int y=2; y<15; y++)
        {
            card.add(new Card((y),suits.get(2)));
        }

    for (int y=2; y<15; y++)
        {
            card.add(new Card((y),suits.get(3)));
        }

}//end of public deck

public ArrayList deal()// deal method
{
    hand=new ArrayList<>();

    for(int x = 0; x < 5; ++x)//build 5 card hand
        {
        hand.add(card.get(x));

        System.out.println(card.get(x));

         }

    return hand;

}//end of public void deal

}// end of public class deck

then i have the main
import java.util.ArrayList;

import java.util.*;

public class gamePlay
    {
        private static gamePlay player1;
        public Deck fullDeck;
        private ArrayList<Card> yourHand;

    public gamePlay()
    {
        fullDeck=new Deck();
        System.out.println("Your poker hand is a");
        yourHand = fullDeck.deal();

        //System.out.println(yourHand);

    }
public static void main(String[] args)
{
player1 = new gamePlay();
}
}

It is printing out some crazy stuff for the value and suit of the cards in the hand
i think they are either memory locations from the arraylist or hexidecimal values i am not sure need it to print suit and rank any help is appreciated

A:

If your classes implement a proper toString method, it will show up perfectly.
You can easily change your existing method displayCard in the Card class to a toString method. This leads to more flexibility than to let the Card print out itself by calling System.out.println in the card's method.
@Override
public String toString() {
    return value + " of " + suit;
}

If you want the card to print to System.out you just do System.out.println(card);
Normal arrays can also be converted to String, using Arrays.toString(array) (if you would have a Card[] variable for example). Most implementations of Lists already implement a proper toString method so it will show you a comma-separated list of the entries.


Q:

How to convert Iterable[Try[U]] filter successed to Iterable[U]?

I tried
val tryValues : Iterable[Try[Int]] = ...
val successValues = tryValues.filter(_.isSuccess).map(_.get)

but compiler give warning that map may throw exception.
Is there any way free of warning?

A:

You want to use collect to pattern match out all the values which are Success, and discard anything else.
val successValues: List[Int] = tryValues collect { case Success(x) => x }

collect accepts a PartialFunction as an argument. Any values from the collection that the PartialFunction is defined for will be mapped, and the rest will be discarded.
Example:
scala> val tryValues = List(1, 1, 0, 1, 1).map(x => Try(1 / x))
tryValues: List[scala.util.Try[Int]] = List(Success(1), Success(1), Failure(java.lang.ArithmeticException: / by zero), Success(1), Success(1))

scala> val successValues = tryValues collect { case Success(x) => x }
successValues: List[Int] = List(1, 1, 1, 1)

A:

Another option here, if you don't care to log anything about the fails is to flatMap using toOption on the Try.  Like so:
val successValues = tryValues.flatMap(_.toOption)


Q:

Keep UILocalNotification Banner visible while app is in background

I'm working on a VoIP phone for iOS, and if a call comes in while running in the background, I do a presentLocalNotificationNow with a UILocalNotification message to inform the user. This works fine, however the banner expires and rolls off the screen before the user has enough of a chance to swipe and answer. I have tried scheduling further notifications at regular intervals, but that fills up the notification centre and causes the banner to appear to be tumbling.
Is there some way to prevent the banner from disappearing until I cancel it in some manner? Both the Skype app and Bria VoIP app have managed to come up with a solution where the banner stays until the call is answered, or the callee hangs up.

A:

The best way to do this is to add a sound to the local notification.
The default notification without a sound lasts 5 seconds as a banner, however you can include
a sound that is longer, up to 30 seconds that you can play when the local notification is posted.  The banner notification will stay on screen as long as the sound is playing.


Q:

How to add navigationController to existing tab application?

I have an iPhone application with 2 tabs. This is my application delegate:
 (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
 {
// Override point for customization after application launch.
// Add the tab bar controller's current view as a subview of the window
self.window.rootViewController = self.tabBarController;
[self.window makeKeyAndVisible];
return YES;
 }

My first tab is a subclass of UITableViewController. I would like to push a new view controller when someone clicks on a row of my table. I know that this is done in didSelectRowAtIndexPath like this:
TableViewDetailViewController *fvController = [[TableViewDetailViewController alloc] initWithNibName:@"TableViewDetailViewController" bundle:[NSBundle mainBundle]];
    [self.navigationController pushViewController:fvController animated:YES];
    [fvController release];
    fvController = nil;

My self.navigationController is NIL so nothing gets pushed to the view stack. Where should I create my navigationController, so there would be as little code to change as possible?

A:

We have direct solution using Interface builder.
In interface builder go to xib in which you have added tabBarController and delete the tabBarItem with which you have connected your tableViewController .
Now, drag and drop an UINavigationController from library in your tabBar and set this navigationController's rootViewController as your tableViewController.
Thanks


Q:

Thread errors when running Java game

I am getting some strange errors when running my Java game. I've been working on this game for weeks as a project for my computer science class and it is due on 6/4/2015, so I appreciate any help. Initially I wrote the game in a class called Game and ran it from a static method called run. Later, I decided to add a GUI menu in a class called Control. To run the game now, I call the main method in the Control class. This menu has a button with an action listener. When the button is clicked, the run method in the Game class is called. If I click and run the run method directly the game works fine. But if I click the button which calls the run method it draws a frame, but not the actual game.
Here is my code for the GUI:
    public class Control extends JFrame implements ActionListener {

    // JPanel
    public JPanel pnlButton = new JPanel();

    // Buttons
    public JButton btnAddFlight = new JButton("Multiplayer");
    public JButton single = new JButton("Singleplayer");

    public Control() throws IOException,InterruptedException {
        super("Bouncy Ball");
        //Set button size
        btnAddFlight.setBounds(150, 400, 220, 30);
        single.setBounds(150,350,220,30);

        // JPanel bounds
        pnlButton.setBounds(0, 0, 500, 500);
        pnlButton.setBackground(Color.WHITE);

        // Adding the Bouncy Ball logo to JPanel
        String path = "gg.jpg";
        File file = new File(path);
        BufferedImage image = ImageIO.read(file);
        JLabel label = new JLabel(new ImageIcon(image));
        label.setBounds(179,50,150,150);

        //Action Listener setup
        single.addActionListener(this);

        //add buttons and title logo to JPanel
        pnlButton.add(btnAddFlight);
        pnlButton.add(label);
        pnlButton.add(single);

        //Set up and add the instructions to the JPanel
        JLabel gg = new JLabel("Welcome to Bouncy Ball, a game where you have to manipulate");
        gg.setFont(new Font("Serif", Font.PLAIN, 18));
        gg.setBounds(0,10,500,500);
        pnlButton.add(gg);
        JLabel f = new JLabel("the window size with WASD to win! Click the buttons to start.");
        f.setFont(new Font("Serif", Font.PLAIN, 18));
        f.setBounds(0,28,500,500);
        pnlButton.add(f);
        pnlButton.setLayout(null);

        //Add JPanel to JFrame
        this.add(pnlButton);

        // JFrame properties
        setSize(500, 500);
        setTitle("Bouncy Ball");
        setLocationRelativeTo(null);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setVisible(true);;
    }

    @Override
    public void actionPerformed(ActionEvent submitClicked) {
        try{
            isClicked = true;

            Game.run();
        }
        catch(InterruptedException a){}
    }

    public static void main(String[] args) throws IOException,InterruptedException{
        new Control();
    }
}

and here is the run method in my game class:
public static void run() throws InterruptedException {
    //Setting up JFrame
    frame = new KeyFrame("Bouncy Ball");
    frame.setSize(1000, 1000);

    //Setting up Scanner and get user level input
    Scanner scan = new Scanner (System.in);
    System.out.println("Level one, two, three, or four?(must be an int, four is multiplayer)");
    f = scan.nextInt();

    //Display JFrame
    frame.setVisible(true);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.toFront();

    //Add Game JPanel
    game = new Game();
    frame.add(game);

    //Setting up game basics
    b = new Ball(game,0,0,30,30);
    setUpLevel();
    objList.add(0,b);

    //Main Game Loop
    while (true) {
        //Request Focus
        game.requestFocusInWindow();

        //Update current Time
        lastStartTime = System.currentTimeMillis();

        //Move the ball and the player
        p.move();
        b.move();

        //Refresh JPanel
        game.repaint();
        Thread.sleep(10);

        //Check if the player wins or loses
        checkWin();
        checkLoss();
    }
}

If I call the run method directly it works, but not if I click the button in the GUI. I have a feeling that it is a thread issue, because the main thread ends once run is called. I'm not a 100% percent sure as to the cause though. I'd appreciate any responses, I've been working on this game for weeks as a project for my computer science class and it is due on 6/4/2015.

A:

Swing is single threaded - all painting, events, etc...occur on this thread (named the EDT). The Game.run method is called on the EDT, which in turn executing a long running task (eg while (true), Thread.sleep) - this prevents the EDT from doing anything else. To perform animation, consider using a Thread, or better yet a Swing Timer.


Q:

Initialise data member array elements to zeros on VS2012?

I have a class Y which contains an array of size 100 X objects.
class Y{
    unsigned int x_array[100];
};

I need to initialise this array so that all the elements are zero. Is it this possible to do in Visual Studio and if not what can I do? If I do:
unsigned int x_array[100] = {0};

I get a compile error saying data member initialisation is not allowed.
(Intel C++ Compiler v13)

A:

What you are trying to do is available only since C++11, in C++03 the following should do:
class Y{
public:
    Y() : x_array() { }
    unsigned int x_array[100];
};

Also consider using std::vector<unsigned int> instead:
#include <vector>

class Y{
public:
    Y() : x(std::vector<unsigned int>(100, 0)) { }
    std::vector<unsigned int> x;
};


Q:

Animate on Scroll JS

I am new to JavaScript and trying to add some animations on scroll to a site.
I have multiple divs each with a unique class name and all with the same .section class.
I want to animate each .section on scroll without triggering the other .sections

$(window).on("scroll",function(){
    var winTop = $(this).scrollTop();
    var section = $(".section").offset().top;

    if(winTop >= section-400) {
      $(".section").addClass("animate");
    };
});

The code above obviously triggers every .section when the first reaches it's position on scroll.
I can't get my head around how I would trigger one .section as it comes into view.
I may be doing this the complete wrong way, so if I am, your help would be much appreciated.

A:

Here, you need to loop through all the available sections and whichever section matches, you have to apply the class.
if (winTop >= section - 400) {
  $(".section").addClass("animate");
};

Plus, you don't have a ; at the end of if statement.
Your final code will be like:
$(window).on("scroll", function(){
  var winTop = $(this).scrollTop();

  $(".section").each(function () {
    var section = $(this).offset().top;
    if(winTop >= section-400) {
      $(this).addClass("animate");
    }
  });
});

I would suggest removing the class animate from all the other sections. So, change your code this way:
$(window).on("scroll", function(){
  var winTop = $(this).scrollTop();

  $(".section").removeClass("animate").each(function () {
    var section = $(this).offset().top;
    if(winTop >= section-400) {
      $(this).addClass("animate");
    }
  });
});

Also, once you start adding the class, you don't want the other ones to have the class in them. So, give a top value too.
$(window).on("scroll", function(){
  var winTop = $(this).scrollTop();

  $(".section").removeClass("animate").each(function () {
    var section = $(this).offset().top;
    if(winTop >= section-400) {
      $(".section").removeClass("animate");
      $(this).addClass("animate");
    }
  });
});

Working Snippet:

$(window).on("scroll", function(){
  var winTop = $(this).scrollTop();

  $(".section").removeClass("animate").each(function () {
    var section = $(this).offset().top;
    if(winTop >= section-400) {
      $(".section").removeClass("animate");
      $(this).addClass("animate");
    }
  });
});
.section {
  height: 750px;
}
.animate {
  background: #960;
}

Section one

Section two

Section three

Section four

Preview:

A demo that you can see working by scrolling slowly: JSBin Demo.


Q:

How to delete all files in subfolders but not subfolders themselves via command line on Windows?

For a given folder, I need to delete all files (various extensions) in all subfolders but not the subfolders themselves because I need to preserve the folder structure. Is there a way to do that via command line or a batch file?

A:

Run the Command Prompt and enter the following commands:
cd /D "your folder"
del /S /Q *.*

This will list all the files as they are being deleted.
To not see this, change the second command to:
del /S /Q *.* >nul


Q:

What exactly is a PRNG seed and how does it work in c++?

From what I’ve read on the c++ website, the srand function, puts a seed in the rand function, but I don’t really understand what a seed is.

A:

"I don’t really understand what a seed is" - A seed in the context of a Pseudo Random Number Generator (PRNG) is a starting value to use for the generation of the pseudo random sequence.
A PRNG that starts with the same seed will (in most cases) produce the same sequence of random numbers. This is great for replayability of a scenario, but is not generally what you want in production. Usually you want to provide a unique/unpredictable seed to the generator for each instance of the application, so that each run gives a unique stream of pseudo random numbers.
I would recommend using the new random facilities (since C++11) that are available in the random header over srand()/rand() since rand has a very low range and usually also a very low period. The new facilities are much better.
You may also find this talk enlightening: rand() Considered Harmful
The Wikipedia page on pseudo random number generators is also worth a read.


Q:

Iframe body when accessed through iframeElement.contentDocument.body is an empty node

I have a very simple setup on a dev server (both pages are on my local test server localhost:5500) where I have a main page
<!DOCTYPE html>

  <title>Example Mockup</title>

and a nested page

Hello, World

when I load the main page in my browser the output written to console is:
I can access the element #hello using iframe.contentDocument.getElementById('hello') but I want the body element including child elements. Can anyone please explain to me why is this happening

A:

You have to wait until iframe loaded completely to access it's body.
var iframe = document.getElementById('frame');

iframe.onload = function () {
    console.log(iframe.contentDocument.body);
}


Q:

h2 element won't stay centered unless it is set to 100%

This seems like it should be a very simple issue to me, although I just can't figure it out on my own. I have a h2 element that I want to keep at 85%, and it contains a short line of text. I want it to be centered in its containing div, not just for the text to be centered in the h2 element.
Here's some code:

Three words of text

CSS:
div.main{
  text-align:center
}
div.secondary{
  text-align:center
}
h2{
  text-align:center
  width:85%
}

I made a Fiddle, too
Thanks to anyone who can help.

A:

Add:
margin: 0 auto;

To the h2 style rule.
http://jsfiddle.net/wF57b/1/


Q:

Google Maps clear placed MarkerClusters on new search

I'm having trouble getting my map to clear the clusters on a new search.  Any ideas?
function clearLocations() {
    //infoWindow.close();
    for (var i = 0; i < markers.length; i++) {
        markers[i].setMap(null);
    }
    markers.length = 0;

    // clear #side_bar bottom text
    document.getElementById("side_bar").innerHTML = "";
    // clear .alertBox text
    $('.alertBox').html('');
}

function searchLocationsNear(center) {
    clearLocations();

    var searchUrl = 'phpsqlsearch_genxml.php?lat=' + center.lat() + '&lng=' + center.lng();
    downloadUrl(searchUrl, function (data) {
        var xml = parseXml(data);
        var markerNodes = xml.documentElement.getElementsByTagName("marker");
        if (markerNodes.length > 0) {

            var bounds = new google.maps.LatLngBounds();
            for (var i = 0; i < markerNodes.length; i++) {
                var name = markerNodes[i].getAttribute("name");
                var address = markerNodes[i].getAttribute("address");
                var distance = parseFloat(markerNodes[i].getAttribute("distance"));
                var category = markerNodes[i].getAttribute("category");
                var latlng = new google.maps.LatLng(
                    parseFloat(markerNodes[i].getAttribute("lat")),
                    parseFloat(markerNodes[i].getAttribute("lng")));

                // createOption(name, distance, i);
                createMarker(latlng, name, address, category);
                bounds.extend(latlng);
            }
            map.fitBounds(bounds);
            var markerclusterer = new MarkerClusterer(map, markers);
          // markerclusterer.setMap(null);
            makeSidebar();

        } else {
            $('.alertBox').html('Sorry, there are no jobs that are close to your location.');
        }
   });
}

A:

You should try this :
if (markers) {
    for (i in markers) {
        markers[i].setMap(null);
    }
    markers = [];
    markerclusterer.clearMarkers()
}

According to the docs the clusterer can be clear with clearMarkers() method.
UPDATE
Call clear only when we have already create the MarkerClusterer.
if(markerclusterer)
{
    clearLocations();
}


Q:

Crystal Report how to change the display order in a group

I have a crystal report like below image:

The report is group by "Quot No.", by default it's ordered by "Times Used" (8th column)
How can I change the ordering so that it will order by "Total amount"?
The total amount is a field in the report which is the sum of a field named "quotamt" in the datasource:

I've tried looking in the change group options, took a look at the "Use a formula as group sort order", but the formula only provides three options (ascending, descending, original order), and is unable to sort by another column

The desired result is:

How can I do that?

A:

What I suggest, rather than doing this task in crystal report, good to done at sqlserver side means database side.
This is simplest suggestion when you have this type of situation.
You can give the condition on sqlserver side too. and get the data order same as you want.
Yes, this can be done in report side, but it take time for this.


Q:

Unable to trigger chrome.browserAction.onClicked.addListener with google chrome extensions

I'm a bit stuck here and was wondering if anyone can point out where I might be wrong.
I am simply trying to make the body color change to red on click of the app icon.
manifest.json
{
    "name": "Bagde",
    "description": "",
    "version": "1",
    "manifest_version": 2,
    "background": {
        "scripts": [
            "background.js"
        ]
    },
    "browser_action": {
        "default_title": "Test",
        "default_popup": "popup.html"
    }
}

popup.html

Some Content ..

popup.js
document.addEventListener("DOMContentLoaded", function () {
    //Get Reference to Functions
    backGround = chrome.extension.getBackgroundPage();
    //Call Function
    backGround.updateIcon();
  });

background.js
var i = 1;

function updateIcon() {
    i = 1;
    chrome.browserAction.setBadgeText({
        text: 'Test'
    });
    chrome.browserAction.setPopup({
        popup: "popup.html"
    });
}

chrome.browserAction.setBadgeBackgroundColor({
    color: [200, 0, 0, 100]
});

window.setInterval(function () {
    chrome.browserAction.setBadgeText({
        text: String(i)
    });
    i++;
}, 4000);

chrome.browserAction.onClicked.addListener(function(tab) {
    chrome.tabs.executeScript(null,
        {code:"document.body.bgColor='red'"});
});

any ideas what I may be doing wrong? Thanks for taking your time to reading this.

A:

If you define default_popup, you can't have a listener for browserAction.onClicked. In this case you can simply add the code in your handler to your popup.js.
EDIT: That is, add to popup.js the following:
chrome.tabs.executeScript(null, {code:"document.body.bgColor='red'"});


Q:

How would I Pull Values of 1000+ Checkboxes in Excel?

I am needing to pull the value of a checkbox (Form Control version) and insert it into a cell. I am aware of the method of Right-Clicking on a checkbox - Format Control - Control Tab - Cell Link, but for the spreadsheet I'm needing to do this for has 1000+ checkboxes. So performing that process would be an immense ordeal!
Is there a value a checkbox adheres to within an excel function? In other words, what variable would that checkbox respond to if I were to call that checkbox into a function?
i.e: =IF(CheckBox3 = TRUE, "Complete", " ") (I'm referring to the CheckBox3 text)
Or is there an alternative method to obtaining this information? Any help or suggestions would be much appreciated! (Photo of checkbox example)

A:

You could loop the shapes collection and test whether it is a checkbox and apply your formula
Option Explicit
Public Sub GetValues()
    Dim shp As Shape, counter As Long
    Application.ScreenUpdating = False
    With Worksheets("Sheet1")
        For Each shp In .Shapes
            If shp.Type = msoFormControl Then
                counter = counter + 1
                .Cells(counter, 1) = shp.NAME
                 If shp.ControlFormat.Value = 1 Then .Cells(counter, 2) = "Complete"
            End If
        Next
    End With
    Application.ScreenUpdating = True
End Sub

You may need to add an additional test, for example if they are called Check Box 1, Check Box 2 etc then something like:
If shp.Type = msoFormControl And InStr(shp.NAME, "Check Box") > 0 Then


Q:

Creation of a simple field failed in MySql

CREATE TABLE bdt.transactions (
`transaction no`     int UNSIGNED NOT NULL  AUTO_INCREMENT,
data                 date    ,
by                   int  NOT NULL  ,
hours                int  NOT NULL  ,
for                  int  NOT NULL  ,
`transaction type`   set('normale','corso')   NOT NULL DEFAULT 'normale' ,
activity             text  NOT NULL  ,
CONSTRAINT pk_transactions PRIMARY KEY ( `transaction no` ) ) engine=InnoDB

Error:

You have an error in your SQL syntax; check the manual that
  corresponds to your MySQL server version for the right syntax to use
  near  'by                   int  NOT NULL  ,  hours                int
  NOT NULL  ,  for                  int  NOT NULL    at line 4

With backquotes is now OK

A:

by is a reserved word, and so is for
You should surround reserved words with backquotes (`) if you use them as table or column names. Just to be on the safe side, surround all column names with backquotes
CREATE TABLE bdt.transactions (
`transaction no`     int UNSIGNED NOT NULL  AUTO_INCREMENT,
`data`               date    ,
`by`                 int  NOT NULL  ,
`hours`              int  NOT NULL  ,
`for`                int  NOT NULL  ,
`transaction type`   set('normale','corso')   NOT NULL DEFAULT 'normale' ,
`activity`           text  NOT NULL  ,
CONSTRAINT pk_transactions PRIMARY KEY ( `transaction no` ) ) engine=InnoDB

Give it a Try !!!


Q:

codeacademy "Functions & if/else"

I can't seem to find an answer to why this returns an error. The other questions regarding this section of code academy had to do with missing or misplaced "{}" and missing or misplaced ";". I don't believe I am having that problem, but it is still returning an error.
var sleepCheck = function(numHours)
{
    if (sleepCheck>8)
    {
        return "You're getting plenty of sleep! Maybe even too much!";
    }
    else
    {
    return "Get some more shut eye!";
}
};
sleepCheck(10);
sleepCheck(5);
sleepCheck(8);

A:

sleepCheck is a function you are using it as a variable.
You need to use numHours parameter passed to function in if condition

Code
var sleepCheck = function (numHours) {
    if (numHours > 8) {
        return "You're getting plenty of sleep! Maybe even too much!";
    } else {
        return "Get some more shut eye!";
    }
};
sleepCheck(10);
sleepCheck(5);
sleepCheck(8);

DEMO


Q:

Spring Cloud Stream error handling... error

That's not really an issue, beacause I found a workaround, but it conflicts with the documentation, so I wanted to share and document about it.
FYI Spring Boot 2.1.10 + SCSt 2.1.4 + RabbitMQ binder
I first implemented an application local error handler as given into official docs :
@StreamListener(Sink.INPUT)
public void handle(Person value) {
    throw new RuntimeException("BOOM!");
}
@ServiceActivator(inputChannel = Sink.INPUT + ".my-group.errors")  // won't work
public void error(ErrorMessage message) {
    log.error("Handling ERROR: " + message.getPayload().getMessage());
}

spring.cloud.stream.bindings.input.destination=persons.inputs
spring.cloud.stream.bindings.input.group=my-group

But that didn't go well, to say the least. This is what I eventually had to keep:
@ServiceActivator(inputChannel = "persons.inputs.my-group.errors")

As you can see, what's happening is that I had to stick to the actual destination definition instead of the channel's; which I think is very uncomfortable! And I want to underline, again, that this is contradictory to the official docs here: https://docs.spring.io/spring-cloud-stream/docs/current/reference/htmlsingle/#_application_error_handling (plus there are noticeable typos, IMHO: they even write that the destinationName is actually required)
Can anyone share thoughts about the situation with me? Have I done it right and am I right to think that this is wrong?

A:

It's a bug in the documentation; it is, indeed, unfortunate the binding name was not used in the error channel name instead of the destination and group, but it's too late to change it now. We could possibly do something in a future release.
Please open 2 GitHub issues to

fix the documentation
consider adding an option to name the error channel using the binding name instead.


Q:

How do I convert wireshark capture files to text files?

How can I convert wirshark captures (.cap) files to text files or some format from which I can read the file and parse its contents ?

A:

Open up Wireshark, select your .cap file, and then go to File->Export and choose the options that you want.
So, if you need to do it from the command line, use tshark.exe, as follows.
>tshark -i - < "c:\filename.cap" > "c:\output.txt

If you want to write the decoded form of packets to a file, run TShark without the -w option, and redirect its standard output to the file (do not use the -w option).

A:

The -A option of tcpdump prints each packet in human readable ASCII and happily deals with wireshark files and you can do it all from the command line:
tcpdump -A -r stackoverflow.cap > stackoverflow.txt

The output looks like:
9:22:33.664874 IP 192.168.1.11.33874 > stackoverflow.com.www: Flags [P.], seq 1117095075:1117095829, ack 3371415182, win 9648, options [nop,nop,TS val 9533909 ecr 313735664], length 754
E..&..@.@../....E;...R.PB.........%........
..y...9.GET / HTTP/1.1
Host: serverfault.com
Connection: keep-alive
User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US) AppleWebKit/533.4 (KHTML, like Gecko) Chrome/5.0.375.70 Safari/533.4
Accept: application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3
Cookie: __qca=P0-141773580-1259521886021; __utmz=81883924.1275328201.133.5.utmcsr=google|utmccn=(organic)|utmcmd=organic|utmctr=hudson%20build%20dir; usr=t=kXSBoIG5Jk6S&s=wGmaIuhAD0eH; __utma=81883924.2034104685.1272993451.1276186265.1276193655.189; __utmc=81883924; __utmb=81883924.6.10.1276193655
If-Modified-Since: Thu, 10 Jun 2010 10:17:12 GMT

A:

I use the tshark -x -r file.pcap command line when hexdump like output is good for post processing.


Q:

Should I book flights for multiple people together or separately?

I am trying to book a Ryanair flight, which gives me one price (Say £50) per person if I book one person, but a higher price (say £60) when I try to book 4 people. Is there any way we can arrange to all book separately at the same time to get the same solo price, or do we have to book together and take the hit? Does anyone have any general advice?

A:

If you get a higher price for a booking for multiple persons, then most likely there are not enough seats for the cheap fare available any more. So you will most probably end up with the same total amount, when you book separately. An edge case could be, that a booking engine would choose the same more expensive fare for the whole booking, even e.g. one seat with the cheap fare would still be available.


Q:

Default argument to Python attribute that is a function

I was wondering if it is possible in Python to specify a default argument to a function attribute in Python (I know this is not the right terminology so here is an example):
def foo(x, y):
    return x + y

my_foo = foo(y=50)

my_foo(25) #returns 75

Does this sound possible?

A:

from functools import partial
def foo(x, y): return x + y
my_foo = partial(foo, y=50)
my_foo(100)
Out[433]: 150

But you should know about this.


Q:

Retirar sequencia númerica de string

Estou com o seguinte problema, acredito que consiga resolve-lo com expressões regulares, mas sou pessimo com o mesmo.
Digamos que eu tenha uma string desse jeito: CONECTOR BNC FEMEA + F MACHO 024267 ou assim PLUG P-4 UNIVERSAL 006-096, a posição dos números podem estar em qualquer lugar, começo, meio ou fim, preciso tirar as sequências númericas que sejam iguais ou maiores que 3 digitos.
Esses digitos geralmente são como referência e estou usando essas informações para buscar imagens usando a API do Google Custom Search, se eles forem passados para realizar a busca geralmente não retorna nenhum resultado.
Resultado desejado:
Entrada: CONECTOR BNC FEMEA + F MACHO 024267
Saída: CONECTOR BNC FEMEA + F MACHO

A:

Para capturar/substituir três ou mais digitos seguidos use a regex \d{3,}. \d significa números (0-9), as chaves funcionam como quantificador no caso obrigam três digitos ou mais a serem capturados.
$str = 'CONECTOR BNC FEMEA + F MACHO 024267 23';
$nova = preg_replace('/\d{3,}/', '', $str);
echo $nova;

Resultado:
CONECTOR BNC FEMEA + F MACHO 23


Q:

Can I install both shared .so and static .a versions of a library?

My questions is related to this: Creating both static and shared C++ libraries
I'm compiling a library in order to install it in ~/local on two different systems.  It seems that every time I do this I end up with linker problems that take me hours to figure out.  The specific library I'm looking at is primesieve.  In that library, it's the default to build static libraries only.  Unfortunately the example code count_primes.cpp wouldn't link with the static version of the library on one of my systems, for whatever reason.  Eventually I figured out how to build the shared version and the code now compiles nicely, with no ugly hacks necessary.
Given the above, it seems to be that compiling both static and shared versions is a good idea if you're working with multiple systems and want the best chance of having your code compile.  Is this true?  Are there reasons not to build both versions?  I realize that this is a bit of a subjective question but it's a serious programming issue that I think many people here have probably encountered.

PS.
This is what I ended up using to compile and install both shared and static versions of primesieve to ~/local:
make
make lib
make install PREFIX=~/local
make clean
make lib SHARED=yes
make install PREFIX=~/local

The make clean is because of this.  I then added this to my .bash_profile:
export LIBRARY_PATH=$LIBRARY_PATH:~/local/lib
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:~/local/lib
export CPLUS_INCLUDE_PATH=$CPLUS_INCLUDE_PATH:~/local/include

Alternatively, without changing the environment variables I was able to compile the example program count_primes.cpp like this:
g++ -I ~/local/include/ -L ~/local/lib/ -lprimesieve count_primes.cpp

A:

To use a static library you can just include it in the compilation as if it were a regular object file, e.g.
g++ -o foo foo.cpp /path/to/mylib.a

Of course, this means static linking too.
You can still statically link with a dynamic library, so there's not much use for static libraries really.


Q:

Google maps searchbox console errors

I get these errors, apperantly he can't find some images. However these are out of my control because of the library.
GET file://maps.gstatic.com/mapfiles/api-3/images/powered-by-google-on-white2.png net::ERR_FILE_NOT_FOUND VM3702:22
GET file://maps.gstatic.com/mapfiles/api-3/images/autocomplete-icons.png net::ERR_FILE_NOT_FOUND

This is the used library
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?libraries=places"></script>

A:

Are you running your website locally? Seems that the library is trying to fetch the file using the current protocol, which defaults to file.
Put your website on a local server and it should default to http


Q:

Oracle Proc to SQL Reporting Services: character set name is not recognized

A few months ago Oracle queries stopped working on our reporting services server after a service pack on the reporting server.  I ended up having to grant permissions on Oracle directories to eliminate the first error and then renamed the NLS_LANG registry entry (effectively deleting it) to get rid of the second error.  The old value was: AMERICAN_AMERICA.WE8MSWIN1252
Now we are moving some new reports into production which use Oracle stored procedures and they are getting this error.
   --- End of inner exception stack trace ---
w3wp!processing!8!7/27/2009-09:26:09:: e ERROR: An exception has occurred in data source 'CSUD3_RPTAPL'. Details: Microsoft.ReportingServices.ReportProcessing.ReportProcessingException: Query execution failed for data set 'MYDATASET'. ---> System.Data.OracleClient.OracleException: ORA-06550: line 1, column 57:
PLS-00553: character set name is not recognized
ORA-06550: line 0, column 0:
PL/SQL: Compilation unit analysis terminated

I've created a test procedure that simply returns
select 'test' "field1" from dual;

It gets the same error.  Tonight I will try setting NLS_LANG back to it's old value and see if that fixes the procedures - although it will break the regular oracle reports.  If anyone has a clue what is going on, please enlighten me.
From what I've read, the client should be using the database default if the charset is not specified on the client.

A:

The key was the first error message:
ORA-12705: Cannot access NLS data files or invalid environment specified.
Which led to this:
http://www.dba-oracle.com/t_ora_12705_error.htm
And then a closer examination of the folder permissions.  I needed to grant perms to authenticated users on the ORACLE_HOME directory and subdirs.
Working now!


Q:

Changing an Image.Source property in Windows Phone 8 app causes proximity event subscription to stop working

Very simple repro app - created a new Windows Phone 8 C# app from template in Visual Studio, added an Image to the content panel, then subscribed for NDEF proximity messages as shown:
// Constructor
    public MainPage()
    {
        InitializeComponent();

        ProximityDevice device = ProximityDevice.GetDefault();
        if (device != null)
        {
            device.SubscribeForMessage("NDEF", handler);
        }
    }

    private void handler(ProximityDevice sender, ProximityMessage message)
    {
        Debug.WriteLine("Received message");
        Dispatcher.BeginInvoke(() =>
            {
                myImage.Source = new BitmapImage(new Uri("Assets/test.png", UriKind.Relative));
            });
    }

First event works fine (image source is changed successfully). However, after this event has fired once it no longer fires if I touch another NFC tag. If I remove the call to update the image source, it will fire on each touch.
I can't understand why there would be any interaction here. The phone I'm testing on is a Nokia Lumia 620.

A:

Just a shot in the dark: try to keep reference to your ProximityDevice somewhere. Make it a member of the class and assign in constructor.
class MainPage : PhoneApplicationPage
{
    private ProximityDevice device;
    public MainPage()
    {
        InitializeComponent();

        device = ProximityDevice.GetDefault();
        if (device != null)
        {
            device.SubscribeForMessage("NDEF", handler);
        }
    }
    ...
}

As it correctly mentioned in comments, this is caused by the Garbage Collector, which collects the instance of the ProximityDevice. When new BitmapImage is created, memory consumption grows, and this triggers the GC process. That's why you don't have such issue when you don't create the image.


Q:

Where do I define WCF client endpoints in a test project?

I have a class library-- call it Services.dll-- which is a wrapper for some third party functionality.  The third party gave us a bunch of DLLs and those "inner" DLLs call a WCF service.
Normally, when Services.dll is running, it lives within the web site's process, and uses the web.config associated with the site.  So when I want to define the WCF client endpoints, I edit web.config.  This is very straightforward.
But now I want to write an automated integration test suite.  The test project is of course a class library (let's call it Services.Tests.dll), so it will take whatever config is defined for the hosting process. But I think in the case of a test project, the hosting process is Visual Studio itself. The test project certainly does not emit an .exe of its own.
So where do I define the WCF client endpoints for the test project?  Which config file do I edit?  Do I edit devenv.exe.config?  Do I set up some kind of "satellite" config file (e.g. Services.Tests.dll.config)-- if so, how do I get the Visual Studio test runner to pick up the config?
Or... is there a way to do this without config, by intercepting/mocking calls to System.Configuration?  I can't unfortunately change the third party DLLs.
Or.. do I override with some clever use of ServicePointManager, so that config is not an issue? Not sure how I would do that.
Or... is the best practice to write an integration test project not as a class library but as an .exe, with its own app.config?
Please note-- I am not running unit tests (those are separate).  These are integration tests, so I don't want to isolate away the WCF calls.  I need them, and I need them to be configured to point at the right test servers.

A:

There is a simple trick you can use.
Visual Studio will load the app.config for the test project into it's host process if it's present. However, test projects don't usually have app.configs. You can force visual studio to create one by adding settings to your project:

Right click your project and select "properties".
Go to the "Settings" option, on the left-side bar.
Insert anything on this page. Just anything will work.
Save the project.

Now, you'll see that your test project has now a app.config file. Just add your WCF endpoints/bindings there and you're good.


Q:

redux-form unable to type values in fields

I'm not able to type values in input fields using redux-form. I have the following reducer
import {combineReducers} from 'redux';
import session from './sessionReducer';
import profile from './profileReducer';
import map from './mapReducer';
import { reducer as formReducer } from 'redux-form'

const rootReducer = combineReducers({
    // short hand property names
    session,
    profile,
    map,
    form: formReducer
})

export default rootReducer;

and here is the store
import { createStore, combineReducers, applyMiddleware } from 'redux'
import createLogger from 'redux-logger'
import thunk from 'redux-thunk'
import { routerReducer, routerMiddleware, push } from 'react-router-redux'
import reducers from '../reducers'
import { browserHistory } from 'react-router';

const middleware = [ thunk ];
if (process.env.NODE_ENV !== 'production') {
    middleware.push(createLogger());
}

middleware.push(routerMiddleware(browserHistory));

// Add the reducer to your store on the `routing` key
const store = createStore(
    combineReducers({
        reducers,
        routing: routerReducer
    }),
    applyMiddleware(...middleware),

)

export default store;

component
import React, {PropTypes, Component} from 'react';
import Upload from './Upload';
import {bindActionCreators} from 'redux';
import {connect} from 'react-redux';
import * as profileActions from '../../../actions/profileActions';
import EventsCalendar from '../../common/EventsCalendar';
import { Field, reduxForm } from 'redux-form'
import ProfileForm from './ProfileForm';

import {
    Form,
    FormGroup,
    FormControl,
    ControlLabel,
    Tabs,
    Tab,
    InputGroup,
    Label,
    HelpBlock,
    Grid,
    Row,
    Button,
    Col

} from 'react-bootstrap';

class Profile extends Component {

    static propTypes = {
        profile: PropTypes.object.isRequired,
    };

    constructor(props) {
        super(props);

        this.state = {
            profile: {
                username: '',
                password: '',
                email: ''
            }
        }
        //this.onUpdate = this.onUpdate.bind(this)
    }

    handleSubmit = (values) => {
        // Do something with the form values
        console.log(values);
    }

    componentDidMount() {
        this.props.actions.getProfile()
    }

    componentWillReceiveProps(nextProps) {
        if (nextProps.profile !== this.props.profile) {

        }
    }

    render() {
        console.log(this.props.profile);
        const {profile} = this.props.profile;
        const { handleSubmit } = this.props;

        return (
            <div className="row">
                <Col lg={10}>
                    <Tabs defaultActiveKey={1} id="uncontrolled-tab-example">
                        <Tab eventKey={1} title="Vendor Data">
                            <ProfileForm onSubmit={this.handleSubmit}  data = {this.props.profile}/>
                        </Tab>
                        <Tab eventKey={3} title="Events Calendar">
                            <EventsCalendar/>
                        </Tab>
                    </Tabs>

                </Col>

                <Col lg={2}>
                    <Upload/>
                </Col>
            </div>
        );
    }
}

function mapStateToProps(state) {

    return {
        profile: state.default.profile,
    };
}

function mapDispatchToProps(dispatch) {
    return {
        actions: bindActionCreators(profileActions, dispatch)
    };
}

Profile = reduxForm({
    form: 'profileForm' // a unique name for this form
})(Profile);

export default connect(mapStateToProps, mapDispatchToProps)(Profile);

when I'm typing I see in console that the state is changing

the attached form component
import React, {Component} from 'react';
import {Field, reduxForm} from 'redux-form';
import FieldFormControl from '../../common/FieldFormControl';

import {
    FormGroup,
    FormControl,
    ControlLabel,
    Button

} from 'react-bootstrap';

class ProfileForm extends Component {
    render() {
        const {handleSubmit, profile, pristine, reset, submitting} = this.props;

        return (
            <form onSubmit={handleSubmit}>
                <FormGroup controlId="signup-name">
                    <Field type="text" name="firsname" placeholder="test" value component={FieldFormControl}>Vorname</Field>
                </FormGroup>
                <FormGroup controlId="signup-username">
                    <Field type="text" name="lastname" placeholder={profile.username} value={profile.username} component={FieldFormControl}>Name</Field>
                </FormGroup>
                <FormGroup controlId="signup-email">
                    <Field type="text" name="email" placeholder={profile.username} value={profile.username} component={FieldFormControl}>Vorname</Field>
                </FormGroup>

                <Button
                    bsStyle="primary"
                    type="submit"
                    //disabled={pristine || submitting}
                    block
                >Speichern</Button>
            </form>
        );
    }
}

// Decorate the form component
ProfileForm = reduxForm({
    form: 'profileForm' // a unique name for this form
})(ProfileForm);

export default ProfileForm;

the bootstrap override to be compatible with redux-form
import React, { Component } from 'react';
import {FormGroup, FormControl, ControlLabel} from 'react-bootstrap';

export default class FieldFormControl extends Component {

    render () {

        const { placeholder, type, input, meta} = this.props;

        return (
            <FormGroup controlId={input.name} validationState={meta.error ? 'error' : 'success'}>
                <ControlLabel>{this.props.children}</ControlLabel>
                <FormControl type={type} placeholder={placeholder} value={input.value} onChange={input.onChange} />
                <FormControl.Feedback />
            </FormGroup>
        );
    }
}

A:

Remove the value prop from your Field components, redux-form handles updating the value and passing it to the component that you pass it. I'm assuming the idea here is to provide initial value, but this is not the place to do that.
<Field type="text" name="email" placeholder={profile.username} component={FieldFormControl}>Vorname</Field>

You can also pass all the input props to your FormControl in your FieldFormControl so you get onFocus, onBlur, etc., all provided by redux-form.
<FormControl placeholder={placeholder} {...input} />

If you want to initialize the fields with values, either use initialValues when you connect using reduxForm, or initialize if it needs to happen after the form mounts.
And finally, you're using combineReducers twice in such a way that most of your reducers are nested in a way that you didn't intend. To simplify this, I would import the routerReducer in your reducers/index.js file, and add it to your combineReducers there.
const rootReducer = combineReducers({
    // short hand property names
    session,
    profile,
    map,
    form: formReducer,
    routing: routerReducer,
});

Then, in your store, you'll just have
const store = createStore(
    reducers,
    applyMiddleware(...middleware),
);

You should then see that you'll have all your keys in your state (session, profile, form, routing, etc.) instead of just default and routing.


Q:

Table row indented

I have a TableLayout which I populate with a bunch of ImageViews so that the user can draw a diagram with icons on the side. But for some reason the TableRows aren't starting from the edge of the table, but rather a few pixels in, this gives the layout an ugly look which I want to get rid of. I don't have any margin/padding assigned so I have no idea why this is happening. My TableLayout is inside a HorizontalScrollView and VerticalScrollView so that I can scroll across the table.

Here is the xml(the ImageViewss are being dynamically added)
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="match_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
android:gravity="left">

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="700dp"
    android:layout_height="wrap_content"
    android:id="@+id/mainScrollView"
    android:layout_alignParentTop="true"
    android:layout_toRightOf="@+id/lvTools"
    android:layout_marginTop="60dp"
    android:background="@drawable/rectangle"
    android:layout_marginBottom="4dp"
    android:layout_toLeftOf="@+id/editScrollView">

    <HorizontalScrollView xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="wrap_content" android:layout_height="fill_parent">

        <TableLayout
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:layout_marginLeft="30dp"
            android:id="@+id/drawTable"
            android:visibility="visible"></TableLayout>
    </HorizontalScrollView>
</ScrollView>

<ListView
    android:layout_width="85dp"
    android:layout_height="wrap_content"
    android:id="@+id/lvTools"
    android:layout_alignParentTop="true"
    android:layout_alignParentLeft="true"
    android:layout_marginTop="60dp"
    android:background="@drawable/rectangle" />

<Button
    android:background="@drawable/custom_buttons"
    android:layout_width="170dp"
    android:layout_height="wrap_content"
    android:text="New Drawing"
    android:id="@+id/btnNew"
    android:layout_alignParentTop="true"
    android:layout_alignParentLeft="true"
    android:layout_marginTop="5dp"
    android:layout_marginLeft="10dp"
    android:onClick="onClick" />

<Button
    android:background="@drawable/custom_buttons"
    android:layout_width="170dp"
    android:layout_height="wrap_content"
    android:text="Load Drawing"
    android:id="@+id/btnLoad"
    android:layout_alignParentTop="true"
    android:layout_alignParentRight="true"
    android:layout_marginTop="5dp"
    android:layout_marginRight="10dp"
    android:onClick="onClick" />

<ScrollView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/editScrollView"
    android:background="@drawable/rectangle"
    android:layout_alignParentBottom="true"
    android:layout_alignParentRight="true"
    android:layout_alignParentEnd="true"
    android:layout_alignTop="@+id/mainScrollView">

    <LinearLayout
        android:orientation="vertical"
        android:layout_width="243dp"
        android:layout_height="match_parent"
        android:id="@+id/editLayout">

    </LinearLayout>
</ScrollView>

A:

Remove this attribute from your TableLayout.
android:layout_marginLeft="30dp"


Q:

xml DOM- Newline adds the text/attribute content twice in java DOM parser

I am working on parsing an XML file. I developed a swing application that reads data from xml file. It adds the chapters in comboBxCh based on the subject value set in comboBxSb.
The code is below:
Java code:
public void loadChapters(JComboBox comboBxCh, JComboBox comboBxSb)
{
    tempList = xmlDoc.getElementsByTagName("subject");
    NodeList secNodeList = null;
    Element ele=null;
    int i, j, totalElements;
    totalElements = tempList.getLength();
    i = j =0;
    for(i=0;i<totalElements;i++)
    {
        secNodeList = tempList.item(i).getChildNodes();
        for(j=0;j<secNodeList.getLength();j++)
        {
            if(secNodeList.item(j).getNodeType()==Node.ELEMENT_NODE)
            {
                ele = (Element)secNodeList.item(j);
            }

            if(ele!=null && ele.getTagName()=="sname" && ele.getTextContent()==comboBxSb.getSelectedItem().toString() )
            {
                for(i=0;i<secNodeList.getLength();i++)
                {
                    if(secNodeList.item(i).getNodeType()==Node.ELEMENT_NODE)
                        ele = (Element)secNodeList.item(i);
                    if(ele.getTagName()=="chapter") //Adding it solves my problem-> &&i%2==1
                    {
                            comboBxCh.addItem(ele.getAttribute("name"));
                    }
                }
                return;
            }
        }
    }
}

XML Code:
<subjects>
    <subject id="1">
        <sname>Quantitave Aptitude</sname>
        <chapter name="Number series"/>
        <chapter name="Time and work"/>
        <chapter name="Trains and rivers"/>
    </subject>
    <subject id="2">
        <sname>English</sname>
        <chapter name="Articles"/>
        <chapter name="Nouns"/>
        <chapter name="Comprehension text"/>
    </subject>
    <subject id="3">
        <sname>Logical Reasoning</sname>
        <chapter name="What's next"/>
        <chapter name="Next figure"/>
        <chapter name="Series"/>
    </subject>
    <subject id="4">
        <sname>GK</sname>
    </subject>
</subjects>

When swing application loads then comboBxSb contains all four subjects and Quantitative Aptitude (with id="1") remains selected in beginning hence its three chapters load in the comboBxCh. But its each chapter loads twice! In xml file if I remove the \n from between chapter names in each line then repetition doesn't happen. That is ->
    <subject id="1">
        <sname>Quantitave Aptitude</sname>
        <chapter name="Number series"/><chapter name="Time and work"/><chapter name="Trains and rivers"/>
    </subject>

.
    /-------------------------------------/
There is a screenshot of the application:

The solution to this, without modifying XML, is already mention in comment. That's I can add only odd(or even) no. of chapters. But my question is Why is this happening? It also happens if I put the names of chapters as text content between <chapter> </chapter> tags and the extracting text with 'getTextContent()`

A:

It's hard to be 100% sure, as you've only provided an out-of-context code snippet, but my "guess" is you've not cleared the JComboBox of any previous values.
Having said that though, your loadChapters method could be better done.  Instead, you could make use of the xpath API to query the XML document and return only those values you actually want, like you might do for a database, for example...
public static List<String> loadChapters(Document xmlDoc, String name) throws XPathExpressionException {
    List<String> results = new ArrayList<>(25);
    XPathFactory xf = XPathFactory.newInstance();
    XPath xPath = xf.newXPath();

    String query = "/subjects/subject[sname[text()='" + name + "']]/chapter/@name";
    XPathExpression xExp = xPath.compile(query);
    NodeList nl = (NodeList) xExp.evaluate(xmlDoc, XPathConstants.NODESET);
    for (int index = 0; index < nl.getLength(); index++) {
        Node node = nl.item(index);
        results.add(node.getNodeValue());
    }
    return results;
}

Using something like...
try {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    Document doc = dbf.newDocumentBuilder().parse(new File("Test.xml"));
    List<String> chapters = loadChapters(doc, "Quantitave Aptitude");
    for (String chapter : chapters) {
        System.out.println(chapter);
    }
} catch (ParserConfigurationException | SAXException | IOException | XPathExpressionException exp) {
    exp.printStackTrace();
}

this prints...
Number series
Time and work
Trains and rivers

so we can ensure that the loadChapters method is not returning duplicates.
Now to make your life easier, you could create a custom ComboBoxModel which is backed by a List....
public class ListComboBoxModel<E> extends AbstractListModel<E> implements MutableComboBoxModel<E> {

    private List<E> values;
    private Object selectedItem;

    public ListComboBoxModel() {
        this.values = new ArrayList<>(25);
    }

    public ListComboBoxModel(List<E> values) {
        this.values = new ArrayList<>(values);
    }

    @Override
    public int getSize() {
        return values.size();
    }

    @Override
    public E getElementAt(int index) {
        return values.get(index);
    }

    @Override
    public void addElement(E item) {
        values.add(item);
    }

    @Override
    public void removeElement(Object obj) {
        values.remove((E)obj);
    }

    @Override
    public void insertElementAt(E item, int index) {
        values.add(index, item);
    }

    @Override
    public void removeElementAt(int index) {
        values.remove(index);
    }

    @Override
    public void setSelectedItem(Object anItem) {
        selectedItem = anItem;
    }

    @Override
    public Object getSelectedItem() {
        return selectedItem;
    }

}

So you can create a new using something like...
ComboBoxModel<String> model = new ListComboBoxModel<String>(loadChapters(doc, "Quantitave Aptitude"));

and then apply the new model directly to the JComboBox


Q:

Who gets the money from auctioning the North Pole?

(Asking in the same spirit as a previous question I asked about Heinlein's The Moon Is a Harsh Mistress, only it's a lot more money this time.)
Jules Verne's novel Sans dessus dessous (English titles The Purchase of the North Pole or Topsy-Turvy) starts with an auction that sells a huge area of land near the North Pole.  That land has so far been unexplored and inaccessible, so also unclaimed by any country.  The United States of America buys the land for 814000 US dollars.  The Gun Club pays that money on behalf of the States, mostly from a donation by the rich widow Mrs Evangélina Scorbitt.
Who gets that money?  How is it used?

A:

Noting that the land was essentially unclaimed (except by the poor schmoes who live there), a corporation called the North Polar Practical Association asked the US Government to host an auction to determine its ownership. As such, any monies raised would go to the US Government, minus a fee for the auction company (but see below).

“It can thus be considered that the region extending from the eighty-fourth parallel to the Pole is still undivided among the different States of the globe. It is, therefore, excellently adapted for annexation as a private estate after formal purchase in public auction.
“The property belongs to nobody by right of occupation, and the Government of the United States of America, having been applied to in the matter, have undertaken to name an official auctioneer for the purposes of its disposal.
“A company has been formed at Baltimore, under the title of the North Polar Practical Association, which proposes to acquire the region by purchase, and thus obtain an indefeasible title to all the continents, islands, islets, rocks, seas, lakes, rivers, and watercourses whatsoever of which this Arctic territory is composed, although these may be now covered with ice, which ice may in summertime disappear.

The US is explicitly named as the nominator. We learn that a sizeable proportion of that money (and possibly all of it) will be used support the winner in their claim by settling any counter-claims from countries bordering the region.

It may be that this communication will be considered as a madman’s freak; but at any rate it must be admitted that in its clearness and frankness it left nothing to be desired. The serious part of it was that the Federal Government had undertaken to treat a sale by auction as a valid concession of these undiscovered territories.
...
The advertisement, it will have been noticed, assumed the principle that regions not known geographically and belonging to nobody in particular belonged to the world at large. That the majority of the Powers would admit this contention was supposable, but it was possible that States bordering on these Arctic regions, or considering the regions as the prolongation of their dominions towards the north, might claim a right of possession. And their pretensions would be all the more justified by the discoveries that had been made having been chiefly due to these regions; and of course the Federal Government, as nominators of the auctioneer, would give these Powers an opportunity of claiming compensation, and satisfy the claim with the money realized by the sale. At the same time, as the partisans of the North Polar Practical Association continually insisted, the property was uninhabited, and as no one occupied it, no one could oppose its being put up to auction.

So the answer is that all of the countries mentioned in the earlier part of the story whose territories border onto the North pole (Great Britain, the United States, Denmark, Sweden, Norway, Holland, and Russia) plus countries whose explorers have visited the region (France, Germany, Austria-Hungary) would likely end up with a cut of the winnings.