问:
Smyfony 3 UcWords prior to record insert
I'm sure this is super simple but I cannot find a explanation of how to do it.  I have a form that asks for the user's name (amongst other things).  Before I insert the record I want to ucwords on the name field.

How do I do this when I am inserting the record thus...

```<code>$em = $this->getDoctrine()->getManager();
$em->persist($profile);
$em->flush();
</code>```

答:
There is multiple places where you could do this.

In your entity

```<code>classs Profile
{
    //...

    public function setName($name)
    {
        $this->name = ucwords($name);
    }
}
</code>```

In your form

using a data transformer

```<code>class ProfileType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        // ...
        $builder->add('name', TextType::class);

        $builder->get('name')
            ->addModelTransformer(new CallbackTransformer(
                function ($name) {
                    // from model to form (not needed, but won't hurt)
                    return ucwords($name);
                },
                function ($name) {
                    // this is the direction were we need it
                    return ucwords($name);
                },
           ))
    ;
}
</code>```

There are other places, e.g. a Entity Listener or form events, but really one of these places is where I would look first. If it's a general requirement that the name is supposed to be uppercased I would go with the setter to make sure it's stored that way as well. If you are not sure all the data is persisted as needed you can put it in the entities getter as well, but even then I would look at making sure to fix the malformed data instead and ensure it's saved in the format you want, unless there are compelling reasons against it.

I wouldn't go with the combination suggested in the comment as this will lead to inconsistent data when someone forgets to call the setter with the ucwords.

Body:
I'm sure this is super simple but I cannot find a explanation of how to do it.  I have a form that asks for the user's name (amongst other things).  Before I insert the record I want to ucwords on the name field.

How do I do this when I am inserting the record thus...

$em = $this->getDoctrine()->getManager();
$em->persist($profile);
$em->flush();

Body:
There is multiple places where you could do this.

In your entity

classs Profile
{
    //...

    public function setName($name)
    {
        $this->name = ucwords($name);
    }
}

In your form

using a data transformer

class ProfileType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        // ...
        $builder->add('name', TextType::class);

        $builder->get('name')
            ->addModelTransformer(new CallbackTransformer(
                function ($name) {
                    // from model to form (not needed, but won't hurt)
                    return ucwords($name);
                },
                function ($name) {
                    // this is the direction were we need it
                    return ucwords($name);
                },
           ))
    ;
}

There are other places, e.g. a Entity Listener or form events, but really one of these places is where I would look first. If it's a general requirement that the name is supposed to be uppercased I would go with the setter to make sure it's stored that way as well. If you are not sure all the data is persisted as needed you can put it in the entities getter as well, but even then I would look at making sure to fix the malformed data instead and ensure it's saved in the format you want, unless there are compelling reasons against it.

I wouldn't go with the combination suggested in the comment as this will lead to inconsistent data when someone forgets to call the setter with the ucwords.


来源: stackexchange

问:
Pattern to initialize a function when angular component launch
Recently I had initialize a function when the angular component launch.

I had seen this comment and I'd like to know if is it a good pattern or could be better declare the function and call it after such the code below:

