问:
Strange django admin error
I've just fired my project clean on new machine and when entering admin I got the following error, which indicates some syntax error in forms.py ( I believe admin's forms). Anyone seen anything like this before ? :

```<code>Environment:

Request Method: GET
Request URL: http://djtest.test.rte.ie/access/admin/ Django Version: 1.1.2
Python Version: 2.4.3
Installed Applications:
['django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.admin', 'tagging', 'rte_utils.filetransfers', 'rte_utils.syncr', 'rte_utils.twitter', 'rte_utils.youtube', 'rte_utils.flickr', 'rte_site', 'rte_site.static_pages', 'rte_site.artifact', 'rte_site.candid', 'rte_site.events', 'rte_site.playforward', 'rte_site.setspy', 'debug_toolbar'] Installed Middleware:
('django.middleware.cache.UpdateCacheMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.middleware.common.CommonMiddleware', 'rte_site.middleware.FlatpageFallbackMiddleware', 'django.middleware.cache.FetchFromCacheMiddleware')

Template error:
In template /usr/lib/python2.4/site-packages/django/contrib/admin/templates/admin/base.html, error at line 30
Caught SyntaxError while rendering: invalid syntax (forms.py, line 227) 20 :

21 :

22 :

23 : {% block branding %}{% endblock %}

24 :

25 : {% if user.is_authenticated and user.is_staff %}

26 :

27 : {% trans 'Welcome,' %}

28 : {% filter force_escape %}{% firstof user.first_name user.username %}{% endfilter %}.

29 : {% block userlinks %}

30 : {% url django-admindocs-docroot as docsroot %}

31 : {% if docsroot %}

32 : {% trans 'Documentation' %} /

33 : {% endif %}

34 : {% url admin:password_change as password_change_url %}

35 : {% if password_change_url %}

36 :

37 : {% else %}

38 :

39 : {% endif %}

40 : {% trans 'Change password' %} /

Traceback:
File "/usr/lib/python2.4/site-packages/django/core/handlers/base.py" in get_response
99. response = callback(request, callback_args, **callback_kwargs) File "/usr/lib/python2.4/site-packages/django/contrib/admin/sites.py" in root
480. return self.index(request) File "/usr/lib/python2.4/site-packages/django/views/decorators/cache.py" in _wrapped_view_func
44. response = view_func(request, args, kwargs) File "/usr/lib/python2.4/site-packages/django/contrib/admin/sites.py" in index
377. context_instance=context_instance File "/usr/lib/python2.4/site-packages/django/shortcuts/init.py" in render_to_response
20. return HttpResponse(loader.render_to_string(*args, kwargs), *httpresponse_kwargs) File "/usr/lib/python2.4/site-packages/django/template/loader.py" in render_to_string
108. return t.render(context_instance) File "/usr/lib/python2.4/site-packages/django/template/init.py" in render
165. return self.nodelist.render(context) File "/usr/lib/python2.4/site-packages/django/template/init.py" in render
784. bits.append(self.render_node(node, context)) File "/usr/lib/python2.4/site-packages/django/template/debug.py" in render_node
71. result = node.render(context) File "/usr/lib/python2.4/site-packages/django/template/loader_tags.py" in render
97. return compiled_parent.render(context) File "/usr/lib/python2.4/site-packages/django/template/init.py" in render
165. return self.nodelist.render(context) File "/usr/lib/python2.4/site-packages/django/template/init.py" in render
784. bits.append(self.render_node(node, context)) File "/usr/lib/python2.4/site-packages/django/template/debug.py" in render_node
71. result = node.render(context) File "/usr/lib/python2.4/site-packages/django/template/loader_tags.py" in render
97. return compiled_parent.render(context) File "/usr/lib/python2.4/site-packages/django/template/init.py" in render
165. return self.nodelist.render(context) File "/usr/lib/python2.4/site-packages/django/template/init.py" in render
784. bits.append(self.render_node(node, context)) File "/usr/lib/python2.4/site-packages/django/template/debug.py" in render_node
71. result = node.render(context) File "/usr/lib/python2.4/site-packages/django/template/defaulttags.py" in render
240. return self.nodelist_true.render(context) File "/usr/lib/python2.4/site-packages/django/template/init.py" in render
784. bits.append(self.render_node(node, context)) File "/usr/lib/python2.4/site-packages/django/template/debug.py" in render_node
71. result = node.render(context) File "/usr/lib/python2.4/site-packages/django/template/defaulttags.py" in render
250. return self.nodelist_true.render(context) File "/usr/lib/python2.4/site-packages/django/template/init.py" in render
784. bits.append(self.render_node(node, context)) File "/usr/lib/python2.4/site-packages/django/template/debug.py" in render_node
71. result = node.render(context) File "/usr/lib/python2.4/site-packages/django/template/loader_tags.py" in render
24. result = self.nodelist.render(context) File "/usr/lib/python2.4/site-packages/django/template/init.py" in render
784. bits.append(self.render_node(node, context)) File "/usr/lib/python2.4/site-packages/django/template/debug.py" in render_node
71. result = node.render(context) File "/usr/lib/python2.4/site-packages/django/template/defaulttags.py" in render
367. url = reverse(self.view_name, args=args, kwargs=kwargs, current_app=context.current_app) File "/usr/lib/python2.4/site-packages/django/core/urlresolvers.py" in reverse
357. return iri_to_uri(u'%s%s' % (prefix, resolver.reverse(view, File "/usr/lib/python2.4/site-packages/django/core/urlresolvers.py" in reverse
279. possibilities = self.reverse_dict.getlist(lookup_view) File "/usr/lib/python2.4/site-packages/django/core/urlresolvers.py" in get_reverse_dict
199. self.populate() File "/usr/lib/python2.4/site-packages/django/core/urlresolvers.py" in populate
179. for name in pattern.reverse_dict: File "/usr/lib/python2.4/site-packages/django/core/urlresolvers.py" in get_reverse_dict
199. self.populate() File "/usr/lib/python2.4/site-packages/django/core/urlresolvers.py" in populate
191. lookups.appendlist(pattern.callback, (bits, p_pattern)) File "/usr/lib/python2.4/site-packages/django/core/urlresolvers.py" in get_callback
135. self.callback = get_callable(self._callback_str) File "/usr/lib/python2.4/site-packages/django/utils/functional.py" in wrapper
130. result = func(args) File "/usr/lib/python2.4/site-packages/django/core/urlresolvers.py" in get_callable
62. lookup_view = getattr(import_module(mod_name), func_name) File "/usr/lib/python2.4/site-packages/django/utils/importlib.py" in import_module
35. import(name) File "/usr/lib/python2.4/site-packages/allaccess/rte_site/management/views.py" in ?
38. from forms import AdminForm

Exception Type: TemplateSyntaxError at /admin/
Exception Value: Caught SyntaxError while rendering: invalid syntax (forms.py, line 227)
</code>```

If the forms.py file mentioned in traceback is the one I think it is, then this is the line causing problems:

```<code>def __init__(self, *args, **kwargs):
    self.father = kwargs.pop('parent', None) if kwargs else None
</code>```

anything wrong here for python 2.4 ?

答:
No, the error is in "/usr/lib/python2.4/site-packages/allaccess/rte_site/management/views.py", which is a package you have installed yourself.

The reason it comes up where it does is because Django needs to import all views in order to reverse-lookup URLs, and importing this view gives a syntax error.

Edited after post update Yes, that ternary if syntax - y if x else z - is only for Python 2.5 and above. For lower versions, you'd need to rewrite it as a standard if statement block.

Title: Strange django admin error

Body:
I've just fired my project clean on new machine and when entering admin I got the following error, which indicates some syntax error in forms.py ( I believe admin's forms). Anyone seen anything like this before ? :

Environment:

Request Method: GET
Request URL: http://djtest.test.rte.ie/access/admin/ Django Version: 1.1.2
Python Version: 2.4.3
Installed Applications:
['django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.admin', 'tagging', 'rte_utils.filetransfers', 'rte_utils.syncr', 'rte_utils.twitter', 'rte_utils.youtube', 'rte_utils.flickr', 'rte_site', 'rte_site.static_pages', 'rte_site.artifact', 'rte_site.candid', 'rte_site.events', 'rte_site.playforward', 'rte_site.setspy', 'debug_toolbar'] Installed Middleware:
('django.middleware.cache.UpdateCacheMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.middleware.common.CommonMiddleware', 'rte_site.middleware.FlatpageFallbackMiddleware', 'django.middleware.cache.FetchFromCacheMiddleware')

Template error:
In template /usr/lib/python2.4/site-packages/django/contrib/admin/templates/admin/base.html, error at line 30
Caught SyntaxError while rendering: invalid syntax (forms.py, line 227) 20 :

21 :

22 :

23 : {% block branding %}{% endblock %}

24 :

25 : {% if user.is_authenticated and user.is_staff %}

26 :

27 : {% trans 'Welcome,' %}

28 : {% filter force_escape %}{% firstof user.first_name user.username %}{% endfilter %}.

29 : {% block userlinks %}

30 : {% url django-admindocs-docroot as docsroot %}

31 : {% if docsroot %}

32 : {% trans 'Documentation' %} /

33 : {% endif %}

34 : {% url admin:password_change as password_change_url %}

35 : {% if password_change_url %}

36 :

37 : {% else %}

38 :

39 : {% endif %}

40 : {% trans 'Change password' %} /

