Most efficient way to check if user is allowed to update an object

So I have an user which can create his own Locations. data model

I implemented a webservice in order to add and update locations. If the user is not the owner of the location i want to throw an appropriate exception so that the user knows whats wrong.

The current method looks like this:

private void updateLocation(String loginToken, MapLocation ml) throws Exception{     String username = this.getUsernameBySingInToken(loginToken); //throws exception is wrong token, otherwise returns username      PreparedStatement stmt = conn.prepareStatement("SELECT username FROM Location WHERE idLoc=?");     stmt.setInt(1, ml.getLocationId());     ResultSet rs = stmt.executeQuery();     String actuallUsername = null;     while (rs.next()) {        actuallUsername=rs.getString("username");     }     if(actuallUsername==null)         throw new Exception("no location found!!"); //appropriate exception       if(!username.equals(actuallUsername) || !username.equals(ml.getUsername()))         throw new Exception("you are not the creator of this location!"); //appropriate exception       PreparedStatement stmtVerification = conn.prepareStatement("UPDATE Location SET positionX=?,positionY=?"             + " WHERE idLoc=?");     stmtVerification.setDouble(1, ml.getPosX());     stmtVerification.setDouble(2, ml.getPosY());     stmtVerification.setInt(3, ml.getLocationId());     stmtVerification.executeUpdate();      disconnectFromMySQL(); } 

The second method I implemented is shorter but the errors are not clear:

private void updateLocationV2(String loginToken, MapLocation ml) throws Exception{     String username = this.getUsernameBySingInToken(loginToken);     if(!username.equals(ml.getUsername()))         throw new Exception("username is not the same as username of maplocation object"); //not sure if neccesary       PreparedStatement stmtVerification = conn.prepareStatement("UPDATE Location SET positionX=?,positionY=?"             + " WHERE idLoc=? and username=?");     stmtVerification.setDouble(1, ml.getPosX());     stmtVerification.setDouble(2, ml.getPosY());     stmtVerification.setInt(3, ml.getLocationId());     stmtVerification.setString(4, username);      int executeUpdate = stmtVerification.executeUpdate();     if(executeUpdate==0)         throw new Exception("update failed. either wrong username or idLocation is wrong"); //not clear what is the error BUT shorter     disconnectFromMySQL(); }     

So yeah, now I have two methods which update my location but I am not sure which of them is the best. The first method has the advantage that the errors are clear but its slower since I have two queries (select and update). the second method is faster but the errors are not clear. WHich one of them is better, or is there even a better solution?

EDIT: This is my webservice method which calls the update function:

@PUT @Path("/update") @Consumes({MediaType.APPLICATION_JSON}) public Response update(String token, MapLocation ml) {     Response r = Response.status(Response.Status.OK).entity("location updated").build();     try {         isUpdated = db.updateLocation(token,ml);     } catch (Exception ex) {         r = Response.status(Response.Status.BAD_REQUEST).entity(ex.getMessage()).build();     }     return r; } 

Return whether a string is a palindrome if you can delete at most k elements

The task:

Given a string which we can delete at most k, return whether you can make a palindrome.

For example, given ‘waterrfetawx’ and a k of 2, you could delete f and x to get ‘waterretaw’.

The following solution is partially inspired by @Oh My Goodness’s answer.

const s = "waterrfetawx"; const del = 2;  function palindromePossible(str, deleteAtMost) {   const set = new Set();   for (let i = 0, len = str.length; i < len; i++) {     const char = str[i];     void(set.delete(char) || set.add(char)); // <--is this good code?   }    let iStart = 0, iEnd = str.length - 1, possibleDeletion = 0;    function isSame() {     do {       if (str[iStart] === str[iEnd]) {         iStart++;         iEnd--;         return true;       }       if (++possibleDeletion > deleteAtMost) { return false; }       if (set.has(str[iStart])) { iStart++; }       if (set.has(str[iEnd])) { iEnd--; }       if (iStart > iEnd) { return false; }     } while(str[iStart] !== str[iEnd]);      return true;   }    if (set.size <= deleteAtMost + 1) {     for (let i = 0, len = Math.floor(str.length/2); i < len && iStart <= iEnd; i++) {       if (!isSame()) { return false; }     }     return true;   }   return false; }  console.log(palindromePossible(s, del)); 

Estimating the number of functions which are at most $c$-to-$1$ for some constant $c \ge 2$

Notation: $ [m] := \{1, 2, \dots, m \}$ .

How many functions are there $ f: [a] \to [b]$ ? The answer is easily seen to be $ b^a$ .

How many $ 1$ -to-$ 1$ functions are there $ f: [a] \to [b]$ ? Again the answer is well known, and it is sometimes called the falling factorial: $ $ b(b-1) \dots (b-a+1).$ $

How many functions are there $ f: [a] \to [b]$ that are no more than $ c$ -to-$ 1$ ?

I don’t expect that there is an exact formula, and I am more interested in the asymptotics. For example, can we give “reasonable” upper and lower bounds, in the case that $ c \ge 2$ and $ |A| / |B|$ are fixed, and $ |A| \to \infty$ ?

For a concrete example, roughly how many functions are there $ [5n] \to [n]$ that are at most $ 8$ -to-$ 1$ ? Call this function $ g(n)$ .

Clearly we have $ $ \frac{(5n)!}{5!^n} \le g(n) \le n^{5n}.$ $ The function $ {(5n)!}/{5!^n}$ counts functions that are exactly 5-to-1 (which all satisfy the criterion that they are at most 8-to-1), and the function $ n^{5n}$ counts all functions.

Applying Stirling’s approximation to the first function gives something like $ $ \alpha^n n^{5n} \le g(n) \le n^{5n},$ $ for some small constant $ \alpha > 0$ .

It seems like there is room for improvement. Is it true, for example, that $ $ \log g(n) = 5n \log n + C n + o(n) $ $ for some constant $ C > 0$ ?

Btrade Automated Review Official Download Most Powerful Bitcoin Trading Software Of 2019

Btrade Automated Signup: https://btradeauto.signuum.io/track?aid=14&oid=1&lid=1 Btrade Automated comes to us courtesy of the same people that have already released several other awesome trading systems. This is just the next addition to their long line of highly successful semi-automated trading programs. We are here doing a Btrade Automated Bot review to give you all of the info you need to trade with this awesome new system. If you think that this is just another automated…

Btrade Automated Review Official Download Most Powerful Bitcoin Trading Software Of 2019

How to prevent most syncing with Google in Android 7.0 Nougat on Samsung devices?

In Android 7.0 Nougat on Samsung devices, you can go to Settings -> Clouds and accounts -> Accounts -> Google to see a list of all the Google sync options.

Currently,

  1. Sync Calendar says “Tap to sync now” with “Last synced date” of when I factory wiped the device.

  2. Sync Contacts is the same as Calendar.

  3. Sync Google Fit data is the same as Calendar.

  4. Sync Google Play Books says “Tap to sync now” and “Sync turned off”.

  5. Sync Google Play Movies & TV is the same as Play Books.

  6. Sync Google Play Music says nothing under it.

  7. Sync People details says “Tap to sync now” with “Last synced date” of today!

  8. Sync Play Games Cloud Save is the same as Calendar.

There are no enable/disable toggle checkmarks next to any of the items.

In Settings -> Clouds and accounts -> Backup and restore -> Back up my data is turned off.

I want all syncing with Google to be turned completely off, and any synced data to be deleted.

The exceptions are for Books, Movies & TV, and Music, for which I would like to manually sync once in a while.

How can this be done?

How do you empirically estimate the most popular seat and get an upper bound on total variation?

Say there are $ n$ seats $ \{s_1, …, s_n\}$ in a theater and the theater wants to know which seat is the most popular. They allow $ 1$ person in for $ m$ nights in a row. For all $ m$ nights, they record which seat is occupied.

They are able to calculate probabilities for whether or not a seat will be occupied using empirical estimation: $ P(s_i ~\text{is occuped})= \frac{\# ~\text{of times} ~s_i~ \text{is occupied }}{m}$ . With this, we have an empirical distribution $ \hat{\mathcal{D}}$ which maximizes the likelihood of our observed data drawn from the true distribution $ \mathcal{D}$ . This much I understand! But, I’m totally lost trying to make this more rigorous.

  • What is the upper bound on $ \text{E} ~[d_{TV}(\hat{\mathcal{D}}, \mathcal{D})]$ ? Why? Note: $ d_{TV}(\mathcal{P}, \mathcal{Q})$ is the total variation distance between distributions $ \mathcal{P}$ and $ \mathcal{Q}$ .
  • What does $ m$ need to be such that $ \hat{\mathcal{D}}$ is accurate to some $ \epsilon$ ? Why?
  • How does this generalize if the theater allows $ k$ people in each night (instead of $ 1$ person)?
  • Is empirical estimation the best approach? If not, what is?

If this is too much to ask in a question, let me know. Any reference to a textbook which will help answer these questions will happily be accepted as well.