angular.module('app').controller('control',[...,
  function(){
    ...
    var init = function () {
      //what i wish run on launch
    };

    // function call to launch
    init();

  }
)
```

<p>or as mentioned in comment:</p>

<pre class="lang-js prettyprint-override"><code>(function(){
    //code to run
}());
</code>```

What do you have been used or even are there known problems when use this last approach?

答:
I would suggest you use principal of "bindable members on top" and use function declarations instead of function expressions so that functions can be hidden at bottom of controller and will get  hoisted.

```<code>angular.module('app').controller('control',[...,
  function(){

    // function call to launch
    init();

    // declare functions at bottom
    function init() {
      //what i wish run on launch
    }

  }
)
</code>```

Reference:  John Papa Angular Style guide

ContentLicense: CC BY-SA 3.0

Body:
Recently I had initialize a function when the angular component launch.

I had seen this comment and I'd like to know if is it a good pattern or could be better declare the function and call it after such the code below:

angular.module('app').controller('control',[...,
  function(){
    ...
    var init = function () {
      //what i wish run on launch
    };

    // function call to launch
    init();

  }
)

or as mentioned in comment:

(function(){
    //code to run
}());

What do you have been used or even are there known problems when use this last approach?

Body:
I would suggest you use principal of "bindable members on top" and use function declarations instead of function expressions so that functions can be hidden at bottom of controller and will get  hoisted.

angular.module('app').controller('control',[...,
  function(){

    // function call to launch
    init();

    // declare functions at bottom
    function init() {
      //what i wish run on launch
    }

  }
)

Reference:  John Papa Angular Style guide


问:
hibernate table does not exist error
In configuration hibernate.cfg.xml, i add
<property name="hibernate.hbm2ddl.auto">create</property>
Hibernate do create table automatically when i run the application. However, i remove the table from database manually by running drop table sql. Then run the hibernate application again. The exception appear

Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'test.person' doesn't exist

only way to fix the problem is restart the Mysql database. Could anyone explain this issue for me?

this is my hibernate.cfg.xml

```<code><hibernate-configuration>
<session-factory>
    <property name="hibernate.connection.driver_class">
        com.mysql.jdbc.Driver
    </property>
    <property name="hibernate.connection.url">
        jdbc:mysql://localhost/test
    </property>
    <property name="connection.username">root</property>
    <property name="connection.password">root</property>
    <property name="dialect">
        org.hibernate.dialect.MySQLDialect
    </property>

    <!-- Drop and re-create the database schema on startup -->
    <property name="hibernate.hbm2ddl.auto">create</property>

    <!-- Enable Hibernate's automatic session context management -->
    <property name="current_session_context_class">thread</property>

    <!-- Disable the second-level cache  -->
    <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>

    <!-- Echo all executed SQL to stdout -->
    <property name="show_sql">true</property>

    <!-- Mapping files -->
    <mapping resource="com/mapping/Event.hbm.xml" />
    <mapping resource="com/mapping/Person.hbm.xml"/>
</session-factory>
</code>```

Thx

答:
I don't believe using create will update an in-place schema to re-add the table that you dropped. Try:

```<code><property name="hibernate.hbm2ddl.auto">update</property>
</code>```

This is create a schema if one doesn't exist, and attempt to modify an existing one to match the mapping you have defined.

Also, read this question about all the possible values.

ContentLicense: CC BY-SA 2.5

Title: hibernate table does not exist error

Body:
In configuration hibernate.cfg.xml, i add
<property name="hibernate.hbm2ddl.auto">create</property>
Hibernate do create table automatically when i run the application. However, i remove the table from database manually by running drop table sql. Then run the hibernate application again. The exception appear

Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'test.person' doesn't exist

only way to fix the problem is restart the Mysql database. Could anyone explain this issue for me?

this is my hibernate.cfg.xml

<hibernate-configuration>
<session-factory>
    <property name="hibernate.connection.driver_class">
        com.mysql.jdbc.Driver
    </property>
    <property name="hibernate.connection.url">
        jdbc:mysql://localhost/test
    </property>
    <property name="connection.username">root</property>
    <property name="connection.password">root</property>
    <property name="dialect">
        org.hibernate.dialect.MySQLDialect
    </property>

    <property name="hibernate.hbm2ddl.auto">create</property>

    <property name="current_session_context_class">thread</property>

    <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>

    <property name="show_sql">true</property>

    <mapping resource="com/mapping/Event.hbm.xml" />
    <mapping resource="com/mapping/Person.hbm.xml"/>
</session-factory>

Thx

Body:
I don't believe using create will update an in-place schema to re-add the table that you dropped. Try:

<property name="hibernate.hbm2ddl.auto">update</property>

This is create a schema if one doesn't exist, and attempt to modify an existing one to match the mapping you have defined.

Also, read this question about all the possible values.


问:
How to install MySQL-python on Amazon Web Services EC2 instance?
I have a EC2 instance created on AWS and use PuTTY to connect to it.

I'm unable to install MySQL-python using python pip command as follows:

pip install MySQL-python(via root privileges)

Here is the console output of the error

```<code>Collecting MySQL-python
Using cached MySQL-python-1.2.5.zip
Complete output from command python setup.py egg_info:
sh: mysql_config: command not found
Traceback (most recent call last):
File "<string>", line 20, in <module>
File "/tmp/pip-build-JGbAEI/MySQL-python/setup.py", line 17, in <module>
metadata, options = get_config()
File "/tmp/pip-build-JGbAEI/MySQL-python/setup_posix.py", line 43, in get_config
libs = mysql_config("libs_r")
File "/tmp/pip-build-JGbAEI/MySQL-python/setup_posix.py", line 25, in mysql_config
raise EnvironmentError("%s not found" % (mysql_config.path,))
EnvironmentError: mysql_config not found
----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-JGbAEI/MySQL-python
</code>```

However I'm able to install other packages using pip

Please Guide.

答:
mysql_config is available after installation of the following package on Amazon Linux:

```<code>sudo yum install -y mysql-devel
</code>```

Body:
I have a EC2 instance created on AWS and use PuTTY to connect to it.

I'm unable to install MySQL-python using python pip command as follows:

pip install MySQL-python(via root privileges)

Here is the console output of the error

Collecting MySQL-python
Using cached MySQL-python-1.2.5.zip
Complete output from command python setup.py egg_info:
sh: mysql_config: command not found
Traceback (most recent call last):
File "<string>", line 20, in <module>
File "/tmp/pip-build-JGbAEI/MySQL-python/setup.py", line 17, in <module>
metadata, options = get_config()
File "/tmp/pip-build-JGbAEI/MySQL-python/setup_posix.py", line 43, in get_config
libs = mysql_config("libs_r")
File "/tmp/pip-build-JGbAEI/MySQL-python/setup_posix.py", line 25, in mysql_config
raise EnvironmentError("%s not found" % (mysql_config.path,))
EnvironmentError: mysql_config not found
----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-JGbAEI/MySQL-python

However I'm able to install other packages using pip

Please Guide.

Body:
mysql_config is available after installation of the following package on Amazon Linux:

sudo yum install -y mysql-devel


问:
Promise not getting resolved when using Page Object Model with Protractor
I'm trying to implement the Page Object Model in my project, and I'm having trouble getting it to work. I want to the title of the current page using browser.getTitle(), which works perfectly when used directly in login.spec.js, but doesn't work when moved to login.po.js. Here's what my setup currently looks like:

login.spec.js

```<code>var LoginPage = require('../../pages/user/login.po.js'),
    expect = require('chai').expect;

describe('Login', function() {
    var page;

    beforeEach(function () {
        page = new LoginPage();
    });

    it('should be able to get the page title', function() {
        expect(page.getLoginPageTitle).to.equal('Test');
    });
});
</code>```

login.po.js

```<code>'use strict';

var LoginPage = function(){
    browser.get('http://localhost:3000/');
};

LoginPage.prototype = Object.create({}, {
    getLoginPageTitle: {get: function() {
        browser.getTitle().then(function(res){
            return res;
        });
    }}
});

module.exports = LoginPage;
</code>```

And the error I get:
    AssertionError: expected undefined to equal 'Test'

Upon further investigating, it seems like the browser.getTitle() promise in my login.po.js isn't getting resolved.

Any ideas on what I'm doing wrong? The page loads correctly in Chrome and Chrome shows the correct page title.

答:
Figured it eventually! (no pun intended)

I simply had to use chai-as-promised as well as use wswebcreation's answer. Here's my setup now:

login.spec.js

```<code>var LoginPage = require('../../pages/user/login.po.js'),
    chai = require('chai'),
    expect = require('chai').expect,
    chaiAsPromised = require('chai-as-promised');

chai.use(chaiAsPromised)

describe('Login', function() {
    var page;

    beforeEach(function () {
        page = new LoginPage();
    });

    it('should be able to get the page title', function() {
        expect(page.getLoginPageTitle).to.eventually.equal('Test');
    });
});
</code>```

login.po.js

```<code>'use strict';

var LoginPage = function(){
    browser.get('http://localhost:3000/');
};

LoginPage.prototype = Object.create({}, {
    getLoginPageTitle: {get: function() {
        return browser.getTitle();
    }}
});

module.exports = LoginPage;
</code>```

Body:
I'm trying to implement the Page Object Model in my project, and I'm having trouble getting it to work. I want to the title of the current page using browser.getTitle(), which works perfectly when used directly in login.spec.js, but doesn't work when moved to login.po.js. Here's what my setup currently looks like:

login.spec.js

var LoginPage = require('../../pages/user/login.po.js'),
    expect = require('chai').expect;

describe('Login', function() {
    var page;

    beforeEach(function () {
        page = new LoginPage();
    });

    it('should be able to get the page title', function() {
        expect(page.getLoginPageTitle).to.equal('Test');
    });
});

login.po.js

'use strict';

var LoginPage = function(){
    browser.get('http://localhost:3000/');
};

LoginPage.prototype = Object.create({}, {
    getLoginPageTitle: {get: function() {
        browser.getTitle().then(function(res){
            return res;
        });
    }}
});

module.exports = LoginPage;

And the error I get:
    AssertionError: expected undefined to equal 'Test'

Upon further investigating, it seems like the browser.getTitle() promise in my login.po.js isn't getting resolved.

Any ideas on what I'm doing wrong? The page loads correctly in Chrome and Chrome shows the correct page title.

Body:
Figured it eventually! (no pun intended)

I simply had to use chai-as-promised as well as use wswebcreation's answer. Here's my setup now:

login.spec.js

var LoginPage = require('../../pages/user/login.po.js'),
    chai = require('chai'),
    expect = require('chai').expect,
    chaiAsPromised = require('chai-as-promised');

chai.use(chaiAsPromised)

describe('Login', function() {
    var page;

    beforeEach(function () {
        page = new LoginPage();
    });

    it('should be able to get the page title', function() {
        expect(page.getLoginPageTitle).to.eventually.equal('Test');
    });
});

login.po.js

'use strict';

var LoginPage = function(){
    browser.get('http://localhost:3000/');
};

LoginPage.prototype = Object.create({}, {
    getLoginPageTitle: {get: function() {
        return browser.getTitle();
    }}
});

module.exports = LoginPage;


问:
VB.net send keypress to game
ive seen other questions about this issue but none of them resolved it for me so here i go. I'm trying to send a keypress to a game to save the progress(its a 64bit game). what i've coded so far is :

```<code>Dim p() As Process
Dim GameID As Integer = 0
 Dim p As Process() = Process.GetProcessesByName("Gamename")

    If p.Length > 0 Then
        For i As Integer = 0 To p.Length - 1
            GameID = (p(i).Id)
        Next
    End If
AutoSaveTimer.Enabled = True
    Dim Test As Integer = 0
    GetAsyncKeyState(Test)
    AppActivate("GameName")
    My.Computer.Keyboard.SendKeys(";", True)
</code>```

now i've tried Sendkeys.Send(";") but without luck, and the game runs under "GameName" but then the keypress needs to be sent in a window under the game :
Blacked out is the game and under the first window is where the keypress needs to be sent

thanks in advance for the help

答:
I use InputSimulator in my app and it works great.

https://inputsimulator.codeplex.com/

It could be this easy to send keys. The active window will see that as if the user actually used those keys.

```<code>var sim = new InputSimulator();
sim.Keyboard.KeyPress(VirtualKeyCode.SPACE);
sim = null;
</code>```

Here's a screen shot of the methods you can use for keyboard.

Title: VB.net send keypress to game

Body:
ive seen other questions about this issue but none of them resolved it for me so here i go. I'm trying to send a keypress to a game to save the progress(its a 64bit game). what i've coded so far is :

Dim p() As Process
Dim GameID As Integer = 0
 Dim p As Process() = Process.GetProcessesByName("Gamename")

    If p.Length > 0 Then
        For i As Integer = 0 To p.Length - 1
            GameID = (p(i).Id)
        Next
    End If
AutoSaveTimer.Enabled = True
    Dim Test As Integer = 0
    GetAsyncKeyState(Test)
    AppActivate("GameName")
    My.Computer.Keyboard.SendKeys(";", True)

now i've tried Sendkeys.Send(";") but without luck, and the game runs under "GameName" but then the keypress needs to be sent in a window under the game :
Blacked out is the game and under the first window is where the keypress needs to be sent

thanks in advance for the help

Body:
I use InputSimulator in my app and it works great.

https://inputsimulator.codeplex.com/

It could be this easy to send keys. The active window will see that as if the user actually used those keys.

var sim = new InputSimulator();
sim.Keyboard.KeyPress(VirtualKeyCode.SPACE);
sim = null;

Here's a screen shot of the methods you can use for keyboard.


问:
How to implement template function to create arbitrary class instance?
I need to implement a template function which would allow me to create an instance of arbitrary class using arbitrary constructor with any possible parameters which can be any combination of lvalues and rvalues.

Lets say I have two classes - A and B - which are as follows:

```<code>class A
{
public:

A(){}

};

class B
{
    A& a1; // I want to be able to call non-constant methods and modify object
    const A& a2; // This I need only as const member
    int i; //can be initialized with a temporary object

    public:

    B(A& a1_, const A& a2_, int i_) : a(a_), a2(a2_), i(i_) {}
};
</code>```

I tried to implement something like below but it would only allow me to use lvalues (named objects) and I will not be able to pass temporary objects.
Adding const keyword partly solves the issue but disallows ability to modify objects which may be required.

```<code>template <typename TType, typename ... TArgs>
TType create(TArgs&... args)
{
    return TType(args...);
}
</code>```

I want to use 'create' function like this:

```<code>int main()
{
   A a1;
   A a2;
   //function takes both lvalue and rvalue
   B b = create<B>(a1, a2, 1);
}
</code>```

Could someone please suggest a possible solution?

答:
As commented above by Alan Stokes, you can use forwarding references to receive lvalue and rvalue expressions:</p>

```<code>template <typename TType, typename ... TArgs>
TType create(TArgs&&... args)
{
    return TType(std::forward<TArgs>(args)...);
}
</code>```

Body:
I need to implement a template function which would allow me to create an instance of arbitrary class using arbitrary constructor with any possible parameters which can be any combination of lvalues and rvalues.

Lets say I have two classes - A and B - which are as follows:

class A
{
public:

A(){}

};

class B
{
    A& a1; // I want to be able to call non-constant methods and modify object
    const A& a2; // This I need only as const member
    int i; //can be initialized with a temporary object

    public:

    B(A& a1_, const A& a2_, int i_) : a(a_), a2(a2_), i(i_) {}
};

I tried to implement something like below but it would only allow me to use lvalues (named objects) and I will not be able to pass temporary objects.
Adding const keyword partly solves the issue but disallows ability to modify objects which may be required.

template <typename TType, typename ... TArgs>
TType create(TArgs&... args)
{
    return TType(args...);
}

I want to use 'create' function like this:

int main()
{
   A a1;
   A a2;
   //function takes both lvalue and rvalue
   B b = create(a1, a2, 1);
}

Could someone please suggest a possible solution?

Body:
As commented above by Alan Stokes, you can use forwarding references to receive lvalue and rvalue expressions:

template <typename TType, typename ... TArgs>
TType create(TArgs&&... args)
{
    return TType(std::forward<TArgs>(args)...);
}


问:
openOptionsMenu() will not work in appcompat-v7 22.1.0 or newer
I've seen several reports of issues where openOptionsMenu() will not work on various Android versions, eg:

openOptionsMenu() across android versions

openOptionsMenu() not working

but the issue I have seems to be related to the version of the appcompat-v7 support library being used.

In essence, with the newer versions of appcompat-v7 the menu will appear fine when openOptionsMenu() is called if your activity extends Activity but will not work if you extend ActionBarActivity or AppCompatActivity (ie use the compatibility library). In older versions of appcompat-v7 it works fine.

It is reproducible, as follows:

In Android Studio, Import Sample 'ActionBarCompat-Basic'

Add a button to the screen, which invokes openOptionsMenu()

Note that this works fine, as the old version of the library, appcompat-v7:21.0.3 is used in the sample

Change the dependency to use appcompat-v7:23.0.1, rebuild, and when clicking on the button the menu will not appear.

Change the main activity to extend Activity (ie no app compatability) - it works

Change the main activity to extend AppCompatActivity (ie using app compatibility libarry) - it fails

After some testing, I've found that this stopped working in appcompat-v7:22.1.0, and will no longer work in any newer version of this jar.

This behaviour is identical on the emulator and on a physical device, and on Android versions 5.1.1(23) and 2.1(7) which were the two versions I tested it with.

I've added a comment to this bug: Android issue tracker bug

Any suggestions, ideas or workarounds appreciated!

-Steve

答:
I think I may have actually found a workaround for this. It involves overriding the openOptionsMenu() method:

```<code>@Override
public void openOptionsMenu()
{
    mActionBar.showOverflowMenu();
}
</code>```

In order for showOverflowMenu() to work on devices with a physical menu key that are below API 19, use this: How to force action bar overflow icon to show

mActionBar is assigned as such:

```<code>android.support.v7.widget.Toolbar mActionBar = (android.support.v7.widget.Toolbar) getActionBar(getWindow().getDecorView())
</code>```

This is the getActionBar() method:

```<code>public static ViewGroup getActionBar(View view)
{
    try
    {
        if (view instanceof ViewGroup)
        {
            ViewGroup viewGroup = (ViewGroup) view;

            if (viewGroup instanceof android.support.v7.widget.Toolbar)
            {
                return viewGroup;
            }

            for (int i = 0; i < viewGroup.getChildCount(); i++)
            {
                ViewGroup actionBar = getActionBar(viewGroup.getChildAt(i));

                if (actionBar != null)
                {
                    return actionBar;
                }
            }
        }
    }
    catch (Exception e)
    {
        e.printStackTrace();
    }

    return null;
}
</code>```

Calling openOptionsMenu() from an AppCompatActivity now works!

NOTE: I tested this on API 26, but seeing as the getActionBar() method works far below that, I see no reason the rest of this will fail.

Body:
I think I may have actually found a workaround for this. It involves overriding the openOptionsMenu() method:

@Override
public void openOptionsMenu()
{
    mActionBar.showOverflowMenu();
}

In order for showOverflowMenu() to work on devices with a physical menu key that are below API 19, use this: How to force action bar overflow icon to show

mActionBar is assigned as such:

android.support.v7.widget.Toolbar mActionBar = (android.support.v7.widget.Toolbar) getActionBar(getWindow().getDecorView())

This is the getActionBar() method:

public static ViewGroup getActionBar(View view)
{
    try
    {
        if (view instanceof ViewGroup)
        {
            ViewGroup viewGroup = (ViewGroup) view;

            if (viewGroup instanceof android.support.v7.widget.Toolbar)
            {
                return viewGroup;
            }

            for (int i = 0; i < viewGroup.getChildCount(); i++)
            {
                ViewGroup actionBar = getActionBar(viewGroup.getChildAt(i));

                if (actionBar != null)
                {
                    return actionBar;
                }
            }
        }
    }
    catch (Exception e)
    {
        e.printStackTrace();
    }

    return null;
}

Calling openOptionsMenu() from an AppCompatActivity now works!

NOTE: I tested this on API 26, but seeing as the getActionBar() method works far below that, I see no reason the rest of this will fail.


问:
How can I Group By Month, Day from a Date field using Python/Pandas
I have a Data-frame df which is as follows:

```<code>| date      | Revenue | Cost |
|-----------|---------|------|
| 6/1/2017  | 100     | 20   |
| 5/21/2017 | 200     | 40   |
| 5/21/2017 | 300     | 60   |
| 6/20/2017 | 400     | 80   |
| 6/1/2017  | 500     | 100  |
</code>```

I need to group the above data by Month and then by Day to get output as:

```<code>| Month | Day | SUM(Revenue) | SUM(Cost) |
|-------|-----|--------------|-----------|
| May   | 21  | 500          | 100       |
| June  | 1   | 600          | 120       |
| June  | 20  | 400          | 80        |
</code>```

I tried this code but it did not work:

```<code>df.groupby(month('date'), day('date')).agg({'Revenue': 'sum', 'Cost': 'sum' })
</code>```

I want to only use Pandas or Numpy and no additional libraries

答:
Let's use set_index and sum with argument level:

```<code>df['date'] = pd.to_datetime(df['date'])
df['Month'] = df['date'].dt.strftime('%b')
df['Day'] = df['date'].dt.day
df.set_index(['Month','Day']).sum(level=[0,1]).reset_index()
</code>```

Output:

```<code>  Month  Day  Revenue  Cost
0   Jun    1      600   120
1   Jun   20      400    80
2   May   21      500   100
</code>```

Body:
I have a Data-frame df which is as follows:

| date      | Revenue | Cost |
|-----------|---------|------|
| 6/1/2017  | 100     | 20   |
| 5/21/2017 | 200     | 40   |
| 5/21/2017 | 300     | 60   |
| 6/20/2017 | 400     | 80   |
| 6/1/2017  | 500     | 100  |

I need to group the above data by Month and then by Day to get output as:

| Month | Day | SUM(Revenue) | SUM(Cost) |
|-------|-----|--------------|-----------|
| May   | 21  | 500          | 100       |
| June  | 1   | 600          | 120       |
| June  | 20  | 400          | 80        |

I tried this code but it did not work:

df.groupby(month('date'), day('date')).agg({'Revenue': 'sum', 'Cost': 'sum' })

I want to only use Pandas or Numpy and no additional libraries

Body:
Let's use set_index and sum with argument level:

df['date'] = pd.to_datetime(df['date'])
df['Month'] = df['date'].dt.strftime('%b')
df['Day'] = df['date'].dt.day
df.set_index(['Month','Day']).sum(level=[0,1]).reset_index()

Output:

  Month  Day  Revenue  Cost
0   Jun    1      600   120
1   Jun   20      400    80
2   May   21      500   100


问:
Pure functional programming on android
Are there any advancements in this area? I want to be able to write purely functional code on Android in Haskell or similar languages. I've tried some examples with Scala but it seems to be a pain to get started. Are there any other functional JVM languages which I can use to write Android applications?

Edit: functional languages that write native android applications. My mistake about the JVM.

答:
I you want a painless solution in terms of Gradle builds etc., you have only two options: Java and Kotlin, of which of course you should choose Kotlin ;)

Kotlin has most of the things you need to write in functional style:

functions as first class citizen

higher-order functions

immutable collections

var and val like in Scala

if-else as a statement

elements of pattern matching (where statement)

tail recursion

and more...

If you also include funKTionale and kotlinx.collections.immutable, you'll have all the functional goodies like: Option, Try, currying, memoization, persistent data structures and so on...

To start with Kotlin just install the latest Android Studio 3 Preview, which already has built-in Kotlin support.

BTW, don't be so polarized into "pure" functional ;) After all, being 100% "pure" means no side-effects, which means your app can't interact with the user ;)

Hope this helps :)

