Q:

Manipulate Excel table macro to another format. Remove duplicates and reformat

I'm around 2 months in my VBA journey and I have encountered a problem which I can't find a solution to online. I'm having problems manipulating an Excel table to another format which has been created by another macro that I have programmed. I have a table with country and name of a figure on different rows, listed on a couple of rows. I want it to be dynamic since this table will be updated everyday
I have written below on how I want it to look. My idea is to code the country as a digit and then remove duplicats in the country region.
I have tried to create a loop and I'm thinking that I might have to create a range for each country.
Sub ManipulateTable()
Dim Country as String
Dim USA as Range
Dim EU as Range
Dim India as Range

Const StartRow As Byte = 7
Dim LastRow as Long
LastRow = Range("A" & StartRow.(End(xlDown).Row

For i StartRow to LastRow
Country = Range("A" & i).Value

If Country = "USA" Then Range("C" & i).value = 1
If Country = "EU" Then Range("C" & i).value = 2
If Country = "India" Then Range("C" & i).value = 3
Next i
' This to remove duplicates from column a
Range("A7:A30").RemoveDuplicates Columns:=Array(1). Header:= xlYes
' I thinking that I need to create a loop here
' But I dont know where to start
For i StartRow to LastRow
Countryindex =  Range("C").Value
If Countryindex = 1 Then put under USA
If Countryindex = 2 Then put under EU

My Table looks like this with separate columns
    "A" "B"
     Data
1    USA Sales
2    USA Employment Figures
3    USA Tax
4    EU Sales
5    EU Employment Figures
6    India Sales
7    India Expenses
8    India Employment Figures

I want a table which looks like this
 "A"
 Data
1    USA: (With some color)
2    Sales
3    Employment
4    Tax
5    EU: (With some color)
6    Sales
7    Employment
8    India: (With some color)
9    Sales
10   Expenses
11   Employment

All help is highly appriciated.
Country Data Time

Country:
Data Time

A:

Save a copy before you run this it will overwrite your data.
Dim lastrow As Long
    Dim iter As Long
    Dim diter As Long
    Dim countrydict As Object
    Dim country As String
    Dim data As String
    Dim key As Variant

    Set countrydict = CreateObject("Scripting.Dictionary")

    With ActiveSheet
        lastrow = .Cells(.Rows.Count, "A").End(xlUp).row

        For iter = 1 To lastrow
            country = Trim(.Cells(iter, 1).value)
            data = Trim(.Cells(iter, 2).value)
            If countrydict.Exists(country) Then
                If Not InStr(1, countrydict(country), data) > 0 Then ' Remove Dupes
                    countrydict(country) = countrydict(country) & "|" & data ' an array would work but we can instr a string
                End If
            Else
                countrydict.Add country, data
            End If
        Next
        iter = 1
        For Each key In countrydict
            .Cells(iter, 1).value = key & ":"
            .cells(iter, 1).font.bold = True
            .cells(iter, 1).font.colorindex = 30
            iter = iter + 1
            For diter = 0 To UBound(Split(countrydict(key), "|"))
                .Cells(iter, 1).value = Split(countrydict(key), "|")(diter)
                iter = iter + 1
            Next
        Next
        .Columns("B").Clear
    End With


Q:

How to add view in top of view hierarchy in Swift?

I have been using this:
UIApplication.sharedApplication().keyWindow?.rootViewController!.view.addSubview(self.customView)

To add a modal view over all the views in the view hierarchy in app.
But this is giving me problem. It adds subview as expected sometimes but sometimes it doesn't' work.
In what case this wont work and what's the best way to add modal view in view hierarchy like UIAlertView.

A:

Depending on what's happening, there can be more than one UIWindow at a time - for example, if a system alert shows up, you will have two separate windows (one for your view controller, one for the alert itself).
A similar example can be made for the system keyboard. If the keyboard has focus, that will be your keyWindow.
A way of making sure you are adding the subview on top of all windows, could be: UIApplication.sharedApplication().windows.last?.addSubview(yourSubView).
I've also seen people using the application delegate, with: UIApplication.sharedApplication().delegate?.window.


Q:

Does an "efficient" random number generator exist?

Given some number $n$ and a seed number $s$<$n$, I want a random number generator (RNG) that will go through all integers `<$n$ before coming back to $s$.  The resulting random number must be roughly uniformly distributed (which of course it will be if you go through the entire sequence, so I mean for any "large" subsequence) and roughly un-autocorrelated.  Furthermore I want the RNG to be "efficient" in that it takes up little memory and little computation.  Perhaps I can say that it is $O(1)$ w.r.t. $n$ in terms of memory and computation.
For instance, I can think of a RNG right now that will fulfill the former requirements, but not the latter: Create a list of all numbers $0$ through $n-1$.  "Mark off" the seed number $s$.  Then take a random number $r$ from a Mersenne Twister RNG, move $r$ numbers to the right and if that number hasn't been marked off report it back and then mark it off.  Continue the process until you've marked off all numbers in the list. -  This method will report back non-repeating, un-autocorrelated integers, but will be super memory and time intensive.
I imagine the ideal answer to be some sort of small equation to provide the next number in the sequence based upon this number (or perhaps the last few).
Can such a RNG be proven to exist?  Are such specific RNGs know to exist? Can their existence be disproven?
Editorial note: If anyone reading has super edit power... please feel free to clean up my post to make me sound more mathy (I am but a lowly engineer).  Retag me too please.

A:

Knuth, the art of computer programming vol II theorem A section 3.2.1.2 gives conditions for a linear congruential sequence x -> ax+c mod m to cycle through all numbers mod m, which may be what you want as these are often reasonable pseudorandom number generators. The conditions are that c is coprime to m, and  a-1 is a multiple of all divisors of m that are prime or 4.

A:

Your requirements aren't rigorously stated, so it's hard to say what you can prove exists or doesn't exist.  In the strictest sense, a pseudo-random number generator cannot possibly be "roughly uniformly distributed".  Every PRNG is an expansion of entropy from its settings to the set of possible sequences, and it is easy to see for reasons similar to your comments about memory requirements that the set of possible sequences has vastly more entropy than the settings.  What a PRNG really does is passes certain computationally feasible tests of randomness and not necessarily other tests.
There are conjectures in computer science that "one-way functions exist".  Some of these conjecture would imply that there are PRNGs that look random for any polynomial-time test, and for some conjectures permutations that look random for any polynomial-time test.  However, these conjectures are harder than the P vs NP problem, so no one is about to prove them.  In any case, if you just want a PRNG for your own practical use, it's overkill to look for one that has been analyzed cryptographically.
It is known that modular exponentiation is a pretty good PRNG.  If you want something that looks like a permutation, let $p$ be a prime number, and let $a$ be a carefully chosen residue mod $p$.  (Carefully chosen means that $a$ should be a primitive residue far away from $0$.)  Then the function
$$f_a(k) = a^k \bmod p$$
is already statistically okay.  This is a permutation of the numbers $1 \le k \le p-1$.
Now, the most common way to compute $f_a$ is to store $f_a(k)$ and then multiply by $a$ to get the next power.  (As Richard Borcherds mentions, the iteration $x \mapsto ax+b \bmod n$ is a similar idea and a major standard, including in Knuth's book and in the Unix RNG "drand48".)   However, these days that level of efficiency isn't so important, and it is interesting that you can compute $f_a$ directly by repeated squaring.  So you can improve the strength of $f_a$ by making a composition such as $f_b(f_a(k)+c)$, where the addition is taken mod $p-1$. Or you could insert a more creative transformation.  For instance, if $p$ is a Mersenne prime, then permuting the bits of $k$ is a simple transformation that can be inserted between applications of $f_a$.
If you want a permutation of some $n$ that is not of the form $p-1$, then you can find some prime $p > n$ that is not much larger and use the above same tricks.  You can just skip values that are out of range.
Decades ago, I wanted a pseudo-random permutation for a scrambled screen fade in a computer game.  I just used consecutive values of $f_a$ for some convenient modulus (which doesn't have to be prime; there are other variations) and it looked fine.

A:

I assume that n is a power of 2.
You can try an LFSR (check Wikipedia), but that will cycle (given the correct feedback) only over the non-zero integers in your range.
Another possibility is the map x += (x*x) | 5, where you can actually replace 5 with any number of the form 8n+5. I don't remember the reference for that.


Q:

Netbeans project doesn't run on localhost

I set up my ubuntu enviroment correctly, installed apache2 which is running, localhost from firefox gives Apache2 Ubuntu Default Page but whenever i try to access my website i created using netbeans I get 404 error. http://localhost/PhpProject1/index.php is the url netbeans tries to run my code. All of the settings were default when creating this project. Source folder: /var/www/PhpProject2 When trying to run the project I get this:
Not Found

The requested URL /PhpProject2/index.php was not found on this server.

A:

The new default root folder of apache is /var/www/html, thus your Source folder should read /var/www/html/PhpProject2.


Q:

C# - Emulate device - Parallel to Serial Port

We are trying to emulate a device that runs off a parallel port.
We have the exact same model that runs on RS232, and can run a null modem cable from one port to another and emulate the device with the following settings:
_port = new SerialPort
                {
                    PortName = comport,
                    BaudRate = 9600,
                    DataBits = 8,
                    Parity = Parity.None,
                    StopBits = StopBits.One,
                    DtrEnable = true,
                    RtsEnable = true,
                };

So to emulate the same device with a parallel port, we merely got a cable that runs from parallel to a RS-232 port.  Although, we are not sure if it is the correct cable we need.
What are the System.IO.Ports.SerialPort settings that would allow the parallel device to work?
We have a serial port monitoring program and no data is coming through, this makes us think that our baud rate, stop bits, data bits, etc. are incorrect.
Does anyone know how parallel communication is translated to RS-232 on the other end?
Any suggestions?  Is this even possible?  We want to avoid having 2 parallel ports and using C# to communicate over parallel (it would be time consuming).

A:

You need more than just a cable, you need a converter. Here is one such device. I haven't used this model, but I've used other converters in the past successfully.


Q:

Laravel - can't access an object property

I have the following code:
$items = Item::where('type','egg')
        ->select('id','name','image','description')
        ->with('craft.reqItem')->get();

foreach($items as $item) {
            if (sizeof($item->craft)) {
                foreach ($item->craft as $craftItem)
                    return $craftItem;
            }
        }

The output is the following JSON:

When I'm trying to access the req_item from the code, laravel outputs nothing.
I'm trying to do it by changing:
return $craftItem to:
return $craftItem->req_item
If I'm trying to output any other property other than req_item (such as id,item_id,quantity) - laravel do return the right value.
Any idea why I can't access the req_item object?
dd req_item

A:

That's it, $craftItem->reqItem is an object and you can't simply "output" an object.
But you can do something like $craftItem->reqItem->req_item_id (that in the case you eager loaded reqItem, assuming its a relationship).
If that's not the case, then you simply call the query like $craftItem->reqItem()->req_item_id
Although I'd prefer eager loading, which probably you'll want to read about in the docs... But just to test your example is working, you can do something like $item->load('reqItem') before the conditional statement. And then you can access it as a property.
As devk mentioned, relationships have to be camelCase named. You may want to change it to reqItem() for simplicity.


Q:

"Esperance" rock on Mars formed by erosion or weathering? or is there any rock on Mars not formed by erosion?

I was wondering if the "Esperance" rock that was found on Mars by the Opportunity rover was formed due erosion or weathering? I have been reading a lot online but I did not seem to find anything. Does anyone know a type of rock on Mars that was not formed by erosion?

A:

Rocks on Mars, just like rocks on Earth, can be igneous (formed from the cooling magma or lava) Sedimentary (formed from sediments that were laid down by water or wind) or Metamorphic (sedimentary rocks that have been changed by exposure to heat and pressure) (there may be other categories, such as meteorites)
After they have formed, rocks are subject to erosion and weathering. These processes don't form the rock, but can shape it or move it. The process of weathering produces sand, silt and clay, that can later form new rocks.
The Esperance rock has a significant amount of "clay" (a sedimentary rock). The clay in Esperance was formed by the weathering of other rocks to very fine particles, these then gathered together in wet environment to form a clay. When the water evaporated, the clay hardened into a rock. The significance of Esperance is that the water under which it formed must have been chemically neutral, not strongly acidic.


Q:

Entity Framework: Explicit loaded foreign key attribute is null after creating new object

In my Entity Framework project, lazy loading is disabled and it want it to be disabled by default.
Up to now I've used to load foreign key values in case they're needed for further processing explictly with the Include() method.
However, whenever I put one of the objects which is holding a loaded foreign key object into another object, from the perspective of the outer object the foreign key seems to be null.
var teams = (from team in db.Teams.Include("Captain")
             orderby team.Name
             select new ExtendedTeam {
                Team = team
             }).AsEnumerable();
// teams.First().Customer.Captain is null though the Captain property was explictly included

How can I access the Captain property without disabling lazy loading at all? I'd prefer not to add a Captain property to the Extended Team class.

A:

Your projection seems to be screwing up the Include.
I'm not sure where the "customer" variable came from, but if you need to do a projection like that you can do something similar to:
var teams = (from team in db.Teams
             orderby team.Name
             select new {
                 Team = team,
                 Captain = team.Captain,
             }).ToList(); // execute the query

That will give you an anonymous type of Customer and Captain. You can extract the data however you need to from that to populate your ExtendedTeam object.
Since I called ToList() on the query I have executed the query, and my anonymous object has the Team object and the Captain object. As a side effect of this, Entity Framework has also done a "fix-up" of the relationships. If you inspect the anonymous type Team property, you will notice that Captain is also populated in it. EF was smart enough to know that they were related and it did relationship fix-up on the Team objects. You can now process the results like so:
var extended = teams.Select(t => new ExtendedTeam { Team = t });

That should work.


Q:

Converting nested JSON file to R dataframe

I'm trying to convert a JSON file with multiple levels of nesting into a dataframe in R. I've looked at some existing questions/answers on this problem (e.g., Convert JSON to R dataframe and Flatten nested JSON to dataframe in R and Nested JSON to dataframe in R), but as this is my first time handling a JSON file I'm really struggling.
The JSON file is pretty large and contains twitter data. Here's a sample to show what the nesting structure is like:
[
{
    "Corpus": "ALM",
    "Tweets": [
        {
            "tweet_id": "521033092132503552",
            "tweet_text": "no tweet text available",
            "date": "no date available",
            "annotations": [
                {
                    "annotator": "annotator00",
                    "annotation": "care"
                },
                {
                    "annotator": "annotator01",
                    "annotation": "care,purity"
                },
                {
                    "annotator": "annotator02",
                    "annotation": "care,purity"
                },
                {
                    "annotator": "annotator03",
                    "annotation": "care"
                }
            ]
        },
        {
            "tweet_id": "537681598989475841",
            "tweet_text": "Wholeheartedly support these protests & acts of civil disobedience & will join when I can! #Ferguson #AllLivesMatter",
            "date": "Wed Nov 26 18:57:37 +0000 2014",
            "annotations": [
                {
                    "annotator": "annotator00",
                    "annotation": "subversion"
                },
                {
                    "annotator": "annotator01",
                    "annotation": "subversion"
                },
                {
                    "annotator": "annotator02",
                    "annotation": "loyalty"
                },
                {
                    "annotator": "annotator03",
                    "annotation": "loyalty,subversion"
                }
            ]
        },

Here's some dput of this same data file, but different observations/tweets (note that because the file is so large the largest nesting level gets cut off):
list(tweet_id = "500745903054258177", tweet_text = "@MichaelSkolnik Thank you for joining the solidarity effort #DearMikesMom #AllLivesMatter",
    date = "Sat Aug 16 20:48:21 +0000 2014", annotations = list(
        list(annotator = "annotator01", annotation = "loyalty"),
        list(annotator = "annotator02", annotation = "loyalty"),
        list(annotator = "annotator03", annotation = "loyalty"))),
list(tweet_id = "621859689270120448", tweet_text = "no tweet text available",
    date = "no date available", annotations = list(list(annotator = "annotator01",
        annotation = "betrayal"), list(annotator = "annotator02",
        annotation = "non-moral"), list(annotator = "annotator03",
        annotation = "fairness"))), list(tweet_id = "551227029874438145",

My desired output would look like this:
   corpus tweet_id               tweet_text              date    annotator           annotation
1     ALM  5210...  no tweet text available  no date available          00                 care
2     ALM  5210...  no tweet text available  no date available          01         care, purity
3     ALM  5210...  no tweet text available  no date available          02         care, purity
4     ALM  5210...  no tweet text available  no date available          03                 care
5     ALM  5376...  Wholeheartedly suppo...  Wed Nov 26 18:...          00           subversion
6     ALM  5376...  Wholeheartedly suppo...  Wed Nov 26 18:...          01           subversion
7     ALM  5376...  Wholeheartedly suppo...  Wed Nov 26 18:...          02              loyalty
8     ALM  5376...  Wholeheartedly suppo...  Wed Nov 26 18:...          03  loyalty, subversion
...

How can I convert the JSON file to my desired dataframe output?

I've imported the JSON file and tried to flatten it like so:
myData <- fromJSON(file = "my_json_file.json")
myData_flat <- as.data.frame(myData)

But this clearly does not suffice:
str(myData_flat)
'data.frame':   1 obs. of  352130 variables:
 $ Corpus                              : Factor w/ 1 level "ALM": 1
 $ Tweets.tweet_id                     : Factor w/ 1 level "521033092132503552": 1
 $ Tweets.tweet_text                   : Factor w/ 1 level "no tweet text available": 1
 $ Tweets.date                         : Factor w/ 1 level "no date available": 1
 $ Tweets.annotations.annotator        : Factor w/ 1 level "annotator00": 1
 $ Tweets.annotations.annotation       : Factor w/ 1 level "care": 1
 $ Tweets.annotations.annotator.1      : Factor w/ 1 level "annotator01": 1
 $ Tweets.annotations.annotation.1     : Factor w/ 1 level "care,purity": 1
 $ Tweets.annotations.annotator.2      : Factor w/ 1 level "annotator02": 1
 $ Tweets.annotations.annotation.2     : Factor w/ 1 level "care,purity": 1
 $ Tweets.annotations.annotator.3      : Factor w/ 1 level "annotator03": 1
 $ Tweets.annotations.annotation.3     : Factor w/ 1 level "care": 1
 $ Tweets.tweet_id.1                   : Factor w/ 1 level "537681598989475841": 1
 $ Tweets.tweet_text.1                 : Factor w/ 1 level "Wholeheartedly support these protests & acts of civil disobedience & will join when I can! #Ferguson #A"| __truncated__: 1
 $ Tweets.date.1                       : Factor w/ 1 level "Wed Nov 26 18:57:37 +0000 2014": 1
 $ Tweets.annotations.annotator.4      : Factor w/ 1 level "annotator00": 1
 $ Tweets.annotations.annotation.4     : Factor w/ 1 level "subversion": 1
 $ Tweets.annotations.annotator.5      : Factor w/ 1 level "annotator01": 1
 $ Tweets.annotations.annotation.5     : Factor w/ 1 level "subversion": 1
 $ Tweets.annotations.annotator.6      : Factor w/ 1 level "annotator02": 1
 $ Tweets.annotations.annotation.6     : Factor w/ 1 level "loyalty": 1
 $ Tweets.annotations.annotator.7      : Factor w/ 1 level "annotator03": 1
 $ Tweets.annotations.annotation.7     : Factor w/ 1 level "loyalty,subversion": 1
...

A:

There are several packages in R to read in JSON data and have a fromJSON() function. RJSONOIO, jsonlite and rjson are the ones I know about. It seems you are using the rjson::fromJSON() in your code.
Since the json format is very flexible in how it can store data and is able to store complex, nested structures, when we convert it into the relatively under complex format of a data.frame, we have to be very explicit about the structure of the data. Your case is rather simple, but it can be very tedious, to capture the full range of data representations in a json file when converting to the rectangular shape of a data.frame.
rjson::fromJSON() generates a nested list, that resembles the structure of the JSON file.
The structure of your myData list looks something like this:
myData[[1]]:
  - $Corpus
  - $Tweets
      - $[[1]]
          - tweet data
      - $[[2]]
          - tweet data

In order to extract the data you are looking for, you want to cycle through the entries of the mydata[[1]]$tweets sub-list, convert them to a data.frame and then bind together all those data.frames to one big data.frame. You can do that with a for loop or something like lapply(). I'd suggest using purrr::map_dfr() as it automatically binds together the results of each nested operation into one data.frame.
I found that the following should work for your data. Luckily tibble::as.tibble() works well for your data. You apply it once to each tweet entry and after that apply it to each set of annotator, annotion and you'll have the result you are looking for.
library(rjson)
myData <- fromJSON(file = "my_json_file.json")

library(purrr)
library(dplyr)

myData_df <- map_dfr(myData[[1]]$Tweets, as.tibble)

annotations_df <- map_dfr(myData_df$annotations, as.tibble)

myData_df %>%
  select(-annotations) %>%
  bind_cols(annotations_df)

># A tibble: 8 x 5
>  tweet_id      tweet_text                                               date              annotator annotation
  <chr>         <chr>                                                    <chr>             <chr>     <chr>
1 521033092132… no tweet text available                                  no date available annotato… care
2 521033092132… no tweet text available                                  no date available annotato… care,purity
3 521033092132… no tweet text available                                  no date available annotato… care,purity
4 521033092132… no tweet text available                                  no date available annotato… care
5 537681598989… Wholeheartedly support these protests & acts of civ… Wed Nov 26 18:57… annotato… subversion
6 537681598989… Wholeheartedly support these protests & acts of civ… Wed Nov 26 18:57… annotato… subversion
7 537681598989… Wholeheartedly support these protests & acts of civ… Wed Nov 26 18:57… annotato… loyalty
8 537681598989… Wholeheartedly support these protests & acts of civ… Wed Nov 26 18:57… annotato… loyalty,subv…


Q:

iOS viewWillTransitionToSize and device orientation

I'm using viewWillTransitionToSize to detect when a device is rotating to landscape. Depending on the target size, I can detect if heading for landscape and adjust my traits as required...
override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) {

    if size.width > size.height {
        self.setOverrideTraitCollection(UITraitCollection(horizontalSizeClass: UIUserInterfaceSizeClass.Regular), forChildViewController: viewController)
    }
    else{
        self.setOverrideTraitCollection(nil, forChildViewController: viewController)
    }

    super.viewWillTransitionToSize(size, withTransitionCoordinator: coordinator)
}

However, I want to be able to detect whether my device is transitioning to landscape-left or landscape-right. This will allow me to create different behaviours or views, depending on specific orientation of device. (left or right).
Is this possible without using any deprecated functions?
I thought of using status-bar orientation...
    let orientation = UIApplication.sharedApplication().statusBarOrientation;
    if( orientation == UIInterfaceOrientation.LandscapeLeft )
    {
        // Do something
    }
    else if( orientation == UIInterfaceOrientation.LandscapeRight )
    {
        // Do something else
    }

...but that doesn't help because this appears to give the 'old' status orientation.
How can I get the specific target orientation?

A:

You can get orientation while rotating use UIViewControllerTransitionCoordinator as follows:
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
    super.viewWillTransition(to: size, with: coordinator)

    // will execute before rotation

    coordinator.animate(alongsideTransition: { (context: UIViewControllerTransitionCoordinatorContext) in

        // will execute during rotation
        let orientation = UIApplication.shared.statusBarOrientation
        if orientation == .landscapeLeft
        {
            // Do something
        }
        else if orientation == .landscapeRight
        {
            // Do something else
        }
    }) { (context: UIViewControllerTransitionCoordinatorContext) in
        // will execute after rotation
    }
}


Q:

Why [wordpress] tag on WordPress Answers?

Is there any special reason for its existence?
I can't think of any use for it. What do you think? Am I missing something?
https://wordpress.stackexchange.com/questions/tagged/wordpress

A:

Excellent point -- I deleted the tag and added it to the tag blacklist.
(we also ban the "apple" tag on apple.se and the "android" tag on android.se for similar reasons of redundancy)
However, there are now 23 questions tagged untagged which means wordpress was the only tag they had. We'll need some help retagging these.


Q:

How can I stop my script asking the same question?

I'm making this quiz, it grabs a question randomly in an Array then is suppose to check if the question is not already in the Array so it isn't asked again. But when I submit to continue playing it keeps asking the same question.
var Question = function(question, answerChoice, answerRight, congrats, woops) {
    this.question = question;
    this.answerChoice = answerChoice;
    this.answerRight = answerRight;
    this.congrats = congrats;
    this.woops = woops;
}

var questionOne = new Question("What is the capital of France?", "1: Paris, 2: London", 1, "Well done!", "Woops");
var questionTwo = new Question("Smoking kills?", "1: Yes, 2: No", 1, "Well done!", "Woops");
var questionThree = new Question("Is coke good for your health?", "1: Yes, 2: No", 2, "Well done!", "Woops");
var questionFour = new Question("Do birds fly?", "1: Yes, 2: No", 1, "Well done!", "Woops");
var questionFive = new Question("Is green a color", "1: Yes, 2: No", 1, "Well done!", "Woops");
var questionSix = new Question("Do cars have wheels?", "1: No, 2: Yes", 2, "Well done!", "Woops");

var quiz = [questionOne, questionTwo, questionThree, questionFour, questionFive, questionSix];
var randomQ = quiz[Math.floor(Math.random() * quiz.length)];
var checkPrevious = [];
var gameScore = [0];

function gameInit(randomQuestion) {

  if (checkPrevious.includes(randomQuestion) === randomQuestion) {
      gameInit(randomQ);
  } else {

  checkPrevious.push(randomQuestion);
  console.log(randomQuestion.question);
  console.log(randomQuestion.answerChoice);
  var answerPrompt = prompt("What is the right answer?");
  var answer = parseInt(answerPrompt);

  randomQuestion.answerRight === answer ? (console.log(randomQuestion.congrats), gameScore += 1, console.log(gameScore))  : console.log(randomQuestion.woops);
  var continueP = prompt("Carry on playing ? write y to continue. Otherwise type any other key.");

  if (continueP === "y") {
    gameInit(randomQ);

  } else {
      alert("Thanks for playing !")
  }

  }
}

gameInit(randomQ);

A:

You are not generating random number again when calling a gameInit again if the user presses 'y'. Generate it
if (continueP === "y") {
    randomQ=quiz[Math.floor(Math.random() * quiz.length)];
    gameInit(randomQ);

}

and also checking repetition, we have to check if it exists.If it exists regenerate the randomQuestion.If it doesn't exists then only push into checkPrevious.
if (checkPrevious.includes(randomQuestion)) {
    randomQ=quiz[Math.floor(Math.random() * quiz.length)];
    gameInit(randomQ);
  }
 else{
  checkPrevious.push(randomQ)
  ..other code
 }

var Question = function(question, answerChoice, answerRight, congrats, woops) {
  this.question = question;
  this.answerChoice = answerChoice;
  this.answerRight = answerRight;
  this.congrats = congrats;
  this.woops = woops;
}

var questionOne = new Question("What is the capital of France?", "1: Paris, 2: London", 1, "Well done!", "Woops");
var questionTwo = new Question("Smoking kills?", "1: Yes, 2: No", 1, "Well done!", "Woops");
var questionThree = new Question("Is coke good for your health?", "1: Yes, 2: No", 2, "Well done!", "Woops");
var questionFour = new Question("Do birds fly?", "1: Yes, 2: No", 1, "Well done!", "Woops");
var questionFive = new Question("Is green a color", "1: Yes, 2: No", 1, "Well done!", "Woops");
var questionSix = new Question("Do cars have wheels?", "1: No, 2: Yes", 2, "Well done!", "Woops");

var quiz = [questionOne, questionTwo, questionThree, questionFour, questionFive, questionSix];
var randomQ = quiz[Math.floor(Math.random() * quiz.length)];
var checkPrevious = [];
var gameScore = [0];

function gameInit(randomQuestion) {
  if (checkPrevious.includes(randomQuestion)) {
    randomQ=quiz[Math.floor(Math.random() * quiz.length)];
    gameInit(randomQ);
  } else {
    checkPrevious.push(randomQuestion);
    console.log(randomQuestion.question);
    console.log(randomQuestion.answerChoice);
    var answerPrompt = prompt("What is the right answer?");
    var answer = parseInt(answerPrompt);
    randomQuestion.answerRight === answer ? (console.log(randomQuestion.congrats), gameScore += 1, console.log(gameScore)) : console.log(randomQuestion.woops);
    var continueP = prompt("Carry on playing ? write y to continue. Otherwise type any other key.");
    if (continueP === "y") {
      randomQ = quiz[Math.floor(Math.random() * quiz.length)];
      gameInit(randomQ);
    } else {
      alert("Thanks for playing !")
    }

  }
}

gameInit(randomQ);


Q:

Can't set multiple selected value select2 on edit mode

I'm trying to load selected values from db and set it on the select2. i'm using the select2 4.0.10 version. im loading the data using ajax and set the select option to the select2 element after the document is ready.
so, i tried using the $("#area").val(selectedValues).trigger("change"); but nothing seems to be selected.
here is some code of my view.
<input class="form-control" type="text" id="sourceValues" value="CMS,KDY,RWG">

here is my select2 element

            Area Tagih Kolektor

                <select id="area" class="js-example-basic-multiple form-control" name="area[]" multiple="multiple" required>

                </select>

and here is my script for set the selected values.

there is no error when im running the script.

A:

You need to change the way you are appending options to Select Box in your ajax success callback.
Instead of following way to append options.
                data = JSON.parse(data);
                for(j=0; j<data.length; j++){
                    html += '<option value="'+data[j].GroupBranchID+'">'+data[j].branch+'</option>';
                }

You need to append options using the following method
            for(j=0; j<data.length; j++){
                var option = new Option(data[j].branch, data[j].GroupBranchID );
                $("#area").append(option);
            }

Document states that

New options can be added to a Select2 control programmatically by creating a new Javascript Option object and appending it to the control:

Here is the JS Fiddle which adds New Option to Select Box on a Click Event. In your case, Click Event fires an AJAX Call and remotely fetches data.


Q:

Does Android Virtual Device SD Card size consumes computer's HD space?

I am learning from the online tutorial to create a new Android Virtual Device. There isn't much written for the settings of the AVD.
Question 1) If I set the SD Card size to (say 2GB), does it literally "eats up" my computer's Harddisk space of 2GB by creating an image file of 2GB?
Question 2) If it does takes up my computer's HD space, in future when I create multiple AVDs, it will requires a lot of HD space am I right?
EDIT: So when I delete the created AVDs, does it free up my HD space immediately, or do I need to do a series of thing to do a "clean" AVD deletion?
Sorry for the addition question. Thank you for all your replies. I will undoubtedly vote up all your constructive solutions by tomorrow.

A:

Yes, the harddisk space is immediately allocated.
# First, I created a new AVD device called 2gb-sdcard and an AVD
# device called no-sdcard (which uses the minimum size of 10MB)
# Both are same device type, SDK, skin, etc.
#
$ cd ~/.android/avd/2gb-sdcard.avd
$ du -h
2.4G    .

$ cd ~/.android/avd/no-sdcard.avd
$ du -h
410M    .


Q:

Splitting a big project to create a multi-module Maven project

I am working on a Spring-MVC application in which we are using Maven for dependency management. As the project is big, we are thinking of splitting the project into several parts. I had some doubts, which I hopefully will get answers here.
Currently, we are deploying a single WAR file as ROOT.war on Apache tomcat on our server. As the project is big, there are parts in the webapp like Notifications and Email, Third party services, PUSH (Cometd),REST API's, etc. Currently all of them are clubbed and are dependent on each other. For example, Notification object also depends on Person object, as Notifications are tailored for users.
The main intention of splitting the big project is to be able to work on individual modules, for bug fixes, adding features, testing, etc. And when satisfied, then only this module can be replaced on the server instead of the entire application. Is this possible?
As I already mentioned before, there are dependencies and mappings between objects. How will those be managed across different sub-modules, or will just the import statements change to include other projects?
As I said, the intention is to work on individual modules and be able to deploy them(preferably hot). Currently, we have only a single WAR file as ROOT.war. Will splitting create multiple war files, which are then referred by URL as domain-name.com/module_name/some_mapping?
I am currently checking the documentation, but this is the primary objective we want to achieve with multi module provided by Maven and interested to know if this is feasible. If there is any more information required, please let me know.
Currently I am using a parent POM from spring as follows:
<parent>
    <groupId>io.spring.platform</groupId>
    <artifactId>platform-bom</artifactId>
    <version>1.1.3.RELEASE</version>
    <relativePath />
</parent>

A:

Is it possible ?
Yes certainly. I have in the past structure a few projects like this, here some bits I hope will get you started.
There are two main features of Maven you will use to weave things together:

Normal dependecies
Modules

Divide and conquer
You will need to split your projects in multiple independent projects. Here by independent I mean that all references to code outside the project is done through dependencies in Maven and not directly merging the source tree.
Depending on the state of your source tree this could represent a lot of work.  That said you are not doing it to shoehorn to Maven but rather as a mean to structure and sanitize your code base. Think of it as your toolshed, much easier to find things here:

than here:

Maven relies heavily on convention so the better organized your stuff is the more Maven can help you. That said, It may require you to re-organize to better fit it's own convention and if I have to give one piece of advice here is that it's MUCH easier to change your stuff to fit Maven's conventions than it is to try and configure Maven to understand your convention.
If these projects could be usable outside the main application they could live as truly independent libraries and included though maven dependencies. They should live in their own repository (not in the application source tree) and should not depend on any part of the main application.
Core parts of your application, once split in projects can be put together as modules. Typically you will have them placed as sub-folder of the main source folder of your app.
Also your parent POM for your app will contain the module declaration. You will also place in there all the common dependencies for your app as well as declare most of the build plugins and their configuration. In here also I stronly reccomend you place a group of properties for things such as the version of the application which you can reuse in the modules. Much easier to manage when everything have the same version and having the version in one place makes this just work.
Tooling
If you are a team larger than 1 I would also strongly reccomend that you install a repository for your Maven dependencies. Look at Artifactory, Nexus or Archiva. You can configure the POM file to install to these directly so once running it should not be much of an overhead but will save your team a lot of time resolving the dependencies with the correct jar in the correct place.
On the subject of tooling the next logical step here is a continuous integration system (Jenkins, there are many more). It will handle building the source running the tests and pushing to the artifactory, with all this in place all you have to do is work the code and the rest just works.
Since you are packaging your app as a war maven can handle building the war and place all the dependencies in their proper places without having to merge jar files or other similar work around, so no worries there.
Example
I could go on much longer here but nothing beats a good example. Look on github for projects of similar magnitude and see how they built their pom files and folder hierarchies. Look at more than one, some will fit your setup better than others, none really incarnate the truth but you should find enough to fuel your thoughts on how to get it done.
Take Jenkins for example:
You can see their parent POM is quite extensive.
They do use modules as you can see in this section:
<modules>
    <module>core</module>
    <module>war</module>
    <module>test</module>
    <module>cli</module>
</modules>

And each module correspond a sub-folder with the same name that also contains a POM. You could nest as many as you want like this, though do keep it within sanity levels ;).
Start Small
If you have never used Maven I would suggest however you do not start with modules right away. Take it slow, start with, say one of the simpler libraries you may have and make it a maven project. Then make your main application a simple maven project.  Once that work, start adding simple dependencies, then split your first module and so on.
Maven is a great tool but it can also be a super pain in the neck especially when things are not going your way. Starting with the whole whammy on your first go is a recipee for disaster (was for me!).
If things are a bit weird you can always use mvn help:effective-pom command to see what Maven actually understood.
plugins
From your comment I understand better what you want to acheive. In this case I would go for plugins approach.  Create a project that exposes the API of extention points where you want to isolate the work. Then you can use this as a dependency in a new project that will implement it. In your main application just add the proper dependencies for these implementations (not using maven modules this time) and you should be good to go. Eventually the main application project will carry nearly no source code everything being done in external projects and loaded through dependencies.
You will need to re-deploy the whole application however with this approach, regardless if the core changed or not as the war is statically built from the dependencies, changing one of them implies rebuilding the whole thing. It sounds worst than it actually is, In effect only the new changes will actually get built, the rest will basically be a copy of the previous jar(s). But since everything is in the war file it will need to be re-built, and the server will need to be stopped and restarted.
If you need to go further things get a tad bit more complicated, though not impossible. I would reccomend you look into OSGI, Apache Felix could get you started, though there are other implementations as well. This will allow you to take the external jar and make them into proper plugins. You will gain a lot more control on the runtime lifecycle of the components opening the door to dynamic reloads and updates. It will however require major changes to your core so again, probably not a good starting point. However once you have a project that is well separated and have all the parts isolated the way you want, that could be a natural next step if starting and stopping the application on update is a major problem.
The basic difference between Modules and dependencies is this:

Modules will live in the same source tree as the main application, as sub-folders ideally.
Dependencies can be anywhere.

You can find the bible here.
Hope this helps, good luck.


Q:

The real numbers $x,y$ and $z$ are such that $x-7y+8z=4$ and $8x+4y-z=7$. What is the maximum value $x^2-y^2+z^2?$

The real numbers $x,y$ and $z$ are such that
$x-7y+8z=4$ and $8x+4y-z=7$. What is the maximum value of $x^2-y^2+z^2?$
From those equations I got:
$12z-5x=13y$
$12x+5z=13$
$12y+5=13z$
$12-5y=13x$
I know that $5,12,13$ is a pythag triplet but I don’t know what to do next. I think lagrange multipliers could be used but there should be a solution that doesn’t require calculus
Hints, suggestions and solutions would be appreciated.
Taken from the 2014 KIMC https://chiuchang.org/imc/wp-content/uploads/sites/2/2018/01/2014-IWYMIC-Individual.x17381.pdf

A:

Solving the system
$$x-7y+8z=4$$
$$8x+4y-z=-7$$
we get
$$y=\frac{12}{5}-\frac{13}{5}x$$
$$z=\frac{13}{5}-\frac{12}{5}x$$
and we get
$$x^2-y^2+z^2=1$$
Very NICE!
Below please find an image of the surface $x^2-y^2+z^2=1$ together with the (thick red) line of intersection of the two given planes.


Q:

One type of delimiter in one date time string in RegEx

Is there any way to write a Regex that can validate one type of delimiter in one date time string only?
For example, 30/04/2010 is correct but 30-04/2010 is incorrect.
I googled and found something about backtrack but I am not very sure how to use it. For example, if i have this regex:
(?P<date>((31(?![\.\-\/\—\ \,\–\-]{1,2}(Feb(ruary)?|Apr(il)?|June?|(Sep(?=\b|t)t?|Nov)(ember)?)))|((30|29)(?![\.\-\/\—\ \,\–\-]{1,2}Feb(ruary)?))|(29(?=[\.\-\/\—\ \,\–\-]{1,2}Feb(ruary)?[\.\-\/\—\ \,\–\-]{1,2}(((1[6-9]|[2-9]\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00)))))|(0?[1-9])|1\d|2[0-8])[\.\-\/\—\ \,\–\-]{1,2}(Jan(uary)?|Feb(ruary)?|Ma(r(ch)?|y)|Apr(il)?|Ju((ly?)|(ne?))|Aug(ust)?|Oct(ober)?|(Sep(?=\b|t)t?|Nov|Dec)(ember)?)[\.\-\/\—\ \,\–\-]{1,2}((1[6-9]|[2-9]\d)\d{2}))
Then how am I supposed to use backtrack here?
Thank you very much.

A:

Not an answer to your question, but have you considered using strtotime()?
It is a very flexible function able to parse about any english date and time:
Feb 2, 2010
February 2, 2010
02/02/10
4 weeks ago
Next Monday

If a date is unparseable, the function will return false (or -1 prior to PHP 5.1).
There are a few gotchas - I think I remember that when using xx-xx-xxxx notation, it tends to assume an european DD-MM-YYYY date - but all in all, you may fare much better with it than with a regex.


Q:

Stub a service's instance method and check whether it received a call to it

I'm writing specs for a Rails project that uses an external service (Aws::S3 in this case). I would to stub calls to upload_file on any instance of Aws::S3::Object, and also be able to check afterwards whether an instance of this class has received a call to upload_file.
What I did so far:
allow_any_instance_of(Aws::S3::Object).to receive(:upload_file).and_return('Stubbed!')

and
expect_any_instance_of(Aws::S3::Object).to receive(:upload_file)

but somehow the expectation doesn't work (my code calls upload_file but RSpec doesn't see it).

A:

Moving forward, I would suggest avoiding the use of x_any_instance_of methods for reasons outlined in the RSpec Mocks documentation.
Instead, stub out the call to .new on the Aws::S3::Object class, and have an instance_double stand in for the actual object that gets initialized in your app so that you can make assertions on it directly.
Here's some example code and specs comparing both syntaxes:
module Aws
  module S3
    class Object
      def upload_file
        # upload the file
      end
    end
  end
end

class FileUploader
  def self.upload
    Aws::S3::Object.new.upload_file
  end
end

RSpec.describe FileUploader do
  describe '.upload' do
    context 'using any_instance_of' do
      before do
        allow_any_instance_of(Aws::S3::Object).to receive(:upload_file)
      end

      it 'calls to upload the file on the S3 Object' do
        expect_any_instance_of(Aws::S3::Object).to receive(:upload_file)
        described_class.upload
      end
    end

    context 'using an instance double' do
      let(:s3_object) { instance_double('Aws::S3::Object') }

      context 'stubbing a method to return the double on allow' do
        before do
          allow(Aws::S3::Object).to receive(:new).and_return(s3_object)
        end

        it 'uploads the file on the S3 Object' do
          expect(s3_object).to receive(:upload_file)
          described_class.upload
        end
      end

      context 'stubbing a method to return the double on expect' do
        it 'uploads the file on the S3 Object' do
          expect(Aws::S3::Object).to receive(:new).and_return(s3_object)
          expect(s3_object).to receive(:upload_file)
          described_class.upload
        end
      end
    end
  end
end


Q:

Turn Off SSL Certificate Verification in Mulesoft 3.8

I am using HTTP connector and using protocol "https". But for the development purpose I wanted to Turn Off the SSL certificate Verification. How to achieve this in Mulesoft 3.8

A:

[
in TLS/SSL tab of HTTP connector, select Custom TLS setting and checked the 'Insecure'


Q:

Error occuring in Select Into Statement

I have the following statement which has a syntax error in the 'From' clause, which has a couple of curly table names. The actual database names are the same as the tables, so they are all seperate.
I open a connection to the SealRegister mdb, which is empty (no tables yet), then ExecuteNonQuery on the statement. This I think should create the table SealRegister in the SealRegister.mdb.
sqlcommand = @"Select ""Plant"" As Geometry, A.Asset_ID, B.RoadID, A.AssetType, B.RoadName, B.SegmentNo, C.AadtCount, C.CommVehCnt " +
  @"Into [SealRegister] " +
    @"From [C:\AR\Plant\Accounting\2015].ARPlntPA_2015_07-2016_06+10yrs As A " +
      @"LEFT OUTER JOIN ([C:\AR\Lines\Accounting\2015].ARLnPA_2015_07-2016_06+10yrs As B " +
        @"LEFT OUTER JOIN [C:\AR\Lines\TEMP].ARLnX As C On B.Asset_ID = C.Asset_ID) On A.Parent_ID = B.Asset_ID " +
          @"WHERE AssetType = 'Wearing Course'";

What do I need to do to correct the syntax
[EDIT]

connStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data
  Source=C:\AR\TEMP\SealRegister.mdb"

A:

This works:
sqlcommand = @"Select ""Plant"" As Geometry, A.Asset_ID, B.RoadID, A.AssetType, B.RoadName, B.SegmentNo, C.AadtCount, C.CommVehCnt " +
  @"Into [SealRegister] " +
    @"From [C:\AR\Plant\Accounting\2015\ARPlntPA_2015_07-2016_06+10yrs].[ARPlntPA_2015_07-2016_06+10yrs] As A " +
      @"LEFT OUTER JOIN ([C:\AR\Lines\Accounting\2015\ARLnPA_2015_07-2016_06+10yrs].[ARLnPA_2015_07-2016_06+10yrs] As B " +
        @"LEFT OUTER JOIN [C:\AR\Lines\TEMP].ARLnX As C On B.Asset_ID = C.Asset_ID) On A.Parent_ID = B.Asset_ID " +
          @"WHERE AssetType = 'Wearing Course'";


Q:

Proper way to free allocated pointer on crash

Imagine causing a segfault in C program which is common (and bad). Should I be aware about 'still reachable' pointers that were allocated during the runtime?
I googled about Valgrind's opinion on still reachable pointers (also read other related stackoverflow topics) and what I learned is that basically it's not a big problem and I don't have to worry about it. But I do.
In C++ it could be kinda fixed by using freeing destructor which will be always called according to standard.

void lose_definetly() {
  int * array = calloc(4,sizeof(int));
  array[3] = 1232;
}

void proper_free() {
  int * array = calloc(4,sizeof(int));
  array[3] = 1232;
  free(array);
}

void cause_segfault() {
  int * array = calloc(4,sizeof(int));
  array[-1232142144] = 1232;
  free(array);
}

int main() {
  lose_definetly();
  proper_free();
  cause_segfault();
  return 0;
}

Program output is expected segfault:
Segmentation fault (core dumped)

Valgrind's report on leaks:
==134==    definitely lost: 16 bytes in 1 blocks
==134==    indirectly lost: 0 bytes in 0 blocks
==134==      possibly lost: 0 bytes in 0 blocks
==134==    still reachable: 16 bytes in 1 blocks
==134==         suppressed: 0 bytes in 0 blocks

So, please, suggest if I should care of this case and how can I aware myself aside from writing a proper code and pointers control. Is it possible to create a callback function on this case (or override interrupt signal)?

A:

Trying to clean up after a crash of this type is a fool's errand. More than likely, the runtime environment will be too corrupt to permit recovery anyway and, worse, the corrupt environment may cause your free calls to have unexpected, possibly even harmful, results.
This is like trying to clean your room when your house is on fire. Just get out as quickly as you can before you get badly burned.

A:

When a process receives a segfault, it will be terminated, and the OS will release its allocated resources. There is no point in worrying about leaks at that point.

In C++ it could be kinda fixed by using freeing destructor

No. Destructors are not executed upon abnormal termination.
What you can do is catch a segfault signal, but you are limited to using async signal safe functions. Functions dealing with memory allocation are not signal safe. If there are resources allocated by something other than the operating system (possibly on some remote system), then you can attempt to release them in the handler, but that can be challenging due to the limitations of async signal handlers.


Q:

Match dates with different formats in Powershell

I am trying to match the boot up time with the file modified date to be within a couple minutes of each other.
I can get the data but don't know how to do the computations.  Here is what I get:
PS E:\> $disk=gci -Attributes hidden E:\filename.ext | Select LastWriteTime
PS E:\> $disk

LastWriteTime
-------------
6/23/2014 12:55:48 PM

PS E:\> $boottime=Get-CimInstance -ClassName win32_operatingsystem | select last bootuptime
PS E:\> $boottime
lastbootuptime
--------------
6/23/2014 12:55:39 PM

What I am looking for in English is a way to say "If lastwritetime is within 5 minutes of lastboot time, then all is good.  If not, all is bad"
How can I do that with powershell?

A:

I would subtract the datetimes and use the resulting TimeSpan object.  Also, note that using the -ExpandProperty is needed to get a bare value with select-object.
$disk=gci -Attributes hidden E:\filename.ext | Select -ExpandProperty LastWriteTime

$boottime=Get-CimInstance -ClassName win32_operatingsystem | select -ExpandProperty lastbootuptime

if(($disk-$bootTime).TotalMinutes -lt 5){
  "all is good"
}


Q:

Algorithm to find peaks in 2D array

Let's say I have a 2D accumulator array in java int[][] array. The array could look like this:
(x and z axes represent indexes in the array, y axis represents values - these are images of an int[56][56] with values from 0 ~ 4500)

or

What I need to do is find peaks in the array - there are 2 peaks in the first one and 8 peaks in the second array. These peaks are always 'obvious' (there's always a gap between peaks), but they don't have to be similar like on these images, they can be more or less random - these images are not based on the real data, just samples. The real array can have size like 5000x5000 with peaks from thousands to several hundred thousands... The algorithm has to be universal, I don't know how big the array or peaks can be, I also don't know how many peaks there are. But I do know some sort of threshold - that the peaks can't be smaller than a given value.
The problem is, that one peak can consist of several smaller peaks nearby (first image), the height can be quite random and also the size can be significantly different within one array (size - I mean the number of units it takes in the array - one peak can consist from 6 units and other from 90). It also has to be fast (all done in 1 iteration), the array can be really big.
Any help is appreciated - I don't expect code from you, just the right idea :) Thanks!

edit: You asked about the domain - but it's quite complicated and imho it can't help with the problem. It's actually an array of ArrayLists with 3D points, like ArrayList< Point3D >[][] and the value in question is the size of the ArrayList. Each peak contains points that belong to one cluster (plane, in this case) - this array is a result of an algorithm, that segments a pointcloud . I need to find the highest value in the peak so I can fit the points from the 'biggest' arraylist to a plane, compute some parameters from it and than properly cluster most of the points from the peak.

A:

He's not interested in estimating the global maximum using some sort of optimization heuristic - he just wants to find the maximum values within each of a number of separate clusters.

These peaks are always 'obvious' (there's always a gap between peaks)

Based on your images, I assume you mean there's always some 0-values separating clusters?  If that's the case, you can use a simple flood-fill to identify the clusters.  You can also keep track of each cluster's maximum while doing the flood-fill, so you both identify the clusters and find their maximum simultaneously.
This is also as fast as you can get, without relying on heuristics (which could return the wrong answer), since the maximum of each cluster could potentially be any value in the cluster, so you have to check them all at least once.

Note that this will iterate through every item in the array.  This is also necessary, since (from the information you've given us) it's potentially possible for any single item in the array to be its own cluster (which would also make it a peak).  With around 25 million items in the array, this should only take a few seconds on a modern computer.


Q:

Converter diversos nós em XML para struct

Procurei alguns exemplos na documentação oficial do golang e em alguns tutoriais online porém só encontro exemplos simples vejam:
<data>
    <person>
        <firstname>Nic</firstname>
        <lastname>Raboy</lastname>
        <address>
            <city>San Francisco</city>
            <state>CA</state>
        </address>
    </person>
    <person>
        <firstname>Maria</firstname>
        <lastname>Raboy</lastname>
    </person>
</data>

Para lêr esta estrutura xml eu só preciso de 2 struct sendo elas: data e person, este exemplo foi retirado deste site junto com a resolução: thepolyglotdeveloper
Structs:
type Data struct {
    XMLName    xml.Name `xml:"data" json:"-"`
    PersonList []Person `xml:"person" json:"people"`
}

type Person struct {
    XMLName   xml.Name `xml:"person" json:"-"`
    Firstname string   `xml:"firstname" json:"firstname"`
    Lastname  string   `xml:"lastname" json:"lastname"`
    Address   *Address `xml:"address" json:"address,omitempty"`
}

type Address struct {
    City  string `xml:"city" json:"city,omitempty"`
    State string `xml:"state" json:"state,omitempty"`
}

Minha dúvida é como vou fazer quando um xml tiver mais de um nó como no exemplo abaixo:
<SuccessResponse>
    <Head>
        <RequestId/>
        <RequestAction>XPTP</RequestAction>
        <ResponseType>XPTU</ResponseType>
        <Timestamp>TIMESTAMP</Timestamp>
    </Head>
    <Body>
        <Products>
            <Product>...</Product>
            <Product>...</Product>
        </Products>
    </Body>
</SuccessResponse>

Eu vou precisar criar uma struct para SuccessResponse e dentro dela preciso ter outa struct com o nome Body e dentro de Body Products e assim por diante?

A:

Sim, você deve criar as estruturas aninhadas da mesma forma que o documento original. No exemplo que você deu, isso já acontece em um único nível com Person e Address.
O que pode te facilitar é acessar os campos específicos que você quer na estrutura mais interna e puxá-los mais para fora. Seguindo o exemplo que você pegou, imagine que city seja uma estrutura composta pelo nome da cidade, estado e país:
<data>
    <person>
        <firstname>Nic</firstname>
        <lastname>Raboy</lastname>
        <address>
            <city>
                <name>San Francisco</name>
                <country>USA</country>
                <state>CA</state>
            </city>
        </address>
    </person>
    <person>
        <firstname>Maria</firstname>
        <lastname>Raboy</lastname>
    </person>
</data>

E suponha que você só esteja interessado no nome da cidade e no do país.
É possível construir a seguinte estrutura:
Person struct {
    XMLName   xml.Name `xml:"person" json:"-"`
    Firstname string   `xml:"firstname" json:"firstname"`
    Lastname  string   `xml:"lastname" json:"lastname"`
    City      string   `xml:"address>city>name" json:"city,omitempty"`
    Country   string   `xml:"address>city>country" json:"country,omitempty"`
}

Veja no Go Playground


Q:

Install 13.04 on Mac Mini (End 2012)

I am trying to install Ubuntu 13.04 (the 64-bit Mac variant) onto my Mac Mini.
Thus I shrunk the main MacOSX partition and installed refind.
Now I can boot into rEFInd and then select the usb stick, but it does not boot due to:
Kernel panic - not syncing: VFS: Unable to mount root fs on unknown-block(0,0)

Sadly I cannot find anyone who tried a recent Mac Mini/Ubuntu version.
How best to debug this issue?

Update 1:
So I figured maybe rEFInd does not provide the necessary driver and installed it again via install.sh --drivers-all. Which lead to a WSOD.
Luckily I eventually could get back into restore via Command + R and am now reinstalling MacOSX.

Update 2:
After my MacOSX was working again I did:

installed _rEFIt
set up my future Ubuntu partition as FAT
booted twice
booted into Ubuntu Live CD

And that's where the next trouble started. While wireless and graphics work great in Ubuntu 13.04, they mount the FAT partition as /cdrom, which makes installing on it impossible.

A:

Why not try rEFIt instead  ?
check out http://mabelmzhang.blogspot.com/2013/02/how-to-guide-for-triple-booting-mac-os.html
rEFIT / Ubuntu 12.04 LTS / Kernel 3.9.x worked for me


Q:

Close quarter's defense: when you stand face to face with an attacker

What can we do against a harasser who comes at a distance of two inches of you with a clearly menacing attitude. What strike could be applied at the distance of two inches standing face to face (I suppose the one-inch punch would be the ideal solution, but it's not feasible for me). If you assess the situation and consider a violent confrontation inevitable (but prefer to strike first), and there is no distance for kicking.

A:

At that distance you are most in danger of a headbutt.
Firstly, don't find yourself in that situation. When things start to get hairy, lift up your arms to about chest height, with PALMS FACING OUTWARD IN A NON-MENACING WAY so as to show you want to avoid confrontation. Any cameras (security or people with camera-phones) will show you to be the non-aggressor if you end up in court. This will also serve to keep your personal-space well defined, any breach of that space and you can act quicker.
Secondly, if you do find yourself 2 inches away from an aggressor, just push him away with a double palm push (or strike depending on your point of view) to the chest. Best way is the Wing Chun straight down the centre-line as that will be the quickest, even if your hands are low.

A:

The more important question you should be asking is what's actually going on here? What is the psychology of this situation? Knowing that is the only way of figuring out how you should react. The actual fighting techniques you might use are of secondary importance, and I kind of think any martial art will have a number of techniques and strategies that you can use effectively in this situation.
And by the way, no technique is guaranteed to finish the fight in one blow. That happens only in movies and martial arts folklore. In reality, knowing what to do after that first blow is just as important. Things will go wrong. You need a system. You need training. There are no "trick" techniques that work all the time in this situation.
My observation of the stare-down scenario is this: If the aggressor in this situation has not initiated any physical contact (no pushes, no punches, etc.), then it is an indication that he is unwilling to fight.
If he wanted to fight you, he would not hesitate to shove you hard or punch you. Instead, he is waiting to see what happens. That is a dead giveaway that he doesn't want to actually fight you.
As the defender, you have three choices:

Deescalate by backing away, gesturing, and using your voice.
Preemptively attack by punching, tackling, etc.
Stand your ground (do nothing except stare back confidently).

The fights that I have personally witnessed as well as those I've watched on youtube which started with a stare-down initiated by an aggressor tend to show that the best two choices are #2 and #3. But even #1 will work, though you have to be careful with it.
In the first choice, you deescalate. That means you try to put some distance between you both and turn your body to the side to protect yourself. You put your hands up, palm facing outward to gesture that you don't want to fight. And you ask the guy what's the matter.
Deescalating doesn't always work, of course. The guy could take it as a sign of weakness from you and will try to lunge forward to punch you. Be ready for it. Once he attacks physically, your best option is to fight back, rather than continue to back away.
You need to be able to instantly flip the switch in your mind from deescalation to full-on fight mode. That's something most people just aren't trained to do, even most martial artists. It happens so fast. In most fights whereby someone attacks while the other guy is deescalating, the one who attacks generally wins. And it's because the defender in this case hasn't flipped that switch, and he's probably also very psychologically intimidated and afraid. He's not confident and not ready to engage.
The second choice is to preemptively attack the aggressor. Since he's unwilling to initiate the fight physically, he probably won't be psychologically prepared for your attack. And at this close range, it's quicker to act than to react. You can punch or take him down to the ground before he has a chance to react to it. And chances are, the person who initiates contact first will win in this situation.
But preemptive strikes aren't guaranteed to work. That first strike is just the beginning. You can make it the best punch you've ever made, and it lands square on the jaw, but that guy might not be phased. You need more than just a single strike plan. You need a full fighting system to use after that.
Also, you don't know if this guy has a gun or a knife, or if one of his friends is standing behind you ready to jump on you. There are a lot of ways a preemptive strike could go wrong. The main thing to keep in mind is that you could be hurt, so it is risky.
The last of the 3 choices, in no particular order, is to stand your ground. This is actually not a bad choice. Once again, I observe that the aggressor seems unwilling to fight you if he hasn't initiated physical contact. You might reject choice #1 (deescalation), because you think he will see you backing off and will interpret it as a sign of weakness, so you figure he'll try to punch you or something if he sees that. And choice #2 (a preemptive strike) seems unnecessary or too risky (physically, legally, etc.) to you. So you choose to stand your ground.
Standing your ground here means you're not going to back down, nor are you going to initiate any physical contact here (like by pushing him). You'll stare him in the eyes and not look away. Your posture should be strong and confident, ready to fight. You won't verbally or through gestures try to deescalate (which would signal to him that you're weak). You can verbally indicate a willingness to fight him should he touch you. It's a warning. That's perfectly fine and works well in cases when the aggressor is not confident enough to initiate physical contact like this.
During the stare-down, some aggressors decide to try to escalate the fight by pushing you. If you are ever pushed, you have only one option in my opinion: strike him back and keep striking him (or grapple with him) until he backs off. Why? Because standing your ground no longer makes sense, and deescalation won't work in this case. Once someone has initiated physical contact, they have signaled that they believe the other guy is weak and will continue to attack him, because they believe they will win. If you attempt to deescalate, it will merely confirm his view that you're weak, and he'll use that as an opportunity to hurt you.
But there's also a pretty good chance that the stare-down scenario will result in nothing happening. Simply standing up confidently, not showing fear, and not backing down is usually enough to intimidate someone into backing down. The more time that goes by, also, the cooler the aggressor will become. It gives the guy a chance to vent, say a lot of cuss words, pound his chest, etc. Eventually the guy gets bored and leaves.
My homework assignment to you is to watch candid youtube videos of street fights of all kinds, not just this stare-down scenario. Pay close attention to how the fight starts and who wins. Sometimes it helps watching the fight with the sound turned off, so you can pick up on all of the physical cues. Notice this trend: The one that appears unwilling (who is reluctant) to fight is indicating weakness. The other guy will generally win if he attacks (even if he's not the aggressor).
Legal disclaimer: Of course there's doing what's right, and then there's doing what is legal. I don't give legal advice. You need to look into how the laws in your country, state, town, etc. are setup for self-defense situations. Preemptive strikes are the hardest to sell to a jury. The easiest is to convince the jury you attempted to deescalate the situation and only responded with enough force to stop the attacker from hurting you and then got away (never more than that). Standing your ground could go either way, but it might work in your favor if someone sees that you didn't initiate it. This is critical in situations where either of you are seriously injured or killed.
Hope that helps!


Q:

Magento add custom options with programmatically importing products

I'm programmatically importing simple products in Magento based on a .csv file. Everything works fine, but I have to add some values where I have created some custom attributes for. But I don't know how to add them.
I thought since I added the attribute set where the custom attributes are in, I could add them like
$product->setCustomAttribute(value)
but that doesn't work.
How can I add them?
Rest of the code for reference
if(($handle = fopen("werkbladvoorraad.csv", "r")) !== FALSE){
    while(($data = fgetcsv($handle, 1000, ";")) !== FALSE){
        $row++;

        if($row == 1){
            continue;
        }

    try{
        $product ->setStoreId(1)
                 ->setWebsiteIds(array(1))
                 ->setAttributeSetId(4)
                 ->setTypeId('simple')
                 //->setCreatedAt(strtotime('now'))
                 ->setSku($data[0])
                 ->setName($data[1])
                 //->setWeight()
                 ->setStatus(1)
                 ->setTaxClassId(2)
                 ->setVisibility(Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH)
                 ->setManufacturer($data[14])
                 ->setColor($data[10])
                 ->setPrice($data[6])
                 ->setMaat_heren($data[4]) // CUSTOM ATTRIBUTE
                 ->setStockData(array(
                       'use_config_manage_stock' => 0,
                        'manage_stock'=>1,
                        'min_sale_qty'=>1,
                        'max_sale_qty'=>2,
                        'is_in_stock' =>1,
                        'qty' => 999
                    ));
       $product->save();
    }catch(Exception $e){
        echo ($e->getMessage());
    }
  }
}

Note
There are no error messages displayed

A:

I know it's silly, but you could try cleaning up your cache and then saving the custom attributes in question. If that doesn't work, try forcing the saving with:
$product->setMyCustomAttr('My Custom Attr');
$product->getResource()->saveAttribute($product, 'my_custom_attr');

Just make sure that you have already saved the product and loaded it again with its ID. In order to do that you would use
Mage::getModel('catalog/product')->load(1);

Let me know if this works properly :)


Q:

Planetary core building

Let's say we have 2 planets, one being 'a' (the bigger one) and one being 'b'. Planet a is completely hollow inside with planet b is inside of it. My question is how much gravitational force would planet a have to exert on b to turn b into a molten core.(if it is possible) planet b is about 2.12x10^23kgs. I don't care how much planet a weighs, that's up to you.

A:

TLDR : Not going to happen.
Despite the shell theorem there is a net force between the two.
Object (a) on the outside ("the shell") does not exert any net force on any part of object (b) ("the core") regardless of the relative positions as long as (b) is entirely enclosed in (a) and (a) is spherically symmetrical.  That's an absolute result from the Shell Theorem.
But the core (b) does exert a net attraction on every part of the shell (a).  The shell theorem does not apply outside an object.
So the core will attract the shell and, as there must be an equal and opposite reaction, the core will also feel a force balancing that.
But this is a very, very unstable configuration.
The instant the core's center shifts even a fraction off the exact center of the shell it will inexorably move off the center, most likely accelerating into a collision with the shell.
Likewise if either the core or the shell are not perfectly spherically symmetrical they will drift off and eventually most likely collide.

My question is how much gravitational force would planet a have to exert on b to turn b into a molten core.(if it is possible) planet b is about 2.12x10^23kgs.

Never going to happen.
The net force on every part of the core is not compressive (inward) but outward (an opposite reaction to the attractive force it exerts on the shell).  So while there could be extreme sheering forces if they cease to be in a stable configuration (and they would eventually) there would no be compressive forces globally on the core, only perhaps (a maybe) on local parts of the core undergoing deformation as part of sheering.  But that's unlikely to melt the core, so much as break it up.
Likewise the forces on the shell are all pulling it inward, but this would also require the shell to support itself.  This would almost certainly be impossible - you're describing a Dyson Sphere, in fact.
If you want at least part of the core to be molten it would have to do it under it's own efforts.  This either requires that :

The core was formed in such a way that it has not yet dissipated it's heat of formation - actually Earth's condition, hence our own molten core.
or the core had a very radioactive interior (unlikely to be significant, IMO)

The Earth would have been a molten ball early in it's formation.  It has cooled gradually down.  That's how it works.
I don't think your system is at all possible without artificial support, which would be a feat of staggering difficulty, beyond out current science and probably going to stay that way for many, many tens of thousands of years if at all.


Q:

Proposition about of Purely inseparable extension

In the Book's Algebra, Lang, page 251.
Proposition: Let $E^p$  denote the field of all elementos $x^p$, $x\in E$- Let $E$ be a finite extension of $k$. If  $E^pk=E$, then $E$ is separable over $k$.
Proof:Let $E_0$ be the maximal separable subfield of $E$. Let $E=k(\alpha_1,\ldots,\alpha_n)$. Since $E$ is purely inseparable over $E_0$ there exists $m$ such that $\alpha_i^{p^m}\in E_0$ for each $i=1,\ldots,n$. Hence $E^{p^m}\subset E_0$ . But $E^{p^m}k=E$ whence $E=E_0$ is separable over $k$.
$\textbf{My question's are:}$
1) Why can the same $m$ be used for all the $\alpha_i's$, rather than different $m_i's$?
2)  Please explain why $E^pk=E$ implies $E^{p^m}k=E$
Thank you all.

A:

For (1), there's some $m_i$ that works for each $\alpha_i$. It's enough to let $m$ be the largest of these.
For $(2)$, assume that $E^{p^{m-1}}k = E$. Apply the Frobenius endomorphism to each side of this equality to obtain $E^{p^m} k^p = E^p$, hence $E^{p^m} k = E^{p^m} k^p k = E^p k = E$.


Q:

Gitlab: redirection to non resolvable hostname

I've installed Gitlab on Ubuntu 14.04 with the 2 minutes installation doc and when I access the ui http://server_ip, I'm redirected towards http://hostname/users/sign_in
As hostname is not resolvable I cannot accesd this url. I'm sure I missed something but cannot figure out what.
Any ideas ?

A:

You need to change the 'external_url' field in your /etc/gitlab/gitlab.rb file then run sudo gitlab-ctl reconfigure
See http://docs.gitlab.com/omnibus/settings/configuration.html for more details.


Q:

Is it possible to affix a file extension to php $SESSION files?

While I was customizing my php.ini file as to SESSION, I didn't see anything relevant, and searches on the subject have not turned up anything relevant.
The SESSION data is being reliable stored, and can be modified, no problems with the SESSION itself.  But there is an annoyance in that every time I wish to view the data, Windows complains that it cannot open file of unknown type... selecting NotePad2 via that dialogue box all the time could be avoided if I were able to name the SESSION files.  To add for instance  "    .txt "
Example As IS :
sess_LIH7by43o4ufbql3rvERvp9vho8uHp9u3l4jnpw93rhlkrjdnvv98y29o8u3hvpo8w734h
What I would like:
sess_LIH7by43o4ufbql3rvERvp9vho8uHp9u3l4jnpw93rhlkrjdnvv98y29o8u3hvpo8w734h.txt

A:

As far as I know, you can't modify the session filenames.
Instead, try simply having your text editor open, and dragging the files into the text editor.


Q:

How can a GIF made from a vid be larger than the vid itself?

iPhone 6S Plus
Tumblr app GIF creation feature used for taking vid and making GIF
9 seconds of video taken =949kB
3 second portion used for GIF =1.3MB

How?

my assumption is that app wouldn't use low res vids for high res GIFs
I ask because I figured GIFs would be smaller thus transmit faster and use less data when messaging.

A:

There are several factors at play here. For example, your gif creation app may have a quality slider/setting that influences the size of the output. However, the most likely cause is the difference in compression.
The videos your iPhone records are probably compressed using a highly efficient codec such as H264 (I didn't find any information on what codec/file type the iPhone camera uses, but I'll take an educated guess and say it's mp4). This codec is very efficient at reducing the file size of a video while maintaining relatively high quality.
The gif-format, on the other hand, was built for an entirely different purpose. It was actually intended for small, animated graphics with limited color palettes, not complex videos. The original gif-format is lossless, meaning it stores every frame of the animation completely. Works great for those small animated graphics, but is terrible for actual video. Actually, because of this, many apparent gifs that you see on the internet aren't actually gifs.
In conclusion: Gif is a terrible format to store or transmit video, use a video format instead. Follow the link above if you are interested in the  technical side of this.


Q:

How to validate a list of elements using jquery

here is my form which has the childrenDetails list. I am able to validate all other attributes except this list. please help
<form:form commandName="family"
    action="${pageContext.request.contextPath}/user/family" method="POST"
    id="family-form" novalidate="novalidate">

            <c:set var="marraigeStat" value="married" />
            <c:if test="${personalDetials.marriageStatus eq marraigeStat}">

                    <form:label path="spousesName">Name of Spouse</form:label>

                    <form:input path="spousesName" id="spousesName" />

                    <form:label path="spousesAge">Spouses Age</form:label>
                    <form:input path="spousesAge" id="spousesAge" />

                    <form:label path="weddingDate">Wedding Date</form:label>
                    <form:input path="weddingDate" type="date"
                            name="weddingDate" id="weddingDate" />
                    <form:errors path="weddingDate" />

            </c:if>

            <form:label path="fatherName">Father Name</form:label>
            <form:input path="fatherName" id="fatherName" />

            <form:label path="motherName">Mother Name</form:label>
            <form:input path="motherName" id="motherName" />

            <form:label path="fatherAge">Father Age</form:label>
            <form:input path="fatherAge" type="date" name="fatherAge"
                    id="fatherAge" />

            <form:label path="motherAge">Mother Age</form:label>
            <form:input path="motherAge" type="date" name="motherAge"
                    id="motherAge" />

            <c:set var="childerStat" value="true" />
            <c:if test="${personalDetials.childerStatus eq childerStat}">

child should be there

                <c:forEach items="${family.childrenDetails}" varStatus="status">

                        <form:label
                                path="childrenDetails[${status.index}].childName"> Child Name</form:label>
                        <form:input
                                path="childrenDetails[${status.index}].childName" id="childName" />

                        <form:label
                                path="childrenDetails[${status.index}].childGender">Child Gender</form:label>

                        <form:radiobutton
                                path="childrenDetails[${status.index}].childGender" value="male"
                                label="male" id="childGender" />
                        <form:radiobutton
                                path="childrenDetails[${status.index}].childGender"
                                value="female" label="female" id="childGender" />
                        <form:radiobutton
                                path="childrenDetails[${status.index}].childGender"
                                value="others" label="others" id="childGender" />
                        <form:label
                                path="childrenDetails[${status.index}].childDob">Child Date of Birth</form:label>
                        <form:input
                                path="childrenDetails[${status.index}].childDob" type="date" id="childDob"/>

                        <form:label
                                path="childrenDetails[${status.index}].childCompanyName">Child Company Name</form:label>
                        <form:input
                                path="childrenDetails[${status.index}].childCompanyName" id="childCompanyName" />

                        <form:label
                                path="childrenDetails[${status.index}].childPosition">Child Position</form:label>
                        <form:input
                                path="childrenDetails[${status.index}].childPosition" id="childPosition" />

                </c:forEach>

                    <c:if test="${familyDetails.getChildrenDetails().size()!=0 }">
                    <form:button name="submit" value="ADD">ADD</form:button>
                    <form:button name="submit" value="REMOVE">REMOVE</form:button>
                    </c:if>

            </c:if>

            <c:if test="${family.childrenDetails != null }">

CHILD DISPLAY

                    Child Name
                    childGender
                    childDob
                    childCompanyName
                    childPosition

                    <c:forEach items="${family.childrenDetails}" var="child"
                        varStatus="status">

                            ${child.childName}
                            ${child.childGender}
                            ${child.childDob}
                            ${child.childCompanyName}
                            ${child.childPosition}

                    </c:forEach>

            </c:if>

in the able code i have to this of children details where i have assigned the id for each attributes of the list.
And now with the help of this id's i am trying to validate the fields.
My validations are not working only for the childrenDetails list which is inside the family.
here is my javascript for validation
$(function() {
    $("#family-form").validate({

        rules : {
            spousesName : "required",
            spousesAge : "required",
            weddingDate : "required",
            fatherName : "required",
            motherName : "required",
            fatherAge : "required",
            motherAge : "required",
            childName : "required",
            childGender : "required",
            childDob : "required",
            childCompanyName :  "required",
            childPosition : "required"

        },
        messages : {
            spousesName : "please enter your spouses name",
            spousesAge : "Please enter the age of your spouses",
            weddingDate : "what is your wedding date",
            fatherName : "please enter your father name",
            motherName : "please enter your mother name",
            fatherAge : "please enter your father age",
            motherAge : "please enter your mothers age",
            childName : "required",
            childGender : "required",
            childDob : "required",
            childCompanyName :  "required",
            childPosition : "required"

        },
        submitHandler : function(form) {
            form.submit();
        }

    });
});
function goBack(){
    window.history.back();
}

please help. Thanks in advance

A:

There could be two reasons for the Validation not working.

Uniqueness of id  : MAIN Issue
Dynamic Element : New child details is being created by JavaScript. i.e. After ADD button new form block is generated : Might be the Issue

Case UN-uniqueness
Ok, The problem lies on the UN-uniqueness of the id in the DOM. So, The Basic principle is that id attribute should be unique on the whole rendered document.
<c:forEach items="${family.childrenDetails}" varStatus="status">

            <form:label path="childrenDetails[${status.index}].childName">Child Name</form:label>

                <form:input path="childrenDetails[${status.index}].childName" id="childName" />

                <form:label path="childrenDetails[${status.index}].childGender">Child Gender</form:label>
 //So In this block childName id will be duplicate if more than one children exists

So, Here is the example on the similar issue you are facing when id is duplicate :
JSFIDDLE DEMO 1
So, The solution would be to use class selector instead of id for the Validation. Which you can use as :
    $('#family-form').validate({
            rules : {
            spousesName : "required",
            spousesAge : "required",
            weddingDate : "required",
            fatherName : "required",
            motherName : "required",
            fatherAge : "required",
            motherAge : "required",
        },
        messages : {
            spousesName : "please enter your spouses name",
            spousesAge : "Please enter the age of your spouses",
            weddingDate : "what is your wedding date",
            fatherName : "please enter your father name",
            motherName : "please enter your mother name",
            fatherAge : "please enter your father age",
            motherAge : "please enter your mothers age",
        },
            submitHandler : function(form) {
            form.submit();
        }
        });

        $('.childNameValidation').each(function() {
            $(this).rules('add', {
                required: true,
                messages: {
                    required:  "Child Name is invalid",
                }
            });
        });

It could be hectic to define such for each and every other element though. But, It should do the job.
Needs to include : http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.0/additional-methods.js
JSFIDDLE DEMO 2
CASE Dynamic Element
Please follow this : Adding jQuery validator rules to dynamically created elements in ASP
Diffrent Appraoch for the Issue
The easiest solution for this problem might be using the data-attribute on the form element itself :
See : Declaring jQuery Validate plugin rules -- attribute vs. class vs. code
The solution mentioned above is just my intuitive guess. So, It might or mightn't solve the issue you are facing.


Q:

Proving that if $a \le -1$ then $\underset{n \to \infty}{\lim} a^n$ does not exist

I am trying to show that if $a \le -1$ then $\underset{n\to \infty}{\lim}  a_n $ where $a_n = a^n$ does not exist.
I have already ruled out the cases of negative and positive infinity.
Now supposing that such a limit does exist as a real number, let $\underset{n\to \infty}{\lim} a_n = J$ such that $|a_n - J| \le \epsilon $ for any $\epsilon > 0 $ for some $n>N$.
How can I proceed to find a contradiction?

A:

Suppose $J$ is the limit of $a^n$. Then for any $\epsilon$, we have $|a^n-J|< \epsilon$ for all $n>N$ for some $N$. Then given $\epsilon$, choose $N$ such that $|a^n-J|<\epsilon/|a|$ for $n>N$. Then $|a|\cdot|a^n-J|=|a^{n+1}-aJ|<\epsilon$ for $n>N$. Hence $\lim_{n\to\infty} a^n =J = aJ$. Then $J=aJ$, so either $J=0$, or $J=1$. Of course we know since $a\le -1$, $a1\ne 1$, so we must have $J=0$. But $|a^n| = |a|^n$ is monotonically increasing and always greater than one. Since $|\cdot|$ is continuous, if $\lim_{n\to\infty}a^n=0$, then we would have $\lim_{n\to\infty}|a^n|=|0|=0$. Contradiction.
Alternatively, and perhaps more simply if you are comfortable with the definition of a Cauchy sequence, $|a^{n+1}-a^n|=|a|\cdot|a^n-a^{n-1}|\ge |a^n-a^{n-1}|$. Hence the sequence cannot be Cauchy and cannot converge. (You do have to check that some difference is nonzero, which is why this argument works for $a=-1$, but not $a=1$.)


Q:

Accepted term for method that simply calls another method

Is there a generally accepted term for a method that does nothing more than calling another method (and returning its result)?

A:

By itself, such a function would be a wrapper function.  These are normally used to hide an ugly API or obsolete function names.
A more sophisticated object-oriented wrapper may be designed as a facade or adaptor.


Q:

Can you do a Full Install with Windows 7 Upgrade Media?

Can you do a Full Install with Windows 7 Upgrade Media?

A:

You can do a Full install if you only have the Upgrade media. Microsoft says you can't, but the following link explains otherwise.
http://www.winsupersite.com/win7/clean_install_upgrade_media.asp


Q:

C scanf in loop continues automaticly without input

I'm trying to get input in an array, I expect input like the following.
5 (Number of the second dimensions in the array)
2 (Number of the first dimensions in the array)

So we get an array deeln[2][5] in this example. I try to get it with the following code:
#include <stdio.h>
#include <string.h>
#include <stdbool.h>

bool isinarray(int val, int *arr, int size){
    int countimp;
    for (countimp=0; countimp < size; countimp++) {
        if (arr[countimp] == val)
            return true;
    }
    return false;
}

int main(void){

    int k, d, ci, cj, ck, ta;
    //get input
    scanf("%i", &k);
    scanf("%i", &d);

    int deeln[d][k], temp[k];

    for(ci = 0; ci < d; ci++){
        printf("d= %i, ci= %i \n", d, ci);
        scanf("%s", temp);
        for(cj = 0; cj < k; cj++){
            deeln[ci][cj] = temp[cj*2]-'0';
        }
    }

    //loop while.
}

But i've got a problem, whenever i try to input, the program runs automaticly without getting any  input when it loops around the third scanf for the 2nd or 3rd time. So then i'm not able to input anything.
What to do? Has it something to do with pointers or am i using scanf wrong?
UPDATE:
If I enter a printf after printf("cj is nu %i \n", cj); then the output also just came after the loop was going its own way. and not before i should give more input, using the third scanf.

A:

The solution of my question was quite easy. I found it after thinking of my input. The problem was that in the input, as described, there were spaces. Somehow scanf can't handle with spaces, unless you use some other syntax. But my solution is to just use fgets instead of scanf where I wanted to get the input. So the new and working code is as follows:
#include <stdio.h>
#include <string.h>
#include <stdbool.h>

bool isinarray(int val, int *arr, int size){
    int countimp = 0;
    for (countimp=0; countimp < size; countimp++) {
        if (arr[countimp] == val)
            return true;
    }
    return false;
}

int main(void){

    int t, k = 0, d = 0, ci = 0, cj = 0, ta = 0;

    //get input
    scanf("%i", &k);
    scanf("%i", &d);
    char temp[20];
    int deeln[d][k];

    memset(deeln, 0 , sizeof(deeln));
    memset(temp, 0 , sizeof(temp));

    for(ci = 0; ci < d; ci++){
        fgets(temp, 20, stdin);
        for(cj = 0; cj < k; cj++){
            ta = cj*2;
            deeln[ci][cj] = temp[ta]-'0';
        }
    }

    //loop while.
    return 1;
}

Thanks for helping everbody, even though we all didn't came to this. But I hope it will help others!


Q:

Struggling to update class attribute in my Django form field widgets programmatically

I'm having trouble looping through the fields I have in a form and updating the class attribute in the fields widgets. Here is my loop:
for field in form:
    try:
        field.widget.attrs['class'] += " invalid"
    except:
        pass

I cannot for the life me figure out why. I thought this would be the correct way to access the fields widgets.

A:

Try this:
for field in form:
    try:
        field.field.widget.attrs['class'] = (field.field.widget.attr.get('class') or '') + " invalid"
    except Exception as e:
        print e

The trouble with
    field.field.widget.attrs['class'] += " invalid"
is that it will throw a key error if the key class is not already present because it does something like
    field.field.widget.attrs['class'] = field.field.widget.attrs['class'] +  " invalid"