Traceback:
File "/usr/lib/python2.4/site-packages/django/core/handlers/base.py" in get_response
99. response = callback(request, callback_args, **callback_kwargs) File "/usr/lib/python2.4/site-packages/django/contrib/admin/sites.py" in root
480. return self.index(request) File "/usr/lib/python2.4/site-packages/django/views/decorators/cache.py" in _wrapped_view_func
44. response = view_func(request, args, kwargs) File "/usr/lib/python2.4/site-packages/django/contrib/admin/sites.py" in index
377. context_instance=context_instance File "/usr/lib/python2.4/site-packages/django/shortcuts/init.py" in render_to_response
20. return HttpResponse(loader.render_to_string(*args, kwargs), *httpresponse_kwargs) File "/usr/lib/python2.4/site-packages/django/template/loader.py" in render_to_string
108. return t.render(context_instance) File "/usr/lib/python2.4/site-packages/django/template/init.py" in render
165. return self.nodelist.render(context) File "/usr/lib/python2.4/site-packages/django/template/init.py" in render
784. bits.append(self.render_node(node, context)) File "/usr/lib/python2.4/site-packages/django/template/debug.py" in render_node
71. result = node.render(context) File "/usr/lib/python2.4/site-packages/django/template/loader_tags.py" in render
97. return compiled_parent.render(context) File "/usr/lib/python2.4/site-packages/django/template/init.py" in render
165. return self.nodelist.render(context) File "/usr/lib/python2.4/site-packages/django/template/init.py" in render
784. bits.append(self.render_node(node, context)) File "/usr/lib/python2.4/site-packages/django/template/debug.py" in render_node
71. result = node.render(context) File "/usr/lib/python2.4/site-packages/django/template/loader_tags.py" in render
97. return compiled_parent.render(context) File "/usr/lib/python2.4/site-packages/django/template/init.py" in render
165. return self.nodelist.render(context) File "/usr/lib/python2.4/site-packages/django/template/init.py" in render
784. bits.append(self.render_node(node, context)) File "/usr/lib/python2.4/site-packages/django/template/debug.py" in render_node
71. result = node.render(context) File "/usr/lib/python2.4/site-packages/django/template/defaulttags.py" in render
240. return self.nodelist_true.render(context) File "/usr/lib/python2.4/site-packages/django/template/init.py" in render
784. bits.append(self.render_node(node, context)) File "/usr/lib/python2.4/site-packages/django/template/debug.py" in render_node
71. result = node.render(context) File "/usr/lib/python2.4/site-packages/django/template/defaulttags.py" in render
250. return self.nodelist_true.render(context) File "/usr/lib/python2.4/site-packages/django/template/init.py" in render
784. bits.append(self.render_node(node, context)) File "/usr/lib/python2.4/site-packages/django/template/debug.py" in render_node
71. result = node.render(context) File "/usr/lib/python2.4/site-packages/django/template/loader_tags.py" in render
24. result = self.nodelist.render(context) File "/usr/lib/python2.4/site-packages/django/template/init.py" in render
784. bits.append(self.render_node(node, context)) File "/usr/lib/python2.4/site-packages/django/template/debug.py" in render_node
71. result = node.render(context) File "/usr/lib/python2.4/site-packages/django/template/defaulttags.py" in render
367. url = reverse(self.view_name, args=args, kwargs=kwargs, current_app=context.current_app) File "/usr/lib/python2.4/site-packages/django/core/urlresolvers.py" in reverse
357. return iri_to_uri(u'%s%s' % (prefix, resolver.reverse(view, File "/usr/lib/python2.4/site-packages/django/core/urlresolvers.py" in reverse
279. possibilities = self.reverse_dict.getlist(lookup_view) File "/usr/lib/python2.4/site-packages/django/core/urlresolvers.py" in get_reverse_dict
199. self.populate() File "/usr/lib/python2.4/site-packages/django/core/urlresolvers.py" in populate
179. for name in pattern.reverse_dict: File "/usr/lib/python2.4/site-packages/django/core/urlresolvers.py" in get_reverse_dict
199. self.populate() File "/usr/lib/python2.4/site-packages/django/core/urlresolvers.py" in populate
191. lookups.appendlist(pattern.callback, (bits, p_pattern)) File "/usr/lib/python2.4/site-packages/django/core/urlresolvers.py" in get_callback
135. self.callback = get_callable(self._callback_str) File "/usr/lib/python2.4/site-packages/django/utils/functional.py" in wrapper
130. result = func(args) File "/usr/lib/python2.4/site-packages/django/core/urlresolvers.py" in get_callable
62. lookup_view = getattr(import_module(mod_name), func_name) File "/usr/lib/python2.4/site-packages/django/utils/importlib.py" in import_module
35. import(name) File "/usr/lib/python2.4/site-packages/allaccess/rte_site/management/views.py" in ?
38. from forms import AdminForm

Exception Type: TemplateSyntaxError at /admin/
Exception Value: Caught SyntaxError while rendering: invalid syntax (forms.py, line 227)

If the forms.py file mentioned in traceback is the one I think it is, then this is the line causing problems:

def __init__(self, *args, **kwargs):
    self.father = kwargs.pop('parent', None) if kwargs else None

anything wrong here for python 2.4 ?


来源: stackexchange

问:
How to use $.ajax to receive JSON from API
I'm trying to make a random quote machine, so I started out with this HTML to define the elements:

```<code><div id="quoteDisplay">
  <h1 id="quote">Quote</h1>
  <h2 id="author">- Author</h2>
  <button id="new">New Quote</button>
</div>
</code>```

$('#new').on('click', function(e) {
  e.preventDefault();
  $.ajax({
    url: 'http://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1',
    success: function(data) {
      var post = data.shift();
      $('#author').html(post.title);
      $('#quote').html(post.content);
    }
  })
});
```

However for some reason when I click on the button, nothing happens and I don't understand where the problem is. I'm fully open to other methods of doing this.

答:
You're using $.ajax and one of the options of this method, is the method, which isn't specified.

To understand more about request methods, look at the jQuery docs: http://api.jquery.com/jquery.ajax/

The following code will work.

```<code>$.get({
    url: 'http://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1',
    success: function(data) {
        /* process response */
    }
})
</code>```

There is a working example here: http://jsfiddle.net/1chjtL6h/2/

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to make a random quote machine, so I started out with this HTML to define the elements:

Quote

- Author

  <button id="new">New Quote</button>

$('#new').on('click', function(e) {
  e.preventDefault();
  $.ajax({
    url: 'http://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1',
    success: function(data) {
      var post = data.shift();
      $('#author').html(post.title);
      $('#quote').html(post.content);
    }
  })
});

However for some reason when I click on the button, nothing happens and I don't understand where the problem is. I'm fully open to other methods of doing this.

Body:
You're using $.ajax and one of the options of this method, is the method, which isn't specified.

To understand more about request methods, look at the jQuery docs: http://api.jquery.com/jquery.ajax/

The following code will work.

$.get({
    url: 'http://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1',
    success: function(data) {
        /* process response */
    }
})

There is a working example here: http://jsfiddle.net/1chjtL6h/2/


问:
Loading QDialog is blank when showed
I am working on a code that allows the user to control a piezo (PZ193E) in a MainWindow created with Qt Designer form.

However, when I call the function designed to connect the piezo to the computer (from an external library given by the constructor) my UI freeze until the connection is established.

I am trying to display a QDialog with a QLabel in it, telling the user to wait while the connection is processing, but when I do so, the QDialog shows up but without the label. It is only displayed when the connection is established and when the QDialog can close.

Here is how I coded my dialog :

```<code>In the .h :
QDialog *_waitQD = new QDialog;
QVBoxLayout *_waitQVBL = new QVBoxLayout;
QLabel *_waitQL = new QLabel("Loading...");

In the .cpp :
_waitQD->setMinimumSize(QSize(95,35));
_waitQVBL->addWidget(_waitQL);
_waitQD->setLayout(_waitQVBL);
</code>```

And then I call :

```<code>_waitQD->show();
if (_piezo.connected()) // bool funtion that return true if the connection is established
      _waitQD->close();
</code>```

This is what it looks like:

答: The ideal solution is not blocking the main thread while establishing the connection; the workaround is adding QApplication::processEvents(); after the call to show

Title: Loading QDialog is blank when showed

Body:
I am working on a code that allows the user to control a piezo (PZ193E) in a MainWindow created with Qt Designer form.

However, when I call the function designed to connect the piezo to the computer (from an external library given by the constructor) my UI freeze until the connection is established.

I am trying to display a QDialog with a QLabel in it, telling the user to wait while the connection is processing, but when I do so, the QDialog shows up but without the label. It is only displayed when the connection is established and when the QDialog can close.

Here is how I coded my dialog :

In the .h :
QDialog *_waitQD = new QDialog;
QVBoxLayout *_waitQVBL = new QVBoxLayout;
QLabel *_waitQL = new QLabel("Loading...");

In the .cpp :
_waitQD->setMinimumSize(QSize(95,35));
_waitQVBL->addWidget(_waitQL);
_waitQD->setLayout(_waitQVBL);

And then I call :

_waitQD->show();
if (_piezo.connected()) // bool funtion that return true if the connection is established
      _waitQD->close();

This is what it looks like:


问:
PS MarkSweep is which garbage collector
My jdk version is :

```<code>java version "1.8.0_102"

Java(TM) SE Runtime Environment (build 1.8.0_102-b14)

Java HotSpot(TM) 64-Bit Server VM (build 25.102-b14, mixed mode)
</code>```

this is my test code :

```<code>List<GarbageCollectorMXBean> beans = ManagementFactory.getGarbageCollectorMXBeans();

    for (GarbageCollectorMXBean bean : beans) {
        System.out.println(bean.getName());
    }
</code>```

result is :

```<code>PS Scavenge

PS MarkSweep
</code>```

I know PS Scavenge is "Parallel Scavenge" of young generation garbage collector, "PS MarkSweep" is which, is it "Parallel Old"?

答:
For the benefit of anyone else finding this question, there is a great overview here:

http://www.fasterj.com/articles/oraclecollectors1.shtml

To quote the relevant parts for this question:

Young generation collectors

Copy (enabled with -XX:+UseSerialGC)

  the serial copy collector, uses one thread to copy surviving objects from Eden to Survivor spaces
  and between Survivor spaces until it decides they've been there long
  enough, at which point it copies them into the old generation.

PS Scavenge (enabled with -XX:+UseParallelGC)

  the parallel scavenge collector, like the Copy collector, but uses multiple threads
  in parallel and has some knowledge of how the old generation is
  collected (essentially written to work with the serial and PS old gen
  collectors).

ParNew (enabled with -XX:+UseParNewGC)

  the parallel copy collector, like the Copy collector, but uses multiple threads in
  parallel and has an internal 'callback' that allows an old generation
  collector to operate on the objects it collects (really written to
  work with the concurrent collector).

G1 Young Generation (enabled with -XX:+UseG1GC)

  the garbage first collector, uses the 'Garbage First' algorithm which splits up
  the heap into lots of smaller spaces, but these are still separated
  into Eden and Survivor spaces in the young generation for G1.

Old generation collectors

MarkSweepCompact (enabled with -XX:+UseSerialGC)

  the serial mark-sweep collector, the daddy of them all, uses a serial (one
  thread) full mark-sweep garbage collection algorithm, with optional
  compaction.

PS MarkSweep (enabled with -XX:+UseParallelOldGC)

  the parallel scavenge mark-sweep collector, parallelised version (i.e. uses
  multiple threads) of the MarkSweepCompact.

ConcurrentMarkSweep (enabled with -XX:+UseConcMarkSweepGC)

  the concurrent collector, a garbage collection algorithm that attempts to
  do most of the garbage collection work in the background without
  stopping application threads while it works (there are still phases
  where it has to stop application threads, but these phases are
  attempted to be kept to a minimum). Note if the concurrent collector
  fails to keep up with the garbage, it fails over to the serial
  MarkSweepCompact collector for (just) the next GC.

G1 Mixed Generation (enabled with -XX:+UseG1GC)

  the garbage first collector, uses the 'Garbage First' algorithm which splits up
  the heap into lots of smaller spaces.

Title: PS MarkSweep is which garbage collector

Body:
My jdk version is :

java version "1.8.0_102"

Java(TM) SE Runtime Environment (build 1.8.0_102-b14)

Java HotSpot(TM) 64-Bit Server VM (build 25.102-b14, mixed mode)

this is my test code :

List<GarbageCollectorMXBean> beans = ManagementFactory.getGarbageCollectorMXBeans();

    for (GarbageCollectorMXBean bean : beans) {
        System.out.println(bean.getName());
    }

result is :

PS Scavenge

PS MarkSweep

I know PS Scavenge is "Parallel Scavenge" of young generation garbage collector, "PS MarkSweep" is which, is it "Parallel Old"?


问:
Setting date with spinner - Android
What I want is, when I choose "Today" or "Tomorrow" on spinner to display it in date format in editText. "Pick a date" is working but I can choose date only once so I need this fixed too. Here is code:

```<code>package com.example.android.myapplication;

import android.app.DatePickerDialog;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;

import java.util.Calendar;

public class MainActivity extends AppCompatActivity {
Spinner spinner;
ArrayAdapter<CharSequence> adapter;

private static final String TAG = "MainActivity";

private EditText editText;
private DatePickerDialog.OnDateSetListener mDateSetListener;

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

    editText = (EditText) findViewById(R.id.editText);

    spinner = (Spinner) findViewById(R.id.spinner);
    adapter = (ArrayAdapter.createFromResource(this, R.array.dates, android.R.layout.simple_spinner_item));
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spinner.setAdapter(adapter);
    spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

            switch (spinner.getSelectedItem().toString()) {
                case "Pick a date":
                    Calendar cal = Calendar.getInstance();
                    int year = cal.get(Calendar.YEAR);
                    int month = cal.get(Calendar.MONTH);
                    int day = cal.get(Calendar.DAY_OF_MONTH);

                    DatePickerDialog dialog = new DatePickerDialog(
                            MainActivity.this,
                            android.R.style.Theme_Holo_Light_Dialog_MinWidth,
                            mDateSetListener,
                            year,month,day);
                    dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
                    dialog.show();

                case "Today":
                    //set today's date
                case "Tomorrow":
                    //set tomorrow's date
            }
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {

        }
    });

    mDateSetListener = new DatePickerDialog.OnDateSetListener() {
        @Override
        public void onDateSet(DatePicker datePicker, int year, int month, int day) {
            month = month + 1;
            Log.d(TAG, "onDateSet: mm/dd/yyy: " + month + "/" + day + "/" + year);

            String date = month + "/" + day + "/" + year;
            editText.setText(date);
        }
    };

}
</code>```

答:
for tomorrow just change this one simple thing:

```<code>case "Tomorrow":
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DAY_OF_MONTH,1);
        int year = cal.get(Calendar.YEAR);
        int month = cal.get(Calendar.MONTH);
        int day = cal.get(Calendar.DAY_OF_MONTH);

        SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy");
        String formattedDate = df.format(cal.getTime());

        editText.setText(formattedDate);