Title: Pure functional programming on android


问:
getView on fragment returning null when called from different fragment
I have an activity that contains two fragments. One of the fragments, mainFragment, is the size of the whole screen. There is another fragment, summaryFrag, that is contained in a view inside of mainFragment. I am trying to update text on summaryFrag based on an action that happens in mainFragment.

Goal: When a button is pressed in mainFragment, set the text of a TextView in summaryFrag to something.

I tried to do this by getting the TextView from inside of mainFragment by using

TextView textView = (TextView) summary.getView().findViewById(R.id.prev_guess_txt);

but I get a null pointer exception error

```<code>FATAL EXCEPTION: main
              Process: com.example.damia.bullseyev3, PID: 6049
              java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.View.findViewById(int)' on a null object reference
                  at com.example.damia.bullseyev3.fragments.mainFragment.updatePreviousGuesses(mainFragment.java:83)
                  at com.example.damia.bullseyev3.fragments.mainFragment$1.onClick(mainFragment.java:68)
                  at android.view.View.performClick(View.java:5610)
                  at android.view.View$PerformClick.run(View.java:22260)
                  at android.os.Handler.handleCallback(Handler.java:751)
                  at android.os.Handler.dispatchMessage(Handler.java:95)
                  at android.os.Looper.loop(Looper.java:154)
                  at android.app.ActivityThread.main(ActivityThread.java:6077)
                  at java.lang.reflect.Method.invoke(Native Method)
                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
</code>```

