text:
Q: In jsp page Confirm only appear on first row form button click. On second row form submit it does not appear and my ajax call is executed I have developed spring boot web application, on front end I have JSP pages.
I am displaying list of user in table and there are corresponding action(form for each action) like update, reset, delete etc in my each row. On Delete action I am first displaying confirm message. If user press Ok I am making Ajax get call to Controller which delete user from database and return status 0 or 1. I have notice that on first record it show confirm and on OK it send the call and proper response is return back. When I click on second record delete button it does not show confirm message and submit the form which return error 405 Get Method not supported. I have also observe no other record is work as per behavior.
My JSP code is as below
I have tried different way to show confirm message like onclick I have tried to execute it but same is result.
I have remove all other js/css libraries and only j query on my page but it produce same output. I have also tried to create a simple page and simulate same behavior it also show same.

   <form method="post" action="/createUserDetails">
      <button type="submit" value="Add User"
         class="btn btn-success btn-lg">+</button>
   </form>

            First Name
            Last Name
            Actions

         <c:forEach items="${userList}" var="item">

               ${item.firstName}
               ${item.lastName}

                  <form method="post" action="/assignUserLicense">
                     <input type="hidden" name="userId" value="${item.id}">
                     <input type="hidden" name="customerUniqueId"
                        value="${customerUniqueId}">
                     <button type="submit" value="Assign License"
                        class="btn btn-warning">Assign License</button>
                  </form>

                  <form method="post" action="/unassignUserLicense">
                     <input type="hidden" name="userId" value="${item.id}">
                     <input type="hidden" name="customerUniqueId"
                        value="${customerUniqueId}">
                     <button type="submit" value="UnAssign License"
                        class="btn btn-warning">Unassign License</button>
                  </form>

                  <form method="post" action="/modifyUserDetails"
                     id="modifyUserDetailsForm">
                     <input type="hidden" name="userId" id="userId"
                        value="${item.id}"> <input type="hidden"
                        name="customerUniqueId" id="customerUniqueId"
                        value="${customerUniqueId}"> <input type="hidden"
                        name="displayName" id="displayName"
                        value="${item.displayName}"> <input type="hidden"
                        name="userPrincipalName" id="userPrincipalName"
                        value="${item.userPrincipalName}"> <input
                        type="hidden" name="firstName" id="firstName"
                        value="${item.firstName}"> <input type="hidden"
                        name="lastName" id="lastName" value="${item.lastName}">
                     <button type="submit" value="Modify User"
                        class="btn btn-warning">Modify User</button>
                  </form>

                  <form method="post" action="/resetUserUserDetails">
                     <input type="hidden" name="userId" value="${item.id}">
                     <input type="hidden" name="customerUniqueId"
                        value="${customerUniqueId}">
                     <button type="submit" value="Get User"
                        class="btn btn-warning">Reset Password</button>
                  </form>

                  <form id="myDeleteFrom">
                     <input type="hidden" name="userId" value="${item.id}">
                     <input type="hidden" name="customerUniqueId"
                        value="${customerUniqueId}">
                     <button type="submit" value="Get User"
                        class="btn btn-warning">Delete User</button>
                  </form>

         </c:forEach>

my javascript code
$(document)
            .ready(
                    function() {
                    $("#myDeleteFrom")
                            .submit(
                                    function() {
                                        var confirmResponse = confirm("Are you sure you want to delete this user");

                                        if (confirmResponse) {
                                            //Ajax get call
                                        } else {
                                            return false;
                                        }
                                    });
                });

I am expecting it should work on any row delete form submit button click.


text:
Q: How do I call a certain Episodes in a Genre I am new to django and I am getting confused over that, basically I want to iterate through all of the series and return the ones that are in certain genre.
models.py
class Series(models.Model):
    series_title = models.CharField(max_length=50)
    series_desc = models.TextField(max_length=500)
    series_date_published = models.DateTimeField()

class Genres(models.Model):
    genre_name = models.CharField(max_length=50)
    genre_serie = models.ManyToManyField(Series)

class Episodes(models.Model):
    episode_title = models.CharField(max_length=50)
    episode_desc = models.TextField(max_length=500)
    episode_date_published = models.DateTimeField()
    episode_number = models.IntegerField()
    episode_series = models.ForeignKey(Series, on_delete=models.CASCADE)

views.py
class IndexView(generic.ListView):
    model = Series
    template_name = 'videos/index.html'
    context_object_name = 'series'
    def get_queryset(self):
        return Series.objects.all()

class ViewSeries(generic.ListView):
    model = Episodes
    template_name = 'videos/videos.html'
    context_object_name = 'episodes'
    def get_queryset(self):
        return Episodes.objects.filter(episode_series=self.kwargs['pk'])

class ViewGenres(generic.ListView):
    model = Series
    template_name = 'videos/genres.html'
    context_object_name = 'series'
    def get_queryset(self):
        return Series.objects.filter(genres__genre_serie=self.kwargs['pk'])

And I am trying that to display my series in a genre:
{% for s in series %}
  {{ s.series_title }}
{% endfor %}

urls.py
app_namme = 'videos'
urlpatterns = [
    path('', IndexView.as_view(),name='index'),
    path('viewseries/<int:pk>', ViewSeries.as_view(),name='detail'),
    path('viewgenres/<int:pk>', ViewGenres.as_view(),name='genres'),
]

I placed that url because from there I want to get the link to the series but when I type {% url 'detail' ser.id %} I got NoReverseMatch error.
I am pretty sure that there is an easy solution to all of that and I am doing it really complex that is why I posted the question.

A: There are two problems here: (1) getting the series that belong to a certain genre; and (2) correcting the {% url ... %} lookup:
We can do this by exploiting the reverse relation of a ManyToManyField (this is - if no reverse name is provided - the modelname):
def get_queryset(self):
    return Series.objects.filter(genre__pk=self.kwargs['pk']).distinct()
Then for the {% url ... %} part, you probably need to provide a named parameter (also the url needs to be placed between curly brackets, not round ones, so:
{% for s in series %}
  {{ s.series_title }}
{% endfor %}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Change menubar items based on current NSViewController I have NSViewControllers for things like Orders and Clients.  These all live inside a tab view controller.  When I'm on the Orders, tab, I want the File->New to say New Order, and likewise New Client on that controller.
If I implement validateMenuItem: and change the name it's not just for that controller.  This means that every single view controller I create would have to reset the name back to just New.
How do I change titles of a menu item dynamically, based on the currently selected NSViewController?


text:
Q: How do i define the equation for a line with the following information? I have to find the parametric equation for the line $M_1$ with the following info:

*

*$M_1$ goes through the point $P(1,2,2)$

*Is parallel with the plane $x + 3y + z = 1$

*Has an intersection somewhere with the line $M_2 = 1+t, 2-2t, -1+2t$
So if I understand it correctly, since $M_1$ is parallel with the plane $x + 3y + z = 1$.  I can do $x = 1-3y-z$ and replace $y$ and $z$ with $t$ and $s$ to get the direction of $M_1$. The planes equation will then be:
$$(x,y,z)=(1-3s-t , s , t)$$
So then the $M_1$ should be with the coordinates from $P$:
$$x = 1 + 1-3s-t$$
$$y = 2 + s$$
$$z = 2 + t$$
But it is incorrect because $M_1$ and $M_2$ have no intersections. Where did I go wrong here?
Thanks in advance for the answers!

A: I expect there is a typo in the expression for $M_2$. You've written $-1+2$ for the third coordinate which seems incorrect.  I'll guess you meant $-1+2t$ and compute from there.  If you meant something else, you should be able to adapt the calculation easily enough.
We note that the normal to the given plane is $$\vec n=(1,3,1)$$
We assume the intersection between the desired line and the given line is $P(t)=(1+t,2-2t,-1+2t)$.  Then the vector $\vec {v(t)}=P(t)-P=(t,-2t,-3+2t)$ should be perpendicular to $\vec n$ so we want to solve:  $$t-6t-3+2t=0\implies 3t=-3\implies t=-1$$
Thus $M_1$ is given by $$P+t\vec {v(-1)}=(1,2,2)+t(-1,2,-5)$$
Check:  Since $P$ is not in the given plane we should see that no point in $M_1$ is in the plane.  We try to solve $$1-t+6+6t+2-5t=1$$ and confirm that there is no solution.

A: $M_1$ does not have to be on then plane $x + 3y + z = 1$.  If the line $M_1$ is parallel to the plane $x + 3y + z = 1$, then it must be on the plane
$x + 3y + z = k$ for some real number $k$. Since the line $M_1$ contains the point $P=(1,2,2)$, and since $(1) + 3(2) + (2) = 9$,  then the line is on the plane $x + 3y + z = 9$.
The plane $x + 3y + z = 9$ intersects the line $M_2(t) =  (1+t, 2-2t, -1+2t)$ when
\begin{align}
   (1+t) + 3(2-2t) + (-1+2t) &= 9 \\
   6 - 3t &= 9 \\
   t &= -1
\end{align}
Hence the point $M_2(-1) = (0, 4, -3)$ is also on the line $M_1$. So the line $M_1$ is parallel to the direction
$(1,2,2) - (0, 4, -3) = (1,-2,5)$, then the equation of $M_1$ is
$$M_1(t) = (1,2,2) + t(1,-2,5)$$
We can verify your three requirements

*

*$M_1$ goes through the point $P(1,2,2).$

*

*Because $M_1(0) = (1,2,2)$.

*Is parallel with the plane $x + 3y + z = 1.$

*

*Because $x+3y+z=(1+t)+3(2-2t)+(2+5t) = 9.$

*Has an intersection somewhere with the line $M_2 = 1+t, 2-2t, -1+2t.$

*

*Because $M_2(-1) = (0,4,-3)=M_1(-1)$


text:
Q: Why is this method not sorting the XML parser? I would like to sort my list by Clinic name, the parser works fortunately. However the sorting technique I have used does not. Have I implemented it incorrectly?
    public class BookScreen extends Activity {

        //array
        ArrayList<HashMap<String, String>> songsList;
        ProgressDialog mProgressDialog;
        // All static variables
        static final String URL = "https://dl.dropboxusercontent.com/u/42241589/test.xml";
        // XML node keys
        static final String KEY_CLINIC = "clinic"; // parent node
        static final String KEY_ID = "id";
        static final String KEY_TITLE = "title";
        static final String KEY_DATE = "date";
        static final String KEY_TIME = "time";
        static final String KEY_ADDRESS = "address";
        //static final String KEY_THUMB_URL = "thumbnail";
        ListView list;
        LazyAdapter adapter;

        @SuppressLint("NewApi")
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.book_main);
            new DownloadXML().execute();
        }

        private class DownloadXML extends AsyncTask<Void, Void, Void> {

            protected void onPreExecute() {
                super.onPreExecute();
                mProgressDialog = new ProgressDialog(BookScreen.this);
                mProgressDialog.setTitle("List is loading");
                mProgressDialog.setMessage("Loading...");
                mProgressDialog.setIndeterminate(false);
                mProgressDialog.show();
            }

            protected Void doInBackground(Void... params) {
                songsList = new ArrayList<HashMap<String, String>>();
                XMLParser parser = new XMLParser();
                String xml = parser.getXmlFromUrl(URL); // getting XML from URL
                Document doc = parser.getDomElement(xml); // getting DOM element
                try {
                    NodeList nl = doc.getElementsByTagName(KEY_CLINIC); //define parent node
                    // looping through all song nodes <song>
                    for (int i = 0; i < nl.getLength(); i++) {
                        // creating new HashMap
                        HashMap<String, String> map = new HashMap<String, String>();
                        Element e = (Element) nl.item(i);
                        // adding each child node to HashMap key => value
                        map.put(KEY_ID, parser.getValue(e, KEY_ID));
                        map.put(KEY_TITLE, parser.getValue(e, KEY_TITLE));
                        map.put(KEY_DATE, parser.getValue(e, KEY_DATE));
                        map.put(KEY_TIME, parser.getValue(e, KEY_TIME));
                        map.put(KEY_ADDRESS, parser.getValue(e, KEY_ADDRESS));
                        //map.put(KEY_THUMB_URL, parser.getValue(e, KEY_THUMB_URL));
                        // adding HashList to ArrayList
                        songsList.add(map);
                    }
                } catch (Exception e) {
                    Log.e("Error", e.getMessage());
                    e.printStackTrace();
                }
                return null;
            }

            protected void onPostExecute(Void args) {
                    list=(ListView)findViewById(R.id.list);
                // Getting adapter by passing xml data ArrayList
                Collections.sort(songsList, comparator);
                adapter = new LazyAdapter(BookScreen.this, songsList);
                adapter.notifyDataSetChanged();
                list.setAdapter(adapter);
                //Close dialog
                mProgressDialog.dismiss();
            }
        }
        Comparator<HashMap<String, String>> comparator = new Comparator<HashMap<String, String>>() {
                @Override
                public int compare(HashMap<String, String> map1, HashMap<String, String> map2) {
                    return map1.get(KEY_CLINIC).compareTo(map2.get(KEY_CLINIC));
                }

    };
}