</code>```

Hope it helps!!!

Title: Setting date with spinner - Android

Body:
What I want is, when I choose "Today" or "Tomorrow" on spinner to display it in date format in editText. "Pick a date" is working but I can choose date only once so I need this fixed too. Here is code:

package com.example.android.myapplication;

import android.app.DatePickerDialog;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;

import java.util.Calendar;

public class MainActivity extends AppCompatActivity {
Spinner spinner;
ArrayAdapter<CharSequence> adapter;

private static final String TAG = "MainActivity";

private EditText editText;
private DatePickerDialog.OnDateSetListener mDateSetListener;

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

    editText = (EditText) findViewById(R.id.editText);

    spinner = (Spinner) findViewById(R.id.spinner);
    adapter = (ArrayAdapter.createFromResource(this, R.array.dates, android.R.layout.simple_spinner_item));
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spinner.setAdapter(adapter);
    spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

            switch (spinner.getSelectedItem().toString()) {
                case "Pick a date":
                    Calendar cal = Calendar.getInstance();
                    int year = cal.get(Calendar.YEAR);
                    int month = cal.get(Calendar.MONTH);
                    int day = cal.get(Calendar.DAY_OF_MONTH);

                    DatePickerDialog dialog = new DatePickerDialog(
                            MainActivity.this,
                            android.R.style.Theme_Holo_Light_Dialog_MinWidth,
                            mDateSetListener,
                            year,month,day);
                    dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
                    dialog.show();

                case "Today":
                    //set today's date
                case "Tomorrow":
                    //set tomorrow's date
            }
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {

        }
    });

    mDateSetListener = new DatePickerDialog.OnDateSetListener() {
        @Override
        public void onDateSet(DatePicker datePicker, int year, int month, int day) {
            month = month + 1;
            Log.d(TAG, "onDateSet: mm/dd/yyy: " + month + "/" + day + "/" + year);

            String date = month + "/" + day + "/" + year;
            editText.setText(date);
        }
    };

}

Body:
for tomorrow just change this one simple thing:

case "Tomorrow":
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DAY_OF_MONTH,1);
        int year = cal.get(Calendar.YEAR);
        int month = cal.get(Calendar.MONTH);
        int day = cal.get(Calendar.DAY_OF_MONTH);

        SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy");
        String formattedDate = df.format(cal.getTime());

        editText.setText(formattedDate);

Hope it helps!!!


答:
The reason that the request isn't returning on jsFiddles, is due to the fact that the url entered results in a 'Mixed Content' error. (I.e., requesting a 'HTTP' source on a 'HTTPS' page.)

I think the reason that your code isn't working, is due to the fact that you haven't assigned the 'Document Ready' syntax to your jQuery file (If that is the full code for your JS file). As your code works as can be seen here.

This can be achieved through the shorthand syntax of

```<code>$(function() {
//YOUR CODE HERE
}
</code>```

Or

```<code>$(document).ready(function(){
});
</code>```

Title: How to use $.ajax to receive JSON from API

Body:
The reason that the request isn't returning on jsFiddles, is due to the fact that the url entered results in a 'Mixed Content' error. (I.e., requesting a 'HTTP' source on a 'HTTPS' page.)

I think the reason that your code isn't working, is due to the fact that you haven't assigned the 'Document Ready' syntax to your jQuery file (If that is the full code for your JS file). As your code works as can be seen here.

This can be achieved through the shorthand syntax of

$(function() {
//YOUR CODE HERE
}

Or

$(document).ready(function(){
});


问:
How to get full explanation of Elasticsearch query Java?
I'm currecntly trying to test out some new score functions on my Elasticsearch query but I'm not yielding the results I am expecting.

I found this on their site about explaining queries here

I can run as a curl command but does anyone know how to translate this to use the Java api?

答:
If you're using the ES5 Java API, you can get the explanation like this:

```<code>QueryBuilder query = matchAllQuery(); // your query

ExplainRequest request = new ExplainRequest("index", "type", "id").query(query);
ExplainResponse explainResponse = client.explain(request).actionGet();
Explanation explanation = explainResponse.getExplanation();
</code>```

Where client is your org.elasticsearch.client.Client instance.

Body:
If you're using the ES5 Java API, you can get the explanation like this:

QueryBuilder query = matchAllQuery(); // your query

ExplainRequest request = new ExplainRequest("index", "type", "id").query(query);
ExplainResponse explainResponse = client.explain(request).actionGet();
Explanation explanation = explainResponse.getExplanation();

Where client is your org.elasticsearch.client.Client instance.


问:
Adding several properties with one CASE/FOREACH -statement in Cypher
I'm trying to create a relationship with properties depending on several different cases. I thought I could use FOREACH and CASE.

Here is a simplified version of my code:

```<code>LOAD CSV WITH HEADERS FROM 'file:///hwconnectIDs.csv' AS cnct
MATCH (h1:hardware), (h2:hardware), (c:cable)
WHERE (h1.hwID= cnct.conID1) AND (h2.hwID = cnct.conID2) AND (c.cableID =cnct.cableID)
FOREACH ( plugType IN
          CASE WHEN (h1.plug1=c.plug1 AND c.plug2=h2.plug1)
               THEN [c.plug1,c.plug2]
          CASE WHEN (h1.plug2=c.plug2 AND c.plug1=h2.plug1)
               THEN [c.plug2,c.plug1]
          ELSE [] END
          |
          CREATE (h1)<-[:connect{plug:plugType[0]}]-(c)-[:connect{plug:plugType[1]}]->(h2)
         )
</code>```

Problems:

It seems I cannot create an array-type variable plugType in FOREACH

For the ELSE-case I would like to not create the relationship at all. Right now, the value for the relationship-properties plugType would just be empty rather than the whole relationship not existing.

Note: The WHERE-condition insures that I am working with the correct hardware-devices and cable. The file hwconnectIDs.csv basically gives a list of devices h1 and h2 meant to be linked by cable c.

Is there a way of executing commands according to several different cases in Cypher like if/elseif/../else in other languages?

答:
You may be able to leverage the WITH clause for this (simplified things below) :

```<code>...
WITH h1, h2, c,
CASE
WHEN (h1.plug1=c.plug1 AND c.plug2=h2.plug1) THEN [c.plug1,c.plug2]
WHEN (h1.plug2=c.plug2 AND c.plug1=h2.plug1) THEN [c.plug2,c.plug1]
ELSE [] END AS plugtype
CREATE ...
</code>```

Hope this helps,
Tom

Body:
I'm trying to create a relationship with properties depending on several different cases. I thought I could use FOREACH and CASE.

Here is a simplified version of my code:

LOAD CSV WITH HEADERS FROM 'file:///hwconnectIDs.csv' AS cnct
MATCH (h1:hardware), (h2:hardware), (c:cable)
WHERE (h1.hwID= cnct.conID1) AND (h2.hwID = cnct.conID2) AND (c.cableID =cnct.cableID)
FOREACH ( plugType IN
          CASE WHEN (h1.plug1=c.plug1 AND c.plug2=h2.plug1)
               THEN [c.plug1,c.plug2]
          CASE WHEN (h1.plug2=c.plug2 AND c.plug1=h2.plug1)
               THEN [c.plug2,c.plug1]
          ELSE [] END
          |
          CREATE (h1)<-[:connect{plug:plugType[0]}]-(c)-[:connect{plug:plugType[1]}]->(h2)
         )

Problems:

It seems I cannot create an array-type variable plugType in FOREACH

For the ELSE-case I would like to not create the relationship at all. Right now, the value for the relationship-properties plugType would just be empty rather than the whole relationship not existing.

Note: The WHERE-condition insures that I am working with the correct hardware-devices and cable. The file hwconnectIDs.csv basically gives a list of devices h1 and h2 meant to be linked by cable c.

Is there a way of executing commands according to several different cases in Cypher like if/elseif/../else in other languages?

Body:
You may be able to leverage the WITH clause for this (simplified things below) :

...
WITH h1, h2, c,
CASE
WHEN (h1.plug1=c.plug1 AND c.plug2=h2.plug1) THEN [c.plug1,c.plug2]
WHEN (h1.plug2=c.plug2 AND c.plug1=h2.plug1) THEN [c.plug2,c.plug1]
ELSE [] END AS plugtype
CREATE ...

Hope this helps,
Tom


问:
C# - Detect if "Pause Printing" option in Print Queue is checked
I am currently looking for a way to detect if the "Pause Printing" option in the "See What's Printing" window is checked.

I've searched high and low, and looked into the Win32 native printing API (winspool) to see if there was such a detection available, but to no avail.

Is there anyone who has experience with a successful implementation of this detection?

答:
For those who are interested:

Using GetPrinter with level 2, then the filled PRINTER_INFO_2 struct contains a member Status which should have set the bit PRINTER_STATUS_PAUSED.

Relevant MSDN Articles:

Documents and Printing > Print Spooler API > Print Spooler API Reference  > Print Spooler API Functions > GetPrinter

This will help you build your enum for PRINTER_ATTRIBUTES and PRINTER_STATUS:

https://msdn.microsoft.com/en-us/library/cc244854.aspx

This will help you build the structure for PRINTER_INFO_2:

https://msdn.microsoft.com/en-us/library/windows/desktop/dd162845(v=vs.85).aspx


问:
find common rows of matching column from two tables
I have two tables with a column values mostly matching with each other.

How can I find row that are matching in common to that column.

Here is my fiddle

It is showing Error at B

答:
I think ON is missing</p>

```<code>SELECT count(*)
FROM ForgeRock  A JOIN ForgeRock1  B
on A.ProductName = B.Productname
</code>```

Body:
I think ON is missing

SELECT count(*)
FROM ForgeRock  A JOIN ForgeRock1  B
on A.ProductName = B.Productname


问:
Get value of a text box of a pop up menu
I have a pop up menu,which has a text box,when I go in a inspect elemnt its like the following,my question is how can get the value of this specific box</p>

```<code>< input name="DeviceIP" class="k-input k-textbox" type="text" data-bind="value:DeviceIP" >
</code>```

答:
you can access the element using getElementsByName and then use value :
document.getElementsByName("DeviceIP")[0].value

Body:
I have a pop up menu,which has a text box,when I go in a inspect elemnt its like the following,my question is how can get the value of this specific box

< input name="DeviceIP" class="k-input k-textbox" type="text" data-bind="value:DeviceIP" >


问:
Java Thread: Run method cannot throw checked exception
In Java thread, the 'run' method cannot throw a 'checked exception'. I came across this in the Core Java (vol 1)  book. Can someone please explain the reasoning behind it? </p>

答:
Suppose thread A starts up thread B. Then thread B throws an exception. You might think it would be nice for thread A to catch it. But where? By the time thread B thows the exception, who knows what thread A is doing? To take a trivial example, suppose we have this code in thread A:

```<code>try
{
  threadB=new PurgeAbandonedCarts();
  threadB.start();
}
catch (NullPointerException panic)
{
  ... handle errors purging abandoned carts ...
}
try
{
  processNewOrders();
}
catch (NullPointerException panic)
{
  ... handle problems in new orders ...
}
finally
{
  ... clean up ...
}
</code>```

So we start up thread B to purge abandoned carts. Once it gets starte, we move on to processing new orders. Then thread B throws a null pointer exception.  Should it be caught by the catch block associated with thread B, or the one associated with processing new orders?

If it goes to the new orders catch, it's likely that any code here has nothing to do with cleaning up problems with thread B. That can't be the right answer.

If you say the one associated with thread B, then that means that during the processing of new orders, control could suddenly be yanked out and sent back to try thread B catch block. But then what happenned to processing new orders? Do we just stop in the middle? Do we not even hit the finally block? And when we're done, do we then just keep executing and fall through to processing new orders again? Do we process orders twice? This can't be the right answer either.

Thus, there is nowhere to go if run throws an exception. The only logical thing to do is to have the run method catch any exceptions thrown itself, and handle them within the new thread.

Body:
Suppose thread A starts up thread B. Then thread B throws an exception. You might think it would be nice for thread A to catch it. But where? By the time thread B thows the exception, who knows what thread A is doing? To take a trivial example, suppose we have this code in thread A:

try
{
  threadB=new PurgeAbandonedCarts();
  threadB.start();
}
catch (NullPointerException panic)
{
  ... handle errors purging abandoned carts ...
}
try
{
  processNewOrders();
}
catch (NullPointerException panic)
{
  ... handle problems in new orders ...
}
finally
{
  ... clean up ...
}

So we start up thread B to purge abandoned carts. Once it gets starte, we move on to processing new orders. Then thread B throws a null pointer exception.  Should it be caught by the catch block associated with thread B, or the one associated with processing new orders?

If it goes to the new orders catch, it's likely that any code here has nothing to do with cleaning up problems with thread B. That can't be the right answer.

If you say the one associated with thread B, then that means that during the processing of new orders, control could suddenly be yanked out and sent back to try thread B catch block. But then what happenned to processing new orders? Do we just stop in the middle? Do we not even hit the finally block? And when we're done, do we then just keep executing and fall through to processing new orders again? Do we process orders twice? This can't be the right answer either.

Thus, there is nowhere to go if run throws an exception. The only logical thing to do is to have the run method catch any exceptions thrown itself, and handle them within the new thread.

ContentLicense: CC BY-SA 2.5


问:
How to open excel in read and write mode?
Im opening the excel file from desktop and running a macro but everytime it shows an error stating that it cannot save as it is opened in read only mode

enter image description here

答:
Can you check this and let me know if it works</p>

```<code>Set Wb = Application.WorkBooks.Open(filePath, False, False) '3rd parameter is for opening the workbook in readonly mode
'Your code
'
'Your code
'
Wb.Save ' OR ActiveWorkBook.Save
</code>```

Body:
Can you check this and let me know if it works

Set Wb = Application.WorkBooks.Open(filePath, False, False) '3rd parameter is for opening the workbook in readonly mode
'Your code
'
'Your code
'
Wb.Save ' OR ActiveWorkBook.Save


问:
How to add application name in url bar with jetty server
Hi i have created a maven project with embedded jetty server which is executing fine. After getting jetty server started in eclipse console so to access welcome file (index.jsp) url could be something like this
localhost:8080 is enough but how to add application name into url like below i mention localhost:8080/application_name(FirstAppWithJetty)/

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" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
  <display-name>FirstAppwithJetty</display-name>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  </web-app>
</code>```

pom.xml

```<code><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>
<groupId>com.pradeep.maven</groupId>
<artifactId>FirstAppwithJetty</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>

<dependencies>
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>servlet-api</artifactId>
        <version>3.0-alpha-1</version>
        <scope>provided</scope>
    </dependency>
</dependencies>
<build>
    <finalName>FirstAppwithJetty</finalName>
    <plugins>
        <plugin>
            <groupId>org.eclipse.jetty</groupId>
            <artifactId>jetty-maven-plugin</artifactId>
            <version>9.2.11.v20150529</version>
            <configuration>
                <path>/FirstAppwithJetty</path>
                 <stopPort>8080</stopPort>
              <stopKey>jetty:stop</stopKey>
            </configuration>
        </plugin>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.2</version>
            <configuration>
                <source>1.7</source>
                <target>1.7</target>
            </configuration>
        </plugin>
    </plugins>
</build>
</code>```

Exception:

```<code>Error binding monitor port 8080: java.net.BindException: Address already in use: JVM_Bind
[INFO] Started o.e.j.m.p.JettyWebAppContext@157846d4{/,file:/D:/ProjectWithMaven/FirstAppwithJetty/src/main/webapp/,AVAILABLE}{file:/D:/ProjectWithMaven/FirstAppwithJetty/src/main/webapp/}
[WARNING] !RequestLog
[WARNING] FAILED ServerConnector@7a7ca3bd{HTTP/1.1}{0.0.0.0:8080}: java.net.BindException: Address already in use: bind
java.net.BindException: Address already in use: bind
    at sun.nio.ch.Net.bind0(Native Method)
    at sun.nio.ch.Net.bind(Net.java:444)
    at sun.nio.ch.Net.bind(Net.java:436)
    at sun.nio.ch.ServerSocketChannelImpl.bind(ServerSocketChannelImpl.java:214)
    at sun.nio.ch.ServerSocketAdaptor.bind(ServerSocketAdaptor.java:74)
    at org.eclipse.jetty.server.ServerConnector.open(ServerConnector.java:321)
    at org.eclipse.jetty.server.AbstractNetworkConnector.doStart(AbstractNetworkConnector.java:80)
    at org.eclipse.jetty.server.ServerConnector.doStart(ServerConnector.java:236)
    at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:68)
    at org.eclipse.jetty.maven.plugin.MavenServerConnector.doStart(MavenServerConnector.java:120)
    at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:68)
    at org.eclipse.jetty.server.Server.doStart(Server.java:366)
    at org.eclipse.jetty.maven.plugin.JettyServer.doStart(JettyServer.java:73)
    at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:68)
    at org.eclipse.jetty.maven.plugin.AbstractJettyMojo.startJetty(AbstractJettyMojo.java:534)
    at org.eclipse.jetty.maven.plugin.AbstractJettyMojo.execute(AbstractJettyMojo.java:357)
    at org.eclipse.jetty.maven.plugin.JettyRunMojo.execute(JettyRunMojo.java:167)
    at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:134)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:208)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:153)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:145)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:116)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:80)
    at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build(SingleThreadedBuilder.java:51)
    at org.apache.maven.lifecycle.internal.LifecycleStarter.execute(LifecycleStarter.java:128)
    at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:307)
    at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:193)
    at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:106)
    at org.apache.maven.cli.MavenCli.execute(MavenCli.java:862)
    at org.apache.maven.cli.MavenCli.doMain(MavenCli.java:286)
    at org.apache.maven.cli.MavenCli.main(MavenCli.java:197)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced(Launcher.java:289)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.java:229)
    at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(Launcher.java:415)
    at org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:356)
[WARNING] FAILED org.eclipse.jetty.maven.plugin.MavenServerConnector@5a52059c: java.net.BindException: Address already in use: bind
java.net.BindException: Address already in use: bind
    at sun.nio.ch.Net.bind0(Native Method)
    at sun.nio.ch.Net.bind(Net.java:444)
    at sun.nio.ch.Net.bind(Net.java:436)
    at sun.nio.ch.ServerSocketChannelImpl.bind(ServerSocketChannelImpl.java:214)
    at sun.nio.ch.ServerSocketAdaptor.bind(ServerSocketAdaptor.java:74)
    at org.eclipse.jetty.server.ServerConnector.open(ServerConnector.java:321)
    at org.eclipse.jetty.server.AbstractNetworkConnector.doStart(AbstractNetworkConnector.java:80)
    at org.eclipse.jetty.server.ServerConnector.doStart(ServerConnector.java:236)
    at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:68)
    at org.eclipse.jetty.maven.plugin.MavenServerConnector.doStart(MavenServerConnector.java:120)
    at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:68)
    at org.eclipse.jetty.server.Server.doStart(Server.java:366)
    at org.eclipse.jetty.maven.plugin.JettyServer.doStart(JettyServer.java:73)
    at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:68)
    at org.eclipse.jetty.maven.plugin.AbstractJettyMojo.startJetty(AbstractJettyMojo.java:534)
    at org.eclipse.jetty.maven.plugin.AbstractJettyMojo.execute(AbstractJettyMojo.java:357)
    at org.eclipse.jetty.maven.plugin.JettyRunMojo.execute(JettyRunMojo.java:167)
    at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:134)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:208)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:153)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:145)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:116)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:80)
    at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build(SingleThreadedBuilder.java:51)
    at org.apache.maven.lifecycle.internal.LifecycleStarter.execute(LifecycleStarter.java:128)
    at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:307)
    at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:193)
    at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:106)
    at org.apache.maven.cli.MavenCli.execute(MavenCli.java:862)
    at org.apache.maven.cli.MavenCli.doMain(MavenCli.java:286)
    at org.apache.maven.cli.MavenCli.main(MavenCli.java:197)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced(Launcher.java:289)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.java:229)
    at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(Launcher.java:415)
    at org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:356)
[WARNING] FAILED org.eclipse.jetty.maven.plugin.JettyServer@2bde2e31: java.net.BindException: Address already in use: bind
java.net.BindException: Address already in use: bind
    at sun.nio.ch.Net.bind0(Native Method)
    at sun.nio.ch.Net.bind(Net.java:444)
    at sun.nio.ch.Net.bind(Net.java:436)
    at sun.nio.ch.ServerSocketChannelImpl.bind(ServerSocketChannelImpl.java:214)
    at sun.nio.ch.ServerSocketAdaptor.bind(ServerSocketAdaptor.java:74)
    at org.eclipse.jetty.server.ServerConnector.open(ServerConnector.java:321)
    at org.eclipse.jetty.server.AbstractNetworkConnector.doStart(AbstractNetworkConnector.java:80)
    at org.eclipse.jetty.server.ServerConnector.doStart(ServerConnector.java:236)
    at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:68)
    at org.eclipse.jetty.maven.plugin.MavenServerConnector.doStart(MavenServerConnector.java:120)
    at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:68)
    at org.eclipse.jetty.server.Server.doStart(Server.java:366)
    at org.eclipse.jetty.maven.plugin.JettyServer.doStart(JettyServer.java:73)
    at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:68)
    at org.eclipse.jetty.maven.plugin.AbstractJettyMojo.startJetty(AbstractJettyMojo.java:534)
    at org.eclipse.jetty.maven.plugin.AbstractJettyMojo.execute(AbstractJettyMojo.java:357)
    at org.eclipse.jetty.maven.plugin.JettyRunMojo.execute(JettyRunMojo.java:167)
    at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:134)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:208)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:153)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:145)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:116)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:80)
    at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build(SingleThreadedBuilder.java:51)
    at org.apache.maven.lifecycle.internal.LifecycleStarter.execute(LifecycleStarter.java:128)
    at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:307)
    at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:193)
    at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:106)
    at org.apache.maven.cli.MavenCli.execute(MavenCli.java:862)
    at org.apache.maven.cli.MavenCli.doMain(MavenCli.java:286)
    at org.apache.maven.cli.MavenCli.main(MavenCli.java:197)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced(Launcher.java:289)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.java:229)
    at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(Launcher.java:415)
    at org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:356)
[INFO] Jetty server exiting.
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 7.793 s
[INFO] Finished at: 2017-07-05T14:00:50+05:30
[INFO] Final Memory: 15M/204M
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.eclipse.jetty:jetty-maven-plugin:9.2.11.v20150529:run (default-cli) on project FirstAppwithJetty: Failure: Address already in use: bind -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoExecutionException
</code>```

答:
Below is the configuration to add application context for the web application and to run and stop the jetty server</p>

```<code><plugin>
                <groupId>org.eclipse.jetty</groupId>
                <artifactId>jetty-maven-plugin</artifactId>
                <version>9.2.11.v20150529</version>
                <configuration>
                    <stopPort>9696</stopPort>
                    <stopKey>stop</stopKey>
                    <stopWait>10</stopWait>
                    <webApp>
                        <contextPath>/test</contextPath>
                    </webApp>
                </configuration>
            </plugin>
</code>```

Body:
Hi i have created a maven project with embedded jetty server which is executing fine. After getting jetty server started in eclipse console so to access welcome file (index.jsp) url could be something like this
localhost:8080 is enough but how to add application name into url like below i mention localhost:8080/application_name(FirstAppWithJetty)/

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" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
  <display-name>FirstAppwithJetty</display-name>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  </web-app>

pom.xml

<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>
<groupId>com.pradeep.maven</groupId>
<artifactId>FirstAppwithJetty</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>

<dependencies>
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>servlet-api</artifactId>
        <version>3.0-alpha-1</version>
        <scope>provided</scope>
    </dependency>
</dependencies>
<build>
    <finalName>FirstAppwithJetty</finalName>
    <plugins>
        <plugin>
            <groupId>org.eclipse.jetty</groupId>
            <artifactId>jetty-maven-plugin</artifactId>
            <version>9.2.11.v20150529</version>
            <configuration>
                <path>/FirstAppwithJetty</path>
                 <stopPort>8080</stopPort>
              <stopKey>jetty:stop</stopKey>
            </configuration>
        </plugin>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.2</version>
            <configuration>
                <source>1.7</source>
                <target>1.7</target>
            </configuration>
        </plugin>
    </plugins>
</build>

Exception:

Error binding monitor port 8080: java.net.BindException: Address already in use: JVM_Bind
[INFO] Started o.e.j.m.p.JettyWebAppContext@157846d4{/,file:/D:/ProjectWithMaven/FirstAppwithJetty/src/main/webapp/,AVAILABLE}{file:/D:/ProjectWithMaven/FirstAppwithJetty/src/main/webapp/}
[WARNING] !RequestLog
[WARNING] FAILED ServerConnector@7a7ca3bd{HTTP/1.1}{0.0.0.0:8080}: java.net.BindException: Address already in use: bind
java.net.BindException: Address already in use: bind
    at sun.nio.ch.Net.bind0(Native Method)
    at sun.nio.ch.Net.bind(Net.java:444)
    at sun.nio.ch.Net.bind(Net.java:436)
    at sun.nio.ch.ServerSocketChannelImpl.bind(ServerSocketChannelImpl.java:214)
    at sun.nio.ch.ServerSocketAdaptor.bind(ServerSocketAdaptor.java:74)
    at org.eclipse.jetty.server.ServerConnector.open(ServerConnector.java:321)
    at org.eclipse.jetty.server.AbstractNetworkConnector.doStart(AbstractNetworkConnector.java:80)
    at org.eclipse.jetty.server.ServerConnector.doStart(ServerConnector.java:236)
    at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:68)
    at org.eclipse.jetty.maven.plugin.MavenServerConnector.doStart(MavenServerConnector.java:120)
    at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:68)
    at org.eclipse.jetty.server.Server.doStart(Server.java:366)
    at org.eclipse.jetty.maven.plugin.JettyServer.doStart(JettyServer.java:73)
    at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:68)
    at org.eclipse.jetty.maven.plugin.AbstractJettyMojo.startJetty(AbstractJettyMojo.java:534)
    at org.eclipse.jetty.maven.plugin.AbstractJettyMojo.execute(AbstractJettyMojo.java:357)
    at org.eclipse.jetty.maven.plugin.JettyRunMojo.execute(JettyRunMojo.java:167)
    at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:134)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:208)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:153)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:145)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:116)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:80)
    at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build(SingleThreadedBuilder.java:51)
    at org.apache.maven.lifecycle.internal.LifecycleStarter.execute(LifecycleStarter.java:128)
    at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:307)
    at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:193)
    at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:106)
    at org.apache.maven.cli.MavenCli.execute(MavenCli.java:862)
    at org.apache.maven.cli.MavenCli.doMain(MavenCli.java:286)
    at org.apache.maven.cli.MavenCli.main(MavenCli.java:197)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced(Launcher.java:289)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.java:229)
    at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(Launcher.java:415)
    at org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:356)