mainFragment.java

```<code>@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.fragment_main, container, false);
    scrollView = (ScrollView) v.findViewById(R.id.scroll);
    ll = (LinearLayout)v.findViewById(R.id.linearlayout);

    submitBtn = (Button)v.findViewById(R.id.submit_guess_btn);

    submitBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            updatePreviousGuesses();
        }
    });

    return v;
}

public void updatePreviousGuesses(){
    //TODO add method to check if guess is valid first before updating the scrollview
    FrameLayout holder = new FrameLayout(getActivity());
    holder.setId(R.id.holder);

    summaryFrag summary = summaryFrag.newInstance("","");
    getActivity().getSupportFragmentManager().beginTransaction().add(R.id.holder, summary).commit();

    TextView textView = (TextView) summary.getView().findViewById(R.id.prev_guess_txt);
    textView.setText("test");

    ll.addView(holder, 0);
}
</code>```

summaryFrag.java

```<code>@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (getArguments() != null) {
        mParam1 = getArguments().getString(ARG_PARAM1);
        mParam2 = getArguments().getString(ARG_PARAM2);
    }
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.summary, container, false);

    return v;
}
}
</code>```

(summaryFrag has nothing changed from the default generated fragment code at the moment)

MainActivity.java

```<code>public class MainActivity extends AppCompatActivity {

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

    FragmentManager fm = getSupportFragmentManager();
    mainFragment mainfrag = (mainFragment)fm.findFragmentById(R.id.fragment_container);

    if(mainfrag == null){
        mainfrag = mainFragment.newInstance("","");
        fm.beginTransaction().add(R.id.fragment_container, mainfrag).commit();
    }
}
}
</code>```

I have read a few solutions about this, and I know it is due to the fragment lifestyle and everything, but I still have tried to fix it on my own and have not been successful. I've tried moving some things to onViewCreated instead but I don't know how it works well enough to know what SHOULD be moved there and what shouldn't.

I'm new to callbacks and everything so if your solution includes them could you please explain it to a beginner a bit :)

Thanks

答: Better use setarguments & getarguments when you are trying to interact between fragments</p>

Body:
I have an activity that contains two fragments. One of the fragments, mainFragment, is the size of the whole screen. There is another fragment, summaryFrag, that is contained in a view inside of mainFragment. I am trying to update text on summaryFrag based on an action that happens in mainFragment.

Goal: When a button is pressed in mainFragment, set the text of a TextView in summaryFrag to something.

I tried to do this by getting the TextView from inside of mainFragment by using

TextView textView = (TextView) summary.getView().findViewById(R.id.prev_guess_txt);

but I get a null pointer exception error

FATAL EXCEPTION: main
              Process: com.example.damia.bullseyev3, PID: 6049
              java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.View.findViewById(int)' on a null object reference
                  at com.example.damia.bullseyev3.fragments.mainFragment.updatePreviousGuesses(mainFragment.java:83)
                  at com.example.damia.bullseyev3.fragments.mainFragment$1.onClick(mainFragment.java:68)
                  at android.view.View.performClick(View.java:5610)
                  at android.view.View$PerformClick.run(View.java:22260)
                  at android.os.Handler.handleCallback(Handler.java:751)
                  at android.os.Handler.dispatchMessage(Handler.java:95)
                  at android.os.Looper.loop(Looper.java:154)
                  at android.app.ActivityThread.main(ActivityThread.java:6077)
                  at java.lang.reflect.Method.invoke(Native Method)
                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)

mainFragment.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.fragment_main, container, false);
    scrollView = (ScrollView) v.findViewById(R.id.scroll);
    ll = (LinearLayout)v.findViewById(R.id.linearlayout);

    submitBtn = (Button)v.findViewById(R.id.submit_guess_btn);

    submitBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            updatePreviousGuesses();
        }
    });

    return v;
}

public void updatePreviousGuesses(){
    //TODO add method to check if guess is valid first before updating the scrollview
    FrameLayout holder = new FrameLayout(getActivity());
    holder.setId(R.id.holder);

    summaryFrag summary = summaryFrag.newInstance("","");
    getActivity().getSupportFragmentManager().beginTransaction().add(R.id.holder, summary).commit();

    TextView textView = (TextView) summary.getView().findViewById(R.id.prev_guess_txt);
    textView.setText("test");

    ll.addView(holder, 0);
}

summaryFrag.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (getArguments() != null) {
        mParam1 = getArguments().getString(ARG_PARAM1);
        mParam2 = getArguments().getString(ARG_PARAM2);
    }
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.summary, container, false);

    return v;
}
}

(summaryFrag has nothing changed from the default generated fragment code at the moment)

MainActivity.java

public class MainActivity extends AppCompatActivity {

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

    FragmentManager fm = getSupportFragmentManager();
    mainFragment mainfrag = (mainFragment)fm.findFragmentById(R.id.fragment_container);

    if(mainfrag == null){
        mainfrag = mainFragment.newInstance("","");
        fm.beginTransaction().add(R.id.fragment_container, mainfrag).commit();
    }
}
}

I have read a few solutions about this, and I know it is due to the fragment lifestyle and everything, but I still have tried to fix it on my own and have not been successful. I've tried moving some things to onViewCreated instead but I don't know how it works well enough to know what SHOULD be moved there and what shouldn't.

I'm new to callbacks and everything so if your solution includes them could you please explain it to a beginner a bit :)

Thanks


问:
How to get matplotlib bar chart to match numeric count in python terminal
My main objective is to be consistent with both my numeric output and my visual output. However, I can't seem to get to them to match.

Here is my setup using python 3.x:

```<code>df = pd.DataFrame([ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1,
   1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1,
   1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
   1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2,
   2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 2,
   2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
   2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2],columns=['Expo'])
</code>```

Followed by my setup for the bar chart in matplotlib:

```<code>x = df['Expo']
N = len(x)
y = range(N)
width = 0.125
plt.bar(x, y, width, color="blue")
fig = plt.gcf();
</code>```

A Nice pretty graph produced:

However, using this snippet code to check and see what the actual numeric counts of both classes are...

```<code>print("Class 1: "+str(df['Expo'].value_counts()[1]),"Class 2: "+str(df['Expo'].value_counts()[2]))
</code>```

I get the below:

Class 1: 85 Class 2: 70

Since I have 155 records in the data frame, numerically this makes sense. Having a single bar in the bar chart be at 155 does not.

I appreciate any help in advance.

Body:
My main objective is to be consistent with both my numeric output and my visual output. However, I can't seem to get to them to match.

Here is my setup using python 3.x:

df = pd.DataFrame([ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1,
   1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1,
   1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
   1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2,
   2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 2,
   2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
   2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2],columns=['Expo'])

Followed by my setup for the bar chart in matplotlib:

x = df['Expo']
N = len(x)
y = range(N)
width = 0.125
plt.bar(x, y, width, color="blue")
fig = plt.gcf();

A Nice pretty graph produced:

However, using this snippet code to check and see what the actual numeric counts of both classes are...

print("Class 1: "+str(df['Expo'].value_counts()[1]),"Class 2: "+str(df['Expo'].value_counts()[2]))

I get the below:

Class 1: 85 Class 2: 70

Since I have 155 records in the data frame, numerically this makes sense. Having a single bar in the bar chart be at 155 does not.

I appreciate any help in advance.

Body:
I guess something like this is what you're after:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

df = pd.DataFrame([ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1,
   1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1,
   1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
   1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2,
   2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 2,
   2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
   2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2],columns=['Expo'])

# Count number of '1' and '2' elements in df
N1, N2 = len(df[df['Expo'] == 1]), len(df[df['Expo'] == 2])
width = 0.125
# Plot the lengths in x positions [1, 2]
plt.bar([1, 2], [N1, N2], width, color="blue")
fig = plt.gcf()
plt.show()

Which produces


问:
Java swing BoxLayout center doesn't work
I have a JFrame that has JPanel inside. Inside JPanel there are 2 buttons. JPanel has a BoxLayout. I need buttons to be displayed horizontally in the center of the window. Here is my code:

I just create two buttons, set their alignment to the center (tried all the ways I knew) and add them to the panel horizontally.

```<code>public class UserInterface extends JFrame  {
   public UserInterface()  {
                setup();
   }
   private void setup()  {
         ...
         panel=new UserInterfacePanel();
         add(panel);
   }
}

class UserInterfacePanel extends JPanel {
         private JToggleButton startButton;
         private JToggleButton stopButton;

         public UserInterfacePanel()  {
             setup();
         }

         private void setup()  {
            setLayout(new BoxLayout(this, BoxLayout.X_AXIS));

            setupButtons();
            setupButtonsActions();
            add(startButton);
            add(stopButton);
        }

        private void setupButtons()  {
            ...
            startButton.setHorizontalAlignment(JButton.CENTER);
            stopButton.setHorizontalAlignment(JButton.CENTER);
            startButton.setAlignmentX(CENTER_ALIGNMENT);
            stopButton.setAlignmentX(CENTER_ALIGNMENT);
        }
}
</code>```

And yet it doesn't work. Why doesn't it and how to fix it?

答:
buttons are still located at the left side of the window.

If you want the components center horizontally on the line you need to use "glue"

