iOS Custom Gesture Recognizer works only first time

Question: I'm trying to use the checkmark gesture recognizer example in the documentation but it only works the first time I make the gesture. After recognized it, it doesn't work again.
I'm using the following code:
CheckmarkGestureRecognizer.h
#import <UIKit/UIKit.h>
#import <UIKit/UIGestureRecognizerSubclass.h>

@interface Checkmark2GestureRecognizer : UIGestureRecognizer {
    BOOL strokeUp ;
}

- (void)reset;
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event;
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event;
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event;
- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event;

@property (nonatomic,readwrite) UIGestureRecognizerState state;
@property (nonatomic,assign) CGPoint midPoint;
@end

CheckmarkGestureRecognizer.m
#import "Checkmark2GestureRecognizer.h"

@implementation Checkmark2GestureRecognizer

@synthesize state;
@synthesize midPoint;

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    [super touchesBegan:touches withEvent:event];
            NSLog(@"began");
    strokeUp = NO;
    if ([touches count] != 1) {
        self.state = UIGestureRecognizerStateFailed;
        return;
    }
}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
    [super touchesMoved:touches withEvent:event];
    if (self.state == UIGestureRecognizerStateFailed) return;
    CGPoint nowPoint = [[touches anyObject] locationInView:self.view];
    CGPoint prevPoint = [[touches anyObject] previousLocationInView:self.view];
    if (!strokeUp) {
        // on downstroke, both x and y increase in positive direction
        if (nowPoint.x >= prevPoint.x && nowPoint.y >= prevPoint.y) {
            self.midPoint = nowPoint;
            // upstroke has increasing x value but decreasing y value
        } else if (nowPoint.x >= prevPoint.x && nowPoint.y <= prevPoint.y) {
            strokeUp = YES;
        } else {
            self.state = UIGestureRecognizerStateFailed;
        }
    }
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    [super touchesEnded:touches withEvent:event];
    if ((self.state == UIGestureRecognizerStatePossible) && strokeUp) {
        self.state = UIGestureRecognizerStateRecognized;
            NSLog(@"Ended");
    }

}

- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event {
    [super touchesCancelled:touches withEvent:event];
    self.midPoint = CGPointZero;
    strokeUp = NO;
    self.state = UIGestureRecognizerStateFailed;
    NSLog(@"cancelled");
}

- (void)reset {
    [super reset];
    NSLog(@"reset");
    self.midPoint = CGPointZero;
    strokeUp = NO;
}

@end

Any idea about what am I doing wrong?
Thanks
Answer: I've got similar problem with own gesture recognizer. Seems UIGestureRecognizer doesn't call "reset" method of your class, and doesn't set "state" property to UIGestureRecognizerStatePossible.
I know two ways to make it work:

You can set state property to UIGestureRecognizerStatePossible by yourself in your touchesEnded method. But it seems wrong.
You can use state property of UIGestureRecognizer instead of your own state. I.e. use super.state instead of self.state everywhere.
Answer: Check out this code. It works fine with me.
https://github.com/shahidnasrullah/CustomZGestureIOS.git
Answer: Try removing the @synthesize state; line in your implementation. This is already done in the super class.
You also don't have to copy all the definitions from UIGestureRecognizerSubclass.h into you header file. Best is to remove the as well.


Do homomorphisms preserve order of subgroups?