[WARNING] FAILED org.eclipse.jetty.maven.plugin.MavenServerConnector@5a52059c: java.net.BindException: Address already in use: bind
java.net.BindException: Address already in use: bind
    at sun.nio.ch.Net.bind0(Native Method)
    at sun.nio.ch.Net.bind(Net.java:444)
    at sun.nio.ch.Net.bind(Net.java:436)
    at sun.nio.ch.ServerSocketChannelImpl.bind(ServerSocketChannelImpl.java:214)
    at sun.nio.ch.ServerSocketAdaptor.bind(ServerSocketAdaptor.java:74)
    at org.eclipse.jetty.server.ServerConnector.open(ServerConnector.java:321)
    at org.eclipse.jetty.server.AbstractNetworkConnector.doStart(AbstractNetworkConnector.java:80)
    at org.eclipse.jetty.server.ServerConnector.doStart(ServerConnector.java:236)
    at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:68)
    at org.eclipse.jetty.maven.plugin.MavenServerConnector.doStart(MavenServerConnector.java:120)
    at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:68)
    at org.eclipse.jetty.server.Server.doStart(Server.java:366)
    at org.eclipse.jetty.maven.plugin.JettyServer.doStart(JettyServer.java:73)
    at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:68)
    at org.eclipse.jetty.maven.plugin.AbstractJettyMojo.startJetty(AbstractJettyMojo.java:534)
    at org.eclipse.jetty.maven.plugin.AbstractJettyMojo.execute(AbstractJettyMojo.java:357)
    at org.eclipse.jetty.maven.plugin.JettyRunMojo.execute(JettyRunMojo.java:167)
    at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:134)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:208)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:153)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:145)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:116)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:80)
    at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build(SingleThreadedBuilder.java:51)
    at org.apache.maven.lifecycle.internal.LifecycleStarter.execute(LifecycleStarter.java:128)
    at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:307)
    at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:193)
    at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:106)
    at org.apache.maven.cli.MavenCli.execute(MavenCli.java:862)
    at org.apache.maven.cli.MavenCli.doMain(MavenCli.java:286)
    at org.apache.maven.cli.MavenCli.main(MavenCli.java:197)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced(Launcher.java:289)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.java:229)
    at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(Launcher.java:415)
    at org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:356)