```<code>add(Box.createHorizontalGlue());
add(startButton);
add(stopButton);
add(Box.createHorizontalGlue());
</code>```

Body:
I have a JFrame that has JPanel inside. Inside JPanel there are 2 buttons. JPanel has a BoxLayout. I need buttons to be displayed horizontally in the center of the window. Here is my code:

I just create two buttons, set their alignment to the center (tried all the ways I knew) and add them to the panel horizontally.

public class UserInterface extends JFrame  {
   public UserInterface()  {
                setup();
   }
   private void setup()  {
         ...
         panel=new UserInterfacePanel();
         add(panel);
   }
}

class UserInterfacePanel extends JPanel {
         private JToggleButton startButton;
         private JToggleButton stopButton;

         public UserInterfacePanel()  {
             setup();
         }

         private void setup()  {
            setLayout(new BoxLayout(this, BoxLayout.X_AXIS));

            setupButtons();
            setupButtonsActions();
            add(startButton);
            add(stopButton);
        }

        private void setupButtons()  {
            ...
            startButton.setHorizontalAlignment(JButton.CENTER);
            stopButton.setHorizontalAlignment(JButton.CENTER);
            startButton.setAlignmentX(CENTER_ALIGNMENT);
            stopButton.setAlignmentX(CENTER_ALIGNMENT);
        }
}

And yet it doesn't work. Why doesn't it and how to fix it?

Body:
buttons are still located at the left side of the window.

If you want the components center horizontally on the line you need to use "glue"

add(Box.createHorizontalGlue());
add(startButton);
add(stopButton);
add(Box.createHorizontalGlue());


问:
2 way data binding with Vuex
In the code below I'm 2 way binding the output of a textarea into a p element, once from the component's internal state and once from Vuex. The Vuex state does show the initial value, but the value doesn't update as I add or delete text (as it does correctly with the 1st textarea bound to the internal data). What is the difference that is causing this issue?

Component code:

```<code><template>
  <div>
    <div>
      <textarea name="textarea1" id="txtid" cols="40" rows="30" v-model="internal_state"></textarea>
      <p> {{ internal_state }}</p>
      <hr>

      <textarea name="textarea1" id="txtid" cols="40" rows="30" v-model="this.$store.state.vuex_state"></textarea>
      <p> {{ this.$store.state.vuex_state }}</p>
      <hr>

    </div>
  </div>
</template>

<script>

  export default {
    name: 'WriteArea',
    data () {
      return {
        internal_state: ''
      }
    },
    methods: {

    }
  }

</script>
</code>```

Vuex code:

```<code>import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export const store = new Vuex.Store({
  strict: true,
  state: {
    counter: 0,
    vuex_state: 'starting string'
  },
  getters: {
    vuex_getter1: (state) => {
      return state.vuex_string
    }
  }
})
</code>```

答:
Vuex state should be updated via a mutation. See the documentation for this exact problem. Solution is not to use v-model, but instead to bind to the :value of the textarea and then have a custom event to mutate the Vuex state on input:
https://vuex.vuejs.org/en/forms.html

```<code><input :value="message" @input="updateMessage">
// ...
computed: {
  ...mapState({
    message: state => state.obj.message
  })
},
methods: {
  updateMessage (e) {
    this.$store.commit('updateMessage', e.target.value)
  }
}
</code>```

The other option is to create a setter and getter in the same computed property:

```<code><input v-model="message">
// ...
computed: {
  message: {
    get () {
      return this.$store.state.obj.message
    },
    set (value) {
      this.$store.commit('updateMessage', value)
    }
  }
}
</code>```

Title: 2 way data binding with Vuex

Body:
In the code below I'm 2 way binding the output of a textarea into a p element, once from the component's internal state and once from Vuex. The Vuex state does show the initial value, but the value doesn't update as I add or delete text (as it does correctly with the 1st textarea bound to the internal data). What is the difference that is causing this issue?

Component code:

<template>

      <textarea name="textarea1" id="txtid" cols="40" rows="30" v-model="internal_state"></textarea>

 {{ internal_state }}

      <textarea name="textarea1" id="txtid" cols="40" rows="30" v-model="this.$store.state.vuex_state"></textarea>

 {{ this.$store.state.vuex_state }}

</template>

Vuex code:

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export const store = new Vuex.Store({
  strict: true,
  state: {
    counter: 0,
    vuex_state: 'starting string'
  },
  getters: {
    vuex_getter1: (state) => {
      return state.vuex_string
    }
  }
})

Body:
Vuex state should be updated via a mutation. See the documentation for this exact problem. Solution is not to use v-model, but instead to bind to the :value of the textarea and then have a custom event to mutate the Vuex state on input:
https://vuex.vuejs.org/en/forms.html

<input :value="message" @input="updateMessage">
// ...
computed: {
  ...mapState({
    message: state => state.obj.message
  })
},
methods: {
  updateMessage (e) {
    this.$store.commit('updateMessage', e.target.value)
  }
}

The other option is to create a setter and getter in the same computed property:

<input v-model="message">
// ...
computed: {
  message: {
    get () {
      return this.$store.state.obj.message
    },
    set (value) {
      this.$store.commit('updateMessage', value)
    }
  }
}


问:
How do you name a property of an object with a string plus a variable?
If I have an object:

```<code>var enemies = {};
var enemyNumber = 0;
</code>```

and then how do I make a new property of that object which is named after a string + a variable, like this (I know this is not valid javascript):

```<code>enemyNumber++;
enemies.enemy + enemyNumber.toString() = {};
</code>```

(enemies.enemy + enemyNumber.toString() is another object)

答:
Add dynamically properties to your enemies  object :

```<code>var enemies = {};
var enemyNumber = 0;
enemies.enemy="Coco";
...
enemies.enemyNumber = enemies.enemy + enemyNumber;
</code>```

The toString() is not required when you concatenate a String and a number.

Body:
If I have an object:

var enemies = {};
var enemyNumber = 0;

and then how do I make a new property of that object which is named after a string + a variable, like this (I know this is not valid javascript):

enemyNumber++;
enemies.enemy + enemyNumber.toString() = {};

(enemies.enemy + enemyNumber.toString() is another object)

Body:
Add dynamically properties to your enemies  object :

var enemies = {};
var enemyNumber = 0;
enemies.enemy="Coco";
...
enemies.enemyNumber = enemies.enemy + enemyNumber;

The toString() is not required when you concatenate a String and a number.


答:
If you want to give each object a sequential identifier:

```<code>var enemies = { };
var enemyNumber = 0;

function addEnemy(attributes) {
  attributes.id = enemyNumber;
  enemies[enemyNumber] = attributes;
  enemyNumber++;
}

addEnemy({ name: 'Boss Man' });
</code>```

Remember that you can reference properties of an object with the [...] notation and compute values that way. x.y and x['y'] are equivalent.

Title: How do you name a property of an object with a string plus a variable?

Body:
If you want to give each object a sequential identifier:

var enemies = { };
var enemyNumber = 0;

function addEnemy(attributes) {
  attributes.id = enemyNumber;
  enemies[enemyNumber] = attributes;
  enemyNumber++;
}

addEnemy({ name: 'Boss Man' });

Remember that you can reference properties of an object with the [...] notation and compute values that way. x.y and x['y'] are equivalent.


问:
Nested URLs, controllers and views in Ruby on Rails
What I am trying to do is to nest my pages in Rails for example:

```<code>www.mysite.com/fifa17/ps4
</code>```

This way, once I am on the show.html.erb, I can use use the route to sell my product for specifically that game on that console platform..

At the moment, I have a Console model with has_many :games and a Game model with has_many :consoles, but I can't get the routing and views to work. Do I have just one controller or two?

I have both the Games and Consoles seeded under ActiveRecords by name.
I seem to be able to call one of the actions (i.e. Console.name) but cannot call both the console name and Game name.

答:
A great place to read on this would be in Ruby on Rails Associations Guide and Routing Guide.

What you want to do, is to update your Console and Game associations, to use has_and_belongs_to_many. You can read more on that here

And double check your routing, check this StackOverflow Question for a similar case.

Body:
What I am trying to do is to nest my pages in Rails for example:

www.mysite.com/fifa17/ps4

This way, once I am on the show.html.erb, I can use use the route to sell my product for specifically that game on that console platform..

At the moment, I have a Console model with has_many :games and a Game model with has_many :consoles, but I can't get the routing and views to work. Do I have just one controller or two?

I have both the Games and Consoles seeded under ActiveRecords by name.
I seem to be able to call one of the actions (i.e. Console.name) but cannot call both the console name and Game name.


答:
You can use brackets to create a dynamic property:

var enemies = {};
var enemyNumber = 0;

enemyNumber++;
enemies['enemy' + enemyNumber] = {};

console.log(enemies);```


问:
How to avoid reusability of tableview cell?
When I click on select button at indexpath.row == 0 or any so , only  with respective "session label value" will change but here that will not happen.  it will change the below cell value also i.e. indexpath == 7 or 8 , I think here is reuse of cell so, how I can avoid it.

My code is like below.

1.UITableViewCell Class:

```<code>import UIKit

class DemoTableViewCell: UITableViewCell {