The logcat points to an NullPointerException at `return   map1.get(KEY_CLINIC).compareTo(map2.get(KEY_CLINIC));' in the method comparator.
12-01 11:25:34.730: E/AndroidRuntime(885): FATAL EXCEPTION: main
12-01 11:25:34.730: E/AndroidRuntime(885): Process: com.example.clinicbooker, PID: 885
12-01 11:25:34.730: E/AndroidRuntime(885): java.lang.NullPointerException
12-01 11:25:34.730: E/AndroidRuntime(885):  at com.example.clinicbooker.BookScreen$1.compare(BookScreen.java:102)
12-01 11:25:34.730: E/AndroidRuntime(885):  at com.example.clinicbooker.BookScreen$1.compare(BookScreen.java:1)
12-01 11:25:34.730: E/AndroidRuntime(885):  at java.util.TimSort.countRunAndMakeAscending(TimSort.java:320)
12-01 11:25:34.730: E/AndroidRuntime(885):  at java.util.TimSort.sort(TimSort.java:185)
12-01 11:25:34.730: E/AndroidRuntime(885):  at java.util.TimSort.sort(TimSort.java:169)
12-01 11:25:34.730: E/AndroidRuntime(885):  at java.util.Arrays.sort(Arrays.java:2023)
12-01 11:25:34.730: E/AndroidRuntime(885):  at java.util.Collections.sort(Collections.java:1883)
12-01 11:25:34.730: E/AndroidRuntime(885):  at com.example.clinicbooker.BookScreen$DownloadXML.onPostExecute(BookScreen.java:91)
12-01 11:25:34.730: E/AndroidRuntime(885):  at com.example.clinicbooker.BookScreen$DownloadXML.onPostExecute(BookScreen.java:1)
12-01 11:25:34.730: E/AndroidRuntime(885):  at android.os.AsyncTask.finish(AsyncTask.java:632)
12-01 11:25:34.730: E/AndroidRuntime(885):  at android.os.AsyncTask.access$600(AsyncTask.java:177)
12-01 11:25:34.730: E/AndroidRuntime(885):  at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
12-01 11:25:34.730: E/AndroidRuntime(885):  at android.os.Handler.dispatchMessage(Handler.java:102)
12-01 11:25:34.730: E/AndroidRuntime(885):  at android.os.Looper.loop(Looper.java:137)
12-01 11:25:34.730: E/AndroidRuntime(885):  at android.app.ActivityThread.main(ActivityThread.java:4998)
12-01 11:25:34.730: E/AndroidRuntime(885):  at java.lang.reflect.Method.invokeNative(Native Method)
12-01 11:25:34.730: E/AndroidRuntime(885):  at java.lang.reflect.Method.invoke(Method.java:515)
12-01 11:25:34.730: E/AndroidRuntime(885):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:777)
12-01 11:25:34.730: E/AndroidRuntime(885):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:593)
12-01 11:25:34.730: E/AndroidRuntime(885):  at dalvik.system.NativeStart.main(Native Method)

A: Your comparator is trying to pull an entry with the key KEY_CLINIC, but there was never an entry "put" into the map with that key.


text:
Q: Error: Nonce is too small - Bitfinex api I try to call rest API from Bitfinex by using bitfinex library (https://www.npmjs.com/package/bitfinex). The documentation warned this error when running more than 1 process at the same time with the same API keys. However, I believe that I only run a process at once and even I generate new API keys, the error still happens. I'm thinking about overriding the nonce or extending it but I don't know how to do this. I haved tried some suggestions on the Internet, but still nothing worked.
Below is my code for reference:
import Bitfinex = require('bitfinex');
import pollingtoevent = require('polling-to-event');
import { Logger, LoggerFactory } from '../../common';
import { AppDataServices } from '../../data';

export class BitfinexPoller {
  private static readonly LOGGER: Logger = LoggerFactory.getLogger();
  private bitfinex: any = undefined;
  private emitter: any = undefined;
  private public_key: string = '<my-public-key>';
  private secret_key: string = '<my-secret-key>';
  private nonce: any = new Date().getTime();

  constructor(private appServices: AppDataServices) {
    BitfinexPoller.LOGGER.info('Bitfinex poller init');

    this.bitfinex = new Bitfinex(this.public_key, this.secret_key, this.nonce);

    // Lend book service
    this.emitter = pollingtoevent((done: any) => {
      this.bitfinex.lendbook('USD', (err: any, res: any, orderId: any) => {
        done(err, res);
      });
    }, { interval: 30000, eventName: 'bitfinex-lending' });

    this.emitter.on('bitfinex-lending', (data: any) => {
      BitfinexPoller.LOGGER.info(data);
      if (data.bids !== undefined) {
        for (const row of data.bids) {
          appServices.lendbookService.insert(BitfinexPoller.lendingData('BID', row));
        }
      }
      if (data.asks !== undefined) {
        for (const row of data.asks) {
          appServices.lendbookService.insert(BitfinexPoller.lendingData('ASK', row));
        }
      }
    });

    // Order book service
    this.emitter = pollingtoevent((done: any) => {
      this.bitfinex.orderbook('btcusd', (err: any, res: any, orderId: any) => {
        done(err, res);
      });
    }, { interval: 30000, eventName: 'bitfinex-order' });

    this.emitter.on('bitfinex-order', (data: any) => {
      BitfinexPoller.LOGGER.info(data);
      if (data.bids !== undefined) {
        for (const row of data.bids) {
          appServices.lendbookService.insert(BitfinexPoller.orderData('BID', row));
        }
      }
      if (data.asks !== undefined) {
        for (const row of data.asks) {
          appServices.lendbookService.insert(BitfinexPoller.orderData('ASK', row));
        }
      }
    });
  }
}

A: It's most likely you're firing off two authenticated calls in quick succession. The order that you send requests is not always the same as the order that they're processed, so the second request with the higher nonce is being processed first causing the first request to fail.
You can create and use multiple API keys for different requests or have a pool that you cycle through so you don't use the same api key multiple times in quick succession.

A: My solution with nodejs has been to defer the calls via promises.
Something like this:
function sleep(millis) {
  return new Promise(resolve => setTimeout(resolve, millis));
}

sleep(500).then(() => {
   //do work
  });
  sleep(600).then(() => {
   //do work
  });

Obviously if you are looking at extremely low latency and high speed this isn't for you.


text:
Q: Changes to Touch ID warning after restarting iPhone due to unresponsive app This morning I restarted my iPhone 7 due to an unresponsive app - Facebook, which does not use Touch ID. On restart I had to enter my passcode, which was to be expected after a reboot.
I then tried to view some banking apps, which require Touch ID, the first required my passcode, rather than Touch ID, I thought this was strange, but carried on. The second banking app showed a Touch ID error. Going back to the first app showed the error below.
I have not made any changes to Touch ID since setting up the phone months ago (at which point I filled all 5 slots for fingerprints), so am slightly concerned about this warning.
What could have caused this message? And what is the safest course of action?

A: This looks to be an issue with your bank's app. If I remember correctly, apps are notified anytime a touchID change is made, so things like 1Password will request your Master Password to sign in. This popup seems to be of your bank's design, and a software glitch made your phone think there was a change in TouchID.
For future reference, you can confirm that all fingers enrolled in touchID are yours by going to Settings > Touch ID & Passcode. Then scroll to the part of the pane where it shows your touchID fingerprints:

Now, put each registered finger on the sensor and wait until the fingerprint is highlighted, like so:

Ensure that each fingerprint is yours by making sure that your fingers highlight all of the fingerprint options.
Or, you could just set touchID up again for all your fingers.


text:
Q: Empty UPDATE way slower than corresponding SELECT I am using MySQL 5.1.73 with InnoDB
I have a very slow UPDATE query (about 10s), where the number of changed rows is (often) zero (it takes about the same time if there are a few rows changed):
UPDATE job_queue SET state=4 WHERE error_counter>=5 AND state=1;
Query OK, 0 rows affected (9.33 sec)

However, the corresponding SELECT is quite fast:
SELECT id FROM job_queue WHERE error_counter>=5 AND state=1;
Empty set (0.03 sec)

EXPLAIN SELECT id FROM job_queue WHERE error_counter>=5 AND state=1;
+----+-------------+-----------+-------+--------------------------------------------+---------------------+---------+------+-------+--------------------------+
| id | select_type | table     | type  | possible_keys                              | key                 | key_len | ref  | rows  | Extra                    |
+----+-------------+-----------+-------+--------------------------------------------+---------------------+---------+------+-------+--------------------------+
|  1 | SIMPLE      | job_queue | index | Allinone,state_timeout,state_error_counter | state_error_counter | 5       | NULL | 13515 | Using where; Using index |
+----+-------------+-----------+-------+--------------------------------------------+---------------------+---------+------+-------+--------------------------+

As you can see, this is (should be?) an indexed query, on a not-too-big database (about 9000 rows, although it does contain some blobs so the total DB size is about 800MB).
The questions are:

*

*Why is the update so slow?

*How can I debug it?

*How can I speed it up?

UPDATE:
I tried the same database on a different server with MySQL 5.5.35 (Debian wheezy default). The query is still fast, and the update is still slow, and there is still no explain for updates... I may try to upgrade to mysql 5.6 from dotdeb, or try mariadb. :)
UPDATE 2:
I tried different row formats (dynamic and compressed), but it was not (significantly) faster either.
UPDATE 3:
I updated to MySQL 5.6.17 (from dotdeb), and the performance is generally the same, but I finally got an explain for the update:
EXPLAIN UPDATE job_queue.job_queue SET state=4 WHERE error_counter>=5 AND state=1;
+----+-------------+-----------+-------+---------------+---------+---------+------+-------+-------------+
| id | select_type | table     | type  | possible_keys | key     | key_len | ref  | rows  | Extra       |
+----+-------------+-----------+-------+---------------+---------+---------+------+-------+-------------+
|  1 | SIMPLE      | job_queue | index | NULL          | PRIMARY | 8       | NULL | 70222 | Using where |
+----+-------------+-----------+-------+---------------+---------+---------+------+-------+-------------+

This only confirms what could be suspected all along: the UPDATE is not using any indexes. So the question remains: WHY?
I will try to create a minimal example that produces this behaviour; maybe in the course of that, I will find some answers....

A: I've found the problem! The state column was defined as char(1). Interestingly, SELECTs containing state=1 most of the times do use indexes, but UPDATEs never. However, specifying state="1" always uses indexes.
So in summary, if col is a char and col is indexed:
UPDATE table SET col=2 WHERE col=1

will not use an index and thus be slow, whereas
UPDATE table SET col=2 WHERE col="1"

will use an index and thus be fast.


text:
Q: Show all div if none of link clicked I have a page name url.com/yourfirstpage/ when i go to the page all the div are hidden by default (display:none)
if we target #sec1 as url.com/yourfirstpage/#sec1 it only displays sec1 and hide others.
I was wondering if we go the url without having anchor id like url.com/yourfirstpage/ it needs to show all the divs.

#sec1, #sec2, #sec3{
 display:none;
}
#sec1:target{
 display:block;
}
#sec2:target{
 display:block;
}
#sec3:target{
 display:block;
}
sec1
sec2
sec3

 this is sec1

 this is sec2

 this is sec3

A: Here is a trick in case you are able to modify your HTML structure. The idea is to have the elements visible and then we hide them using :target. Since we don't have previous sibling selector or parent selector, I used id within a parent element to be able to select any element:

#sec1:target .page:nth-child(n+2){
  display: none;
}

#sec2:target .page:nth-child(2n+1){
  display: none;
}

#sec3:target .page:nth-last-child(n+2){
  display: none;
}
sec1
sec2
sec3

 this is sec1

 this is sec2

 this is sec3

It can work with any number of sections and we can improve the CSS code as follow:

#sec1:target .page:not(:nth-child(1)),
#sec2:target .page:not(:nth-child(2)),
#sec3:target .page:not(:nth-child(3)),
#sec4:target .page:not(:nth-child(4)),
#sec5:target .page:not(:nth-child(5)) {
  display: none;
}
sec1
sec2
sec3
sec4
sec5

 this is sec1

 this is sec2

 this is sec3

 this is sec4

 this is sec5

A: this quick approach may help
you can do with ! selector in CSS by using postcss plugins

[...document.querySelectorAll('a')].forEach(a => {
    a.addEventListener('click', () => {
        a.parentElement.classList.add('targeted')
    })
})
.targeted div {
  display: none;
}
.targeted div:target {
  display: block;
}
sec1
sec2
sec3

 this is sec1

 this is sec2

 this is sec3


text:
Q: systemd uwsgi service fails to run automatically but runs when started from interactive session I enabled the uWSGI service in systemd but it fails to run at startup, the log shows the following:
Wed Nov 22 12:36:10 2017 - your processes number limit is 47903
Wed Nov 22 12:36:10 2017 - your memory page size is 4096 bytes
Wed Nov 22 12:36:10 2017 - detected max file descriptor number: 1024
Wed Nov 22 12:36:10 2017 - lock engine: pthread robust mutexes
Wed Nov 22 12:36:10 2017 - thunder lock: disabled (you can enable it with --thunder-lock)
Wed Nov 22 12:36:10 2017 - uwsgi socket 0 bound to UNIX address /run/uwsgi/app/myapp/socket fd 3
Wed Nov 22 12:36:10 2017 - Python version: 2.7.12 (default, Nov 19 2016, 06:48:10)  [GCC 5.4.0 20160609]
Wed Nov 22 12:36:10 2017 - Set PythonHome to /home/me/venv
ImportError: No module named site

However, when I run sudo systemctl restart uwsgi the service starts as expected:
Wed Nov 22 13:31:07 2017 - setuid() to 1000
Wed Nov 22 13:31:07 2017 - your processes number limit is 47903
Wed Nov 22 13:31:07 2017 - your memory page size is 4096 bytes
Wed Nov 22 13:31:07 2017 - detected max file descriptor number: 1024
Wed Nov 22 13:31:07 2017 - lock engine: pthread robust mutexes
Wed Nov 22 13:31:07 2017 - thunder lock: disabled (you can enable it with --thunder-lock)
Wed Nov 22 13:31:07 2017 - uwsgi socket 0 bound to UNIX address /run/uwsgi/app/myapp/socket fd 3
Wed Nov 22 13:31:07 2017 - Python version: 2.7.12 (default, Nov 19 2016, 06:48:10)  [GCC 5.4.0 20160609]
Wed Nov 22 13:31:07 2017 - Set PythonHome to /home/me/venv
Wed Nov 22 13:31:07 2017 - *** Python threads support is disabled. You can enable it with --enable-threads ***
Wed Nov 22 13:31:07 2017 - Python main interpreter initialized at 0xec83c0
Wed Nov 22 13:31:07 2017 - your server socket listen backlog is limited to 100 connections
Wed Nov 22 13:31:07 2017 - your mercy for graceful operations on workers is 60 seconds
Wed Nov 22 13:31:07 2017 - mapped 218304 bytes (213 KB) for 2 cores
Wed Nov 22 13:31:07 2017 - *** Operational MODE: preforking ***
Wed Nov 22 13:31:09 2017 - WSGI app 0 (mountpoint='') ready in 2 seconds on interpreter 0xec83c0 pid: 2744 (default app)
Wed Nov 22 13:31:09 2017 - *** uWSGI is running in multiple interpreter mode ***
Wed Nov 22 13:31:09 2017 - spawned uWSGI master process (pid: 2744)
Wed Nov 22 13:31:09 2017 - spawned uWSGI worker 1 (pid: 2760, cores: 1)
Wed Nov 22 13:31:09 2017 - spawned uWSGI worker 2 (pid: 2761, cores: 1)

What could be the problem?


text:
Q: Android - could not install *smartsocket* listener When I try run my Android application I get this exception:

Error while waiting for device: java.lang.RuntimeException: Unable to
  create Debug Bridge: Unable to start adb server: error: could not
  install smartsocket listener: cannot bind to 127.0.0.1:5037: An
  attempt was made to access a socket in a way forbidden by its access
  permissions. (10013) could not read ok from ADB Server
  * failed to start daemon * error: cannot connect to daemon 'C:\Users\XXX\AppData\Local\Android\Sdk\platform-tools\adb.exe,start-server'
  failed -- run manually if necessary

So I try do it manualy with these commands:

adb kill-server

*

*response: * server not running *

adb start-server

*

*response was next exception:

*daemon not running. starting it now on port 5037 *   error: could not install smartsocket listener: cannot bind to 127.0.0.1:5037: An
  attempt was made to access a socket in a way forbidden by its access
  permissions. (10013) could not read ok from ADB Server
*failed to start daemon * error: cannot connect to daemon

I looking for adb process in my task manager but not running. Any ideas? Thanks.

A: I fixed it by adding the ADB to path:
sudo ln -s ~/Android/Sdk/platform-tools/adb /bin/adb

And then killing the ADB server adb kill-server and starting the server again adb start-server.
Observation: I tried to kill java, tried to find the port where it was running using HTOP and Kill, aside from restarting everything but it was a pain in the ass

A: I solved this for myself by simply closing the shell I'd been running adb commands in and starting a new one, inspired by Vinayak Mestri's answer.

A: Open command prompt and enter following command
netstat -ano | findstr :5037
This will show procees id
TCP    127.0.0.1:5037         0.0.0.0:0              LISTENING       832
832 is procees id
Now run command
tasklist | findstr processID  (e.g tasklist | findstr 832)
It will show process name like bash.exe
just go to task manager and end the task bash.exe
and use following command to start adb
adb start-server
voillllaaaaaaa........

A: If you have the situation where this keeps happening and killing and restarting still doesn't work it may be a problem with your adb installation. I had to reinstall adb to resolve this problem:

*

*Reboot to ensure no instances of adb is running

*Launch SDK Manager in Android Studio: Tools->Android->SDK Manager

*Select the SDK Tools tab

*Deselect Android SDK Platform-Tools item

*Hit Apply

*Check the on screen logs to make sure the un-installation succeeded and that the SDK/platform-tools folder is empty.

This should completely remove adb from your SDK.

*

*Now re-select the Android SDK Platform-Tools item

*Hit apply

*Check the on screen logs that installation was successful.

I suspect in my case an update of the platform tools had failed perhaps because it failed to kill a running adb.exe and only a partial update was applied resulting in an unstable adb installation.

A: In my case, the culprit is Visual Studio 2017.  I found out this with the help of Vinayak's answer. I just closed Visual Studio 2017, then ADB started working.

A: Restarting adb server uns an External terminal (CMD) did the job for me:
Android-SDK/platform-tools/adb.exe kill-server
Android-SDK/platform-tools/adb.exe start-server

A: you just let "command prompt" to run as administrator.
so, you can run the command "nox_adb.exe connect 127.0.0.1:62001"
pic as follow:
https://i.stack.imgur.com/fAmXz.png

A: thanks mestri
List the process id using 5037 port

netstat -ano | findstr :5037

TCP    127.0.0.1:39187        127.0.0.1:5037         ESTABLISHED     5400
  TCP    127.0.0.1:39188        127.0.0.1:5037         ESTABLISHED     5400
  TCP    127.0.0.1:39798        127.0.0.1:5037         ESTABLISHED     5400
  TCP    127.0.0.1:39902        127.0.0.1:5037         ESTABLISHED     7296
  TCP    127.0.0.1:40148        127.0.0.1:5037         ESTABLISHED     5400
here 5400,7296 is the pid number

taskkill /pid pidnumber

THEN \n

adb connect localhost:62001

adb server version (41) doesn't match this client (36); killing...
* daemon started successfully *
connected to localhost:62001


text:
Q: War file deployed on EC2 apache tomcat throws java.lang.NoSuchMethodError: org.glassfish.hk2.utilities.general.GeneralUtilities.getWeakHashClock I have uploaded a war file to EC2 instance with Apache Tomcat running 8.0.41 version. I have a simple get request which returns text response. But when I invoke the get call, I'm getting the following error.enter image description here
But when I deploy the same war to my local instance of tomcat, its working perfect. Any help is much appreciated.

A: There were multiple versions of the same jar file. I removed the old versions and only used the latest jars and that resolved the issue.


text:
Q: API DELETE method issue I have an issue with my javaScript code as the delete feature is working but, it is not deleting the right data ...
Example:
1 - test1
2 - test2
3 - test3
My issue is when I try to delete test1, the program deletes test3 which means the program always deletes the last data in the list.
Please, could you help?
Here's my code:

const url = "https://ghu8xhzgfe.execute-api.us-east-1.amazonaws.com/tasks/2877332";
let theTask = [];
let text = '';
const init = () => {
    document.querySelector("#newTask").addEventListener("click", addNewTask);
    addNewTask();
    getDataa();
};
const addNewTask = () => {
    console.log("Adding a new task...");
    let xhr = new XMLHttpRequest();
    let url = "https://ghu8xhzgfe.execute-api.us-east-1.amazonaws.com/tasks";
    let apiKey = "Itcheui2tB58SlUGe8rrP8mskudGsNDT9nfKKG9S";
    let studentId = "2877332";
    let taskDescription = document.querySelector("#task").value;
    let theTask = taskDescription;

    let params = {
        StudentId: studentId,
        Description: taskDescription
    };
    xhr.open("post", url);

    xhr.setRequestHeader("Content-Type", "application/json");
    xhr.setRequestHeader("x-api-key", apiKey);
    xhr.onreadystatechange = () => {
        if (xhr.readyState == 4) {
        }
    }
    xhr.send(JSON.stringify(params));
    getDataa();
};
const getDataa = () => {
    console.log("get Data")
    fetch(url, {
            method: "GET",
            withCredentials: true,
            headers: {
                "x-api-key": "Itcheui2tB58SlUGe8rrP8mskudGsNDT9nfKKG9S",
                "Content-Type": "application/json"
            }
        })
        .then(resp => resp.json())
        .then(function(data) {
            console.log(data);
            // Loop to access all rows
            for (i = 0; i <= data.ScannedCount; i++) {

                let text = '';
                //const items = data.Items[i].Description;
                Array.from(data.Items).forEach(myFunction);
                // display the data to the end user and link it to the index page
                document.getElementById("displayTable").innerHTML = text;

                function myFunction(item, index) {

                    theTask= data.Items[index].Description;
                    text += ' <button type="button" class="btn" id="task2" onclick="deleteData()">  </button> '+ "  " + data.Items[index].Description +   "
";
                }
            }

        })
        .catch(function(error) {
            console.log(error);
        });
}
async function deleteData() {
    console.log("deleteing data");

    let xhr = new XMLHttpRequest();
    let url = "https://ghu8xhzgfe.execute-api.us-east-1.amazonaws.com/tasks/";
    let studentId = "2877332";
    let taskDescription = theTask;
    fetch(url, {
            method: 'DELETE',

            headers: {
                "Content-Type": "application/json",
                "x-api-key": "Itcheui2tB58SlUGe8rrP8mskudGsNDT9nfKKG9S",
            },

            body: JSON.stringify({
                'StudentId': studentId,
                'Description': taskDescription,
                'version': 'JSON',
            }),
        })
        .then(res => res.json()).then(console.log);
        console.log(taskDescription);
        getDataa();
}
window.onload = init;

A: let taskDescription = theTask; always gets the last value that was ever assigned to theTask. You should make the task a parameter to the deleteData() function.
text and theTask don't need to be global variables.
I'm not sure why you have the loop for (let i = 0; i <= data.ScannedCount; i++). You never use i in the loop.

const url = "https://ghu8xhzgfe.execute-api.us-east-1.amazonaws.com/tasks/2877332";
const init = () => {
  document.querySelector("#newTask").addEventListener("click", addNewTask);
  addNewTask();
  getDataa();
};
const addNewTask = () => {
  console.log("Adding a new task...");
  let xhr = new XMLHttpRequest();
  let url = "https://ghu8xhzgfe.execute-api.us-east-1.amazonaws.com/tasks";
  let apiKey = "Itcheui2tB58SlUGe8rrP8mskudGsNDT9nfKKG9S";
  let studentId = "2877332";
  let taskDescription = document.querySelector("#task").value;
  let theTask = taskDescription;

  let params = {
    StudentId: studentId,
    Description: taskDescription
  };
  xhr.open("post", url);

  xhr.setRequestHeader("Content-Type", "application/json");
  xhr.setRequestHeader("x-api-key", apiKey);
  xhr.onreadystatechange = () => {
    if (xhr.readyState == 4) {}
  }
  xhr.send(JSON.stringify(params));
  getDataa();
};
const getDataa = () => {
  console.log("get Data")
  fetch(url, {
      method: "GET",
      withCredentials: true,
      headers: {
        "x-api-key": "Itcheui2tB58SlUGe8rrP8mskudGsNDT9nfKKG9S",
        "Content-Type": "application/json"
      }
    })
    .then(resp => resp.json())
    .then(function(data) {
      console.log(data);
      // Loop to access all rows
      for (let i = 0; i <= data.ScannedCount; i++) {

        let text = '';
        Array.from(data.Items).forEach(myFunction);
        // display the data to the end user and link it to the index page
        document.getElementById("displayTable").innerHTML = text;

        function myFunction(item) {

          let theTask = item.Description;
          text += ` <button type="button" class="btn" id="task2" onclick="deleteData('${theTask}')"> <i class="fa fa-trash"></i> </button>   ${theTask}<br>`;
        }
      }

    })
    .catch(function(error) {
      console.log(error);
    });
}
async function deleteData(taskDescription) {
  console.log("deleteing data");

  let xhr = new XMLHttpRequest();
  let url = "https://ghu8xhzgfe.execute-api.us-east-1.amazonaws.com/tasks/";
  let studentId = "2877332";
  fetch(url, {
      method: 'DELETE',

      headers: {
        "Content-Type": "application/json",
        "x-api-key": "Itcheui2tB58SlUGe8rrP8mskudGsNDT9nfKKG9S",
      },

      body: JSON.stringify({
        'StudentId': studentId,
        'Description': taskDescription,
        'version': 'JSON',
      }),
    })
    .then(res => res.json()).then(console.log);
  console.log(taskDescription);
  getDataa();
}
window.onload = init;


text:
Q: How to support scrolling when using pygments with Jekyll Is it possible to use horizontal scrolling rather than text wrapping in a code section highlughted with pygments when working in Jekyll.
Source of document:
{% highlight bash %}

Full thread dump OpenJDK Client VM (19.0-b09 mixed mode, sharing):

"Attach Listener" daemon prio=10 tid=0x0a482400 nid=0x5105 waiting on condition [0x00000000]
java.lang.Thread.State: RUNNABLE
....
{% endhighlight %}

Generated page (Notice the hex address being wrapped rather than scrolled):

A: Find your highlight.css at:
/PROJECT_ROOT/assets/themes/THEME_NAME/css/highlight.css
and add this line at the end:
pre { white-space: pre; overflow: auto; }

Thanks @manatwork for the solution.

A: this answer deals specifically with using pygments and jekyll on github pages
the highlighting is generated thusly:

      ... pygments highlighting spans ...

the css that will get you where you want is:
// -- selector prefixed to the wrapper div for collision prevention

.highlight pre code * {
  white-space: nowrap;    // this sets all children inside to nowrap
}

.highlight pre {
  overflow-x: auto;       // this sets the scrolling in x
}

.highlight pre code {
  white-space: pre;       // forces  to respect
 formatting
}

A: I was using Jekyll and Twitter Bootstrap, and the following is what worked for me in the end:
.highlight pre {
    word-wrap: normal;
}

.highlight pre code {
    white-space: pre;
}

A: As for me, using the latest and greates Jekyll & highlighter releases, this nailed the issue:
/* Make code block overflow */
.highlight pre {
  display: inline-block;
}


text:
Q: How to debug NoClassDefFoundError originating from a 3rd party jar? I am getting NoClassDefFoundError while interacting with a 3rd party class which further does some native calls.
Wanted to know what is the best way to debug such an error?
Exception in thread "main" java.lang.NoClassDefFoundError: com/somelib/SomeClass
    at MyTest.foo(MyTest.java:28)
    at MyTest.main(MyTest.java:11)
Caused by: java.lang.ClassNotFoundException: com.somelib.SomeClass
    at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    ... 2 more


text:
Q: Laravel - categories as url segments, category belongs to many I'm creating an application where user can have one speciality.
User can in backend create posts assigned to his speciality, and has to associate it to one category.
I'm wondering how to manage categories when a doctor and an lawyer can use the same category, and not display all posts for all specialities where category is the same.
So actually:

*

*user has one speciality

*speciality has many categories

*category belongs to many specialities
I think i have to create a pivot like category_speciality, as explained in Laravel doc for many to many relationships.
But then i can't figure how to use speciality an category to build dedicated queries and urls.
Any help will be great !

A: For URL's you could do something like:
web.php
Route::get('/articles/{category}/{specialty}', [
    'uses' => 'PostController@index',
    'as' => 'posts.index'
]);

where {category} and {specialty} are a unique slug field of their title. This would result in e.g. example.com/articles/deep-sea/fishing.
PostController
public function index($categorySlug, $specialtySlug)
{
    $specialty = Specialty::where('slug', '=', '$specialtySlug')->first();

    $posts = Posts::where('specialty_id', '=', $specialty->id)->get();

    return view('posts.index', compact('posts'));
}

That is assuming you have specialty_id in Posts table and you have correct relationships set up.
This is just an example.


text:
Q: (DRF) ValueError: Field 'id' expected a number but got ''. Unable to pass in id to the url I am writing a custom function to add favourite to Thread model. The function should expect an id pass in to the get_object_or_404.
@csrf_exempt
def add_favourites(request, id, *args, **kwargs):
    thread = get_object_or_404(Thread, id=id)

    if request.method == 'POST':

        if thread.liked.filter(username=request.user.username).exists():
            thread.liked.remove(request.user.username)

        else:
            thread.liked.add(request.user.username)

and I have my url.py like this to receive an id from axios url:
path('api/public/favourites/<int:id>/', add_favourites, name='add_favourites'),

However, when I perform the axios post request like this:
axiosInstance.post(`api/public/favourites/4/`)

It should be receiving id = 4, but it always return error:
(DRF) ValueError: Field 'id' expected a number but got ''.

Anybody has an idea whats wrong with my code? Much Thanks.

A: thread = get_object_or_404(Thread, pk=id)

Did you try this?


text:
Q: How can use Azure Machine Learning notebooks to connect to SQL Server and Azure SQL databases? I'm trying to find out how I can use a Microsoft Azure Machine Learning notebook to connect to SQL Server and Azure SQL databases.
I am aware of how to connect to SQL Server databases with regular Jupyter files with the use of ODBC connections. But, it looks like I have to try something different when using Azure Machine Learning notebooks.
Could someone describe the best approach to accomplish this?
Note: I am referring to the new Microsoft Azure Machine Learning service, which is currently in preview mode as of May 2020.

A: great question -- the answer depends on whether or not your data sources are in Azure.
data in Azure
for Azure based storage (blob, data lake, Azure SQL, Azure Databricks) you're in luck with Azure ML Datasets, and abstraction on top of azureml-dataprep, a component package of azureml-sdk. IMHO, Azure ML Datasets are slick, TabularDatasets in particular with their to_pandas_dataframe() and .to_spark_dataframe() methods.
Check out the following articles for guidance on how to:

*

*How to connect to data and register as a Dataset

*How to access data during training
Follow the recommendations in this tutorial recommendation would be to make a TabularDataset FileDataset

data not in Azure
For on-premise or IaaS SQL servers, you've got two options that I'm aware of:

*

*Put your SQL server inside the same network at the Azure ML service and ComputeTarget and access the server directly with pyodbc library.

*Use ADF to move the SQL server data to Azure Storage, (you'll need an ADF integration runtime on the SQL server)


text:
Q: Is it possible to apply "Material Design" in the Portable project (Android and iOS)? I just found Xamarin.Droid application references, however I want to apply "Material Design" in a Portable project.
It does not matter if iOS does not use "Material Design", I just want to use the portable project for iOS as well.
I would like my Entry component
<Entry x: Name = "user" Placeholder = "User" Text = "{Binding User}" />

Look like the image below.

I tried some sites, however all developers do not do with portable project.
They use Xamarin for development, but they develop with project Xamarin.Droid and Xamarin.iOS
Tutorial

A: Xamarin does not have its own UI component library. The code that you mentioned:
<Entry x: Name = "user" Placeholder = "User" Text = "{Binding User}" />
is Xamarin Forms xaml markup code. Xamarin Forms is an abstraction over native iOS and Android components. So basically the Entry component will become native text entry field at runtime (UITextField on iOS and EditText on Android).
Now Material design is Android specific. That means that Entry component will look like in your attached gif only on Android.
However you can customize the behavior of Xamarin Forms components using custom renderers.


text:
Q: Android Orientation change results in app crashing This has only happened once but I'm a bit concerned with it. I was testing the app changing the orientation and the application crashed. Never happened before so just want to see if anyone else has had this issue and what I could do to fix it. Please see the log below:
05-15 12:13:07.304: E/AndroidRuntime(2596): FATAL EXCEPTION: main
05-15 12:13:07.304: E/AndroidRuntime(2596): java.lang.RuntimeException: Unable to start activity      ComponentInfo{com./.hearing.InstructionsActivity}:     android.view.InflateException: Binary XML file line #8: Error inflating class <unknown>
05-15 12:13:07.304: E/AndroidRuntime(2596):     at   android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
05-15 12:13:07.304: E/AndroidRuntime(2596):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
05-15 12:13:07.304: E/AndroidRuntime(2596):     at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:3740)
05-15 12:13:07.304: E/AndroidRuntime(2596):     at android.app.ActivityThread.access$700(ActivityThread.java:141)
05-15 12:13:07.304: E/AndroidRuntime(2596):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1262)
05-15 12:13:07.304: E/AndroidRuntime(2596):     at android.os.Handler.dispatchMessage(Handler.java:99)
05-15 12:13:07.304: E/AndroidRuntime(2596):     at android.os.Looper.loop(Looper.java:137)
05-15 12:13:07.304: E/AndroidRuntime(2596):     at android.app.ActivityThread.main(ActivityThread.java:5103)
05-15 12:13:07.304: E/AndroidRuntime(2596):     at java.lang.reflect.Method.invokeNative(Native Method)
05-15 12:13:07.304: E/AndroidRuntime(2596):     at java.lang.reflect.Method.invoke(Method.java:525)
05-15 12:13:07.304: E/AndroidRuntime(2596):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
05-15 12:13:07.304: E/AndroidRuntime(2596):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
05-15 12:13:07.304: E/AndroidRuntime(2596):     at dalvik.system.NativeStart.main(Native Method)
05-15 12:13:07.304: E/AndroidRuntime(2596): Caused by: android.view.InflateException: Binary XML file line #8: Error inflating class <unknown>
05-15 12:13:07.304: E/AndroidRuntime(2596):     at android.view.LayoutInflater.createView(LayoutInflater.java:620)
05-15 12:13:07.304: E/AndroidRuntime(2596):     at com.android.internal.policy.impl.PhoneLayoutInflater.onCreateView(PhoneLayoutInflater.java:56)
05-15 12:13:07.304: E/AndroidRuntime(2596):     at android.view.LayoutInflater.onCreateView(LayoutInflater.java:669)
05-15 12:13:07.304: E/AndroidRuntime(2596):     at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:694)
05-15 12:13:07.304: E/AndroidRuntime(2596):     at android.view.LayoutInflater.rInflate(LayoutInflater.java:755)
05-15 12:13:07.304: E/AndroidRuntime(2596):     at android.view.LayoutInflater.inflate(LayoutInflater.java:492)
05-15 12:13:07.304: E/AndroidRuntime(2596):     at android.view.LayoutInflater.inflate(LayoutInflater.java:397)
05-15 12:13:07.304: E/AndroidRuntime(2596):     at android.view.LayoutInflater.inflate(LayoutInflater.java:353)
05-15 12:13:07.304: E/AndroidRuntime(2596):     at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:267)
05-15 12:13:07.304: E/AndroidRuntime(2596):     at com.actionbarsherlock.internal.ActionBarSherlockNative.setContentView(ActionBarSherlockNative.java:133)
05-15 12:13:07.304: E/AndroidRuntime(2596):     at   com.actionbarsherlock.app.SherlockActivity.setContentView(SherlockActivity.java:229)
05-15 12:13:07.304: E/AndroidRuntime(2596):     at .InstructionsActivity.onCreate(InstructionsActivity.java:40)
05-15 12:13:07.304: E/AndroidRuntime(2596):     at android.app.Activity.performCreate(Activity.java:5133)
05-15 12:13:07.304: E/AndroidRuntime(2596):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
05-15 12:13:07.304: E/AndroidRuntime(2596):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
05-15 12:13:07.304: E/AndroidRuntime(2596):     ... 12 more
05-15 12:13:07.304: E/AndroidRuntime(2596): Caused by: java.lang.reflect.InvocationTargetException
05-15 12:13:07.304: E/AndroidRuntime(2596):     at java.lang.reflect.Constructor.constructNative(Native Method)
05-15 12:13:07.304: E/AndroidRuntime(2596):     at java.lang.reflect.Constructor.newInstance(Constructor.java:417)
05-15 12:13:07.304: E/AndroidRuntime(2596):     at android.view.LayoutInflater.createView(LayoutInflater.java:594)
05-15 12:13:07.304: E/AndroidRuntime(2596):     ... 26 more
05-15 12:13:07.304: E/AndroidRuntime(2596): Caused by: java.lang.OutOfMemoryError
05-15 12:13:07.304: E/AndroidRuntime(2596):     at android.graphics.BitmapFactory.nativeDecodeAsset(Native Method)
05-15 12:13:07.304: E/AndroidRuntime(2596):     at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:503)
05-15 12:13:07.304: E/AndroidRuntime(2596):     at android.graphics.BitmapFactory.decodeResourceStream(BitmapFactory.java:356)
05-15 12:13:07.304: E/AndroidRuntime(2596):     at android.graphics.drawable.Drawable.createFromResourceStream(Drawable.java:800)
05-15 12:13:07.304: E/AndroidRuntime(2596):     at android.content.res.Resources.loadDrawable(Resources.java:2105)
05-15 12:13:07.304: E/AndroidRuntime(2596):     at android.content.res.TypedArray.getDrawable(TypedArray.java:601)
05-15 12:13:07.304: E/AndroidRuntime(2596):     at android.widget.ImageView.<init>  (ImageView.java:127)
05-15 12:13:07.304: E/AndroidRuntime(2596):     at android.widget.ImageView.<init>(ImageView.java:117)
05-15 12:13:07.304: E/AndroidRuntime(2596):     ... 29 more

So to me it looks like it had a issue with inflating the layout. I don't see how because I'd changed the orientation about 4 times before it crashed.
A bit further down there is a java.lang.OutOfMemoryError error so I assume this has caused the android.view.InflateException.
Any help of this would be greatly appreciated. Thanks
Edit:
Here is the activity it crashed on:
public class InstructionsActivity extends MenuActivity {
private ScrollView mScrollButton;
private WebView topContent;
private WebView bottomContent;
private boolean mMoreInfoTop = false;
private int mYdelta = 0;
private int mBottomOffset = 0;
private ActivityHelper activityHelper;
private boolean isPhone;
private String topHtml;
private String bottomHtml;
private String flag;

@TargetApi(Build.VERSION_CODES.HONEYCOMB)
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.instructions);

    activityHelper = new ActivityHelper(this);
    activityHelper.getScreenTag(R.id.instructions);
    activityHelper.getDrawableFolder();
    activityHelper.setTitleTextSize(R.string.Hearing_Test, true);
    isPhone = activityHelper.isPhone();

    if(isPhone){
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    }

    mScrollButton = (ScrollView) findViewById(R.id.scroll_view);
    flag = String.valueOf(getIntent().getStringExtra("Flag"));

    if (flag.equalsIgnoreCase("firstInstructions")) {
        topHtml = this.getString(R.string.top_content);

        Button startTest = (Button) findViewById(R.id.test);
        startTest.setText(R.string.start_test);
    }else if(flag.equalsIgnoreCase("secondInstructions")){
        topHtml = this.getString(R.string.switch_file);

        Button startTest = (Button) findViewById(R.id.test);
        startTest.setText(R.string.continue_test);
    }

    bottomHtml = this.getString(R.string.bottom_content);
    topContent = (WebView) findViewById(R.id.top_content);
    topContent.setBackgroundColor(0);
    bottomContent = (WebView) findViewById(R.id.bottom_content);
    bottomContent.setBackgroundColor(0);
    bottomContent.getSettings().setUseWideViewPort(false);

    topContent.loadUrl("file:///android_asset/html/" + topHtml);
    bottomContent.loadUrl("file:///android_asset/html/" + bottomHtml);

    getMargins();

    setResult(RESULT_OK);
}

public void getMargins() {

    ViewTreeObserver viewTreeObserver = topContent.getViewTreeObserver();

    viewTreeObserver.addOnPreDrawListener(new OnPreDrawListener() {
        @Override
        public boolean onPreDraw() {
            int topHeight = topContent.getMeasuredHeight();
            int bottomHeight = bottomContent.getMeasuredHeight();

            if (isPhone) {
                if (topHeight != 0) {
                    Log.d("Web View Height", "Continue Height: "
                            + topHeight);
                    if (mScrollButton != null) {
                        RelativeLayout instructions = (RelativeLayout) findViewById(R.id.more_info);
                        instructions.post(mAddMargin);
                        topContent.getViewTreeObserver()
                                .removeOnPreDrawListener(this);
                    }
                    topContent.getViewTreeObserver()
                            .removeOnPreDrawListener(this);
                }
            } else if (!isPhone) {
                if (topHeight != 0 && bottomHeight != 0) {
                    Log.d("Web View Height", "top Height: " + topHeight
                            + "bottom height:" + bottomHeight);
                    RelativeLayout instructions = (RelativeLayout) findViewById(R.id.more_info);
                    instructions.post(mAddMargin);
                    topContent.getViewTreeObserver()
                            .removeOnPreDrawListener(this);
                }
            }
            return false;
        }
    });
}

Runnable mAddMargin = new Runnable() {
    @Override
    public void run() {
        try {
            int marginHeight;

            if (isPhone) {
                marginHeight = activityHelper.getMarginHeight(R.id.more_info, R.id.bottom_content);
                RelativeLayout buttonHolder = (RelativeLayout) findViewById(R.id.instructionsLayout);
                mBottomOffset = buttonHolder.getBottom();
                mScrollButton = (ScrollView) findViewById(R.id.scroll_view);
                mYdelta = mScrollButton.getScrollY();
                activityHelper.setMarginHeight(marginHeight, R.id.instructionsLayout);
            } else if (!isPhone) {
 //                 int sideMargin = activityHelper.getWebViewMargin(R.id.bottom_content);
//                  if(sideMargin != 0){
//                      activityHelper.setWebViewMargin(sideMargin, R.id.top_content);
//                      activityHelper.setWebViewMargin(sideMargin, R.id.bottom_content);
//                  }
                marginHeight = activityHelper.getMarginHeight(R.id.more_info, R.id.bottom_content);
                activityHelper.setMarginHeight(marginHeight, R.id.more_info);
            }
        } catch (Exception e) {
            Log.e("Scroll View", "Couldn't run mAddMargin:", e);
        }
    }
};

public void onClickHandler(View aView) {

    if (flag.equalsIgnoreCase("firstInstructions")) {
        Intent intent = new Intent(this, HearingTestActivity.class);
        startActivity(intent);
    }else if(flag.equalsIgnoreCase("secondInstructions")){
        finish();
    }
}

public void infoView(View aView) {
    Intent intent = new Intent(this, InfoActivity.class);
    startActivity(intent);
}

public void onMoreInstructions(View aView) {
    // Scroll the start button to the top of the screen.
    mScrollButton.post(new Runnable() {

        @Override
        public void run() {
            if (mMoreInfoTop) {
                mMoreInfoTop = false;
                mScrollButton.scrollTo(0, mYdelta);
            } else {
                mMoreInfoTop = true;
                mScrollButton.scrollTo(0, mBottomOffset);
            }
        }
    });
}
}

Do you need any other code from me?
New code:
This is my updated code:
public void getMargins() {

    ViewTreeObserver viewTreeObserver = topContent.getViewTreeObserver();

    x = new OnPreDrawListener() {
        @Override
        public boolean onPreDraw() {
            int topHeight = topContent.getMeasuredHeight();
            int bottomHeight = bottomContent.getMeasuredHeight();

            if (isPhone) {
                if (topHeight != 0) {
                    Log.d("Web View Height", "Continue Height: "
                            + topHeight);
                    if (mScrollButton != null) {
                        RelativeLayout instructions = (RelativeLayout) findViewById(R.id.more_info);
                        instructions.post(mAddMargin);
                        topContent.getViewTreeObserver()
                                .removeOnPreDrawListener(this);
                    }
                    topContent.getViewTreeObserver()
                            .removeOnPreDrawListener(this);
                }
            } else if (!isPhone) {
                if (topHeight != 0 && bottomHeight != 0) {
                    Log.d("Web View Height", "top Height: " + topHeight
                            + "bottom height:" + bottomHeight);
                    RelativeLayout instructions = (RelativeLayout) findViewById(R.id.more_info);
                    instructions.post(mAddMargin);
                    topContent.getViewTreeObserver()
                            .removeOnPreDrawListener(this);
                }
            }
            return false;
        }
    };

    viewTreeObserver.addOnPreDrawListener(x);
}

Here I now save the listener to a variable x.
onDestroy method:
@Override
protected void onDestroy() {
    super.onDestroy();
    if(x != null){
        topContent.getViewTreeObserver()
            .removeOnPreDrawListener(x);
    }
}

I then check to see if the variable x is null, if it is remove the listener?
Am I correct in this? Thanks

A: This looks like a classic memory leak situation.
Most likely, you're keeping a live reference to some UI component (or maybe even the Activity) in a listener or an AsyncTask which causes the Activity instance to be leaked (kept from being garbage collected) when you turn the device -- because due to orientation change another Activity instance is created and the old one is supposed to be destroyed and collected.
After you turn the device 3 times you have 4 copies of everything -- hence the OOM.
Another possibility is that you're decoding a Bitmap manually and not calling recycle() on it when your Activity is destroyed.
And yep, as the guys suggest in the comments, nothing more specific can be said until you post your code.
UPD Oh, yeah, now that the code is there, most likely the source of your problem is somewhere in the anonymous classes (the OnPreDrawListener and the Runnable). First, not all conditions guarantee that your listener gets removed -- I'm not sure this is exactly what's causing the leak but consider checking if the listener is still around and removing it in onDestroy() also. But the more general idea is that any untrivial anonymous and nested non-static classes are a bad idea because they store an implicit reference to the instance of the containing class -- in this case, the Activity. Should anything unsuspected happen with any of that code -- it can cause the containing instance to be retained.
So, safest strategy is to avoid using non-static nested (let alone anonymous) classes  unless the logic they carry is so trivial that you're absolutely sure about the implications.
My go-to approach is to create static nested Listeners (or AsyncTasks, Runnables, etc.) that refer to everything they need via WeakReference. Most obvious solution is to store the reference to the Activity in a member WeakReference<InstructionsActivity> and check it for null when the corresponding code gets executed. If it returns null - that means your Activity got destroyed, just return immediately.
UPD
Also, consider using Eclipse MAT (here's a good article, google around for more) to detect memory leaks. It has an awesome ability to run OQL queries on an HPROF dump file, this way you can query for your suspect leaked class (the activity class) and if there are two or more of them -- you know you have a problem. It will even show you what objects keep them retained -- look for paths to GC root

A: This may be causes of configuration change add below property in your mainifest file inside the activity.you can change as per your requirement
android:configChanges="orientation|screenSize|keyboard|screenLayout"


text:
Q: user input choice not recognized I previously posted a question and now my pane displays the question and choices a-d. When user selects choice and clicks next there is no action. I want the user to choose their option, click next, have the quiz display "correct" or "incorrect", and move to the next answer. I believe my error is in the actionPeformed() method or the getSelection() method.  I had to also create a new method with an array to provide the answers. I tried running debugger and getting no variables to display.  Not sure how I made a mess of the code as I thought it would run as expected. Please help. If interested previous post can be found at java quiz only accessing constructor
First file
class Test2 extends JFrame implements ActionListener {

    JPanel panel;
    JPanel panelresult;
    JRadioButton choice1;
    JRadioButton choice2;
    JRadioButton choice3;
    JRadioButton choice4;
    ButtonGroup bg;
    JLabel question;
    JButton next;
    String[][] questions;
    String[][] choices;
    int qaid;

    HashMap<Integer, String> map;

    public Test2() {

        setTitle("Tennis Quiz");
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setSize(430, 350);
        setLocation(300, 100);
        setResizable(false);
        Container cont = getContentPane();
        cont.setLayout(null);
        cont.setBackground(Color.GRAY);
        bg = new ButtonGroup();
        choice1 = new JRadioButton("A");
        choice2 = new JRadioButton("B");
        choice3 = new JRadioButton("C");
        choice4 = new JRadioButton("D");
        bg.add(choice1);
        bg.add(choice2);
        bg.add(choice3);
        bg.add(choice4);
        question = new JLabel("Choose a correct answer");
        question.setForeground(Color.BLUE);
        question.setFont(new Font("Aria", Font.BOLD, 11));
        next = new JButton("Next");
        next.setForeground(Color.GREEN);

        panel = new JPanel();
        panel.setBackground(Color.LIGHT_GRAY);
        panel.setLocation(10, 10);
        panel.setSize(400, 300);
        panel.setLayout(new GridLayout(6, 2));
        panel.add(question);
        panel.add(choice1);
        panel.add(choice2);
        panel.add(choice3);
        panel.add(choice4);
        panel.add(next);
        cont.add(panel);
        setVisible(true);
        setData();
        qaid = 0;
        readqaId(qaid);

    }

    public void actionPerformed(ActionEvent e) {
        switch (next.getText()) {
        case "Next":
            if (qaid < 9) {
                map.put(qaid, getSelection());
                qaid++;
                readqaId(qaid);
            } else {
                map.put(qaid, getSelection());
                next.setText("Show answers");
            }
            break;
        case "Show answers":

            break;
        }
    }

    public void setData() {
        questions = new String[10][5];

        questions[0][0] = "Who is world's number one on the ATP Tennis tour?";
        questions[0][1] = "Del Potro";
        questions[0][2] = "Nadal";
        questions[0][3] = "Djockovic";
        questions[0][4] = "Federer";

        questions[1][0] = "Who is world's number one on the WTA Tennis tour?";
        questions[1][1] = "Venus Williams";
        questions[1][2] = "Serenca Williams";
        questions[1][3] = "Simona Halep";
        questions[1][4] = "Svetlana Kuznetsova";

        questions[2][0] = "Who has the fastest serve?";
        questions[2][1] = "Andy Roddick";
        questions[2][2] = "Milos Roanic";
        questions[2][3] = "Leyton Hewitt";
        questions[2][4] = "Juan Martin Del Potro";

        questions[3][0] = "Who holds the most titles on the mens tour?";
        questions[3][1] = "Roger Federer";
        questions[3][2] = "Raphael Nadal";
        questions[3][3] = "Novak Djokovack";
        questions[3][4] = "Andy Murray";

        questions[4][0] = "Who holds the most titles on the womens tour?";
        questions[4][1] = "Chris Evert";
        questions[4][2] = "Billie Jean King";
        questions[4][3] = "Martina Navratilova";
        questions[4][4] = "Serena Williams";

        questions[5][0] = "Which male tennis player has won the most majors?";
        questions[5][1] = "Donald Young?";
        questions[5][2] = "Raphal Nadal?";
        questions[5][3] = "Roger Federer?";
        questions[5][4] = "Pete Sampras";

        questions[6][0] = "Which male tennis player won the U.S. Open in 2014";
        questions[6][1] = "Roger Federer";
        questions[6][2] = "Lleyton Hewitt";
        questions[6][3] = "Rafael Nadal";
        questions[6][4] = "Marian Celic";

        questions[7][0] = "Which female tennis player has won all 4 Grand Slams?";
        questions[7][1] = "Venus Williams";
        questions[7][2] = "Svetlana Kuznetsova";
        questions[7][3] = "Caroline Wozniacki";
        questions[7][4] = "Serena Williams";

        questions[8][0] = "Which male tennis player won the French Open in 2014";
        questions[8][1] = "Roger Federer";
        questions[8][2] = "Raphael Nadal";
        questions[8][3] = "Milos Roanic";
        questions[8][4] = "Gael Monfils";

        questions[9][0] = "Which female tennis player won the French Open in 2014?";
        questions[9][1] = "Venus Williams";
        questions[9][2] = "Serena Williams";
        questions[9][3] = "Caroline Wozniacki";
        questions[9][4] = "Maria Sharapova";

        map = new HashMap<>();

    }

    public void answerKey() {
        choices = new String[10][2];
        choices[0][0] = "Who is world's number one on the ATP Tennis tour?";
        choices[0][3] = "Djockovic";

        choices[1][0] = "Who is world's number one on the WTA Tennis tour?";
        choices[1][2] = "Serenca Williams";

        choices[2][0] = "Who has the fastest serve?";
        choices[2][2] = "Milos Roanic";

        choices[3][0] = "Who holds the most titles on the mens tour?";
        choices[3][1] = "Roger Federer";

        choices[4][0] = "Who holds the most titles on the womens tour?";
        choices[4][3] = "Martina Navratilova";

        choices[5][0] = "Which male tennis player has won the most majors?";
        choices[5][3] = "Roger Federer?";

        choices[6][0] = "Which male tennis player won the U.S. Open in 2014";
        choices[6][4] = "Marian Celic";

        choices[7][0] = "Which female tennis player has won all 4 Grand Slams?";
        choices[7][4] = "Serena Williams";

        choices[8][0] = "Which male tennis player won the French Open in 2014";
        choices[8][2] = "Raphael Nadal";

        choices[9][0] = "Which female tennis player won the French Open in 2014?";
        choices[9][4] = "Maria Sharapova";
    }

    public String getSelection() {
        String selectedChoice = null;
        Enumeration<AbstractButton> buttons = bg.getElements();
        while (buttons.hasMoreElements()) {
            JRadioButton temp = (JRadioButton) buttons.nextElement();
            if (temp.isSelected()) {
                selectedChoice = temp.getText();
            }
        }
        return (selectedChoice);
    }

    private String readqaId(int qaid) {
        question.setText("" + questions[qaid][0]);
        choice1.setText(questions[qaid][1]);
        choice2.setText(questions[qaid][2]);
        choice3.setText(questions[qaid][3]);
        choice4.setText(questions[qaid][4]);
        choice1.setSelected(true);
        return null;

    }

    public void reset() {
        qaid = 0;
        map.clear();
        readqaId(qaid);
        next.setText("Next");
    }

    public int calCorrectAnswer() {
        int qnum = 10;
        int count = 0;
        for (int qaid = 0; qaid < qnum; qaid++)
            if (choices[qaid][1].equals(map.get(qaid)))
                count++;
        return count;
    }

    public class Report extends JFrame {
        Report() {
            setTitle("Answers");
            setSize(850, 550);
            setBackground(Color.WHITE);
            addWindowListener(new WindowAdapter() {
                public void windowClosing(WindowEvent e) {
                    dispose();
                    reset();
                }
            });
            Draw d = new Draw();
            add(d);
            setVisible(true);
        }

        class Draw extends Canvas {
            public void paint(Graphics g) {
                int qnum = 10;
                int x = 10;
                int y = 20;
                for (int i = 0; i < qnum; i++) {
                    g.setFont(new Font("Aria", Font.BOLD, 12));
                    g.drawString(i + 1 + "." + choices[i][0], x, y);
                    y += 30;
                    g.setFont(new Font("Aria", Font.PLAIN, 12));
                    g.drawString("Correct Answer" + choices[i][1], x, y);
                    y += 30;
                    g.drawString(" Your answer" + map.get(i), x, y);
                    y += 30;
                    if (y > 400) {
                        y = 20;
                        x = 450;
                    }

                }
                int numc = calCorrectAnswer();
                g.setColor(Color.BLUE);
                g.setFont(new Font("Aria", Font.BOLD, 14));
                g.drawString("Number of correct answers." + numc, 300, 500);

            }
        }
    }
}

2nd file
public class QuizProgram
{
   public static void main(String args[])
   {
       Test2 test2 = new Test2();

   }

}

A: You create a button but never add an ActionListener.
Try this:
next = new JButton("Next");
next.addActionListener(this);

(I'm assuming Test2 is the ActionListener you want to use)

A: Your class Test2 implements ActionListener, but I don't see any code that registers the listener.
I'm guessing your intention is that actionPerformed() be called when the user clicks the Next button. In which case your code should have the following line after the Next button is created:
next.addActionListener(this);

("this" being Test2, which is your ActionListener.)


text:
Q: Core Location: best practices for switching between Significant Location service and the Standard Location service? Sometimes my app needs to use the higher precision, more frequent standard location updates and sometimes all it needs are the significant location updates. The most common time that I need to make this switch is when the app switches between foreground and background.
When switching between these services:

*

*Do I need to switch one off and the other on, as if they are separate services that don't affect each other?

*

*Standard->Significant:
[myLocationManager stopUpdatingLocation];
[myLocationManager startMonitoringSignificantLocationChanges];

*Significant->Standard:
[myLocationManager stopMonitoringSignificantLocationChanges];
[myLocationManager startUpdatingLocation];

*Do these services turn each other off when they themselves are turned on, such that I never need to stop them, only start them?

*

*Standard->Significant:
[myLocationManager startMonitoringSignificantLocationChanges];

*Significant->Standard:
[myLocationManager startUpdatingLocation];

*Do I just start the significant service when I set up my app and leave it on, only starting and stopping the standard service (extra accuracy) when needed?

*

*Initial setup:
[myLocationManager startMonitoringSignificantLocationChanges];

*Standard->Significant:
[myLocationManager stopUpdatingLocation];

*Significant->Standard:
[myLocationManager startUpdatingLocation];
The documentation for CLLocationManager is unclear on the details of this behavior. Thank you for any helpful thoughts!
Edit: Just discovered some helpful information on another question, ruling out the second possible behavior mentioned above, but not suggesting the best way to manage this switch: Does calling stopUpdatingLocation on CLLocationManager also stop monitoringSignificantLocationChanges


text:
Q: Solve $\frac{dx}{dt} = \frac{x - t + 2}{2x + t + 1}$ I am having trouble with the following question:
$$\frac{dx}{dt} = \frac{x - t + 2}{2x + t + 1}$$
If the independent terms (meaning $+2$ and $+1$) weren't there, this ode would be a routine application of the solution method for homogeneous ode. Nonetheless they are there, and that makes it untackleable for me, because the methods I know are not applicable.
So I'd be very grateful if some of you show me the light. Thanks in advance.

A: We can transform this equation into a homogeneous one by substituting $t=u+h$ and $x=v+k$ for appropriate values of $h$ and $k$. If we do this, the right-hand side becomes
$$\frac{v+k-u-h+2}{2k+2v+u+h+1},$$
so we want $k-h+2=0$ and $2k+h+1=0$ so that the "independent terms" vanish. Solving these equations simultaneously for $h$ and $k$, we get $h=1=-k$. Thus, we have$^1$
$$\frac{dv}{du}=\frac{v-u}{u+2v},$$
which can be solved homogeneously to get a function $v=v(u)$.
Then to switch back to $x$ and $t$, just substitute back $u=t-1$ and $v=x+1$ into the resulting equation.

$^1$ This is the case since our change of variables are simply translations, so $dx=dv$ and $dt=du$.

A: Substituting $$t=z+1,x=v-1$$ then we get
$$\frac{dv(z)}{dz}=\frac{-z+v(z)}{z+2(v(z)-1)+2}$$
Now we substitute
$$v(z)=zu(z)$$ then we get
$$\frac{\frac{du(z)}{dz}{2(u(z)+1)}}{-2u(z)^2-1}=\frac{1}{z}$$
Can you finish?


text:
Q: iOS: com.apple.root.default-overcommit-priority I received crash from Crashlytics:
Crashed: com.apple.root.default-overcommit-priority
EXC_BAD_ACCESS KERN_INVALID_ADDRESS at 0x8b2b0353

Thread : Crashed: com.apple.root.default-overcommit-priority
0  myApplication                  0x0028f0c4 Parse
1  ???                            0xffffffc9
2  myApplic                       0x00291073 ukeylist_get_scan
3  libsystem_pthread.dylib        0x3aac9c5d _pthread_body + 140
4  libsystem_pthread.dylib        0x3aac9bcf _pthread_start + 102

My questions:

*

*com.apple.root.default-overcommit-priority means? (Maybe memory?)

*Why second line is ???

*How to fix this issue?

Thanks for your time to help me solve this issue.

A: The com.apple.root.default-overcommit-priority is the name of the dispatch queue; I don't think that is anything of importance in this problem.
The second line is interesting, the address being very high.
Is Parse and ukeylist_get_scan methods that you have created or have introduced via a library?
The invalid kernel address you have is interesting; it is a address in a range I'd expect to be valid for code.  Normally you get a really low value such as 0x20 in crashes (which suggests a nil got in somewhere).
I think you have code which parses some input data with a Parse method, but your code is not robust to handle unexpected data.  So I recommend you write more defensive code on the Parse method (assuming it is one of your methods), and try writing some unit test code that passes in bad data.
If this is just the odd issue not seen again, there is not much you can do.  Otherwise you could just look at the overall pattern to see further clues; e.g. always same device, or always a certain OS version, or always a low-end device, etc.


text:
Q: How do I assign the same class value to two or more variables in Python, so they are not under the same ID? Im attempting to implement entities inside of a text based game, but I can't seem to wrap my head around this issue.
class entity:
    name = "0"
    health = 100
    strenght = 10
    speed = 10
    xp = 0
    energy = 100

player = entity
player.name = input("Enter your name: ").strip()
print(f"Welcome, {player.name}.")

enemy = entity
enemy.name = "Some Enemy"
enemy.strenght = 5
enemy.speed = 20
enemy.xp = 100

So what im trying to achieve here is to have both the enemy and the player be defined as "entity" but to be under different ID's.
Any advice?

A: use create object from class instead of change parameters


text:
Q: Is $K $ a $K [X]$ injective module? Let $K $ be a field.  $K $ is a $K [X] $-module with $P\cdot a:= P (0)\cdot a , \forall P\in K [X], a\in K $.
Is $K $ a $K [X]$ injective module?
I know that $K $ is an injective $K [X]$- module iff $Ext^1_{K [X]}(K [X]/I,K)=0$ for any $I $ ideal of $K [X] $.

A: A module $M$ over a principal ideal domain $R$ is injective iff it is divisible, i.e. for all $m \in M$ and all $ r \in R \backslash \{ 0 \}$, there exists an $m' \in M$ such that $rm' = m$. As egreg points out in the comments below, the forward implication actually holds under the weaker assumption that $R$ is a domain.
In this particular example, if we take $m = 1$ and $r = X$, then we cannot find such an $m'$, so the module is not injective.

Edit: If we want to prove non-injectivity of $k$ by computing an Ext module, we can certainly do so. I think it's worth working through this so that we can see the connection between the "divisibility argument" and the "vanishing Ext-module argument", which is quite striking.
First, I suggest we write $k$ as $ k[X]/(X)$, to emphasise its $k[X]$-module structure.
A good Ext module to compute is $${\rm Ext}_{k[X]}^1(k[X]/(X), k[X]/(X)).$$
[I'll explain why when the dust settles.]
To compute this, we need to find a projective resolution of the left-hand $k[X]/(X)$. This is easy:
$$  \dots \to 0 \to  0 \to k[X] \overset{\times X}{\longrightarrow} k[X] $$
Next, we apply the ${\rm Hom}_{k[X]} (., k[X]/(X))$ functor to the projective resolution, giving:
$$ k[X]/(X) \overset{\times X}\longrightarrow k[X]/(X) \to 0 \to 0 \to \dots.$$
But the $\times X$ morphism is not surjective: its image is $0$. Hence
$$ {\rm Ext}_{k[X]}^1 (k[X]/(X), k[X]/(X)) = k[X]/(X) \neq 0.$$
Now here is the interesting point: The image of the $\times X$ morphism is precisely the submodule of elements of $k[X]/(X)$ that are divisible by $X$.  The fact that not all elements of $k[X]/(X)$ are divisible by $X$ is the reason why the Ext group is non-trivial. So that is the connection between the two arguments!
And how can we tell in advance that taking $I = (X)$ in ${\rm Ext}_{k[X]}^1(k[X]/I, k[X]/(X))$ would be a good choice for the purposes of proving that $k[X]/(X)$ is not injective? Because we know in advance that not every element in $k[X]/(X)$ is divisible by $X$!


text:
Q: Создать словарь из многомерного (вложенного) списка Имеется многомерный список
a_list = [[1,0,3,4],[5,1,7,8],[9,2,2,4],[8,3,6,5],[2,4,5,6]]

Список необходимо преобразовать в словарь который для ключа выбирает второй элемент вложенного списка,а значением остальные элементы списка. Например для первого списка [1,0,3,4] ключем в словаре будет key = 0 , значение value = [1,3,4]
Итоговый словарь будет иметь вид
a_dict = {0:[1,3,4],
          1:[5,7,8],
          2:[9,2,4],
          3:[8,6,5],
          4:[2,5,6],}

A: Алгоритм решения:

*

*воспользуйтесь "dictionary comprehension" - res = {key: value for ...}

*в качестве ключа можно использовать метод list.pop(), который удаляет элемент списка и возвращает его

Если правильно реализовать данный алгоритм - у вас получится короткое и эффективное однострочное решение.
PS если приведете в вопросе собственные попытки решения, тогда и я смогу показать реализацию алгоритма в ответе.

A: Вы можете сделать так:
a_list = [[1,0,3,4],[5,1,7,8],[9,2,2,4],[8,3,6,5],[2,4,5,6]]
a_dict = {el.pop(1): el for el in a_list}

A: Вот
a_list = [[1,0,3,4],[5,1,7,8],[9,2,2,4],[8,3,6,5],[2,4,5,6]]
a_dict_ = {}
for a in a_list: # перебор значений списка
    key = a[1] # ключ
    arr = [a[0]] + a[2:] # значение
    a_dict[key] = arr # добавление
print(a_dict)


text:
Q: Extjs 4.02 - Custom component needed I am trying to create a custom container but can't figure just how to do it.
I need it to look like this:

(don't pay attention that it is RTL, this is only a sketch to get started)
where the orange fonts are the title of the page that I would like to be an H1 element.
It has a simple search and an advance search that pops open when the little  arrow next to the search button is clicked.
Questions:
1) What should I extend for that ?
2) How can I implement different advance search forms for different pages ?
3) how can I place a setter for the title that controllers can interact with and manipulate the dom ?
basically any advice will be good as I need a start point.
thanks

A: There are lots of ways of doing this, but this is  what I would do.

*

*I'm not sure about the "advanced forms for different pages" can you go into mre detail about that? Are you looking to autogenerate a search form somehow?

*Extend Ext.form.Panel, and use a table layout for the fields
See: http://docs.sencha.com/ext-js/4-0/#!/api/Ext.layout.container.Table

*use a "tbar" on the panel instead of setting "title". you can place the search combo, tbfill, then a tbtext for the "title". As a convenience you can override the setTitle function of the panel to manipulate this tbtext field instead of the normal behavior. Something like this:
Ext.define('MyApp.view.MyForm', {
   extend: 'Ext.form.Panel',
   alias:'widget.myform',
   layout:{
    type: 'table',
    columns: 4,
        tableAttrs: {
            style: {
                width: '100%'
            }
        }
   },
   //overridden setTitle
   setTitle:function(title){
    Ext.getCmp(this.id + "_search_combo").setText(title)
   },
   defaults:{
    xtype:"combo",
    //rest of combo config here
   },
   items:[{
    //...
   }],
   initComponent:function(config){
      this.tbar = tbar:[{
            xtype:"combo",
            //...
            id:this.id + "_search_combo"
        },{
            xtype:"tbfill"
        },{
            xtype:"tbText",
            cls:"my_form_title",
            value:this.title||""
        }]

        //prevent default title behavior
        delete this.title
        this.callParent(arguments);
   }
})

A: *

*I would suggest you to just extend from Ext.panel.Panel itself, and hijack the dom for all those customized items, add in search bar, etc. If you do not want any of the fancy stuff from Ext.panel.Panel, you can also extend it from Ext.Component, or Ext.container.Container (to contains more components), and even the lowest Ext.util.Observable.

*It seems like you might need to extend a few Ext.menu.Menu and defines some different set of input boxes, so that you could benefit from creating a floated menu (if that's what you want). Or if you have time, you can even just extend from Ext.Component and build your own customized component, or even lower, Ext.util.Observable.

*The setter? It will be in the extended component in (1) then :)
All of these serve as rough opinions. They could be different depends on your requirement.


text:
Q: Powerapps - How to Audit Trail? How would you do to implement Audit Trail eg. add User Action(edit, new, delete, print), OldValue and NewValue in a separate "Audit Trail" table? Something like this:
 ID | DATE    | USERNAME | FORMNAME | ACTION | FIELDNAME | OLDVALUE | NEWVALUE
 01    180513   user       form1      edit      Risk         Low       High

Old values must not be overwritten and I am kind of a stuck there because "patch" overwrites old values...

A: One option may be to confirm each change.
Example:

*

*If user changes an auditable field, show confirmation popup.

*Use the OnSelect Property of the "Confirm" button to write a new line to the Collection/Data Source

*Use the Defaults line in your Patch command to APPEND this line to the Collection/Data Source each time rather than overwriting it.

Good luck!


text:
Q: Change owncloud data directory to an external drive Owncloud 5.0.9 is installed on my raspberry pi and is working flawlessly. But since my raspberry pi hasn't much space, I wanted to move the data directory on an external drive.
I have a 1,5GB external drive formatted in NTFS mounted on /home/pi/media and the new data directory is /home/pi/media/owncloud/data/
The /etc/fstab/ looks like this:
UUID=xxxxxxxxx   /home/pi/media    ntfs-3g     defaults      0       0
It doesn't work if I set the permissions on the ntfs drive with
sudo chown -R www-data:www-data /home/pi/media/owncloud/data
The browser is giving this error if I go to xxx.xxx.xxx.xxx/owncloud/:
Data directory (/home/pi/media/owncloud/data) is readable for other users
Please change the permissions to 0770 so that the directory cannot be listed by other users.
How do I set the permissions right?
Also MiniDLNA is configured to use this drive, so it should not interrupt each other.

A: Got it myself!
By default you are not able to set permissions on NTFS formatted drives, but with NTFS-3G you can. Just enable it on mount.

*

*Add permissions to the options in /etc/fstab/. It should look like this:

UUID=xxxxxxxxx   /home/pi/media    ntfs-3g     defaults,permissions      0       0

*Reboot your Raspberry Pi so that the drive get mounted with permissions.

sudo shutdown -r now

*Now you are able to set permissions. For owncloud like this:

sudo chown -R www-data:www-data /home/pi/media/owncloud/data


text:
Q: VBA Regex to match Two sets of Four Digits with String Im trying to make a Excel Regex pattern to find a certain string. This what Im trying:
I'm trying to make it match 0 and 0000 to 9999
StringToMatch = "a75z6878"

Dim objRegExp As New RegExp
Set objRegExp = CreateObject("vbscript.regexp")
objRegExp.IgnoreCase = True
objRegExp.Global = True

objRegExp.Pattern = "[a-z]([0-9][0-9][0-9][0-9])[a-z]([0-9][0-9][0-9][0-9])"
objRegExp.Pattern = "[a-z]([0-9]{1-4})[a-z]([0-9]{1-4})"

If objRegExp.Test(StringToMatch) Then MsgBox(Found!)

I have tried different patterns but none work.
What am I doing wrong???

A: What is wrong in objRegExp.Pattern = "[a-z]([0-9]{1-4})[a-z]([0-9]{1-4})"
The quantifier must be specified as {m,n} and not {m-n}
change the regex to
[a-z][0-9]{1,4}[a-z][0-9]{1,4}

For example see the link http://regex101.com/r/wA2qM3/1
OR a shorter version like
 [a-z]\d{1,4}[a-z]\d{1,4}


text:
Q: HighCharts : Tooltips exist but line is not drawn in the chart I met with a problem on HighCharts.
I had to gather data from a xml content with ajax in order to draw it in a HighCharts chart.
I get my datas. I can see my points when I move my mouse over it but my chart is not displaying anything.
A picture to see the problem :
mouse over the third point
And some parts from my code if it can help :
var myData=[];

function makeChart() {
var chart;
$(document).ready(function () {
    chart = new Highcharts.Chart({
        chart: {
            renderTo: 'container2',
            type: 'spline',
            borderColor: '#DC143C',
            borderRadius: 20,
            borderWidth: 2,
            marginRight: 130,
            marginBottom: 25
        },
        title: {
            text: ''
        },
        xAxis: {
            categories :[0,1,2,3,4,5]
        },
        yAxis: {
            title: {
                text: 'Values'
            },
        },
        series: [{
                color: '#FF00FF',
                name: '',
                data: myData
            }]
    });
});
}

$(function (){

$(document).ready(function ping(){

    ChartDeOuf();
    makeChart();

    $.ajax({
        type: "GET",
        url: 'http://localhost:8080/SASI/runSimulation',
        dataType: "xml",
        success: function(result){
            var i = 0;

            var xmlDoc = $.parseXML(result);
            var chart = $('#container2').highcharts();
            $result = $(xmlDoc);

            $(result).find('measure').each(function(){
                var $value = $(this);
                var attr = $value.attr("meanValue");

                myData[i]=attr;

                var html = '<p> '+myData[i]+'</p>';
                chart.series[0].addPoint({y: myData[i]},false);

                chart.redraw();
                $('body').append($(html));
                i++;

            })

        },
        error: function(result){
            alert('timeout/error');
        }
    });
});

});

Thanks for reading.

A: Got it, that line saved everything :
myData[i]=parseFloat(attr);


text:
Q: Why not hand when hovering link()? Hi,
I know that its possible to set the cusor to hand when hovering an object like this:
CSS :

cursor:             hand;
cursor:             pointer;

This should be done automaticly with a link element that looks like this :

  Sök

But In my case its not?
With firebug I can see that the followin CSS is applyed
 element
a.btn1 {
    background: url("Images/Menus/bg_button_a.gif") no-repeat scroll right top transparent;
    color: #444444;
    display: block;
    float: left;
    font: 12px arial,sans-serif;
    height: 24px;
    margin-right: 6px;
    padding-right: 18px;
    text-decoration: none;
}
* {
    margin: 0;
    padding: 0;
}
body {
    font-family: Arial,Verdana,serif;
    font-size: 0.81em;
}

And
SPAN element
    a.btn1 span {
        background: url("Images/Menus/bg_button_span.gif") no-repeat scroll 0 0 transparent;
        display: block;
        line-height: 14px;
        padding: 5px 0 5px 18px;
    }
    Controls.css (rad 80)
    * {
        margin: 0;
    }

    a.btn1 {
        color: #444444;
        font: 12px arial,sans-serif;
        text-decoration: none;
    }

    body {
        font-family: Arial,Verdana,serif;
        font-size: 0.81em;
    }

How can I track down this problem?
BestRegards

A: It's likely because your  doesn't have a "href" value, you could change it to

You can also add the following css to force the hand to always appear for links:
a{ cursor: pointer;}

A: Without the href attribute the a tag does not declare a hyperlink. If it possesses a name or id attribute, it may declare the destination of a hyperlink instead. (http://www.w3.org/TR/html4/struct/links.html#anchors-with-id)
If the element you want to declare has no semantic resemblance to a hyperlink and you are relying on CSS to make it appear like one, why bother? You might just as well use any old span.
What you should not do is write a { cursor:pointer; } into your CSS, causing any a elements to display a hand on hover, even those that are not hyperlinks. Instead you should add a href attribute like has been suggested. As a value you could enter # if there is no non-JavaScript functionality to fall back on. Otherwise you should enter the URI of the resource you want to link to.
See also Wikipedia: http://en.wikipedia.org/wiki/HTML_element#Anchor

A: That's not a link.  Links have href attributes.  That's just an anchor that runs JavaScript when clicked.

A: The hand appears only if the ANCHOR has a href attribute set.
Live demo: http://jsfiddle.net/KAEbR/