[WARNING] FAILED org.eclipse.jetty.maven.plugin.JettyServer@2bde2e31: java.net.BindException: Address already in use: bind
java.net.BindException: Address already in use: bind
    at sun.nio.ch.Net.bind0(Native Method)
    at sun.nio.ch.Net.bind(Net.java:444)
    at sun.nio.ch.Net.bind(Net.java:436)
    at sun.nio.ch.ServerSocketChannelImpl.bind(ServerSocketChannelImpl.java:214)
    at sun.nio.ch.ServerSocketAdaptor.bind(ServerSocketAdaptor.java:74)
    at org.eclipse.jetty.server.ServerConnector.open(ServerConnector.java:321)
    at org.eclipse.jetty.server.AbstractNetworkConnector.doStart(AbstractNetworkConnector.java:80)
    at org.eclipse.jetty.server.ServerConnector.doStart(ServerConnector.java:236)
    at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:68)
    at org.eclipse.jetty.maven.plugin.MavenServerConnector.doStart(MavenServerConnector.java:120)
    at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:68)
    at org.eclipse.jetty.server.Server.doStart(Server.java:366)
    at org.eclipse.jetty.maven.plugin.JettyServer.doStart(JettyServer.java:73)
    at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:68)
    at org.eclipse.jetty.maven.plugin.AbstractJettyMojo.startJetty(AbstractJettyMojo.java:534)
    at org.eclipse.jetty.maven.plugin.AbstractJettyMojo.execute(AbstractJettyMojo.java:357)
    at org.eclipse.jetty.maven.plugin.JettyRunMojo.execute(JettyRunMojo.java:167)
    at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:134)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:208)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:153)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:145)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:116)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:80)
    at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build(SingleThreadedBuilder.java:51)
    at org.apache.maven.lifecycle.internal.LifecycleStarter.execute(LifecycleStarter.java:128)
    at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:307)
    at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:193)
    at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:106)
    at org.apache.maven.cli.MavenCli.execute(MavenCli.java:862)
    at org.apache.maven.cli.MavenCli.doMain(MavenCli.java:286)
    at org.apache.maven.cli.MavenCli.main(MavenCli.java:197)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced(Launcher.java:289)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.java:229)
    at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(Launcher.java:415)
    at org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:356)