    @IBOutlet weak var mSelectButton: UIButton!
    @IBOutlet weak var mDateLabel: UILabel!
    @IBOutlet weak var mSessionLabel: UILabel!

    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }
}
</code>```

ViewController Class:-

import UIKit

```<code>    class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

        var month_year = ""
        var fromYear = ""
        var toYear = ""
        var monthYearList = ""
        var monthYearListArray = [String]()
        let picker : UIDatePicker = UIDatePicker()

        var from_date = ""
        var to_date = ""

        //
        var selectedTagValue = Int()
        var aSheetValue = ""
        var isFromActionSheet = Bool()
        var isFromFinalClick = Bool()
        var intArray = [Int]()

        @IBOutlet weak var mTableView: UITableView!

        // MARK:- ViewController Life Cycle Methods

        override func viewDidLoad() {
            super.viewDidLoad()
        }

        override func viewWillAppear(_ animated: Bool) {
            self.printDatesBetweenInterval(self.dateFromString("2017-07-01"), self.dateFromString("2017-07-12"))
        }

        //MARK:- UITableViewDataSource and Delegate Methods

        func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

            return monthYearListArray.count
        }

        func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

            let cell = tableView.dequeueReusableCell(withIdentifier: "DemoTableViewCell")! as! DemoTableViewCell

            cell.mDateLabel.text = monthYearListArray[indexPath.row]

            if isFromActionSheet{

                if indexPath.row == selectedTagValue{
                    cell.mSessionLabel.text = aSheetValue
                    isFromActionSheet = false
                }
            }

            cell.mSelectButton.tag = indexPath.row
            print("cell.mButtonOutlet.tag: \(cell.mSelectButton.tag)")

            cell.mSelectButton.addTarget(self, action: #selector(ViewController.actionOnSelectButtonClick(_:)), for: .touchUpInside)

            if isFromFinalClick{
                if cell.mSessionLabel.text == "Full Day"{
                    self.intArray.append(1)

                }else if cell.mSessionLabel.text == "First Half"{
                    self.intArray.append(2)
                }else{
                    self.intArray.append(3)
                }
            }

            return cell
        }

        // MARK:- IBAction Methods

        func actionOnSelectButtonClick(_ sender: UIButton)  {
            let mButton : UIButton = sender
            selectedTagValue = mButton.tag
            print("selectedTagValue: \(selectedTagValue)")
            isFromActionSheet = true
            openActionSheet()
        }

        // Submit Button

        @IBAction func actionOnSubmitButton(_ sender: Any) {
            isFromFinalClick = true
            mTableView.reloadData()
            print("intArray list: \(intArray)")

        }

        // MARK:- Instance Methods

        func openActionSheet()  {

            // 1
            let optionMenu = UIAlertController(title: nil, message: "Select Session", preferredStyle: .actionSheet)

            // 2
            let fullDayAction = UIAlertAction(title: "Full Day", style: .default, handler: {
                (alert: UIAlertAction!) -> Void in
                print("Full Day")
                self.aSheetValue = "Full Day"
                self.mTableView.reloadData()
            })

            let firstHalfAction = UIAlertAction(title: "First Half", style: .default, handler: {
                (alert: UIAlertAction!) -> Void in
                print("First Half")
                self.aSheetValue = "First Half"
                self.mTableView.reloadData()

            })
            let secondHalfAction = UIAlertAction(title: "Second Half", style: .default, handler: {
                (alert: UIAlertAction!) -> Void in
                print("Second Half")
                self.aSheetValue = "Second Half"
                self.mTableView.reloadData()

            })

            //
            let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: {
                (alert: UIAlertAction!) -> Void in
                print("Cancelled")
            })

            // 4
            optionMenu.addAction(fullDayAction)
            optionMenu.addAction(firstHalfAction)
            optionMenu.addAction(secondHalfAction)
            optionMenu.addAction(cancelAction)

            // 5
            self.present(optionMenu, animated: true, completion: nil)
        }

        // MARK:- Date_List Method

        func printDatesBetweenInterval(_ startDate: Date, _ endDate: Date) {
            var startDate = startDate
            let calendar = Calendar.current

            let fmt = DateFormatter()
            fmt.dateFormat = "yyyy-MM-dd"

            while startDate <= endDate {
                print(fmt.string(from: startDate))
                self.monthYearList = fmt.string(from: startDate)
                print("self.monthYearList: \(self.monthYearList)")
                fmt.dateFormat = "yyyy-MM-dd"
                monthYearListArray.append(fmt.string(from: startDate))
                startDate = calendar.date(byAdding: .day, value: 1, to: startDate)!
            }

            print("monthYearListArray: \(monthYearListArray)")
            mTableView.reloadData()
        }

        func dateFromString(_ dateString: String) -> Date {
            let dateFormatter = DateFormatter()
            dateFormatter.dateFormat = "yyyy-MM-dd"

            return dateFormatter.date(from: dateString)!
        }

    }