Question: I read that the only possible homomorphism from $\mathbb{Z}_7$ to $\mathbb{Z}_{12}$ is the one mapping all elements of $\mathbb{Z}_7$ to $\{0\}$. Since if there is another homomorphism from $\mathbb{Z}_7$ to $\mathbb{Z}_{12}$, it must be able to map any non-trivial subgroup of $\mathbb{Z}_7$, to a subgroup of $\mathbb{Z}_{12}$. However, this means that $\mathbb{Z}_{12}$ would have a subgroup of order $7$, which is impossible.
I guess what is implied in the above statement is that homomorphisms preserve the order of subgroups ... but is this true in general ?
Comment: No, in general if $\phi : G \to G'$ is a homomorphism and $H$ is a subgroup of $G$, then $|\phi(H)|$ is a divisor of $|H|$ but need not equal $|H|$. This follows, for example, from the [first isomorphism theorem](https://mathworld.wolfram.com/FirstGroupIsomorphismTheorem.html)
Comment: More generally, see [this post](https://math.stackexchange.com/questions/766523/examples-of-properties-not-preserved-under-homomorphism) on "properties nor preserved under homomorphisms".
Comment: Indeed, $|\phi(H)|=[H:H\cap\ker\phi]$, so $\left.\phi\right|_H$ is $1$-to-$1$ iff $H\cap\ker\phi$ is trivial.
Answer: It is not true in general. Let  $f: \mathbb Z_6 \to \mathbb Z_6$ given by $f(x)=2x$. The map $f$ is clearly a homomorphism but it does not preserve the order of the group itself.
I think this statement means, since only subgroups of $\mathbb Z_7$ are $\{0\}$ and the group itself, kernel of any non-trivial homomorphism is $\{0\}$ and so any non-trivial homomorphism is injective. This means $\mathbb Z_7$ is isomorphic to image of itself but this cannot happen since image of a homomorphism is a subgroup of $\mathbb Z_{12}$ and this group does not have a subgroup of order $7$.


VSCode rename php classname and filename and also all of it's references

Question: I have a project which has a class called Match, but it is now a reserved keyword in php8,
So I tried changing it with Matche, but there are just too many files that uses this class,
how do I, in vscode, also update all of its references to Matche ?
Comment: Does this answer your question? [How to change all occurrences of variable name in Visual Studio Code for PHP?](https://stackoverflow.com/questions/37523793/how-to-change-all-occurrences-of-variable-name-in-visual-studio-code-for-php)
Answer: Sadly VSCode still doesn't have any built-in feature like this for PHP. Your only option is to use some extension that provides such feature, though there aren't many extensions that can do this and the ones that do have it are paid.
I was looking for something like this too for quite some time and couldn't find anything reliable for so long. Finally today I found what I was looking for in another question (thank you Adi Candra!):
PHP Refactor Tool extension by Son Tung PHAM. Note
Install the PHP Refactor Tool extension and just click on the thing you want to rename and press F2. Type in the new name and voila! It automatically renames all references in all the relevant files and also renames the file itself if renaming a class or another "top-level file construct".

Note: You need to have the PHP Intelephense extension installed for it to work.
Comment: Can I "move" an entire namespace?


Change URL to meaningful name when I use hyperlink target

Question: Scenario:
Book

When I click book, it will scroll down to the block and url will be www.example.com/#block-block-1. Is there anyway to change url to something meaningful like www.example.com/#book?
I've tried suggestions from How to give meaningful id names to blocks?, but it is not really what I want.
Answer: The Block Attributes module will let you add a meaningful id attribute to any Drupal block.

The Block Attributes module allows users to specify additional HTML
  attributes for blocks, through the block's configuration interface,
  such as class, id, style, title and more.


Deeper understanding about how Realm works?

Question: Q1 : Please let me know what is different between two ways of implementation in below (about get realm instance). I want to know which one is faster, lighter in memory and what is recommended ?
1. Set and Get Realm as Default (with specific config)
private void setupCustomRealm() {
        if (!Utils.isStringHasText(databaseName)) {
            databaseName = DbManager.getInstance().getCurrentDb();
        }
        // get config
        RealmConfiguration config = getRealmConfigByDBName(databaseName);
        Realm.setDefaultConfiguration(config);
        Realm.compactRealm(config);

    }

public Realm getCustomRealm() {
      if (firstTime) {
             setupCustomRealm();
      }
      return Realm.getDefaultInstance();
}

2 .Get Realm from config directly
public Realm getCustomRealm(Context context) {
        if (!Utils.isStringHasText(databaseName)) {
            databaseName = DbManager.getInstance().getCurrentDb();
        }
        // get config
        RealmConfiguration config = getRealmConfigByDBName(context, databaseName);
        Realm.compactRealm(config);
        return Realm.getInstance(config);
    }

Q2 :  In my application, now we are consider between 2 ways of implementation.
1: We create a new Realm instance every time when we need to do something with Database (in both of worker thread and UI thread) and close it when task get done.
2: We create only one instance of Realm and let it live along with application, when quit application we close instance above.
Please explain me the advantage and disadvantage of each one and which ways is recommended (My application using Service to handle database and network connection)
If I have 2 heavy tasks (take a long time to complete it's transaction), what is difference between execute 2 task by one Realm instance and execute 2 task on 2 Realm instances in 2 separate thread (I mean one thread have one Realm instances and instance will executes one in 2 tasks above), and which one if safer and faster.
what will happen if there is a problem while executing a transaction (example not responding or throws some exception)
Comment: I will answer this when I'm done with lunch (reply hook comment)
Comment: Great! I'm waiting for your answer!
Comment: I'm also linking the SO Realm docs because they're neat, I kept some of it up to date and stuff: http://stackoverflow.com/documentation/android/3187/realm#t=201608011053013386746
Answer: Note: I am not an official Realm person, but I've been using Realm for a while now.
Here's a TL;DR version

1.) It's worth noting a few things:

A given Realm file should be accessed only with the same RealmConfiguration throughout the application, so the first solution here is preferable (don't create a new config for each Realm).
Realm.compactRealm(RealmConfig) works only when there are no open Realm instances on any threads. So either at application start, or at application finish (personally I found that it makes start-up slower, so I call compactRealm() when my activity count reaches 0, which I manage with a retained fragment bound to the activity - but that's just me).

2.) It's worth noting that Realm.getInstance() on first call creates a thread-local cache (the cache is shared among Realm instances that belong to the same thread, and increments a counter to indicate how many Realm instances are open on that given thread. When that counter reaches 0 as a result of calling realm.close() on all instances, the cache is cleared.
It's also worth noting that the Realm instance is thread-confined, so you will need to open a new Realm on any thread where you use it. This means that if you're using it in an IntentService, you'll need to open a new Realm (because it's in a background thread).
It is extremely important to call realm.close() on Realm instances that are opened on background threads.
Realm realm = null;
try {
    realm = Realm.getDefaultInstance();
    //do database operations
} finally {
    if(realm != null) {
        realm.close();
    }
}

Or API 19+:
try(Realm realm = Realm.getDefaultInstance()) {
    //do database operations
}

When you call realm.close() on a particular Realm instance, it invalidates the results and objects that belong to it. So it makes sense both to open/close Realms in Activity onCreate() and onDestroy(), or open it within the Application and share the same UI thread Realm instance for queries on the UI thread.
(It's not as important to close the Realm instance on the UI thread unless you intend to compact it after all of them are closed, but you have to close Realm instances on background threads.)

Note: calling RealmConfiguration realmConfig = new RealmConfiguration.Builder(appContext).build() can fail on some devices if you call it in Application.onCreate(), because getFilesDir() can return null, so it's better to initialize your RealmConfiguration only after the first activity has started.
With all that in mind, the answer to 2) is:

While I personally create a single instance of Realm for the UI thread, you'll still need to open (and close!) a new Realm instance for any background threads.
I use a single instance of Realm for the UI thread because it's easier to inject that way, and also because executeTransactionAsync()'s RealmAsyncTask gets cancelled if the underlying Realm instance is closed while it's still executing, so I didn't really want that to happen. :)
Don't forget, that you need a Realm instance on the UI thread to show RealmResults<T> from realm queries (unless you intend to use copyFromRealm() which makes everything use more memory and is generally slower)
IntentService works like a normal background thread, so you should also close the realm instance there as well.

Both heavy tasks work whether it's the same Realm instance or the other (just make sure you have a Realm instance on that given thread), but I'd recommend executing these tasks serially, one after the other.
If there's an exception during the transaction, you should call realm.cancelTransaction() (the docs say begin/commit, but it always forgets about cancel).
If you don't want to manually manage begin/commit/cancel, you should use realm.executeTransaction(new Realm.Transaction() { ... });, because it automatically calls begin/commit/cancel for you. Personally I use executeTransaction() everywhere because it's convenient.
Comment: I've also given a shorter and more concise answer on [Github Realm-Java issues](https://github.com/realm/realm-java/issues/3229#issuecomment-236552238)
Comment: do you know what kind of exception will be thrown when we try to compact realm while other instance still were not closed ?
Comment: If I recall correctly, it doesn't throw an exception, it just returns false. It must be noted that encrypted Realms cannot be compacted. The `compactRealm()` call seems to consume any exception, and the message can be seen if you add a `RealmLog.add(new Logger() {...});` somewhere in your code.
Comment: @EpicPandaForce Realm backend is based on LMDB? Is it open source like forntends?
Comment: @Maniero define which part of Realm you mean as "realm backend"
Comment: @EpicPandaForce C++ part. Code which is handling IO (mmap) and internal data structures.
Comment: @Maniero ah you can check that out in the Realm Core https://github.com/realm/realm-core


3 time loop in present like html table?

Question: I have an array:
$A  = array(
         'A'=>
           array('a1'=>array(1,2,3),
                 'a2'=>array(1,2,3),
                 'a3'=>array(1,2,3)),
         'B' =>
            array('b1'=>array(1,2,3),
                  'b2'=>array(1,2,3),
                  'b3'=>array(1,2,3)),
         'C');

How Can I use loop to present data (html table ):
-----------------------------
|    | time1|  time1 | time2 |
----------------------------
A    | 3    |   6   |   8
-----------------------------
 a1  | 1    |   2   |  2
-----------------------------
 a2  | 1    |   2   |  3
-----------------------------
 a3  | 1    |   2   | 3
----------------------------
B
 b1
 b2
 b3
C

I am trying( get the total && display C instead 0):
echo '
';
  echo "
	time1	time2	time3
";
 foreach ($A as $key=>$main){
    echo '
';
      echo "$key	";
      echo "???	";
      echo "???	";
      echo "???	";
    echo '
';

  foreach ($main as $k=>$sub) {
    echo '
';
        echo "$k	";

            foreach ($sub as $kk =>$val) {
                echo "$val	";
            }
     echo '
';
      }

  }
  echo '
';

Answer: <?php

$A  = array(
         'A'=>
           array('a1'=>array(1,2,2),
                 'a2'=>array(1,2,3),
                 'a3'=>array(1,2,3)),
         'B' =>
            array('b1'=>array(1,2,3),
                  'b2'=>array(1,2,3),
                  'b3'=>array(1,2,3)),
         'C'=> null);   // in your case it won't be key it will be value

echo '
';
echo "
	time1	time2	time3
";

foreach($A as $key => $value)
{
   echo "
".$key."	";
   if(!is_array($value))
     continue;

   echo "".implode("	", findSum($value))."
";
   foreach($value as $cKey => $cValue){
      echo "
".$cKey."	";
      echo "".implode("	", $cValue)."	";
   }
   echo "\n";
}

function findSum($value)
{
   if(!is_array($value))
      return array(0);

   $result = array();
   foreach($value as $childValue)
   {
      foreach($childValue as $cKey => $cValue)
          $result[$cKey] = isset($result[$cKey]) ? $result[$cKey] + $cValue : $cValue;
   }
   return $result;
}

Comment: yes,thanks.your approach is using 2 times loop: first loop for display(html) and second for findSum.For me I did not know the better ways than this.

3 time loop in present like html table?


Struct function returns incomplete type

Question: In header.h I have:
typedef struct {
    int score;
    int dice[6];
    int scorecard[2][7];
} player;

Then in definitions.c I have:
struct player do_turn(struct player user) {
    for (int i = 0; i < 6; i++) {
        int die = roll_die();
        user.dice[i] = die;
    }
    return (user);
}

On the function definition I get the error "function do_turn returns incomplete type struct player"
What am i doing wrong?
Comment: `struct player do_turn(struct player user)` -> `player do_turn(player user)` That's what a `typedef` is for.
Comment: in your code you typedef'd the struct as player so you cannot use struct player as datatype name instead you should use player as the struct datatype name. More broader answer you aliased your struct name as player.
Answer: This struct can (only) be accessed as struct player:
struct player {
    int score;
    int dice[6];
    int scorecard[2][7];
};

struct player do_turn(struct player user) { ... }

This struct can (only) be accessed as just player:
typedef struct {
    int score;
    int dice[6];
    int scorecard[2][7];
} player;

player do_turn(player user) { ... }

And this one can be accessed as either player or struct player:
typedef struct player {
    int score;
    int dice[6];
    int scorecard[2][7];
} player;

struct player do_turn(player user) { /* don't actually mix them like this :-P */ }

Depending on how you'd like this to look, change your struct definition, your function definition, or both, to make them match.
Answer: Let's deconstruct the definition of player.
This is the type:
struct {
    int score;
    int dice[6];
    int scorecard[2][7];
}

It is an anonymous struct. While it is correct, an anonymous struct is not very useful because is definition cannot be reused, it has to be typed again when needed.
Let's add the name:
struct {
    int score;
    int dice[6];
    int scorecard[2][7];
} player

Maybe you think player is the name of the struct but this is not true. The type is the same as before (an anonymous struct), player is a variable of this type.
How to name the struct?
Adding a name to the anonymous struct described above is easy: put the name immediately after the struct keyword (before the open curly bracket):
struct _player {
    int score;
    int dice[6];
    int scorecard[2][7];
} player;

player is still a variable but its type now is not anonymous any more. Its type is struct _player (not just _player). The keyword struct is part of the name.
What happens when we put typedef in front?
typedef struct _player {
    int score;
    int dice[6];
    int scorecard[2][7];
} player;

The keyword typedef turns player into a type name (remember it is a variable in the absence of typedef). In the declaration above there is no variable. What it declares are the struct _player type and player that is a different name of struct _player (an alias).
There is no definition of struct player above as there is none in the code you posted. The compiler finds references to struct player and, apart from the information that it is a struct, it doesn't know anything about it. Consequently it displays the error you mentioned.

Struct function returns incomplete type


Are there official rules for touch rugby?

Question: Touch rugby is a sport widely played in New Zealand and Australia, similar to rugby league except the main difference is that the person with the ball is touched instead of tackled.
To the best of my knowledge (mine, and Google's), there is no official rules for touch rugby, or even a touch rugby federation or similar.
This is a big problem in games at school, where technical points get brought up and no-one knows how to handle this.
Are there official rules for touch rugby? If so, where can I find them and who were they made by?
Answer: The official rules for Touch Football, a rugby league derivative, are available from the "Rules and Policies" section of the Touch Football Australia website. As of February 2016, the 7th Edition of the Rules ("reprinted 2007") is current.
However, the document explicitly encourage competitions to vary the rules under which the game is played; from the Foreword:

There is no compulsion for any affiliate of the [Australian Touch Association] to follow these Rules at their local or park level competitions. In fact the ATA encourages Affiliates to set varying features in the rules of their competition so that the player can experience a wide variety of enjoyment from the game.

but they may still give you a basis on which to form your competition's rule set.


$ \int^{\infty}_0 |\frac{1}{(1+x)\sqrt x}|^p ~ \mathrm dx < \infty \implies p=?$

Question: If $ f(x) = \frac{1}{(1+x)\sqrt x} $ how to find all $ p > 0 $ such that
$$ \int^{\infty}_0 |f(x)|^p dx < \infty $$
The integral is with respect to lebesgue measure. Any solution or hints would be helpful. The answer is the integral converges iff $ p\in (\frac{2}{3}, 2) $.
Answer: At $+\infty$, you have
$$
|f(x)|^p\sim \frac{1}{x^{3p/2}}
$$
which converges if and only if $3p/2>1$.
At $0$,
$$
|f(x)|^p\sim\frac{1}{x^{p/2}}
$$
which converges if and only if $p/2<1$.
So your integral converges if and only if
$$
\frac{2}{3}<p<2.
$$
Comment: Thanks. I think the following estimates solve the problem.
Comment: Yes. All you need to know is that $\int_0^11/x^\alpha dx$ converges if and only if $\alpha<1$, and $\int_1^{+\infty}1/x^\beta dx$ converges if and only if $\beta>1$. For a proof, simply compute the integrals.
Comment: Neat solution! I've worked it out for myself and it's a cool problem.
Answer: Hint: Since
$$\int_0^{\infty} f(x)^p dx =\int_0^1 f(x)^p dx+\int_1^{\infty} f(x)^p dx$$
So if $0<p<1$, we can only consider the integral $\int_1^{\infty} f(x)^p dx$, and
$$\int_1^{\infty} f(x)^p dx < \int_1^\infty \left(\frac{1}{x\sqrt{x}}\right)^p dx$$
And
$$\int_1^\infty f(x)^p dx > \int_1^\infty \frac{1}{(1+x)^{3p/2}} dx .$$
Comment: The integral from $0$ to $1$ is also not always bounded for all $p$, I have the answer as if $ p \in (\frac{2}{3},2) $ only then integral is finite, but all of it is not exactly clear from these estimates. A little elaboration would be appreciated.
Answer: Using the change of variables $ z=\frac{1}{1+x} $ and the beta function
$$ \beta(x,y) = \int_{0}^{1}t^{x-1}(1-t)^{y-1}dt,\quad Re(x),\,Re(y)>0, $$
we have
$$ \int_{0}^{\infty} \frac {1}{(1+x)^p x^{\frac{p}{2}}} dx = \int _{0}^{1}\! \left( 1-z \right) ^{-\frac{p}{2}}{z}^{\frac{3p}{2}-2}{dz}.$$
Comparing with the existence conditions for the beta function implies that
$$ 1-\frac{p}{2}>0,\quad\frac{3p}{2}-1 > 0. $$
Solving the two inequalities gives the desired result.
Comment: So you find $p<0$ and $4/30$ and $ \frac{3p}{2}-1>0 $. I already mentioned comparing with the existence conditions for the beta function.


How do I find a future date in PHP, only a few days later?

Question: My date() format is m-d-Y and I want to find a future date, say five days from now.
For instance, if my $todays_date is equal to 04-28-2018, I want $future_date to be equal to 05-03-2018 (five days later). Thanks!
Comment: Possible duplicate of [Set time offset in php](https://stackoverflow.com/questions/8083153/set-time-offset-in-php)
Comment: try `(new DateTime())->modify('+5 days')`
Answer: Procedural you can use strtotime(), and date()
But I prefer using PHP's built in DateTime class
  $Date = new DateTime();
  $Date->modify('+5 days');
  echo $Date->format('Y-m-d');

Outputs
 2018-05-03

You can test it online here
This is based of using what is called relative date formats,  you can read all about it in the PHP manual
Using strtotime
echo date('Y-m-d', strtotime('+5 days'));

Chained version of Datetime
echo (new DateTime())->modify('+5 days')->format('Y-m-d');

Both give the same result as the first one, but are only one line.
Answer: You can use strtotime() see below code.
$date = date("Y-m-d");
$date = date("Y-m-d", strtotime("$date +5 Days"));
$date = date("d-m-Y", strtotime($date));
echo $date;

Hope this help you.
Good Luck.


Aggregation in MongoDB with Array of objects

Question: I have the following mongoDB document -
<code>{
    "_id" : ObjectId("5e71a1f3081c4b70cdbc438f"),
    "DataSetID" : ObjectId("5e71a1f3081c4b70cdbc438e"),
    "row" : [
        {
            "key" : "Region",
            "prev" : "root",
            "value" : "Australia and Oceania",
            "typeOfValue" : "string",
            "currentDepth" : 1
        },
        {
            "key" : "Country",
            "prev" : "root",
            "value" : "Tuvalu",
            "typeOfValue" : "string",
            "currentDepth" : 1
        },
        {
            "key" : "Item Type",
            "prev" : "root",
            "value" : "Baby Food",
            "typeOfValue" : "string",
            "currentDepth" : 1
        },
        {
            "key" : "Sales Channel",
            "prev" : "root",
            "value" : "Offline",
            "typeOfValue" : "string",
            "currentDepth" : 1
        },
        {
            "key" : "Order Priority",
            "prev" : "root",
            "value" : "H",
            "typeOfValue" : "string",
            "currentDepth" : 1
        },
        {
            "key" : "Order Date",
            "prev" : "root",
            "value" : ISODate("2010-05-27T18:30:00.000Z"),
            "typeOfValue" : "date",
            "currentDepth" : 1
        },
        {
            "key" : "Order ID",
            "prev" : "root",
            "value" : 669165933,
            "typeOfValue" : "number",
            "currentDepth" : 1
        },
        {
            "key" : "Ship Date",
            "prev" : "root",
            "value" : ISODate("2010-06-26T18:30:00.000Z"),
            "typeOfValue" : "date",
            "currentDepth" : 1
        },
        {
            "key" : "Units Sold",
            "prev" : "root",
            "value" : 9925,
            "typeOfValue" : "number",
            "currentDepth" : 1
        },
        {
            "key" : "Unit Price",
            "prev" : "root",
            "value" : 255.28,
            "typeOfValue" : "number",
            "currentDepth" : 1
        },
        {
            "key" : "Unit Cost",
            "prev" : "root",
            "value" : 159.42,
            "typeOfValue" : "number",
            "currentDepth" : 1
        },
        {
            "key" : "Total Revenue",
            "prev" : "root",
            "value" : 2533654,
            "typeOfValue" : "number",
            "currentDepth" : 1
        },
        {
            "key" : "Total Cost",
            "prev" : "root",
            "value" : 1582243.5,
            "typeOfValue" : "number",
            "currentDepth" : 1
        },
        {
            "key" : "Total Profit",
            "prev" : "root",
            "value" : 951410.5,
            "typeOfValue" : "number",
            "currentDepth" : 1
        }
    ]
}
</code>
Lets say we have 100's of document like these.
I want to make an aggregation query which groups by lets say values of key == 'Country' i.e. Tuvalu , India , etc and give me sum of values of key == 'Total Profit' for each country.
In other words give me sum of values where key == 'Total Profit' while grouping on values of key == 'Country'.
The data structure can be changed given that what I've in input is unstructured JSON data and I don't know the keys beforehand that is why I came up of json arrays.
In the end Result I want something like this :
<code>[
{
_id : 'Tuvalu',
value : 100
},
{
_id : 'India',
value : 160
}
]
</code>
How can we achieve this ?
Answer: Try below query, it has optional stage for better optimization, You can exclude upon need/choice :
<code>db.collection.aggregate([
  /** Optional match stage but can reduce data set size for further stages
   * (Get docs where rows array has an object with a key field & value 'Country') */
  { $match: { "row.key": "Country" } },
  /** Using project to retain only needed fields which reduce size of doc,
   * Convert row array into row object {country : ..., totalProfit : ... } */
  {
    $project: {
      _id: 0,
      row: {
        /** Iterate on row's, So '$$this' is each object & '$$value' is values in initialValue */
        $reduce: {
          input: "$row",
          initialValue: {
            country: "",
            totalProfit: 0
          },
          in: {
            country: {
             /** If current object key is Country then push value from current object to 'country' in initialValue
              * otherwise return existing 'country' value to 'country' every time */
              $cond: [
                { $eq: ["$$this.key", "Country"] },
                "$$this.value",
                "$$value.country"
              ]
            },
            totalProfit: {
              $cond: [
                { $eq: ["$$this.key", "Total Profit"] },
                "$$this.value",
                "$$value.totalProfit"
              ]
            }
          }
        }
      }
    }
  },
  /** group on country field & sumup values of totalProfit */
  {
    $group: { _id: "$row.country", value: { $sum: "$row.totalProfit" } }
  }
]);
</code>
Test : MongoDB-Playground
Comment: It works.Thanks brother , I've been scratching my brains out since I don't know when.
Also what to do you think about the data structure ?
Do you any suggestions other than this ?
Comment: @SiddhantShah : Unfortunately, I couldn't suggest much about your data structure with knowing completely about your application & data transactions but check this : https://docs.mongodb.com/manual/core/data-modeling-introduction/ , A quick read of it can certainly help you on this..
Comment: In brief , I've to store any type of JSON data which can be 'n' level nested in a form where its easily query able and I can run aggregation queries on it.
I won't be knowing the keys of the JSON object beforehand , so I need a uniform way to store the data.
Comment: @SiddhantShah : I you've to do that then your option is as what you're doing now put it in an array, but keep in mind that try to keep your array size as low as possible cause querying on array fields or creating index on array can be like exploding your one single document into multiple docs :-)
Comment: array size would be equal to the no. of fields.I don't see how I can limit it if the user sends a big JSON data.
Also I've got an index on dataSetID and all queries will first get all matching documents in memory using dataSetID and then query ahead.


JVM crashes after migrating to 64bit

Question: My application started crashing after we migrate it to 64bit. The crash is occuring every 2-3 days on our production linux server. We are using jdk1.6.0_15-x86_64. The crash is happening at the same place when my application uses the Xalan transformer to convert XSLT to HTML.
I have confirmed that this is not happening on our 32bit server and not happening when the application doesn't perform the XSLT to HTML convertion. So it happens only when convertion happens on 64bit server.
Any help will be highly appreciated.
Here is the content from the dump file
<code>    ######################################
    # A fatal error has been detected by the Java Runtime Environment:
    #
    #  SIGSEGV (0xb) at pc=0x00002b288a0457d1, pid=9161, tid=1213643072
    #
    # JRE version: 6.0_15-b03
    # Java VM: Java HotSpot(TM) 64-Bit Server VM (14.1-b02 mixed mode linux-amd64 )
    # Problematic frame:
    # V  [libjvm.so+0x3837d1]
    #
    # If you would like to submit a bug report, please visit:
    #   http://java.sun.com/webapps/bugreport/crash.jsp
    #

    ---------------  T H R E A D  ---------------

    Current thread (0x0000000044267800):  JavaThread "[default]-careers_ente_com-/resume_list_intermediate.html-126.96.36.199-B8FF993FA76C999A3568847142ECA47C.JS1-Thread-57504" daemon [_thread_in_vm, id=18390, stack(0x000000004846b000,0x000000004856c000)]

    siginfo:si_signo=SIGSEGV: si_errno=0, si_code=128 (), si_addr=0x0000000000000000

    Registers:
    RAX=0x0000000000000001, RBX=0x002f840f1fb10f4c, RCX=0x0000000000000000, RDX=0x0000000000000001
    RSP=0x0000000048569d50, RBP=0x0000000048569d70, RSI=0x0000000000000000, RDI=0x0000000043d7c830
    R8 =0x0000000000000001, R9 =0x00002aaab073f9d8, R10=0x00002b288a582c2a, R11=0x0000000044269a98
    R12=0x00002aaab07431c8, R13=0x0000000000000008, R14=0x0000000044267800, R15=0x0000000048569dd0
    RIP=0x00002b288a0457d1, EFL=0x0000000000010202, CSGSFS=0x0000000000000033, ERR=0x0000000000000000
      TRAPNO=0x000000000000000d

    Stack: [0x000000004846b000,0x000000004856c000],  sp=0x0000000048569d50,  free space=1019k
    Native frames: (J=compiled Java code, j=interpreted, Vv=VM code, C=native code)
    V  [libjvm.so+0x3837d1]
    V  [libjvm.so+0x3a2f72]
    j  com.sun.org.apache.xalan.internal.xsltc.runtime.AbstractTranslet.addParameter(Ljava/lang/String;Ljava/lang/Object;Z)Ljava/lang/Object;+8
    j  hrxmlresume2html.topLevel(Lcom/sun/org/apache/xalan/internal/xsltc/DOM;Lcom/sun/org/apache/xml/internal/dtm/DTMAxisIterator;Lcom/sun/org/apache/xml/internal/serializer/SerializationHandler;)V+218
    j  hrxmlresume2html.transform(Lcom/sun/org/apache/xalan/internal/xsltc/DOM;Lcom/sun/org/apache/xml/internal/dtm/DTMAxisIterator;Lcom/sun/org/apache/xml/internal/serializer/SerializationHandler;)V+24
    j  com.sun.org.apache.xalan.internal.xsltc.runtime.AbstractTranslet.transform(Lcom/sun/org/apache/xalan/internal/xsltc/DOM;Lcom/sun/org/apache/xml/internal/serializer/SerializationHandler;)V+9
    j  com.sun.org.apache.xalan.internal.xsltc.trax.TransformerImpl.transform(Ljavax/xml/transform/Source;Lcom/sun/org/apache/xml/internal/serializer/SerializationHandler;Ljava/lang/String;)V+152
    j  com.sun.org.apache.xalan.internal.xsltc.trax.TransformerImpl.transform(Ljavax/xml/transform/Source;Ljavax/xml/transform/Result;)V+119
    j  com.ente.hrxml.resume.HtmlConverter.toHtml(Lorg/jdom/Document;)Ljava/lang/String;+49
    j  com.ente.er.form.hrxmledit.generateHtmlResumeBuilder(Lcom/ente/erom/candidate/Candidate;Ljava/lang/String;)Ljava/lang/String;+42
    j  com.ente.er.form.hrxmledit.save()Lcom/ente/services/webui/UIStatus;+574
    j  com.ente.er.form.hrxmledit.postprocess()Lcom/ente/services/webui/UIStatus;+202

    Java frames: (J=compiled Java code, j=interpreted, Vv=VM code)
    j  com.sun.org.apache.xalan.internal.xsltc.runtime.AbstractTranslet.addParameter(Ljava/lang/String;Ljava/lang/Object;Z)Ljava/lang/Object;+8
    j  hrxmlresume2html.topLevel(Lcom/sun/org/apache/xalan/internal/xsltc/DOM;Lcom/sun/org/apache/xml/internal/dtm/DTMAxisIterator;Lcom/sun/org/apache/xml/internal/serializer/SerializationHandler;)V+218
    j  hrxmlresume2html.transform(Lcom/sun/org/apache/xalan/internal/xsltc/DOM;Lcom/sun/org/apache/xml/internal/dtm/DTMAxisIterator;Lcom/sun/org/apache/xml/internal/serializer/SerializationHandler;)V+24
    j  com.sun.org.apache.xalan.internal.xsltc.runtime.AbstractTranslet.transform(Lcom/sun/org/apache/xalan/internal/xsltc/DOM;Lcom/sun/org/apache/xml/internal/serializer/SerializationHandler;)V+9
    j  com.sun.org.apache.xalan.internal.xsltc.trax.TransformerImpl.transform(Ljavax/xml/transform/Source;Lcom/sun/org/apache/xml/internal/serializer/SerializationHandler;Ljava/lang/String;)V+152
    j  com.sun.org.apache.xalan.internal.xsltc.trax.TransformerImpl.transform(Ljavax/xml/transform/Source;Ljavax/xml/transform/Result;)V+119
    j  com.ente.hrxml.resume.HtmlConverter.toHtml(Lorg/jdom/Document;)Ljava/lang/String;+49
    j  com.ente.er.form.hrxmledit.generateHtmlResumeBuilder(Lcom/ente/erom/candidate/Candidate;Ljava/lang/String;)Ljava/lang/String;+42
    j  com.ente.er.form.hrxmledit.save()Lcom/ente/services/webui/UIStatus;+574
    j  com.ente.er.form.hrxmledit.postprocess()Lcom/ente/services/webui/UIStatus;+202
    J  com.ente.services.webui.Form.process()Lcom/ente/services/webui/UIStatus;
    j  com.ente.er.form.hrxmledit.process()Lcom/ente/services/webui/UIStatus;+1
    J  com.ente.services.webui.Form.eval(Lcom/ente/services/webui/Request;)V
    j  com.ente.services.webui.Nav.evalForm()V+232
    j  com.ente.services.webui.Nav.initPage()Lcom/ente/services/webui/Nav;+151
    j  com.ente.er.ERecruiter.getER(Ljavax/servlet/http/HttpServletRequest;Ljavax/servlet/http/HttpServletResponse;Z)Lcom/ente/er/ERecruiter;+353
    j  com.ente.er.ERecruiter.getER(Ljavax/servlet/http/HttpServletRequest;Ljavax/servlet/http/HttpServletResponse;)Lcom/ente/er/ERecruiter;+3
    j  jsp__careers_2eente_2ecom_80___resume_list_intermediate_2ehtml._jspService(Ljavax/servlet/http/HttpServletRequest;Ljavax/servlet/http/HttpServletResponse;)V+114
    j  org.gjt.jsp.HttpJspPageImpl.service(Ljavax/servlet/http/HttpServletRequest;Ljavax/servlet/http/HttpServletResponse;)V+3
    j  javax.servlet.http.HttpServlet.service(Ljavax/servlet/ServletRequest;Ljavax/servlet/ServletResponse;)V+29
    j  org.gjt.jsp.JspServlet$Page.process(Ljavax/servlet/http/HttpServletRequest;Ljavax/servlet/http/HttpServletResponse;)V+937
    j  org.gjt.jsp.JspServlet.xservice(Ljavax/servlet/http/HttpServletRequest;Ljavax/servlet/http/HttpServletResponse;Ljava/lang/String;)V+39
    j  org.gjt.jsp.JspServlet.service(Ljavax/servlet/http/HttpServletRequest;Ljavax/servlet/http/HttpServletResponse;)V+162
    j  javax.servlet.http.HttpServlet.service(Ljavax/servlet/ServletRequest;Ljavax/servlet/ServletResponse;)V+29
    j  org.apache.jserv.JServConnection.processRequest()V+627
    j  org.apache.jserv.JServConnection.run()V+80
    j  java.lang.Thread.run()V+11
    v  ~StubRoutines::call_stub

    Java Threads: ( => current thread )
    =>0x0000000044267800 JavaThread "[default]-careers_ente_com-/resume_list_intermediate.html-126.96.36.199-B8FF993FA76C999A3568847142ECA47C.JS1-Thread-57504" daemon [_thread_in_vm, id=18390, stack(0x000000004846b000,0x000000004856c000)]
      0x00000000447a1800 JavaThread "3C758A73EA22FCDE9E41A2149C9E8F43.JS1-Thread-54838" daemon [_thread_blocked, id=14006, stack(0x000000004836a000,0x000000004846b000)]
      0x00000000446a5000 JavaThread "220.127.116.11-3C758A73EA22FCDE9E41A2149C9E8F43.JS1-Thread-54742" daemon [_thread_in_native, id=13872, stack(0x000000004745b000,0x000000004755c000)]
      0x000000004400a800 JavaThread "TaskManager-IdleThread" daemon [_thread_blocked, id=20114, stack(0x0000000047057000,0x0000000047158000)]
      0x0000000044a8a800 JavaThread "TaskManager-IdleThread" daemon [_thread_blocked, id=9567, stack(0x0000000046d54000,0x0000000046e55000)]
      0x000000004479a800 JavaThread "TaskManager-IdleThread" daemon [_thread_blocked, id=9566, stack(0x0000000046c53000,0x0000000046d54000)]
      0x0000000044b2d800 JavaThread "TaskManager-IdleThread" daemon [_thread_blocked, id=9565, stack(0x0000000046b52000,0x0000000046c53000)]
      0x0000000043f6b800 JavaThread "TaskManager-IdleThread" daemon [_thread_blocked, id=9564, stack(0x00000000439a4000,0x0000000043aa5000)]
      0x0000000044214000 JavaThread "TaskManager-IdleThread" daemon [_thread_blocked, id=9327, stack(0x0000000043ba6000,0x0000000043ca7000)]
      0x0000000044018000 JavaThread "TaskManager-IdleThread" daemon [_thread_blocked, id=9326, stack(0x0000000043aa5000,0x0000000043ba6000)]
      0x00000000441bc800 JavaThread "TaskManager-IdleThread" daemon [_thread_blocked, id=9324, stack(0x0000000042893000,0x0000000042994000)]
      0x0000000044a89000 JavaThread "TaskManager-IdleThread" daemon [_thread_blocked, id=9323, stack(0x0000000040ec5000,0x0000000040fc6000)]
      0x0000000044923800 JavaThread "internal_careers_ente_com-Timer-Timer-13" daemon [_thread_blocked, id=9318, stack(0x00000000438a3000,0x00000000439a4000)]
      0x0000000045643800 JavaThread "ImportAgent-Timer-Timer-12" daemon [_thread_blocked, id=9317, stack(0x00000000437a2000,0x00000000438a3000)]
      0x00000000461e9000 JavaThread "internal_careers_ente_com-Retry-Timer-Timer-11" daemon [_thread_blocked, id=9316, stack(0x00000000436a1000,0x00000000437a2000)]
      0x000000004466a800 JavaThread "XPostDirector-Timer-Timer-10" daemon [_thread_blocked, id=9315, stack(0x00000000435a0000,0x00000000436a1000)]
      0x0000000044667800 JavaThread "internal_careers_ente_com-EventInformant1554828645.1" daemon [_thread_blocked, id=9314, stack(0x000000004349f000,0x00000000435a0000)]
      0x0000000044798800 JavaThread "internal_careers_ente_com-EventInformant1554828645.2" daemon [_thread_blocked, id=9313, stack(0x000000004339e000,0x000000004349f000)]
      0x0000000044797800 JavaThread "internal_careers_ente_com-EventInformant1554828645.3" daemon [_thread_blocked, id=9312, stack(0x000000004329d000,0x000000004339e000)]
      0x0000000043ff1000 JavaThread "internal_careers_ente_com-EventInformant1554828645.4" daemon [_thread_blocked, id=9311, stack(0x000000004319c000,0x000000004329d000)]
      0x0000000044795000 JavaThread "careers_ente_com-Retry-Timer-Timer-9" daemon [_thread_blocked, id=9310, stack(0x000000004309b000,0x000000004319c000)]
      0x0000000044792800 JavaThread "careers_ente_com-EventInformant190296991.1" daemon [_thread_blocked, id=9309, stack(0x0000000042f9a000,0x000000004309b000)]
      0x0000000046233800 JavaThread "careers_ente_com-EventInformant190296991.2" daemon [_thread_blocked, id=9308, stack(0x0000000042e99000,0x0000000042f9a000)]
      0x0000000046231800 JavaThread "careers_ente_com-EventInformant190296991.3" daemon [_thread_blocked, id=9307, stack(0x0000000042d98000,0x0000000042e99000)]
      0x0000000046231000 JavaThread "careers_ente_com-EventInformant190296991.4" daemon [_thread_blocked, id=9306, stack(0x0000000042c97000,0x0000000042d98000)]
      0x0000000044c0c000 JavaThread "LDAPConnThread ldap5.ente.com:389" daemon [_thread_in_native, id=9305, stack(0x0000000042b96000,0x0000000042c97000)]
      0x0000000044c0a000 JavaThread "LDAPConnThread ldap5.ente.com:389" daemon [_thread_in_native, id=9304, stack(0x0000000042a95000,0x0000000042b96000)]
      0x0000000044c0d800 JavaThread "LDAPConnThread ldap4.ente.com:389" daemon [_thread_in_native, id=9303, stack(0x0000000042994000,0x0000000042a95000)]
      0x0000000044c07800 JavaThread "LDAPConnThread ldap4.ente.com:389" daemon [_thread_in_native, id=9301, stack(0x0000000042691000,0x0000000042792000)]
      0x000000004597d000 JavaThread "LDAPConnThread ldap4.ente.com:389" daemon [_thread_in_native, id=9300, stack(0x0000000041723000,0x0000000041824000)]
      0x000000004404e000 JavaThread "OracleTimeoutPollingThread" daemon [_thread_blocked, id=9226, stack(0x0000000042792000,0x0000000042893000)]
      0x00002aab10677000 JavaThread "careers_ente_com-Timer-Timer-8" daemon [_thread_blocked, id=9224, stack(0x0000000042590000,0x0000000042691000)]
      0x00002aab1059a000 JavaThread "SessionReaper-Timer-7" daemon [_thread_blocked, id=9223, stack(0x000000004248f000,0x0000000042590000)]
      0x00002aab11230000 JavaThread "DebugListener-1234-Thread-16" daemon [_thread_in_native, id=9222, stack(0x000000004238e000,0x000000004248f000)]
      0x00002aab10628800 JavaThread "ImportAgent-Timer-Timer-6" daemon [_thread_blocked, id=9221, stack(0x00000000419ae000,0x0000000041aaf000)]
      0x00002aab106b0800 JavaThread "careers_ente_com-Retry-Timer-Timer-5" daemon [_thread_blocked, id=9219, stack(0x000000004020b000,0x000000004030c000)]
      0x00002aab104c9800 JavaThread "XPostDirector-Timer-Timer-4" daemon [_thread_blocked, id=9218, stack(0x00000000405c3000,0x00000000406c4000)]
      0x00002aab1056c000 JavaThread "careers_ente_com-EventInformant74291610.1" daemon [_thread_blocked, id=9216, stack(0x000000004228d000,0x000000004238e000)]
      0x00002aab1053e000 JavaThread "careers_ente_com-EventInformant74291610.2" daemon [_thread_blocked, id=9215, stack(0x000000004218c000,0x000000004228d000)]
      0x00002aab1048a800 JavaThread "careers_ente_com-EventInformant74291610.3" daemon [_thread_blocked, id=9214, stack(0x0000000041cd6000,0x0000000041dd7000)]
      0x00002aab104e9000 JavaThread "careers_ente_com-EventInformant74291610.4" daemon [_thread_blocked, id=9213, stack(0x00000000408ef000,0x00000000409f0000)]
      0x00002aab1021d800 JavaThread "CacheReporter-Timer-2" [_thread_blocked, id=9212, stack(0x000000004208b000,0x000000004218c000)]
      0x00002aab1000f800 JavaThread "StatsReporter-Timer-1" daemon [_thread_blocked, id=9211, stack(0x0000000041f8a000,0x000000004208b000)]
      0x00002aab10025800 JavaThread "LDAPConnThread ldap5.ente.com:389" daemon [_thread_in_native, id=9210, stack(0x0000000041e89000,0x0000000041f8a000)]
      0x000000004406d800 JavaThread "LDAPConnThread ldap5.ente.com:389" daemon [_thread_in_native, id=9209, stack(0x0000000041622000,0x0000000041723000)]
      0x000000004401e000 JavaThread "Periodic Collector-Timer-0" [_thread_blocked, id=9208, stack(0x00000000418ad000,0x00000000419ae000)]
      0x00002aab10003000 JavaThread "Thread-0" daemon [_thread_blocked, id=9186, stack(0x0000000040a6f000,0x0000000040b70000)]
      0x0000000043e0d000 JavaThread "Low Memory Detector" daemon [_thread_blocked, id=9184, stack(0x0000000041ad4000,0x0000000041bd5000)]
      0x0000000043e0a000 JavaThread "CompilerThread1" daemon [_thread_blocked, id=9183, stack(0x0000000041380000,0x0000000041481000)]
      0x0000000043e05800 JavaThread "CompilerThread0" daemon [_thread_blocked, id=9182, stack(0x0000000040753000,0x0000000040854000)]
      0x0000000043e03800 JavaThread "Signal Dispatcher" daemon [_thread_blocked, id=9181, stack(0x000000004010a000,0x000000004020b000)]
      0x0000000043ddf800 JavaThread "Finalizer" daemon [_thread_blocked, id=9180, stack(0x00000000414fe000,0x00000000415ff000)]
      0x0000000043dde000 JavaThread "Reference Handler" daemon [_thread_blocked, id=9179, stack(0x000000004127f000,0x0000000041380000)]
      0x0000000043d7f000 JavaThread "main" [_thread_in_native, id=9173, stack(0x000000004107d000,0x000000004117e000)]

    Other Threads:
      0x0000000043dd7000 VMThread [stack: 0x00000000403e4000,0x00000000404e5000] [id=9178]
      0x0000000043e0f000 WatcherThread [stack: 0x0000000041bd5000,0x0000000041cd6000] [id=9185]

    VM state:not at safepoint (normal execution)

    VM Mutex/Monitor currently owned by a thread:  ([mutex/lock_event])
    [0x0000000043d7c830] OsrList_lock - owner thread: 0x0000000044267800

    Heap
     PSYoungGen      total 471680K, used 20796K [0x00002aaaed940000, 0x00002aab0abe0000, 0x00002aab0abe0000)
      eden space 465664K, 4% used [0x00002aaaed940000,0x00002aaaeed8f0a8,0x00002aab0a000000)
      from space 6016K, 0% used [0x00002aab0a000000,0x00002aab0a000000,0x00002aab0a5e0000)
      to   space 5760K, 0% used [0x00002aab0a640000,0x00002aab0a640000,0x00002aab0abe0000)
     PSOldGen        total 955776K, used 110793K [0x00002aaab33e0000, 0x00002aaaed940000, 0x00002aaaed940000)
      object space 955776K, 11% used [0x00002aaab33e0000,0x00002aaaba012550,0x00002aaaed940000)
     PSPermGen       total 43072K, used 42828K [0x00002aaaadfe0000, 0x00002aaab09f0000, 0x00002aaab33e0000)
      object space 43072K, 99% used [0x00002aaaadfe0000,0x00002aaab09b32f8,0x00002aaab09f0000)

    VM Arguments:
    jvm_args: -Xms1400m -Xmx1400m -Djava.protocol.handler.pkgs=com.sun.net.ssl.internal.www.protocol -Dsecurity.provider.1=com.sun.net.ssl.internal.ssl.Provider -Der.logfile=var/log/e-Recruiter.log -Dsun.net.inetaddr.ttl=7200 -DHTMLDOCPATH=/usr/bin/htmldoc -Doracle.jdbc.V8Compatible=true -Dldap.enable=true -Dldap.path=ldap://recruiter:firstname.lastname@example.com:389,ldap5.ente.com:389,ldap6.ente.com:389/er-10.15.0.2
    java_command: org.apache.jserv.JServ etc/jserv.properties
    Launcher Type: SUN_STANDARD

    Environment Variables:
    JAVA_HOME=
    PATH=/sbin:/usr/sbin:/bin:/usr/bin
    USERNAME=root
    LD_LIBRARY_PATH=/usr/local/ente-20080222/Sun/jdk1.6.0_15-x86_64/jre/lib/amd64/server:/usr/local/ente-20080222/Sun/jdk1.6.0_15-x86_64/jre/lib/amd64:/usr/local/ente-20080222/Sun/jdk1.6.0_15-x86_64/jre/../lib/amd64:/usr/local/ente/Oracle/client/lib
    SHELL=/bin/bash
    _JAVA_SR_SIGNUM=12

    Signal Handlers:
    SIGSEGV: [libjvm.so+0x6bdd00], sa_mask[0]=0x7ffbfeff, sa_flags=0x10000004
    SIGBUS: [libjvm.so+0x6bdd00], sa_mask[0]=0x7ffbfeff, sa_flags=0x10000004
    SIGFPE: [libjvm.so+0x594ed0], sa_mask[0]=0x7ffbfeff, sa_flags=0x10000004
    SIGPIPE: [libjvm.so+0x594ed0], sa_mask[0]=0x7ffbfeff, sa_flags=0x10000004
    SIGXFSZ: [libjvm.so+0x594ed0], sa_mask[0]=0x7ffbfeff, sa_flags=0x10000004
    SIGILL: [libjvm.so+0x594ed0], sa_mask[0]=0x7ffbfeff, sa_flags=0x10000004
    SIGUSR1: SIG_DFL, sa_mask[0]=0x00000000, sa_flags=0x00000000
    SIGUSR2: [libjvm.so+0x597690], sa_mask[0]=0x00000000, sa_flags=0x10000004
    SIGHUP: [libjvm.so+0x5973e0], sa_mask[0]=0x7ffbfeff, sa_flags=0x10000004
    SIGINT: SIG_IGN, sa_mask[0]=0x00000000, sa_flags=0x00000000
    SIGTERM: [libjvm.so+0x5973e0], sa_mask[0]=0x7ffbfeff, sa_flags=0x10000004
    SIGQUIT: [libjvm.so+0x5973e0], sa_mask[0]=0x7ffbfeff, sa_flags=0x10000004

    ---------------  S Y S T E M  ---------------

    OS:CentOS release 5.4 (Final)

    uname:Linux 2.6.18-164.15.1.el5 #1 SMP Wed Mar 17 11:30:06 EDT 2010 x86_64
    libc:glibc 2.5 NPTL 2.5
    rlimit: STACK 10240k, CORE 0k, NPROC infinity, NOFILE 1024, AS infinity
    load average:0.00 0.00 0.00

    CPU:total 2 (1 cores per cpu, 1 threads per core) family 6 model 26 stepping 4, cmov, cx8, fxsr, mmx, sse, sse2, sse3, ssse3, sse4.1, sse4.2

    Memory: 4k page, physical 4044572k(274688k free), swap 2031608k(2031532k free)

    vm_info: Java HotSpot(TM) 64-Bit Server VM (14.1-b02) for linux-amd64 JRE (1.6.0_15-b03), built on Jul  2 2009 15:26:16 by "java_re" with gcc 3.2.2 (SuSE Linux)

    time: Sun Aug 12 21:34:09 2012
    elapsed time: 162182 seconds
</code>
Comment: Update 15 is very old and lots of bugs have been fixed since then, I would try Java 6 update 35 or Java 7 update 7. http://www.oracle.com/technetwork/java/javase/releasenotes-136954.html
Comment: do you use the same memory settings for both the 32bit and 64bit jvms?  be aware that the same code running in a 64bit jvm will use a fair bit more memory due to the change in reference(pointer) sizes.
Comment: In 32bit version our application used to configure using -Xms800m -Xmx800m and now in 64bit verion it has been increased to -Xms1400m -Xmx1400m
Answer: <code> PSPermGen       total 43072K, used 42828K [0x00002aaaadfe0000, 0x00002aaab09f0000, 0x00002aaab33e0000)
      object space 43072K, 99% used [0x00002aaaadfe0000,0x00002aaab09b32f8,0x00002aaab09f0000)
</code>
It seems your permgen is being corrupted which could be due to the fact that your code trying to load libraries. I suspect the libraries being loaded by following code may not be compatible with 64 bit JVM.
Before filing a bug with JVM, I would  check in program following lines of code, which seems culprit.
<code>  com.ente.hrxml.resume.HtmlConverter.toHtml(Lorg/jdom/Document;)Ljava/lang/String;+49
</code>
Comment: I would suggest add XX:+UseCodeCacheFlushin also
Comment: Is there a way to find whether the libraries are compatible with 64bit JVM?
Comment: May be check the version of libraries and go to their website and see release notes.
Comment: @jtahlborn: though I agree with your statement, this is not issue with heap, this is issue with Permgen.
Comment: @jtahlborn/Nambari - checked the permgen size when the application doesn't crash, it always shows 99% but the total and used is lower than 40M. So I believe the 40M is only allocated total and it is not the maximum permgen. Thoughts? –
Answer: I'd suggest increasing the perm gen space (-XX:MaxPermSize) and enabling GC on it (-XX:+CMSPermGenSweepingEnabled) -- 40M isn't much!  If you are loading a lot of libraries, I'd also suggest enabling class unloading (-XX:+CMSClassUnloadingEnabled).  Note that if you really do have a memory leak, this will only give you more breathing room between crashes, you still need to fix the underlying cause.
Comment: I checked the permgen size when the application doesn't crash, it always shows 99% but the total and used is lower than 40M. So I believe the 40M is only allocated total and it is not the maximum permgen. Thoughts?

JVM crashes after migrating to 64bit


How to show the variance of local polynomial regression increases with degree

Question: Assume the data follows  $y_i=f(x_i)+\varepsilon_i$, $\varepsilon_i$ are iid and have zero expectation with variance $\sigma^2$.
The local polynomial regression is
$$
{\min_{\alpha(x_0),\beta_j(x_0),j=1,\cdots,d}}{\sum\limits_{i=1}^{N}}{K_\lambda}({x_0},x_i)\left[y_i-\alpha({x_0})-{\sum\limits_{j=1}^{d}}\beta_j({x_0})x_i^j\right]^2
$$
The solution is
\begin{eqnarray*}
\hat{f}(x)&=&\hat{\alpha}(x_0)+\sum\limits_{j=1}^{d}\beta_j(x_0)x_0^j \\
&=& b(x_0)^T(B^TW(x_0)B)^{-1}B^TW(x_0)y \\
&=& \sum_{i=1}^{N}l_i(x_0)y_i
\end{eqnarray*}
where $b(x)^T=(1 \, x \, x^2 \, \cdots \, x^d)^T$, $B$ is a $N \times (d+1)$ matrix with $i$th row $b(x_i)^T$ and $W(x_0)$ is a $N \times N$ diagonal matrix with $i$th diagonal element  ${K_\lambda}({x_0},x_i)$. ${K_\lambda}({x_0},x_i)$ is a kernel function.
It's easy to see $Var[\hat{f}(x_0)]=\sigma^2\|l(x_0)\|^2$, my question is how to show $\|l(x_0)\|$ increases with $d$.
Comment: Some coclusions may help. $\sum_{i=1}^{N}l_i(x_0)=1$, $\sum_{i=1}^{N}l_i(x_0)(x_i-x_0)^k=0, k=1 \, ,\cdots, \, d$,
Answer: I'll try to expand on the answer by @tankeco. For simplicity, we consider unweighted least squares regression, i.e., with weights $W=I$. Also, I believe the conclusion below works for a general least squares regression, so not restricted to a polynomial least squares regression.
Suppose we have an $N\times d$ design matrix $X_d$, an $N$-vector response $y$, and we fit $\hat{\beta}_d$ using least squares. The variance of the predicted value $\hat{f}_d(x_0)$ at an arbitrary $x_0\in\mathbb{R}^d$ is $\text{var}(\hat{f}_d(x_0))=x_0^T(X_d^TX_d)^{-1}x_0$ (assuming WLOG $\sigma^2=1$). Now we add an additional predictor $x_{d+1}\in\mathbb{R}^N$, so we have an augmented $N\times(d+1)$ design matrix $X=[X_d,x_{d+1}]$. We fit $\hat{\beta}$ using least squares again, and the variance of the predicted value $\hat{f}(x_0')$ at $x_0'=(x_0^T,w)\in\mathbb{R}^{d+1}$ is $\text{var}(\hat{f}(x_0'))=x_0'^T(X^TX)^{-1}x_0'$. The question is, how to show that $\text{var}(\hat{f}(x_0'))\geq\text{var}(\hat{f}_d(x_0))$, so that the variance increases with more predictors. Since $\text{var}(\hat{f}(x_0))=\|l(x_0)\|^2$, we see that $\|l(x_0)\|^2$ increases with the dimension $d$.
First, we look at the two optimization problems
$$\min_{\beta}(y-X_d\beta)^T(y-X_d\beta)\text{ and }\min_{\beta}(y-X\beta)^T(y-X\beta).$$
Setting $\beta_{d+1}=0$ in the latter, we recover the former problem, so the latter in a sense includes the former, and hence the optimized value is smaller. (This is $L_{d+1}\leq L_d$ in @tankeco's answer.) In equations,
$$(y-X_d\hat{\beta}_d)^T(y-X_d\hat{\beta}_d)\geq(y-X\hat{\beta})^T(y-X\hat{\beta}).$$
Now using $X\hat{\beta}=Hy$, where $H=X(X^TX)^{-1}X^T$ and similarly for $H_d$, we see that
$$y^T(I-H_d)^T(I-H_d)y\geq y^T(I-H)^T(I-H)y.$$
As a projection matrix, $H$ is idempotent, and so is $I-H$, and hence
$$y^T(I-H_d)y\geq y^T(I-H)y.$$
Equivalently,
$$y^TH_dy\leq y^THy.$$
If you're familiar with the geometry of least squares projections, then another way to view this is through the identity
$$\|y\|^2=\|\hat{y}\|^2+\|y-\hat{y}\|^2.$$
With more predictors, $\|y-\hat{y}\|^2$ gets smaller (as the residual sum of squares), so $\|\hat{y}\|^2$ gets larger. Now expressing $H_d$ and $H$ using $X$, we have
$$y^TX_d(X_d^TX_d)^{-1}X_d^Ty\leq y^TX(X^TX)^{-1}X^Ty.$$
Recall that we wish to show, for an arbitrary $x_0'=(x_0^T,w)\in\mathbb{R}^{d+1}$, that $\text{var}(\hat{f}(x_0'))\geq\text{var}(\hat{f}_d(x_0))$, or equivalently,
$$x_0'^T(X^TX)^{-1}x_0'\geq x_0^T(X_d^TX_d)^{-1}x_0.$$
It's important to note that the inequality above involving $y$ works for any $y\in\mathbb{R}^N$, and also that $X$ is assumed to be of full rank (with $d+1\leq N$). This means that for any $x_0'\in\mathbb{R}^{d+1}$, there exists a $y\in\mathbb{R}^N$ such that $x_0'=X^Ty$. Now substitute this $y$ in and the proof is complete.
I believe the weighted case is similar using the arguments above.
Answer: \begin{eqnarray*}
&&min \sum_{i=1}^{N}K_{\lambda}(x_0,x_i)\left[y_i-\alpha(x_0)-\sum_{j=1}^{d}\beta_j(x_0)x_i^j\right]^2 \\
&=&min (Y-B\theta)^TW(x_0)(Y-B\theta)=L_d
\end{eqnarray*}
where $Y=[y_1\,\,y_2\,\,\cdots\,\,y_N], \quad\theta=[\alpha(x_0)\,\,\beta_1(x_0)\,\,\beta_2(x_0)\,\,\cdots\,\,\beta_d(x_0)]^T$
Using the fact that $L_{d+1}\le L_{d}$, it's easy to prove.


Difference between the respondent's cholesterol level and maximum blood pressure. Is this a paired t-test?

Question: This is probably an easy question, but wanted to confirm before I start doing the analysis for my intro stats course...
So a question I have to answer is as below:

Test the difference between the respondent's cholesterol level and
maximum blood pressure. If so, write the difference.

As I understand paired/dependent t-test are for the same subject, however most of the time they are the same measure (ie. before/after). However the two variables I have been given are totally different (continuous) measures... Is this still a paired t-test?
Data example
Comment: If you have a table of data, there may be a column with the differences explicitly written making it paired.
Comment: Unfortunately there is not. I have added a picture of the data I was given
Answer: A paired t-test is used when the difference between the two variables is specific to the subject/sample-point. More specifically, we use it when we expect there to be some correlation between the variables that is subject specific. When the two variables are totally independent we use a two sample t-test.
So if your question said something like: 'Is the average cholesterol level and maximum blood pressure significantly different in this population?' And if your data from cholesterol level and blood pressure came from two different random samples, then I would say a non-paired test.
However, your question specifically said "the respondents" which tells me you have one sample with two variables.  You know both the cholesterol level and blood pressure level for a single respondent.  Furthermore, this is health data related to the heart, there is likely a correlation within respondents.
Comment: OK, so regardless if they are totally different measures/means we are comparing to, it is a paired t-test if it is the same subject?
Comment: It typically is if you have the same subject.  There are also instances when they are different subjects but it still a paired t-test (matched pairs).


Erro ao retornar dados do array JS

Question: Preciso atribuir os atributos ao objeto de forma relativa, sem saber quantos parâmetros irão vir, dessa forma não está retornando resultados, existe outro método?
<code>    var menu = document.getElementById("funcaoMenu").value;

    res = menu.split(","); //divide os resultados pela "," e cria um array

    oi = new Object(); // instância um novo objeto

    for (var i = 0; i < res.length; i++) {
        oi.i = res[i]; // recebe os dados do array e alterna a chave
    };
</code>
os dados que recebo são parâmetros em string, exemplo: "menu","rodapé","ola".
e preciso executar esses dados em um parâmetro em php para usar a função e func_num_args e func_get_args.
Comment: Podes dar um exemplo dos dados que recebes e do formato que queres obter?
Answer: Creio que você deva fazer a atribuição assim:
<code>oi[i] = res[i];
</code>

Erro ao retornar dados do array JS


php calling parent function makes parent unable to load own vars

Question: I have a Handler class that looks like this:
class Handler{
    public $group;

    public function __construct(){
        $this->group = $this->database->mysql_fetch_data("blabla query");
        //if i print_r($this->group) here it gives proper result

        new ChildClass();
    }

    public function userGroup(){
        print_r($this->group); //this is empty
                    return $this->group;
    }
}

class ChildClass extends Handler{

    public function __construct(){
        $this->userGroup();
        //i tried this too
        parent::userGroup();
        //userGroup from parent always returns empty
    }

}

Workflow:

Handler is called from my index.php and the __construct is called
Handler needs to create $group
Handler creates child class
Child class calls Handler function
When I try to return $group in the function It tries to get $this->group from Child instead of Handler

Whenever I try to ask the parent something I can only access the parent function then inside the function the parent class can't find any of it's own variables
EDIT:
I figured using 'extends' would be useful in calling parent functions but it seems just passing $this on to the child will be easier.
Answer: You never called the parent constructor, so the group object is never initialized. You will want to do something like this.
class Handler{
    public $group;

    public function __construct(){
        $this->group = $this->database->mysql_fetch_data("blabla query");
        //if i print_r($this->group) here it gives proper result

        new ChildClass();
    }

    public function userGroup(){
        print_r($this->group); //this is empty
                    return $this->group;
    }
}

class ChildClass extends Handler{

    public function __construct(){
        parent::__construct();
        $this->userGroup();
    }

}

If you had not overwritten the __construct method in your extended class, then the parent __construct would have automatically been called, but since you overwrote it in the extended class, you must tell it to call the parent's __construct in your extended class' __construct.
Comment: Or maybe he wants `public $group` to be static and not actually have two different objects. :p
Comment: @Basti either way, he has to do the above, and since he didn't mention what you are talking about, I'm not sure why you bring it up.
Comment: If i do this the parent calls on the child again and there is a endless loop
Comment: @Basti If i make it static it says Notice: Undefined property: ChildClass::$group
Comment: I'm bringing it up as an extension to your answer. No harm done.
Comment: @Makura You need to make some more changes if you want `$group` to be static. You are also missing some initialisation statements like `new Handler()`. It's not clear what you are trying to do just from your class definition.
Comment: Edited post, New Handler() is done in index, i asumed you would expect handler to be called since i stated that inside handler construct $this->group is filled
Comment: @dqhendricks I have looked though php.net extends page but could not find a solution, and i use the handler class to call many difrent classes depending on what page i'm on. and i find it usefull to be able to use functions of the Handler class everywhere, If there is a other solution to achieve that it would work too.
Comment: @MakuraYami oy. you may want to read up on Agile development, Single Responsibility Principle, Dependency Injection, Composition over Inheritance.


cordova push plugin MismatchSenderId when send with php

Question: I install cordova and add the latest offiical push plugin v2x.
I use phonegap desktop app to run the cordova project
and I successfully get the registration token from phonegap developer android app.
I can send with window cmd command, the developer app can receive the push message, but when I send with php, it shows the error bellow?
<code>{"multicast_id":7703228532457629637,"success":0,"failure":1,"canonical_ids":0,"results":[{"error":"MismatchSenderId"}]}
</code>
I test with firebase console too, can't received too
Please help I am newbies in cordova
Answer: now is can, cannot use the phonegap developer app to receive notice from eg php post, maybe this developer app can receive via cmd only
must use emulator or real apk and can receive it


Inverse covariance matrix vs covariance matrix in PCA

Question: In PCA, does it make a difference if we pick principal components of the inverse covariance matrix OR if we drop eigenvectors of the covariance matrix corresponding to large eigenvalues?
This is related to the discussion in in this post.
Answer: Observe that for positive definite covariance matrix $\mathbf \Sigma = \mathbf{UDU}'$ the precision is $\boldsymbol \Sigma^{-1} = \mathbf {U D}^{-1} \mathbf U'$.
So the eigenvectors stay the same, but the eigenvalues of the precision are the reciprocals of the eigenvalues of the covariance. That means the biggest eigenvalues of the covariance will be the smallest eigenvalues of the precision.  As you have the inverse, positive definiteness guarantees all eigenvalues are greater than zero.
Hence if you retain the eigenvectors relating to the $k$ smallest eigenvalues of the precision this corresponds to ordinary PCA. Since we have already taken reciprocals ($\bf D^{-1}$), only the square root of the precision eigenvalues should be used in order to complete the whitening of the transformed data.
Comment: +1 but I think your "So yes, it makes a difference" sentence might be confusing for the OP; the Q is not very clear but I think they were asking whether there is a difference between selecting largest eigenvalues of inv cov matrix and selecting smallest eigenvalues ( = dropping the largest ones) of the cov matrix. To this question the answer is that **it is equivalent.** So perhaps if you simply cut out this sentence, the answer will be clearer.
Comment: Thanks, I see what you mean and have edited accordingly.
Comment: Actually the last sentence was good, I would have kept it!
Comment: @conjectures Thank you, that's the perfect explanation.
Answer: In addition, the inverse covariance matrix is proportionnal to the partial correlation between the vectors:
<code>Corr(Xi, Xj | (Xothers )
</code>
Correlation between Xi and Xj when all others are fixed, it is very useful for time series.
Comment: This is true, but what does that have to do with PCA?


How do I pass a DynamoDB table address and Redis port and address to my EC2 instance in CloudFormation?

Question: I have a system that requires an EC2 instance that has connections to a DynamoDB table and a Redis instance.  How do I set those up as options for my EC2 instance in CloudFormation using YAML?
I've created OptionSettings to set the values as environmental variable for my process on the EC2 instance. I know that I need to do !Ref [something here], but the documentation did not have examples that made sense to me.
Here's a simplified version of the code:
---
AWSTemplateFormatVersion: "2010-09-09"

Description: CloudFormation template

Resources:
  # Beanstalk application
  MyApp:
    Type: AWS::ElasticBeanstalk::Application
  ConfigurationTemplate:
    Type: AWS::ElasticBeanstalk::ConfigurationTemplate
    Properties:
      ApplicationName: !Ref MyApp
      OptionSettings:
      - Namespace: "aws:elasticbeanstalk:application:environment"
        OptionName: REDIS_CACHE_PORT
        Value: !Ref AttributeCache.Port # Should be 6379
      - Namespace: "aws:elasticbeanstalk:application:environment"
        OptionName: REDIS_CACHE_ADDRESS
        Value: !Ref MyCache. # Something that AWS creates
      - Namespace: "aws:elasticbeanstalk:application:environment"
        OptionName: DYNAMODB_TABLE_ADDRESS
        Value: !Ref MyDynamoTable. # Something that AWS creates
      SolutionStackName: 64bit Amazon Linux 2018.03 v4.8.1 running Node.js

  # Redis cache
  MyCache:
    Type: AWS::ElastiCache::CacheCluster
    Properties:
      ClusterName: MyCacheCluster
      Engine: redis
      EngineVersion: 4.0.10
      NumCacheNodes: 1
      Port: 6379

  # DynamoDB table
  MyDynamoTable:
    Type: "AWS::DynamoDB::Table"
    Properties:
      AttributeDefinitions:
      - AttributeName: theAttributeName
        AttributeType: S
      KeySchema:
      - AttributeName: theAttributeName
        KeyType: HASH
      TableName: myDynamoTable

I am unsure of how to access something that CloudFormation will create.
Is !Ref correct, or do I need the !GetAtt instead?
Here are the links to the two different function docs.
https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-ref.html
https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-getatt.html
Even just pointing me at the thing that I'm missing would be of help.
Answer: This kind of information is specified under Return Values section in the documentation for every service. This doc section also provides information whether you have to use !Ref or !GetAtt in order to retrieve certain parameter. For example CacheCluster docs say that you have to use !GetAtt MyCache.RedisEndpoint.Port to get redis' port and Dynamo docs say that you have to use !Ref MyDynamoTable to get table name.
      OptionSettings:
      - Namespace: "aws:elasticbeanstalk:application:environment"
        OptionName: REDIS_CACHE_PORT
        Value: !GetAtt MyCache.RedisEndpoint.Port
      - Namespace: "aws:elasticbeanstalk:application:environment"
        OptionName: REDIS_CACHE_ADDRESS
        Value: !GetAtt MyCache.RedisEndpoint.Address
      - Namespace: "aws:elasticbeanstalk:application:environment"
        OptionName: DYNAMODB_TABLE_ADDRESS
        Value: !Ref MyDynamoTable # You got this one right, but no dot in the end


Configuracoes ambiente timezones django postgres linux

Question: Bom dia a todos.
Tenho um site (Django) em um serviço de hospedagem linux com banco Postgre SQL que fica em Nova Jersey (EUA).
Os usuários estão no Brasil, portanto tenho uma diferença de timezone.
Tenho certeza que isso é algo bem bobo, com um ajuste resolvo tudo, mas estou confuso porque as mudanças e testes que fiz deram resultados incorretos.
Primeiro vou postar as configurações dos ambientes.
Servidor Linux (USA):
$cat /etc/timezone
Etc/UTC

Postgres Console (USA):
postgres=# show timezone;
UTC

Django settings.py (USA):
TIME_ZONE = 'America/Sao_Paulo'
USE_TZ = True

Mas agora vamos aos resultados.
Aqui no Brasil são:

10:07h

Lá no servidor Linux(USA):

12:07:52 UTC

Aqui pra mim já tá errado, lá não são 3 horas e diferença, 2 horas com horário de verão?
No POSTGRES:
select now();
2018-01-16 12:07:36.967415+00

Tenho um Modelo chamado COLETA que tem um campo que é chama-se DATA_LEITURA.
data_leitura = models.DateTimeField(null=True)

Então acabei de inserir um registro nessa tabela com o horário 10:07:16h.
Eu crio o datetime que atribuo ao modelo COLETA.data_leitura é esse:
br_tz = timezone('America/Sao_Paulo')
coleta.data_leitura = datetime(2018, 01, 16, 10, 07, 16, tzinfo=br_tz)

Acessei o console do linux (NJ) no postgres e dei um select:
SELECT data_leitura FROM coleta;
2018-01-16 15:13:16+00

O Valor exibido na página web para o cliente aqui no Brasil é:

15:13:16

Antes não tinha a linha br_tz = timezone('America/Sao_Paulo')
Então aparecia uma mensagem de NAIVE DATETIME e o horário também estava errado!
Estou experimentando mudar cada configuração e sempre dá mais errado ainda, isso quer dizer que há 2 fatores errados aí para se corrigir.
É minha primeira experiência nisso com estes ambientes e frameworks.
O que devo mudar? sugestões?
Obrigado desde já pela ajuda da comunidade!
Answer: Você pode configurar uma variável de ambiente chamada TIMEZONE, que informa ao banco de dados a região na qual o cliente conectado ao servidor, isso faz com que o servidor saiba converter as horas de forma adequada:
SET TIMEZONE = 'America/Sao_Paulo';
SELECT NOW();

Comment: Mudei no /etc/postgresql/9.5/main/postgresql.conf o valor para timezone="America/Sao_Paulo", e o horário apareceu mais errado ainda, agora que são 12:23 lá no banco está sendo gravado e exibido como 17:23h (5 horas diferença), isso quer dizer que essa configuração possa estar correta, mas algum outra está prejudicando o valor dessa.
Tentei mudar pra New_York também para ver como funciona e deixar UTC. Todas retornam valores errados!
Comment: Vc está mudando a configuração de timezone do servidor. Você precisa alterar a configuração do seu cliente.
Comment: O cliente abre uma página django(html) que mostra os dados trazidos direto do Coleta.filter(), não faço nenhum comando sobre essa mudança. Eu simplesmente lá no template/html coloquei {{coleta.data_leitura}}, como eu faria essa configuração? Pensei que o TIME_ZONE do django já faria isso sozinho, sempre que ele exibir, será o horário do BR. Até porque não terei usuários lá nos EUA, apenas o server está lá.
Comment: Pelo que percebi o problema está na INSERÇÃO dos dados, pois o SELECT que dou no postgres já mostra que o insert gravou a data já errada (converteu sozinho).
Comment: Se por acaso o dado *já foi inserido no banco de dados* usando o timezone incorreto, mudar as configurações do cliente e/ou servidor vai piorar o problema. Antes de mais nada, você deve corrigir os dados que foram gravados com o timezone incorreto.


My vuejs code is infinite looping while in the production

Question:        <template>

{{ year }}

Volume {{ index }} Issue {{ issue }}

{{ cYear }} | Volume {{ cVolume }} - Issue {{ cIssue }}

{{ paper.paper_title }}

Author: {{ paper.paper_author }}

Article Type: {{ paper.paper_articletype }}

Pages: {{ paper.paper_pages }}

                  Paper Details
                  Download PDF
                  Google

{{ paperDetails.paper_title }}

                    Download PDF

Author(s) : {{ paperDetails.paper_author }}

Submission-Year,Month :
                 {{ paperDetails.year }}, {{paperDetails.month }}
 ` <
      !--
 --> <
      !--
 -->
      <
      p class = "pb-3" >  Pages: {{ paperDetails.paper_pages }}

          <
          !--
 --> <
          !--
 -->
          <
          p class = "pb-3" >  Article Type: {{ paperDetails.paper_articletype }}

          <
          !--
 --> <
          !--
 -->
          <
          p class = "pb-3" >  DOI: {{ paperDetails.paper_doi }}

          <
          !--
 --> <
          /div> <
          /div>  <
          div class = "row p-3 paperBox" >
          <
          h4 class = "mb-2" > Abstract
 <
          p class = "abstract-details" > {
              {
                  paperDetails.paper_abstract
              }
          } <
          /p> <
          /div> <
          /div> <
          /div> <
          /div> <
          /div>

          <
          /section> <
          /template>

          <
          script >
          export default {
              data: function () {
                  return {
                      archives: {},
                      years: [],
                      papersList: [],
                      listVisible: false,
                      paperPage: false,
                      cYear: "",
                      cVolume: "",
                      cIssue: "",
                      paperDetails: {},
                  };
              },
              methods: {
                  getArchivesData: function () {
                      this.api.getDataModule("archives/3/getarchives", "journals/v1/").then(
                          (res) => {
                              console.log(res.data);
                              this.archives = res.data.archives;
                              this.sortData();
                          },
                          (err) => {
                              console.log(err);
                          }
                      );
                  },
                  getPapersList: function (year, volume, issue) {
                      this.api
                          .getDataModulePagination(
                              "archives/3/getpaperslist",
                              "journals/v1/",
                              "year=" + year + "&volume=" + volume + "&issue=" + issue
                          )
                          .then(
                              (res) => {
                                  this.papersList = res.data.papersList;
                              },
                              (err) => {
                                  console.log(err);
                              }
                          );
                  },
                  getPaperDetails: function (paperid) {
                      this.api
                          .getDataModulePagination(
                              "archives/3/getpaperdetails",
                              "journals/v1/",
                              "paperid=" + paperid
                          )
                          .then(
                              (res) => {
                                  this.paperDetails = res.data.paperdetails;
                              },
                              (err) => {
                                  console.log(err);
                              }
                          );
                  },
                  sortedIssues: function (val) {
                      return val.sort().reverse();
                  },
                  sortData: function () {
                      this.years = Object.keys(this.archives).sort().reverse();
                  },
                  viewIssueData: function (year, volume, issue) {
                      this.getPapersList(year, volume, issue);
                      this.cYear = year;
                      this.cVolume = volume;
                      this.cIssue = issue;
                      this.listVisible = true;
                      this.$router.push({
                          path: "archives",
                          query: {
                              year: year,
                              volume: volume,
                              issue: issue
                          },
                      });
                  },
                  viewPaperDetails: function (paperid) {
                      this.getPaperDetails(paperid);
                      this.paperPage = true;
                      this.$router.push({
                          path: "archives",
                          query: {
                              paperid: paperid
                          }
                      });
                  },
                  downloadPDF: function (paperURL) {
                      window.open(paperURL, "_blank");
                  },
                  googleSearch(url) {
                      window.open(url, "_blank");
                  },
              },
              watch: {
                  $route: function () {
                      console.log("here");
                      if (
                          !this.paperPage &&
                          this.listVisible &&
                          this.cYear == this.$route.query.year &&
                          this.cVolume == this.$route.query.volume &&
                          this.cIssue == this.$route.query.issue
                      ) {
                          this.listVisible = true;
                      } else {
                          this.listVisible = false;
                      }

                      if ("paperid" in this.$route.query) {
                          this.viewPaperDetails(this.$route.query.paperid);
                      } else {
                          this.paperPage = false;
                          this.getArchivesData();
                      }
                  },
              },
              mounted: function () {
                  if ("paperid" in this.$route.query) {
                      this.viewPaperDetails(this.$route.query.paperid);
                  } else {
                      this.listVisible = false;
                      this.paperPage = false;
                      this.getArchivesData();
                      console.log("thre");
                  }
              },
          }; <
      /script>

    Error: [Vue warn]: You may have an infinite update loop in a component render function.

    found in
 <ArchivesVue> at src/components/page_components/Archives/Archives.vue

Its perfectly running in the local host but in the production build its occuring infinite loop
I want to find out why the above code is infinite loop while on the production and I'm getting the waring also in the console. Need to fix this`. Just this was not working while on the production build need to rectify this. what changes need to do and why this was happening while on the production
Answer: Upon component mount, you are invoking the viewPaperDetails method. Within this method, you are utilizing $router.push, which subsequently triggers the route watch method. However, inside the route watch, you are once again invoking the viewPaperDetails method. Consequently, this creates an infinite update loop within the component.


Alterando dados de uma coluna inteira tabela - Python

Question: batalha no laço "FOR"continua. bom, me deparei com um problema que nao consigo resolver. tenho uma tabela e todos seus dados são do tipo string, em uma certa coluna os dados de cada linha são letras e números, isso nao é um problema, eu fiz um laço "FOR", e limitei o tamanho da string assim:
i = []
for i in tabela['Valor']:
    i = i[3:7] # isso funcionou perfeitamente, mas nao consigo substituir os valores na coluna.
    #tabela['Valor'] = i # nessa tentativa nao funciona ficando apenas um numero em toda a coluna
    print(i)

tentei essa solução, mas "grava"apenas o ultimo dado do laço.
data = pd.DataFrame()
data['Valor'] = tabela['Valor']
i = []
for i in data['Valor']:
    i = i[0:8]
    print(i)
    tabela['Valor'] = i
    tabela = tabela.replace(tabela['Valor'])

quando mando printar a tabela, os valores da coluna 'Valor' fica sempre o mesmo o que está errado.
parte do dataset a ser alterado:
tabela['Valor']
output:
tabela['Valor']
0                            R$ 0,02 por ação ITAUSA ON
1                 R$ 0,02120838006 por ação BANESTES ON
2                R$ 0,06270328053 por ação IHPARDINI ON
3                  R$ 0,816430716 por ação BRB BANCO ON
4                 R$ 0,02120838006 por ação BANESTES ON
5                            R$ 0,02 por ação ITAUSA ON
6             R$ 0,23690201678 por ação TELEF BRASIL ON
7                    R$ 6,4876594827 por ação COPASA ON
8                    R$ 0,02310 por ação CELUL IRANI ON
9     R$ 0,907735758004401 por ação SUL AMERICA UNT ...
10                  R$ 0,19477374027 por ação BRASIL ON
11                R$ 0,7158810908 por ação UNIPAR ON N1
12                  R$ 0,05652210279 por ação TAESA UNT
13                  R$ 1,19237597898 por ação TAESA UNT
14               R$ 0,19813998 por ação SLC AGRICOLA ON
15               R$ 0,34644526 por ação SAO MARTINHO ON
16                    R$ 0,2551403880 por ação TEGMA ON
17                    R$ 0,0850467960 por ação TEGMA ON
18             R$ 0,03264206955 por ação AES TIETE E ON

o objetivo final é reduzir o tamanho dessa string e aparecer apenas os 4 primeiros números.
Comment: Opa, vc pode colocar pelo menos um pedaço do dataset?
Comment: Olá Paulo, feito... veja se ficou mais claro agora.
Answer: Vamos aos passos usando somente o pandas
Criar DataFrame
>>> import pandas as pd

>>> df = pd.DataFrame({"A": ["R$ 0,921222 qualquer coisa", "R$ 1,2345 outra coisa", "R$ 0,32212 ultima coisa"]})

>>> df

                            A
0  R$ 0,921222 qualquer coisa
1       R$ 1,2345 outra coisa
2     R$ 0,32212 ultima coisa

Copiar de uma coluna para outra somente o que se quer
>>> df["B"] = df["A"].str[3:7]

>>> df
                            A     B
0  R$ 0,921222 qualquer coisa  0,92
1       R$ 1,2345 outra coisa  1,23
2     R$ 0,32212 ultima coisa  0,32

Atualização do post 22/11/2020
Conforme sugerido pelo Flavio Moraes nos comentários, uma possiblidade mais adequada seria a utilização de expressões regulares para achar os valores.
Segue abaixo a forma de se fazer isso
>>> df["C"] = df["A"].str.extract(r'(\d,\d+)')

>>> df
                            A     B         C
0  R$ 0,921222 qualquer coisa  0,92  0,921222
1       R$ 1,2345 outra coisa  1,23    1,2345
2     R$ 0,32212 ultima coisa  0,32   0,32212

Perceba, neste ponto, que as duas colunas são string e possuem a vírgula como delimitador para os decimais.
Fim da atualização
O pandas trabalha com ponto para a separação das casas decimais. Ainda temos vírgula.
Converter vírugula para ponto
>>> df["B"] = df["B"].str.replace(",", ".")

>>> df
                            A     B
0  R$ 0,921222 qualquer coisa  0.92
1       R$ 1,2345 outra coisa  1.23
2     R$ 0,32212 ultima coisa  0.32

Converter string para float
>>> df["B"] = df["B"].astype(float)

>>> df
                            A     B
0  R$ 0,921222 qualquer coisa  0.92
1       R$ 1,2345 outra coisa  1.23
2     R$ 0,32212 ultima coisa  0.32

Pronto. Agora é só trabalhar com os números da coluna B (neste exemplo)
Continuação da atualização
Neste ponto, caso vc tenha testado a substituição da vírgula por ponto e a conversão das duas colunas para float. Você teria:
>>> df
                            A     B         C
0  R$ 0,921222 qualquer coisa  0.92  0.921222
1       R$ 1,2345 outra coisa  1.23  1.234500
2     R$ 0,32212 ultima coisa  0.32  0.322120

Perceba que para a coluna C temos todas as casas decimais encontradas pela expressão regular. Caso queira que seja apresentada apenas duas, basta configurar o pandas para tal
>>> pd.options.display.float_format = "{:,.2f}".format

>>> df
                            A    B    C
0  R$ 0,921222 qualquer coisa 0.92 0.92
1       R$ 1,2345 outra coisa 1.23 1.23
2     R$ 0,32212 ultima coisa 0.32 0.32

fim da continuação da atualização
Espero que ajude.
Comment: Se vc achar pertinente, marque esta resposta como solução do seu problema. Respondendo: Se não forem muitas colunas, vc pode fazer `df.columns = ["A", "B", "C"...]`. De próxima vez, evite colocar uma nova pergunta nos comentários, abra uma outra pergunta.
Comment: Paulo dei um upvote na sua resposta porque além de funcional é bastante didática. Porém acredito que usar regex para obter a parcela da string referente ao valor é importante não apenas para lidar com problemas na formatação, mas também para casos em que os valores tenham mais ou menos do que 4 digitos. Outra opção menos segura seria usar split ou strip, que ainda sim seriam melhores do que a substring.
Comment: @FlavioMoraes, muito obrigado pela sugestão do `regex`. Atualizei o post incluindo isso.
Comment: Creio que neste caso em especifico o regex não é necessário(vai aumentar a complexidade e pode levar mais tempo), tendo em vista que os valores estão bem definidos e você não precisa buscar os valores no meio de textos mais complexos. Talvez um split bastaria. Mas muito boa a resposta. Grande abraço e um up vote pela resposta!
Comment: Incrível! ficou perfeito....
Comment: Paulo, veja se pode ajudar-me novamente, nesse Data Frame tem 2 colunas com mesmo nome, como mudar ? é possível ?
Comment: @PauloMarques, excelente solução


Omnsharp's Intellisense not working

Question: I'm on Windows 8.1, using VS Code 1.0.0 and C# for VS Code version 1.0.1-rc2.
The problem is that I can't get Intellisense to work when opening C# projects, but when developing extensions, I do have intellisense enabled.

One thing though, is that when VS Code opens, Omnisharp starts...but, there is an error:

[INFO] Starting OmniSharp at 'c:\dev\TestI'... [ERROR]
  Error: connect ETIMEDOUT 188.8.131.52:443

This is my project.json file:
<code>{
  "version": "1.0.0-*",
  "compilationOptions": {
    "emitEntryPoint": true
  },
  "dependencies": {
    "Microsoft.NETCore.App": {
      "type": "platform",
      "version": "1.0.0-rc2-3002392"
    }
  },
  "frameworks": {
    "netcoreapp1.0": {}
  }
}
</code>
I also have "http.proxy" set up already.
Any help is appreciated.
Thanks.
Answer: Just in case someone has the same problem. Altough it doesn't seem to be a proxy problem there are manual steps to solve the issue.
Go to, https://github.com/OmniSharp/omnisharp-roslyn/releases/ and download the version of omnisharp you need. Unpack it, add a new item in the VS Code preferences: "csharp.omnisharp": "path/to/where/you/unpacked/the/files/".
Restart VS Code.
Taken from: https://github.com/OmniSharp/omnisharp-vscode/issues/200
Answer: First,you should download omnisharp-win-x64-netcoreapp1.0.zip  from https://github.com/OmniSharp/omnisharp-roslyn/releases, then unzip to C:\tmp\omnisharp-win-x64-netcoreapp1.0.You will get file C:\tmp\omnisharp-win-x64-netcoreapp1.0\OmniSharp.exe。
setting vscode config for c# Intellisense prompt。
Open vscode menu "File "->"Option"->"setting", you can edit file settings.json.Add newLine
go to:http://www.freemanwoman.com/running-c-aspnet-core-rc2-in-visual-studio-code-with-the-latest-omnisharp-plugin

Omnsharp's Intellisense not working


Dockerized nginx shuts down after a few seconds

Question: I'm working with Ubuntu 18 and I´m trying to run a dockerized nginx with a shared file between the host machine and the container: /home/ric/wrkspc/djangodocker/djangodocker/nginx.conf
I do so by running the following command, after which I'm prompted with container's ID:
$ sudo docker container run -v /home/ric/wrkspc/djangodocker/djangodocker/nginx.conf:/etc/nginx/nginx.conf:ro -d nginx
facc4d32db31de85d6f360e581bc7d36f257ff66953814e985ce6bdf708c3ad0

Now, if I try to list all the running containers, the nginx one doesn't appear listed:
(env) ric@x:~/wrkspc/djangodocker/djangodocker$ sudo docker container ls
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                               NAMES
36090ff0759c        mysql               "docker-entrypoint.s…"   3 days ago          Up 3 days           0.0.0.0:3306->3306/tcp, 33060/tcp   boring_panini

Sometimes, if I run the docker ls command fast enough, I can see the nginx container listed for just a few seconds and then it disappears.
Why is the nginx container not being listed?
Comment: Without knowing anything else about your config: did you remember to set `daemon off;`? I always forget that...
Comment: Surely your container has stopped, maybe for a configuration error. You can see logs of the container with `docker logs `
Comment: `docker ps -a` also lists terminated containers with their status und exit code
Answer: I think container immediately exits after started.
can you troubleshoot by looking into docker logs using the command
docker logs containerID
Also, you can try running the container interactively to identify the error without using -d option
Comment: Thank you. Using the `logs` subcommand I found that the problem was this: `nginx: [emerg] "upstream" directive is not allowed here in /etc/nginx/nginx.conf:1`. Oh, well.


Create button which change string value every time clicked

Question: I want to create a button which will change the string value every time I click in C#.
Here is my C# code:
partial class Translator2 : Page
{

    public string from = "en"; // initial value
    public string to = "ja"; // initial value

    public async void Submit(object sender, EventArgs e)
    {
        string from1 = from;
        string to1 = to;
        string uri = "https://api.microsofttranslator.com/v2/Http.svc/Translate?text=" + HttpUtility.UrlEncode(text) + "&from=" + from1 + "&to=" + to1;

 public  void Switch(object sender, EventArgs e)
    {

        if (from == "en" & to== "ja")
        {
            from = "ja";
            to = "en";
        }
        else if(from == "ja"& to =="en")
        {
            from = "en";
           to = "ja";
        }

    }

If I click the switch button, the string value changed from ja and to en. However, if I click again, nothing changed. What is wrong with my code?
Comment: It is `&&`, not `&`.
Comment: Did you set the two texts also in the Page_Load event? Did you protect this setting under !IsPostback ?
Comment: I am not sure what page_load event is and isPostback setting. I don't setting anything.
Comment: How are the `from` and `to` fields  getting initialized? Shouldn't they be getting their initial values from the request itself?
Answer: I suggest using an enum for clarity.
public enum Language {
    En_Ja,
    Ja_En
}

Language lang = Language.En_Ja;

 public  void Switch(object sender, EventArgs e) {
     lang = lang == Language.En_Ja ? Language.Ja_En : Language.En_Ja;
 }

Comment: Agree, and additional to @Edwin Surya, you should use properties instead of public fields. See http://csharpindepth.com/Articles/Chapter8/PropertiesMatter.aspx for more information.
Answer: Short Answer:
The from and to fields need to be initialized by the HTTP request. Something like:
partial class Translator : Page
{
    string from, to;

    protected override void OnLoad(EventArgs e)
    {
         var to = Context.Request.QueryString["to"];
         var from = Context.Request.QueryString["from"];

         switch(from.ToUpper())
         {
             case "EN": { this.from = "en"; break; }
             case "JA": { this.from = "ja"; break; }
         }

         switch(to.ToUpper())
         {
             case "EN": { this.to = "en"; break; }
             case "JA": { this.to = "ja"; break; }
         }

         if(to == null) throw new Exception();
         if(from == null) throw new Exception();

    }
}

Longer Answer:
This is actually a good use case for polymorphism:
/* C# 7 syntax */

abstract class LanguageSetting
{
    public static LanguageSetting English = JA.alt;
    public static LanguageSetting Japanese = EN.alt;

    public abstract LanguageSetting Alternate { get; }
    public abstract override string ToString();

    sealed class EN : LanguageSetting
    {
        public static readonly LanguageSetting alt = new JA();

        public override LanguageSetting Alternate => alt;
        public override string ToString() => "en";
    }

    sealed class JA : LanguageSetting
    {
        public static readonly LanguageSetting alt = new EN();

        public override LanguageSetting Alternate => alt;
        public override string ToString() => "js";
    }
}

Then your Submit() and Switch methods are simply:
void Submit(object Sender, EventArgs e)
{
    string from = lang.ToString();
    string to = lang.Alternate.ToString();

    string uri = "https://api.microsofttranslator.com/v2/Http.svc/Translate?text=" +
                  HttpUtility.UrlEncode(text) + "&from=" + from1 + "&to=" + to1;

}

and
void Switch(object Sender, EventArgs e)
{
    lang = lang.Alternate;
}

Finally, we initialize with something like:
protected override void OnLoad(EventArgs e)
{
     var from = Context.Request.QueryString["from"];

     switch(from.ToUpper())
     {
         case "EN": { lang = LanguageSetting.English; break; }
         case "JA": { lang = LanguageSetting.Japanese; break; }
     }

     if(lang == null) throw new Exception();

}

Comment: I disagree. I think the solution of Mr Awesome is much more readable for the given context. In the given example he only shows that he wants inversion of 'ja' and 'en'.


Prove that $\text{dom }\bigcup\mathfrak{A}=\bigcup\{\text{dom }R|R\in\mathfrak{A}\}$

Question: I have to solve the following question:

Show that for any set $\mathfrak{A}$: $$\text{dom }\bigcup\mathfrak{A}=\bigcup\{\text{dom }R|R\in\mathfrak{A}\}$$

I don't understand how. Take $\mathfrak{A}=\{\{\{a\},\{a,b\}\},\{\{c\},\{e,f\}\},\{\{g\},\{c,d\}\}\}$.
Then $\text{dom }\mathfrak{A}=\{a,c\}$. However, $\bigcup\{\text{dom }R|R\in\mathfrak{A}\}=\{a\}$. How I worked that out is I took each element of $\mathfrak{A}$, and saw if it was f the form $\{\{x\},\{x,y\}\}$. If it was, then $x\in\text{dom }R$. If not, then move on to the next element.
Thanks in advance!
Answer: I think that thinking about ordered pairs in the Kuratowski definition obfuscates the meaning, and it makes it somewhat harder to understand this question.
Instead of writing $\{\{\{a\},\{a,b\}\ldots$, write $\{R,S\}$ and $R=\{\langle a,b\rangle\}$ and $S=\{\langle a,c\rangle,\langle b,d\rangle\}$.
Then $\{\operatorname{dom} R\mid R\in\frak A\}$ is the set $\{a,b\}$ and $\operatorname{dom}\bigcup\frak A$ is the domain of the relation $\{\langle a,b\rangle,\langle a,c\rangle,\langle b,d\rangle\}$ which happens to be exactly $\{a,b\}$.
Work with the definition of $\operatorname{dom}$, and use $\langle a,b\rangle$ notation -- the less braces, the easier it is for humans to parse the statement.
Comment: How is the set I wrote down the same as $\{\langle a,b\rangle, \langle a,c\rangle, \langle b,d\rangle\}$?
Comment: It's not. It's a simpler example, and through this example I hoped to help you see clearly into the question.


Finding last case with square brackets?

Question: This is probably extremely simple.
Using dplyr and group_by(users), if I use something like filter(Date[1] == "01-14-15") within the group it will find users that have their first date as 01-14-15.
How do I set it so it will find the user's last date instead of their first date?
filter(Date[1] == "01-14-15"): find users with first case of date
filter(Date[?] == "01-14-15"): find users with last case of date?
Comment: Can you show me a piece of data? like head().
Comment: replace`?` with`nrow(dt)`?
Answer: If we need to filter the last row per group that also is the same as a particular Date, then, we can use
library(dplyr)
group_by(df1, Users) %>%
       filter(row_number()==n() & Date=='2012-01-03')

Or if you need to get all the rows of a group whose last 'Date' is the same as a particular Date, then
group_by(df1, Users) %>%
               filter(Date[n()]=='2012-01-01')

data
set.seed(24)
df1 <- data.frame(Users=sample(LETTERS[1:4], 20, replace=TRUE),
 Date= sample(seq(as.Date('2012-01-01'), length.out=4, by='1 day'),
          20, replace=TRUE), stringsAsFactors=FALSE)

Comment: Or `group_by(df1, Users) %>%
  filter(Date=='2012-01-03') %>%
  tail(1)`
Comment: @SamFirke Thanks for the comments, I guess that will be for the first option I mentioned.   But, I am not sure it will work as `tail(1)` gets the last observation
Comment: @SamFirke Suppose, if I change `df1$Date[20] <- '2012-01-03'`, this would only give a single row
Comment: Good catch.  A better implementation of my approach for your first option is `group_by(df1, Users) %>%
  slice(n()) %>%
  filter(Date=='2012-01-03')`

Finding last case with square brackets?