[INFO] Jetty server exiting.
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 7.793 s
[INFO] Finished at: 2017-07-05T14:00:50+05:30
[INFO] Final Memory: 15M/204M
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.eclipse.jetty:jetty-maven-plugin:9.2.11.v20150529:run (default-cli) on project FirstAppwithJetty: Failure: Address already in use: bind -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoExecutionException

Body:
Below is the configuration to add application context for the web application and to run and stop the jetty server

<plugin>
                <groupId>org.eclipse.jetty</groupId>
                <artifactId>jetty-maven-plugin</artifactId>
                <version>9.2.11.v20150529</version>
                <configuration>
                    <stopPort>9696</stopPort>
                    <stopKey>stop</stopKey>
                    <stopWait>10</stopWait>
                    <webApp>
                        <contextPath>/test</contextPath>
                    </webApp>
                </configuration>
            </plugin>


问:
Angular js - Call function inside controller from view in ng-admin
I am working with the feature of multiple languages for ng-admin.
In the file header.html, I have added a dropdown with a list of languages. Clicking each option fires a function call.

The function itself is inside a controller in /js/main.js

Clicking in any of the languages results in ReferenceError: serve_language is not defined.

This is the content of both files:

header.html

```<code><ul class="nav navbar-top-links navbar-right hidden-xs">
    <li uib-dropdown ng-controller="languageCtrl">
        <a uib-dropdown-toggle href="#" aria-expanded="true">
            <i class="fa fa-user fa-lg"></i>  Language <i class="fa fa-caret-down"></i>
        </a>
        <ul class="dropdown-menu dropdown-user" role="menu">
            <li><a href="#" onclick="serve_language('en')"><i class="fa fa-sign-out fa-fw"></i> English</a></li>
            <li><a href="#" onclick="serve_language('ge')"><i class="fa fa-sign-out fa-fw"></i> German</a></li>
            <li><a href="#" onclick="serve_language('fr')"><i class="fa fa-sign-out fa-fw"></i> French</a></li>
            <li><a href="#" onclick="serve_language('sp')"><i class="fa fa-sign-out fa-fw"></i> Spanish</a></li>
        </ul>
    </li>
</ul>
</code>```

main.js

```<code>'use strict'
var myApp = angular.module('myApp', ['ng-admin','ng-admin.jwt-auth', 'nvd3']);
myApp.controller('languageCtrl', ['$translate', '$scope', function ($translate, $scope) {
    $scope.serve_language = function (langKey) {
       console.log("@langctrl");
    };
}]);
</code>```

I also tried calling the function as languageCtrl.serve_language(), but that resulted in ReferenceError: languageCtrl is not defined

答:
You should change onclick to ng-click

```<code><ul class="dropdown-menu dropdown-user" role="menu">
            <li><a ng-click="serve_language('en')"><i class="fa fa-sign-out fa-fw"></i> English</a></li>
            <li><a ng-click="serve_language('ge')"><i class="fa fa-sign-out fa-fw"></i> German</a></li>
            <li><a ng-click="serve_language('fr')"><i class="fa fa-sign-out fa-fw"></i> French</a></li>
            <li><a ng-click="serve_language('sp')"><i class="fa fa-sign-out fa-fw"></i> Spanish</a></li>
        </ul>
</code>```