</code>```

答:
The correct thing to do is that you need to always set these UI element in cellForRow.

The reason is that UITableView is not preparing table view cells for display until the user is trying to scroll to that position(namely when user is trying to see that cell). So the idea of reusing cells is to keep some cell template in reused location so that in the next time, your phone does not need to create everything from scratch again. The only thing needed to do is to set the cell to correct state again. This will also make the scroll more smooth.

By setting UI element, I mean that you have to set value to your UI element on your cell every time when your cellForRow method is called. Look at this piece of your code

```<code>if isFromActionSheet{//What if this if is not called? Your cell.mSessionLabel will not get set
    if indexPath.row == selectedTagValue{//What if this if is not called? Your cell.mSessionLabel will not get set
        cell.mSessionLabel.text = aSheetValue
        isFromActionSheet = false
    }
}
</code>```

If either of the two if statement is not true, then your mSessionLabel on your cell will not get new value, and may display some other value that is from the template cell. So you have to create two else statements add set mSessionLabel in the two else statement.

Body:
When I click on select button at indexpath.row == 0 or any so , only  with respective "session label value" will change but here that will not happen.  it will change the below cell value also i.e. indexpath == 7 or 8 , I think here is reuse of cell so, how I can avoid it.

My code is like below.

1.UITableViewCell Class:

import UIKit

class DemoTableViewCell: UITableViewCell {

    @IBOutlet weak var mSelectButton: UIButton!
    @IBOutlet weak var mDateLabel: UILabel!
    @IBOutlet weak var mSessionLabel: UILabel!

    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }
}

ViewController Class:-

import UIKit

    class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

        var month_year = ""
        var fromYear = ""
        var toYear = ""
        var monthYearList = ""
        var monthYearListArray = [String]()
        let picker : UIDatePicker = UIDatePicker()

        var from_date = ""
        var to_date = ""

        //
        var selectedTagValue = Int()
        var aSheetValue = ""
        var isFromActionSheet = Bool()
        var isFromFinalClick = Bool()
        var intArray = [Int]()

        @IBOutlet weak var mTableView: UITableView!

        // MARK:- ViewController Life Cycle Methods

        override func viewDidLoad() {
            super.viewDidLoad()
        }

        override func viewWillAppear(_ animated: Bool) {
            self.printDatesBetweenInterval(self.dateFromString("2017-07-01"), self.dateFromString("2017-07-12"))
        }

        //MARK:- UITableViewDataSource and Delegate Methods

        func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

            return monthYearListArray.count
        }

        func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

            let cell = tableView.dequeueReusableCell(withIdentifier: "DemoTableViewCell")! as! DemoTableViewCell

            cell.mDateLabel.text = monthYearListArray[indexPath.row]

            if isFromActionSheet{

                if indexPath.row == selectedTagValue{
                    cell.mSessionLabel.text = aSheetValue
                    isFromActionSheet = false
                }
            }

            cell.mSelectButton.tag = indexPath.row
            print("cell.mButtonOutlet.tag: \(cell.mSelectButton.tag)")

            cell.mSelectButton.addTarget(self, action: #selector(ViewController.actionOnSelectButtonClick(_:)), for: .touchUpInside)

            if isFromFinalClick{
                if cell.mSessionLabel.text == "Full Day"{
                    self.intArray.append(1)

                }else if cell.mSessionLabel.text == "First Half"{
                    self.intArray.append(2)
                }else{
                    self.intArray.append(3)
                }
            }

            return cell
        }

        // MARK:- IBAction Methods

        func actionOnSelectButtonClick(_ sender: UIButton)  {
            let mButton : UIButton = sender
            selectedTagValue = mButton.tag
            print("selectedTagValue: \(selectedTagValue)")
            isFromActionSheet = true
            openActionSheet()
        }

        // Submit Button

        @IBAction func actionOnSubmitButton(_ sender: Any) {
            isFromFinalClick = true
            mTableView.reloadData()
            print("intArray list: \(intArray)")

        }

        // MARK:- Instance Methods

        func openActionSheet()  {

            // 1
            let optionMenu = UIAlertController(title: nil, message: "Select Session", preferredStyle: .actionSheet)

            // 2
            let fullDayAction = UIAlertAction(title: "Full Day", style: .default, handler: {
                (alert: UIAlertAction!) -> Void in
                print("Full Day")
                self.aSheetValue = "Full Day"
                self.mTableView.reloadData()
            })

            let firstHalfAction = UIAlertAction(title: "First Half", style: .default, handler: {
                (alert: UIAlertAction!) -> Void in
                print("First Half")
                self.aSheetValue = "First Half"
                self.mTableView.reloadData()

            })
            let secondHalfAction = UIAlertAction(title: "Second Half", style: .default, handler: {
                (alert: UIAlertAction!) -> Void in
                print("Second Half")
                self.aSheetValue = "Second Half"
                self.mTableView.reloadData()

            })

            //
            let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: {
                (alert: UIAlertAction!) -> Void in
                print("Cancelled")
            })

            // 4
            optionMenu.addAction(fullDayAction)
            optionMenu.addAction(firstHalfAction)
            optionMenu.addAction(secondHalfAction)
            optionMenu.addAction(cancelAction)

            // 5
            self.present(optionMenu, animated: true, completion: nil)
        }

        // MARK:- Date_List Method

        func printDatesBetweenInterval(_ startDate: Date, _ endDate: Date) {
            var startDate = startDate
            let calendar = Calendar.current

            let fmt = DateFormatter()
            fmt.dateFormat = "yyyy-MM-dd"

            while startDate <= endDate {
                print(fmt.string(from: startDate))
                self.monthYearList = fmt.string(from: startDate)
                print("self.monthYearList: \(self.monthYearList)")
                fmt.dateFormat = "yyyy-MM-dd"
                monthYearListArray.append(fmt.string(from: startDate))
                startDate = calendar.date(byAdding: .day, value: 1, to: startDate)!
            }

            print("monthYearListArray: \(monthYearListArray)")
            mTableView.reloadData()
        }

        func dateFromString(_ dateString: String) -> Date {
            let dateFormatter = DateFormatter()
            dateFormatter.dateFormat = "yyyy-MM-dd"

            return dateFormatter.date(from: dateString)!
        }

    }

Body:
The correct thing to do is that you need to always set these UI element in cellForRow.

The reason is that UITableView is not preparing table view cells for display until the user is trying to scroll to that position(namely when user is trying to see that cell). So the idea of reusing cells is to keep some cell template in reused location so that in the next time, your phone does not need to create everything from scratch again. The only thing needed to do is to set the cell to correct state again. This will also make the scroll more smooth.

By setting UI element, I mean that you have to set value to your UI element on your cell every time when your cellForRow method is called. Look at this piece of your code

if isFromActionSheet{//What if this if is not called? Your cell.mSessionLabel will not get set
    if indexPath.row == selectedTagValue{//What if this if is not called? Your cell.mSessionLabel will not get set
        cell.mSessionLabel.text = aSheetValue
        isFromActionSheet = false
    }
}

If either of the two if statement is not true, then your mSessionLabel on your cell will not get new value, and may display some other value that is from the template cell. So you have to create two else statements add set mSessionLabel in the two else statement.


问:
java.lang.NoClassDefFoundError On a google app engine & maven
I'm building a google app engine website with server currently having this error, i googled it and found several fixes but none of them worked so I'm thinking its a different problem

I'm also using maven and a rest server

```<code>WARNING: Error starting handlers
java.lang.NoClassDefFoundError: org/glassfish/jersey/server/spi/Container
    at java.lang.ClassLoader.defineClass1(Native Method)
    at java.lang.ClassLoader.defineClass(ClassLoader.java:800)
    at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
    at java.net.URLClassLoader.defineClass(URLClassLoader.java:449)
    at java.net.URLClassLoader.access$100(URLClassLoader.java:71)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:361)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
    at com.google.appengine.tools.development.IsolatedAppClassLoader.loadClass(IsolatedAppClassLoader.java:195)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
    at org.mortbay.util.Loader.loadClass(Loader.java:91)
    at org.mortbay.util.Loader.loadClass(Loader.java:71)
    at org.mortbay.jetty.servlet.Holder.doStart(Holder.java:73)
    at org.mortbay.jetty.servlet.ServletHolder.doStart(ServletHolder.java:242)
    at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:50)
    at org.mortbay.jetty.servlet.ServletHandler.initialize(ServletHandler.java:685)
    at org.mortbay.jetty.servlet.Context.startContext(Context.java:140)
    at org.mortbay.jetty.webapp.WebAppContext.startContext(WebAppContext.java:1250)
    at org.mortbay.jetty.handler.ContextHandler.doStart(ContextHandler.java:517)
    at org.mortbay.jetty.webapp.WebAppContext.doStart(WebAppContext.java:467)
    at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:50)
    at org.mortbay.jetty.handler.HandlerWrapper.doStart(HandlerWrapper.java:130)
    at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:50)
    at org.mortbay.jetty.handler.HandlerWrapper.doStart(HandlerWrapper.java:130)
    at org.mortbay.jetty.Server.doStart(Server.java:224)
    at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:50)
    at com.google.appengine.tools.development.JettyContainerService.startContainer(JettyContainerService.java:268)
    at com.google.appengine.tools.development.AbstractContainerService.startup(AbstractContainerService.java:284)
    at com.google.appengine.tools.development.AutomaticInstanceHolder.startUp(AutomaticInstanceHolder.java:26)
    at com.google.appengine.tools.development.AbstractModule.startup(AbstractModule.java:87)
    at com.google.appengine.tools.development.Modules.startup(Modules.java:105)
    at com.google.appengine.tools.development.DevAppServerImpl.doStart(DevAppServerImpl.java:262)
    at com.google.appengine.tools.development.DevAppServerImpl.access$000(DevAppServerImpl.java:45)
    at com.google.appengine.tools.development.DevAppServerImpl$1.run(DevAppServerImpl.java:217)
    at com.google.appengine.tools.development.DevAppServerImpl$1.run(DevAppServerImpl.java:215)
    at java.security.AccessController.doPrivileged(Native Method)
    at com.google.appengine.tools.development.DevAppServerImpl.start(DevAppServerImpl.java:215)
    at com.google.appengine.tools.development.DevAppServerMain$StartAction.apply(DevAppServerMain.java:349)
    at com.google.appengine.tools.util.Parser$ParseResult.applyArgs(Parser.java:47)
    at com.google.appengine.tools.development.DevAppServerMain.run(DevAppServerMain.java:222)
    at com.google.appengine.tools.development.DevAppServerMain.main(DevAppServerMain.java:213)
Caused by: java.lang.ClassNotFoundException: org.glassfish.jersey.server.spi.Container
    at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
    at com.google.appengine.tools.development.IsolatedAppClassLoader.loadClass(IsolatedAppClassLoader.java:195)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
    ... 43 more
</code>```

pom.xml:

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

    <modelVersion>4.0.0</modelVersion>
    <packaging>war</packaging>
    <version>0.0.1-ALPHA</version>

    <groupId>pt.unl.fct.di.nextech.fixtr</groupId>
    <artifactId>fixtr</artifactId>

    <properties>
        <app.id>fixtr-nextech</app.id>
        <app.version>1</app.version>
        <appengine.sdk.version>1.9.51</appengine.sdk.version>
        <appengine.version>${appengine.sdk.version}</appengine.version>
        <gcloud.plugin.version>2.0.9.133.v201611104</gcloud.plugin.version>

        <jersey.version>2.25.1</jersey.version>

        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <maven.compiler.source>1.7</maven.compiler.source>
        <maven.compiler.target>1.7</maven.compiler.target>
        <maven.compiler.showDeprecation>true</maven.compiler.showDeprecation>
        <archiveClasses>true</archiveClasses>
    </properties>

    <prerequisites>
        <maven>3.3.9</maven>
    </prerequisites>

    <dependencies>
        <!-- Compile/runtime dependencies -->
        <dependency>
            <groupId>com.google.appengine</groupId>
            <artifactId>appengine-api-1.0-sdk</artifactId>
            <version>${appengine.version}</version>
        </dependency>
        <dependency>
            <groupId>com.google.appengine.tools</groupId>
            <artifactId>appengine-gcs-client</artifactId>
            <version>RELEASE</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>jstl</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
        <dependency>
            <groupId>org.glassfish.jersey.containers</groupId>
            <artifactId>jersey-container-servlet</artifactId>
            <version>${jersey.version}</version>
        </dependency>
        <dependency>
            <groupId>org.glassfish.jersey.core</groupId>
            <artifactId>jersey-server</artifactId>
            <version>${jersey.version}</version>
        </dependency>
        <dependency>
            <groupId>org.glassfish.jersey.media</groupId>
            <artifactId>jersey-media-json-jackson</artifactId>
            <version>${jersey.version}</version>
        </dependency>
        <dependency>
            <groupId>org.glassfish.jersey.media</groupId>
            <artifactId>jersey-media-multipart</artifactId>
            <version>${jersey.version}</version>
        </dependency>
        <dependency>
            <groupId>org.glassfish.jersey.media</groupId>
            <artifactId>jersey-media-jaxb</artifactId>
            <version>${jersey.version}</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>2.9.0.pr2</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.9.0.pr2</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <version>2.9.0.pr2</version>
        </dependency>
        <dependency>
            <groupId>commons-codec</groupId>
            <artifactId>commons-codec</artifactId>
            <version>1.10</version>
        </dependency>
        <dependency>
            <groupId>javax.ws.rs</groupId>
            <artifactId>javax.ws.rs-api</artifactId>
            <version>2.0.1</version>
        </dependency>

        <!-- Test Dependencies -->
        <dependency>
            <groupId>com.google.appengine</groupId>
            <artifactId>appengine-testing</artifactId>
            <version>${appengine.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.google.appengine</groupId>
            <artifactId>appengine-api-stubs</artifactId>
            <version>${appengine.version}</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <sourceDirectory>src</sourceDirectory>

        <resources>
            <resource>
                <directory>src</directory>
                <excludes>
                    <exclude>**/*.java</exclude>
                </excludes>
            </resource>
        </resources>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.5.1</version>
                <configuration>
                    <source>1.7</source>
                    <target>1.7</target>
                </configuration>
            </plugin>
            <plugin>
                <artifactId>maven-war-plugin</artifactId>
                <version>3.0.0</version>
                <configuration>
                    <warSourceDirectory>WebContent</warSourceDirectory>
                    <outputDirectory>war</outputDirectory>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>
</code>```