Body:
I am working with the feature of multiple languages for ng-admin.
In the file header.html, I have added a dropdown with a list of languages. Clicking each option fires a function call.

The function itself is inside a controller in /js/main.js

Clicking in any of the languages results in ReferenceError: serve_language is not defined.

This is the content of both files:

header.html

              Language

 English

 German

 French

 Spanish

main.js

'use strict'
var myApp = angular.module('myApp', ['ng-admin','ng-admin.jwt-auth', 'nvd3']);
myApp.controller('languageCtrl', ['$translate', '$scope', function ($translate, $scope) {
    $scope.serve_language = function (langKey) {
       console.log("@langctrl");
    };
}]);

I also tried calling the function as languageCtrl.serve_language(), but that resulted in ReferenceError: languageCtrl is not defined

Body:
You should change onclick to ng-click

<ul class="dropdown-menu dropdown-user" role="menu">
            <li><a ng-click="serve_language('en')"><i class="fa fa-sign-out fa-fw"></i> English</a></li>
            <li><a ng-click="serve_language('ge')"><i class="fa fa-sign-out fa-fw"></i> German</a></li>
            <li><a ng-click="serve_language('fr')"><i class="fa fa-sign-out fa-fw"></i> French</a></li>
            <li><a ng-click="serve_language('sp')"><i class="fa fa-sign-out fa-fw"></i> Spanish</a></li>
        </ul>


问:
hide NavigationBar when scrolling at down CollectionView
i made NavigationBar and TabBar programmatically, but hide navigationBar when i scroll at down collectionView. here is code
import Foundation

import Foundation
import UIKit

class HomeMyBazar: UICollectionViewController, UICollectionViewDelegateFlowLayout {

```<code>let cellId = "cellId"

let productCellId = "productCellId"
let dealsCellId = "dealsCellId"

let titles = ["Hello world", "Product", "Deals", "Store world"]

override func viewDidLoad() {
    super.viewDidLoad()

    navigationController?.navigationBar.isTranslucent = false

    setupNavBarButtons()

    setupMenuBar()

    setupCollectionView()

}

func setupNavBarButtons() {

lazy var settingsLauncher: SettingsLauncher = {
    let launcher = SettingsLauncher()
    launcher.homeController = self
    return launcher
}()

func targetMyBazar() {

    let secondViewController = ViewController1()
    self.navigationController?.pushViewController(secondViewController, animated: true)

}

func targetSearch() {

    let viewController = ViewController4()
    self.navigationController?.pushViewController(viewController, animated: true)
}

func targetUser() {

    let viewController = ViewController3()
    self.navigationController?.pushViewController(viewController, animated: true)
}

func targetCart() {

    let viewController = ViewController5()
    self.navigationController?.pushViewController(viewController, animated: true)
}

func handleMore() {

    settingsLauncher.showSettings()
}

func showControllerForSetting(_ setting: Setting) {
    let dummySettingsViewController = UIViewController()
    dummySettingsViewController.view.backgroundColor = UIColor.white
    dummySettingsViewController.navigationItem.title = setting.name.rawValue
    navigationController?.navigationBar.tintColor = UIColor.white
    navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.white]
    navigationController?.pushViewController(dummySettingsViewController, animated: true)
}

func scrollToMenuIndex(_ menuIndex: Int) {
    let indexPath = IndexPath(item: menuIndex, section: 0)
    collectionView?.scrollToItem(at: indexPath, at: UICollectionViewScrollPosition(), animated: true)

}

fileprivate func setTitleForIndex(_ index: Int) {
    if let titleLabel = navigationItem.titleView as? UILabel {
        titleLabel.text = "  \(titles[index])"
    }

}

lazy var menuBar: MenuBar = {
    let mb = MenuBar()
    mb.homeController = self
    return mb
}()

fileprivate func setupMenuBar() {
    navigationController?.hidesBarsOnSwipe = true

    let blackView = UIView()

    blackView.backgroundColor = .lightGray

    view.addSubview(blackView)
    view.addConstraintsWithFormat("H:|[v0]|", views: blackView)
    view.addConstraintsWithFormat("V:[v0(50)]", views: blackView)

    view.addSubview(menuBar)
    view.addConstraintsWithFormat("H:|[v0]|", views: menuBar)
    view.addConstraintsWithFormat("V:[v0(80)]", views: menuBar)

    menuBar.topAnchor.constraint(equalTo: topLayoutGuide.bottomAnchor).isActive = true
}

override func scrollViewDidScroll(_ scrollView: UIScrollView) {
    menuBar.horizontalBarLeftAnchorConstraint?.constant = scrollView.contentOffset.x / 4
}

override func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {

    let index = targetContentOffset.pointee.x / view.frame.width

    let indexPath = IndexPath(item: Int(index), section: 0)
    menuBar.collectionView.selectItem(at: indexPath, animated: true, scrollPosition: UICollectionViewScrollPosition())

    setTitleForIndex(Int(index))
}

func setupCollectionView() {

    if let flowLayout = collectionView?.collectionViewLayout as? UICollectionViewFlowLayout {
        flowLayout.scrollDirection = .horizontal
        flowLayout.minimumLineSpacing = 0
    }

    collectionView?.backgroundColor = UIColor.blue

    collectionView?.register(MyBazarCell.self, forCellWithReuseIdentifier: cellId)

    collectionView?.register(ProductCell.self, forCellWithReuseIdentifier: productCellId)
    collectionView?.register(DealsCell.self, forCellWithReuseIdentifier: dealsCellId)

    collectionView?.contentInset = UIEdgeInsetsMake(110, 0, 0, 0)

    collectionView?.isPagingEnabled = true
}

override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return 4
}

override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    let identifier: String
    if indexPath.item == 1 {
        identifier = productCellId
    } else if indexPath.item == 2 {
        identifier = dealsCellId
    } else {
        identifier = cellId
    }

    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: identifier, for: indexPath)

    return cell
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    return CGSize(width: view.frame.width, height: view.frame.height - 50)
}
</code>```

}

import Foundation

import UIKit

struct Item {
    var imageName: String
    var text: String
}

class MenuBar: UIView, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {

```<code>lazy var collectionView: UICollectionView = {

    let layout = UICollectionViewFlowLayout()

    let cv = UICollectionView(frame: .zero, collectionViewLayout: layout)

    cv.backgroundColor = UIColor.black
    cv.dataSource = self
    cv.delegate = self
    return cv
}()

let data: [Item] = [
    Item(imageName: "service", text: "Service"),
    Item(imageName: "product", text: "Product "),
    Item(imageName: "deals", text: " Deals"),
    Item(imageName: "store", text: "Store")
]

let cellId = "cellId"
let imageNames = ["service", "product", "deals", "store"]
let imageTitle = ["Servic", "Product", "Deals", "Store"]

var homeController: HomeMyBazar?

override init(frame: CGRect) {
    super.init(frame: frame)

    collectionView.register(MenuCell.self, forCellWithReuseIdentifier: cellId)

    addSubview(collectionView)
    addConstraintsWithFormat("H:|[v0]|", views: collectionView)
    addConstraintsWithFormat("V:|[v0]|", views: collectionView)

    let selectedIndexPath = IndexPath(item: 0, section: 0)
    collectionView.selectItem(at: selectedIndexPath, animated: false, scrollPosition: UICollectionViewScrollPosition())

    setupHorizontalBar()
}

var horizontalBarLeftAnchorConstraint: NSLayoutConstraint?

func setupHorizontalBar() {
    let horizontalBarView = UIView()

    horizontalBarView.backgroundColor = UIColor.red
    horizontalBarView.translatesAutoresizingMaskIntoConstraints = false
    addSubview(horizontalBarView)

    horizontalBarLeftAnchorConstraint = horizontalBarView.leftAnchor.constraint(equalTo: self.leftAnchor)
    horizontalBarLeftAnchorConstraint?.isActive = true

    horizontalBarView.bottomAnchor.constraint(equalTo: self.bottomAnchor).isActive = true
    horizontalBarView.widthAnchor.constraint(equalTo: self.widthAnchor, multiplier: 1/4).isActive = true
    horizontalBarView.heightAnchor.constraint(equalToConstant: 4).isActive = true
}

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

    homeController?.scrollToMenuIndex(indexPath.item)

}

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

    return data.count
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! MenuCell

    let item = data[indexPath.item]
    cell.imageView.image = UIImage(named: item.imageName)
    cell.imageTitle.text = item.text

    cell.tintColor = UIColor.white

    return cell
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    return CGSize(width: frame.width / 4, height: frame.height)
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
    return 0
}

required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}
</code>```

}

class MenuCell: BaseCell {

```<code>let imageTitle: UILabel = {
    let label = UILabel()
    label.text = "hellow world label"
    label.textColor = .white
    return label
}()

let imageView: UIImageView = {
    let iv = UIImageView()
    iv.image = UIImage(named: "service")?.withRenderingMode(.alwaysTemplate)

    iv.tintColor = .white
    return iv
}()

override var isHighlighted: Bool {
    didSet {

        imageView.tintColor = isHighlighted ? UIColor.white : UIColor.white
    }
}

override var isSelected: Bool {
    didSet {

        imageView.tintColor = isSelected ? UIColor.white : UIColor.white
    }
}

override func setupViews() {
    super.setupViews()

    addSubview(imageTitle)
    addSubview(imageView)

    addConstraintsWithFormat("H:|-25-[v0(80)]|", views: imageTitle)
    addConstraintsWithFormat("V:|-45-[v0(20)]|", views: imageTitle)

    addConstraintsWithFormat("H:[v0(28)]", views: imageView)
    addConstraintsWithFormat("V:|-15-[v0(28)]|", views: imageView)

    addConstraint(NSLayoutConstraint(item: imageTitle, attribute: .centerX, relatedBy: .equal, toItem: self, attribute: .centerX, multiplier: 1, constant: 0))
    addConstraint(NSLayoutConstraint(item: imageTitle, attribute: .centerY, relatedBy: .equal, toItem: self, attribute: .centerY, multiplier: 1, constant: 0))

    addConstraint(NSLayoutConstraint(item: imageView, attribute: .centerX, relatedBy: .equal, toItem: self, attribute: .centerX, multiplier: 1, constant: 0))
    addConstraint(NSLayoutConstraint(item: imageView, attribute: .centerY, relatedBy: .equal, toItem: self, attribute: .centerY, multiplier: 1, constant: 0))
}
</code>```

}