web.xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
    version="3.0">

    <servlet>
        <servlet-name>fixtr-servlet</servlet-name>
        <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
        <init-param>
            <param-name>jersey.config.server.provider.packages</param-name>
            <param-value>pt.unl.fct.di.nextech.fixtr.service</param-value>
        </init-param>
        <init-param>
            <param-name>jersey.config.server.provider.scanning.recursive</param-name>
            <param-value>false</param-value>
        </init-param>
    </servlet>

    <servlet-mapping>
        <servlet-name>fixtr-servlet</servlet-name>
        <url-pattern>/rest/v1/*</url-pattern>
    </servlet-mapping>

    <session-config>
        <session-timeout>60</session-timeout>
    </session-config>

    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
    </welcome-file-list>

    <error-page>
        <error-code>404</error-code>
        <location>/error.html</location>
    </error-page>
    <error-page>
        <error-code>500</error-code>
        <location>/error.html</location>
    </error-page>

</web-app>
</code>```

答: Ok I fixed the problem, it was probably a corrupted jar, i deleted all of the jars and downloaded them with maven again and it worked fine.</p>

Body:
I'm building a google app engine website with server currently having this error, i googled it and found several fixes but none of them worked so I'm thinking its a different problem

I'm also using maven and a rest server

WARNING: Error starting handlers
java.lang.NoClassDefFoundError: org/glassfish/jersey/server/spi/Container
    at java.lang.ClassLoader.defineClass1(Native Method)
    at java.lang.ClassLoader.defineClass(ClassLoader.java:800)
    at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
    at java.net.URLClassLoader.defineClass(URLClassLoader.java:449)
    at java.net.URLClassLoader.access$100(URLClassLoader.java:71)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:361)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
    at com.google.appengine.tools.development.IsolatedAppClassLoader.loadClass(IsolatedAppClassLoader.java:195)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
    at org.mortbay.util.Loader.loadClass(Loader.java:91)
    at org.mortbay.util.Loader.loadClass(Loader.java:71)
    at org.mortbay.jetty.servlet.Holder.doStart(Holder.java:73)
    at org.mortbay.jetty.servlet.ServletHolder.doStart(ServletHolder.java:242)
    at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:50)
    at org.mortbay.jetty.servlet.ServletHandler.initialize(ServletHandler.java:685)
    at org.mortbay.jetty.servlet.Context.startContext(Context.java:140)
    at org.mortbay.jetty.webapp.WebAppContext.startContext(WebAppContext.java:1250)
    at org.mortbay.jetty.handler.ContextHandler.doStart(ContextHandler.java:517)
    at org.mortbay.jetty.webapp.WebAppContext.doStart(WebAppContext.java:467)
    at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:50)
    at org.mortbay.jetty.handler.HandlerWrapper.doStart(HandlerWrapper.java:130)
    at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:50)
    at org.mortbay.jetty.handler.HandlerWrapper.doStart(HandlerWrapper.java:130)
    at org.mortbay.jetty.Server.doStart(Server.java:224)
    at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:50)
    at com.google.appengine.tools.development.JettyContainerService.startContainer(JettyContainerService.java:268)
    at com.google.appengine.tools.development.AbstractContainerService.startup(AbstractContainerService.java:284)
    at com.google.appengine.tools.development.AutomaticInstanceHolder.startUp(AutomaticInstanceHolder.java:26)
    at com.google.appengine.tools.development.AbstractModule.startup(AbstractModule.java:87)
    at com.google.appengine.tools.development.Modules.startup(Modules.java:105)
    at com.google.appengine.tools.development.DevAppServerImpl.doStart(DevAppServerImpl.java:262)
    at com.google.appengine.tools.development.DevAppServerImpl.access$000(DevAppServerImpl.java:45)
    at com.google.appengine.tools.development.DevAppServerImpl$1.run(DevAppServerImpl.java:217)
    at com.google.appengine.tools.development.DevAppServerImpl$1.run(DevAppServerImpl.java:215)
    at java.security.AccessController.doPrivileged(Native Method)
    at com.google.appengine.tools.development.DevAppServerImpl.start(DevAppServerImpl.java:215)
    at com.google.appengine.tools.development.DevAppServerMain$StartAction.apply(DevAppServerMain.java:349)
    at com.google.appengine.tools.util.Parser$ParseResult.applyArgs(Parser.java:47)
    at com.google.appengine.tools.development.DevAppServerMain.run(DevAppServerMain.java:222)
    at com.google.appengine.tools.development.DevAppServerMain.main(DevAppServerMain.java:213)
Caused by: java.lang.ClassNotFoundException: org.glassfish.jersey.server.spi.Container
    at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
    at com.google.appengine.tools.development.IsolatedAppClassLoader.loadClass(IsolatedAppClassLoader.java:195)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
    ... 43 more

pom.xml:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

    <modelVersion>4.0.0</modelVersion>
    <packaging>war</packaging>
    <version>0.0.1-ALPHA</version>

    <groupId>pt.unl.fct.di.nextech.fixtr</groupId>
    <artifactId>fixtr</artifactId>

    <properties>
        <app.id>fixtr-nextech</app.id>
        <app.version>1</app.version>
        <appengine.sdk.version>1.9.51</appengine.sdk.version>
        <appengine.version>${appengine.sdk.version}</appengine.version>
        <gcloud.plugin.version>2.0.9.133.v201611104</gcloud.plugin.version>

        <jersey.version>2.25.1</jersey.version>

        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <maven.compiler.source>1.7</maven.compiler.source>
        <maven.compiler.target>1.7</maven.compiler.target>
        <maven.compiler.showDeprecation>true</maven.compiler.showDeprecation>
        <archiveClasses>true</archiveClasses>
    </properties>

    <prerequisites>
        <maven>3.3.9</maven>
    </prerequisites>

    <dependencies>

        <dependency>
            <groupId>com.google.appengine</groupId>
            <artifactId>appengine-api-1.0-sdk</artifactId>
            <version>${appengine.version}</version>
        </dependency>
        <dependency>
            <groupId>com.google.appengine.tools</groupId>
            <artifactId>appengine-gcs-client</artifactId>
            <version>RELEASE</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>jstl</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
        <dependency>
            <groupId>org.glassfish.jersey.containers</groupId>
            <artifactId>jersey-container-servlet</artifactId>
            <version>${jersey.version}</version>
        </dependency>
        <dependency>
            <groupId>org.glassfish.jersey.core</groupId>
            <artifactId>jersey-server</artifactId>
            <version>${jersey.version}</version>
        </dependency>
        <dependency>
            <groupId>org.glassfish.jersey.media</groupId>
            <artifactId>jersey-media-json-jackson</artifactId>
            <version>${jersey.version}</version>
        </dependency>
        <dependency>
            <groupId>org.glassfish.jersey.media</groupId>
            <artifactId>jersey-media-multipart</artifactId>
            <version>${jersey.version}</version>
        </dependency>
        <dependency>
            <groupId>org.glassfish.jersey.media</groupId>
            <artifactId>jersey-media-jaxb</artifactId>
            <version>${jersey.version}</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>2.9.0.pr2</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.9.0.pr2</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <version>2.9.0.pr2</version>
        </dependency>
        <dependency>
            <groupId>commons-codec</groupId>
            <artifactId>commons-codec</artifactId>
            <version>1.10</version>
        </dependency>
        <dependency>
            <groupId>javax.ws.rs</groupId>
            <artifactId>javax.ws.rs-api</artifactId>
            <version>2.0.1</version>
        </dependency>

        <dependency>
            <groupId>com.google.appengine</groupId>
            <artifactId>appengine-testing</artifactId>
            <version>${appengine.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.google.appengine</groupId>
            <artifactId>appengine-api-stubs</artifactId>
            <version>${appengine.version}</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <sourceDirectory>src</sourceDirectory>

        <resources>
            <resource>
                <directory>src</directory>
                <excludes>
                    <exclude>**/*.java</exclude>
                </excludes>
            </resource>
        </resources>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.5.1</version>
                <configuration>
                    <source>1.7</source>
                    <target>1.7</target>
                </configuration>
            </plugin>
            <plugin>
                <artifactId>maven-war-plugin</artifactId>
                <version>3.0.0</version>
                <configuration>
                    <warSourceDirectory>WebContent</warSourceDirectory>
                    <outputDirectory>war</outputDirectory>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

web.xml:

<?xml version="1.0" encoding="utf-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
    version="3.0">

    <servlet>
        <servlet-name>fixtr-servlet</servlet-name>
        <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
        <init-param>
            <param-name>jersey.config.server.provider.packages</param-name>
            <param-value>pt.unl.fct.di.nextech.fixtr.service</param-value>
        </init-param>
        <init-param>
            <param-name>jersey.config.server.provider.scanning.recursive</param-name>
            <param-value>false</param-value>
        </init-param>
    </servlet>

    <servlet-mapping>
        <servlet-name>fixtr-servlet</servlet-name>
        <url-pattern>/rest/v1/*</url-pattern>
    </servlet-mapping>

    <session-config>
        <session-timeout>60</session-timeout>
    </session-config>

    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
    </welcome-file-list>

    <error-page>
        <error-code>404</error-code>
        <location>/error.html</location>
    </error-page>
    <error-page>
        <error-code>500</error-code>
        <location>/error.html</location>
    </error-page>

</web-app>