after scrolling

答:
You can try this</p>

```<code>self.navigationController.hidesBarsOnSwipe = true
</code>```

Body:
i made NavigationBar and TabBar programmatically, but hide navigationBar when i scroll at down collectionView. here is code
import Foundation

import Foundation
import UIKit

class HomeMyBazar: UICollectionViewController, UICollectionViewDelegateFlowLayout {

let cellId = "cellId"

let productCellId = "productCellId"
let dealsCellId = "dealsCellId"

let titles = ["Hello world", "Product", "Deals", "Store world"]

override func viewDidLoad() {
    super.viewDidLoad()

    navigationController?.navigationBar.isTranslucent = false

    setupNavBarButtons()

    setupMenuBar()

    setupCollectionView()

}

func setupNavBarButtons() {

lazy var settingsLauncher: SettingsLauncher = {
    let launcher = SettingsLauncher()
    launcher.homeController = self
    return launcher
}()

func targetMyBazar() {

    let secondViewController = ViewController1()
    self.navigationController?.pushViewController(secondViewController, animated: true)

}

func targetSearch() {

    let viewController = ViewController4()
    self.navigationController?.pushViewController(viewController, animated: true)
}

func targetUser() {

    let viewController = ViewController3()
    self.navigationController?.pushViewController(viewController, animated: true)
}

func targetCart() {

    let viewController = ViewController5()
    self.navigationController?.pushViewController(viewController, animated: true)
}

func handleMore() {

    settingsLauncher.showSettings()
}

func showControllerForSetting(_ setting: Setting) {
    let dummySettingsViewController = UIViewController()
    dummySettingsViewController.view.backgroundColor = UIColor.white
    dummySettingsViewController.navigationItem.title = setting.name.rawValue
    navigationController?.navigationBar.tintColor = UIColor.white
    navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.white]
    navigationController?.pushViewController(dummySettingsViewController, animated: true)
}

func scrollToMenuIndex(_ menuIndex: Int) {
    let indexPath = IndexPath(item: menuIndex, section: 0)
    collectionView?.scrollToItem(at: indexPath, at: UICollectionViewScrollPosition(), animated: true)

}

fileprivate func setTitleForIndex(_ index: Int) {
    if let titleLabel = navigationItem.titleView as? UILabel {
        titleLabel.text = "  \(titles[index])"
    }

}

lazy var menuBar: MenuBar = {
    let mb = MenuBar()
    mb.homeController = self
    return mb
}()

fileprivate func setupMenuBar() {
    navigationController?.hidesBarsOnSwipe = true

    let blackView = UIView()

    blackView.backgroundColor = .lightGray

    view.addSubview(blackView)
    view.addConstraintsWithFormat("H:|[v0]|", views: blackView)
    view.addConstraintsWithFormat("V:[v0(50)]", views: blackView)

    view.addSubview(menuBar)
    view.addConstraintsWithFormat("H:|[v0]|", views: menuBar)
    view.addConstraintsWithFormat("V:[v0(80)]", views: menuBar)

    menuBar.topAnchor.constraint(equalTo: topLayoutGuide.bottomAnchor).isActive = true
}

override func scrollViewDidScroll(_ scrollView: UIScrollView) {
    menuBar.horizontalBarLeftAnchorConstraint?.constant = scrollView.contentOffset.x / 4
}

override func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {

    let index = targetContentOffset.pointee.x / view.frame.width

    let indexPath = IndexPath(item: Int(index), section: 0)
    menuBar.collectionView.selectItem(at: indexPath, animated: true, scrollPosition: UICollectionViewScrollPosition())

    setTitleForIndex(Int(index))
}

func setupCollectionView() {

    if let flowLayout = collectionView?.collectionViewLayout as? UICollectionViewFlowLayout {
        flowLayout.scrollDirection = .horizontal
        flowLayout.minimumLineSpacing = 0
    }

    collectionView?.backgroundColor = UIColor.blue

    collectionView?.register(MyBazarCell.self, forCellWithReuseIdentifier: cellId)

    collectionView?.register(ProductCell.self, forCellWithReuseIdentifier: productCellId)
    collectionView?.register(DealsCell.self, forCellWithReuseIdentifier: dealsCellId)

    collectionView?.contentInset = UIEdgeInsetsMake(110, 0, 0, 0)

    collectionView?.isPagingEnabled = true
}

override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return 4
}

override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    let identifier: String
    if indexPath.item == 1 {
        identifier = productCellId
    } else if indexPath.item == 2 {
        identifier = dealsCellId
    } else {
        identifier = cellId
    }

    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: identifier, for: indexPath)

    return cell
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    return CGSize(width: view.frame.width, height: view.frame.height - 50)
}

}

import Foundation

import UIKit

struct Item {
    var imageName: String
    var text: String
}

class MenuBar: UIView, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {

lazy var collectionView: UICollectionView = {

    let layout = UICollectionViewFlowLayout()

    let cv = UICollectionView(frame: .zero, collectionViewLayout: layout)

    cv.backgroundColor = UIColor.black
    cv.dataSource = self
    cv.delegate = self
    return cv
}()

let data: [Item] = [
    Item(imageName: "service", text: "Service"),
    Item(imageName: "product", text: "Product "),
    Item(imageName: "deals", text: " Deals"),
    Item(imageName: "store", text: "Store")
]

let cellId = "cellId"
let imageNames = ["service", "product", "deals", "store"]
let imageTitle = ["Servic", "Product", "Deals", "Store"]

var homeController: HomeMyBazar?

override init(frame: CGRect) {
    super.init(frame: frame)

    collectionView.register(MenuCell.self, forCellWithReuseIdentifier: cellId)

    addSubview(collectionView)
    addConstraintsWithFormat("H:|[v0]|", views: collectionView)
    addConstraintsWithFormat("V:|[v0]|", views: collectionView)

    let selectedIndexPath = IndexPath(item: 0, section: 0)
    collectionView.selectItem(at: selectedIndexPath, animated: false, scrollPosition: UICollectionViewScrollPosition())

    setupHorizontalBar()
}

var horizontalBarLeftAnchorConstraint: NSLayoutConstraint?

func setupHorizontalBar() {
    let horizontalBarView = UIView()

    horizontalBarView.backgroundColor = UIColor.red
    horizontalBarView.translatesAutoresizingMaskIntoConstraints = false
    addSubview(horizontalBarView)

    horizontalBarLeftAnchorConstraint = horizontalBarView.leftAnchor.constraint(equalTo: self.leftAnchor)
    horizontalBarLeftAnchorConstraint?.isActive = true

    horizontalBarView.bottomAnchor.constraint(equalTo: self.bottomAnchor).isActive = true
    horizontalBarView.widthAnchor.constraint(equalTo: self.widthAnchor, multiplier: 1/4).isActive = true
    horizontalBarView.heightAnchor.constraint(equalToConstant: 4).isActive = true
}

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

    homeController?.scrollToMenuIndex(indexPath.item)

}

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

    return data.count
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! MenuCell

    let item = data[indexPath.item]
    cell.imageView.image = UIImage(named: item.imageName)
    cell.imageTitle.text = item.text

    cell.tintColor = UIColor.white

    return cell
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    return CGSize(width: frame.width / 4, height: frame.height)
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
    return 0
}

required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}

}

class MenuCell: BaseCell {

let imageTitle: UILabel = {
    let label = UILabel()
    label.text = "hellow world label"
    label.textColor = .white
    return label
}()

let imageView: UIImageView = {
    let iv = UIImageView()
    iv.image = UIImage(named: "service")?.withRenderingMode(.alwaysTemplate)

    iv.tintColor = .white
    return iv
}()

override var isHighlighted: Bool {
    didSet {

        imageView.tintColor = isHighlighted ? UIColor.white : UIColor.white
    }
}

override var isSelected: Bool {
    didSet {

        imageView.tintColor = isSelected ? UIColor.white : UIColor.white
    }
}

override func setupViews() {
    super.setupViews()

    addSubview(imageTitle)
    addSubview(imageView)

    addConstraintsWithFormat("H:|-25-[v0(80)]|", views: imageTitle)
    addConstraintsWithFormat("V:|-45-[v0(20)]|", views: imageTitle)

    addConstraintsWithFormat("H:[v0(28)]", views: imageView)
    addConstraintsWithFormat("V:|-15-[v0(28)]|", views: imageView)

    addConstraint(NSLayoutConstraint(item: imageTitle, attribute: .centerX, relatedBy: .equal, toItem: self, attribute: .centerX, multiplier: 1, constant: 0))
    addConstraint(NSLayoutConstraint(item: imageTitle, attribute: .centerY, relatedBy: .equal, toItem: self, attribute: .centerY, multiplier: 1, constant: 0))

    addConstraint(NSLayoutConstraint(item: imageView, attribute: .centerX, relatedBy: .equal, toItem: self, attribute: .centerX, multiplier: 1, constant: 0))
    addConstraint(NSLayoutConstraint(item: imageView, attribute: .centerY, relatedBy: .equal, toItem: self, attribute: .centerY, multiplier: 1, constant: 0))
}

}

after scrolling

Body:
You can try this

self.navigationController.hidesBarsOnSwipe = true