How to change Wordpress Directories?

Question: How do I change the directories of Wordpress e.g.. /wp-admin or wp-login without messing up any internal files? I have tried this before but my Wordpress site stopped working.
Comment: wordpress hard-codes directories/paths into the post data stored in the database. it's an incredible pain to migrate manually. there are migration tools documented on the WP site you can try. the one time I tried it, it seemed to work ok. But the overall experience (as with anything wordpress) just leaves you feeling dirty and abused.
Comment: Why are you trying to do this?
Answer: It is "possible", but you will mess with internal files.
This was already discussed in WordPress StackExchange. You'll find lots of links and references in this post:
Can I rename the wp-admin folder?.
This other one can be helpful for "white-labeling" WordPress:
Steps to Take to Hide the Fact a Site is Using WordPress?

How to change Wordpress Directories?


Visual Studio 2012 and SQL Server 2012

Question: I have a question about these two products. I have Visual Studio 2012 installed and I want to use a database, should I install SQL Server 2012? But SQL Server 2012 is using VS 2010's  shell. So I want to know, can I use VS 2012's shell to implement SQL Server's function? In this case, do I need to install SQL Server 2012?
Comment: @Tian When you start SQL Server 2012 by default you get nothing. It's a service. If you start the server binary manually, it runs in a console. If you start SQL Server Management Studio 2012, which is a different product, you get a user interface just like VS2010.
Comment: "But SQL server 2012 is using VS 2010's shell" - where did you get that idea? And what do you mean by "shell", in this context?
Comment: When you start SQL server 2012, you will get a user interface just like VS 2010
Comment: Yes, I am meaning when you using "SQL Server Management Studio 2012, you get a user interface just like VS2010". Since I have install VS 2012 already, I think it's redundant to have this VS 2010 interface. Can I install SQL Server 2012 without this interface and just use VS email@example.com
Comment: The SQL Server Management Studio (based on the VS 2010 Shell) is an optional component when you install SQL Server 2012 - so yes, you can install SQL Server 2012 - the **database engine** - without installing the *redundant* VS 2010 shell of Management Studio - and just use the Visual Studio 2012 built-in tooling for SQL Server
Answer: You can use whatever database you want. This is something completely separate from Visual Studio itself.
People have been using Visual Studio 2012 with Oracle, MySql, SQL Server 2000/2005/2008/2012 and others without issue.
Comment: Can I use sql server 2014 with VS 2012
Comment: Yes, you can. Why not try before asking?
Comment: I have already tried this but when I create a new database and right click on Table option, No add table option appears. Only Refresh and Properties Option appear.
Comment: Sounds like a permissions issue.
Comment: Do you mean to say permissions in propety?? Even if it was a permission issue, then the Add Table Option should appear in disabled state. But here it is not even showing the option.
Answer: Both product are different you can use any database with your .NET application. Dont need to install only SQL Server for .NET Application.

Visual Studio 2012 and SQL Server 2012


"{}" as type in Typescript

Question: What type is a variable declared as below. In what case is it useful?
let x: {}

In the following type alias what is the meaning of {}. Is it equivalent to object or any? Why you would want to use {} as type instead of any? Does {}, in this case mean "instance" of empty object? (does make sense to me)
type MessageHandler<D, P> = (data: D, payload: P) => void
type MessageHandlerGeneric = MessageHandler<{}, any}

interface MessageHandlers {
  [index: string]: MessageHandlerGeneric
}

let handlers = MessageHandlers = {
  handler1: (data: string, payload: Pyaload),
  handler2: (data: Array<string>, payload: Payload)
}

Comment: The `Object` (with capital O) mainly describes that the object has the common javascript methods like `toString`
Comment: you might want to correct the typo: `Pyaload`  :-)
Comment: `{}` is an object, isn't it? `any` means anything; an object, a number, a string, `undefined`, an array etc. Why do you think that `{}` is the same thing as `any`?
Comment: I think you should check this answer https://stackoverflow.com/questions/18961203/any-vs-object
Comment: As I understand it `any` also could be `undefined` or `null`. So `object` and `any` are similar to me except that the compiler doesn't perform type checks for `any`. Am I wrong?
Comment: Relevant isue on TypeScript's github : https://github.com/Microsoft/TypeScript/issues/8032
Comment: `any` has no restrictions it can be anything, but `{}` has restrictions like an object it only allows you to access to members.
Answer: Object is more restrictive than any.
const b: Object = {};
b.myMethod();

won't compile (where myMethod() is not declared and known method). On the other hand, the method below compiles.
const c: any = {};
c.myMethod();

So, any can be anything (including null/undefined) on the other hand, If you explicitly use Object you will only be able to use the properties that are defined on the Object class.
Answer: As others pointed out - once variable typed as any, compiler won't warn you if you'll try to access non existing properties or assign any value.
Regarding object vs {} - object is a type that represents the non-primitive type, i.e. any thing that is not number | string | boolean | symbol.
const foo: object = 'test'; // error
const bar: {} = 'test'; // ok

"{}" as type in Typescript


How to remove space in jQuery using Select2 plugin

Question: in database the value is saved as Jack, Mike which have space between , and M. But when I want to display at the frontend in edit form using dropdown select2 plugin, an error appear at console. It seems like I need to remove the space in between , M then it will appear in the dropdown select2. the question how to remove the space during to display at the dropdown edit form?
Currently it just display the first name only which is Jack.
DB: Jack, Mike
JS
$("#editLayer2TaskOwner").val(response.data[0]["task_owner"]);

// To allow Select2 to choose selected as stored from DB
$(response.data).each(function(key,value){
    var owners = value.task_owner.split(',');
    $(owners).each(function(k,v){
        $("#editLayer2TaskOwner").append($("<option selected>", {
            response: v,
            text: v
        }));
    });
    $("#editLayer2TaskOwner").val(owners).trigger("change");
});

Comment: Are you able to provide a reproducible example ?
Answer: It very easy just split with , and space. It will work. change your code like below.
$("#editLayer2TaskOwner").val(response.data[0]["task_owner"]);
// To allow Select2 to choose selected as stored from DB
$(response.data).each(function(key,value){
    var owners = value.task_owner.split(', ');
    $(owners).each(function(k,v){
        $("#editLayer2TaskOwner").append($("<option selected>", {
            response: v,
            text: v
        }));
    });
    $("#editLayer2TaskOwner").val(owners).trigger("change");
});


MongoDB with C#.net

Question: I am Very new with MongoDB,I m using windows7 32bit,downloaded mongo exe files from http://www.mongodb.org/display/DOCS/Quickstart+Windows
And downloaded mongodb.dll also
<code> Mongo mongo = new Mongo();
        mongo.Connect();
</code>
gives me the error
Failed to connect to server localhost:27017
Is i m missing something,plz let me know
Comment: Did you actually set up and run the server as the guide tells you to - http://www.mongodb.org/display/DOCS/Quickstart+Windows#QuickstartWindows-Runandconnecttotheserver - If the server is not running then you won't be able to connect to it
Answer: You should use
<code>var connectionString = "mongodb://localhost/?safe=true";
var server = MongoServer.Create(connectionString);
var database = server.GetDatabase("test");
</code>

MongoDB with C#.net


Help in proving the injectivity of this homomorphism (used in the definition of wreath product)

Question: I consider two groups of permutation: the group $H$ that acts faithfully on the set $\Delta$ and the group $K$ that acts faithfully on the set $\Omega$. I suppose that $H$ is not the trivial group.
Let be $B=\{f:\Omega \rightarrow H \:|\: supp(f) <\infty \}$ with the operation $(f \cdot f_1)(x)=f(x)f_1(x)$. I have that $(B,\cdot)$ is a group.
I consider this action of $K$ on $B$ defined is this way:
$\forall g \in K $, $\forall f \in B$ and $\forall x \in \Omega$
$$ f^g(x)=f(x^{g^{-1}}).$$
I have proved that this is an action and that :
$$ (f f_1)^g=f^g f_1^g.$$
So now I can define the following homomorphism:
$$\phi : K \rightarrow Aut(B)$$ where $\phi(g) (f)=f^g$.
My problem: I have difficulties in proving that this homomorphism is injective. How can I deduce that $g=g_1$ from $f(x^{g^{-1}})=f(x^{g_1^{-1}})$ $\forall f \in B$? My idea was to use the fact that the action of $K$ on $\Omega$ is faithful but I don't know how .
Thanks!
Comment: Unless there is something I don't get, it wouldn't be true if $H$ is trivial.
Comment: @ArnaudD. Sorry I forget to add the hypothesis that $H$ is not trivial
Answer: Suppose $g\in \ker (\phi)$, so that $f^g=f$ for all $f\in B$. Choose some $h\in H$ such that $h\neq 1_H$. For every $x\in \Omega$ you can define $$f_x:\Omega\to H :y\mapsto \left\{ \begin{array}{ll} h & \text{if }y=x\\ 1_H & \text{otherwise.}\end{array}\right.$$
Then by assumption $f_x^g=f_x$, so in particular.
$$f_x(x^{g^{-1}})=f_x(x)=h,$$
for all $x$. This implies that $x^{g^{-1}}=x$ for all $x$, and thus that $g=1_K$.
Thus $\ker(\phi)=\{1_K\}$, which means $\phi$ is injective.


Upgrade from 17.10 to 18.04 offline

Question: I have been looking for a way so I can upgrade from Ubuntu 17.10 to Ubuntu 18.04 LTS offline.
There were tips in the internet but they were mostly done online.
thanks in advance
Comment: One easy method: 1) Backup your data. 2) Clean-install 18.04. 3) Restore your data.
Comment: 18.04 is an LTS version : DVD sets are available. https://www.osdisc.com/products
Answer: First things first: backup, backup, backup!
Back up all of your important data to an external HDD. You could also dd the entire contents of your internal HDD to an external one if you want a complete 1:1 image of the HDD.

Warning! I take no responsibility if this fails and you lose your data because you failed to back it up!

Before you begin, run this command to find out your username:
whoami

Write the output down! (Also write down your password)

Now for reinstalling:

Download the Ubuntu 18.04 LTS ISO
Burn the ISO to a DVD, or use the included Startup Disk Creator program to make a live USB drive.
Boot the install media you created in step #2
Choose to install Ubuntu
On the "installation type" screen, choose Something Else
Select Ubuntu system partition, and set its mount point as /. Be sure to keep the same format type, the same size, and untick the "Format" checkbox (else all data on "/" will be deleted!)
When you are asked to create your username and password, USE THE ONES YOU WROTE DOWN EARLIER!!! (Else loose your data)
After the installation finishes, follow the prompts to shutdown, and remove the installation media when it tells you to.
Reboot and cross your fingers.

Upgrade from 17.10 to 18.04 offline


Is there any short trick that will give the minimal polynomial?

Question:
The minimal polynomial of
\begin{bmatrix} 2& 8&0&0&0&0&0 \\ 0&2&0&0&0&0&0 \\ 0&0&4&0&0&0&0 \\ 0&0&1&3&0&0&0 \\ 0&0&0&0&0&3&0 \\ 0&0&0&0&0&0&0 \\ 0&0&0&0&0&0&5\end{bmatrix}
is
$(1)  \ t(t-2)(t-5) \\ (2) \ t(t-2)^2(t-5) \\ (3) \ t^2(t-2)(t-5) \\ (4) \ t^2(t-2)^2(t-5)$.

If I expand the determinant $(A-\lambda I)$, then I will get with more calculation.
But is there any short trick that will give the minimal polynomial ?
Comment: A. SARKAR I think to calculate $|A-\lambda I|$ it's a best way. It's not so complicated.
Comment: @MichaelRozenberg, ok thank you
Comment: Expanding the determinant will give you the _characteristic_ polynomial, not the minimal polynomial. They happen to be the same here, but seeing that requires a bit of additional thought.
Answer: None of the options are correct : this can be seen from the fact that $4$ is an eigenvalue with eigenvector $[0,0,1,1,0,0,0]$. Therefore, since any eigenvalue must be a root of the minimal polynomial, we get that $(t-4)$ must be a factor of the minimal polynomial. This is not the case with any of the given polynomials.

The idea is that the given matrix(call it $A$) is a block matrix (with blocks $A_i$, say) : therefore, if $p$ is any polynomial, then $p(A)$ is also a block matrix with blocks $p(A_i)$. In particular, the matrix $p(A)$ is zero exactly when each of the individual blocks are zero.
We know when the blocks are zero : for this, $p$ must be a multiple of the minimal polynomial of each of the blocks. Naturally, with this in mind, the minimal polynomial of $A$ is seen to be the lcm , of the minimal polynomials of the blocks.
Now, to calculate the lcm of the blocks, let us first see what the blocks are: they are $\begin{bmatrix} 2 \quad 8 \\ 0 \quad 2 \end{bmatrix} $,$\begin{bmatrix} 4 \quad 0 \\ 1 \quad 3 \end{bmatrix}$ , $\begin{bmatrix} 0\quad 3 \\ 0 \quad 0 \end{bmatrix}$ and $[5]$.
Each of these has minimal polynomial : $(t-2)^2$, $(t-4)(t-3)$, $t^2$ and $t-5$ respectively. These four cases are seen from the fact that all the matrices are either upper or lower triangular, so it is easy to see their eigenvalues and thence the minimal polynomial.The LCM is clearly seen to be $t^2(t-2)^2(t-3)(t-4)(t-5)$.
Comment: @M.A.SARKAR Yes, that is true : remember that in the expression $p(A)$ where $p$ is some polynomial, $p$ affects only the diagonal blocks, since the $0$-blocks remain zero regardless of what $p$ is.
Comment: Yes, it's a [Block Diagonal Matrix](https://en.wikipedia.org/wiki/Block_matrix#Block_diagonal_matrices). The diagonal blocks act as independent systems because the rest of the matrix is all zeroes. If you used this matrix in the set of simultaneous equations $A\bar{x}=\bar{b}$, then each block gives you a set of equations independent of the rest, with no variables in common.
Comment: @ why did not you consider other $0$ blocks. I think any $0$ blocks don't have any contribution in minimal polynomial  unless it is a diagonal block. is it the reason ?


Which is the best MVC v.2 learning source?

Question: I would appreciate some suggestions  about useful sources for learning the new features of MVC v.2 Beta .
and the real question is how to learn the features of the MVC 2 before release ?
Answer: Scott Hanselman has a good series of screencasts here
Also a good video from the latest PDC here
Answer:
Download the beta and try it out
Read blogs of MVC team guys

Scott Gu's: http://weblogs.asp.net/scottgu/archive/tags/MVC/default.aspx
Phil Haack: http://haacked.com
And others.

Watch related questions here on SO
Try it yourself on real projects

By the time it's released and there are books published and available, many early adopters won't even need a book.
Comment: And still - some tips would be nice. More like designing and structuring app when using things like Templates. You know - another nerddinner or blog app that leverages use of whole new feature set. :/
Answer: So recently Scott Guthrie posted some articles about MVC 2 which I think is the beat source to start with MVC 2 :
http://weblogs.asp.net/scottgu/archive/2010/01/10/asp-net-mvc-2.aspx


Custom function fails when passing range into it

Question: Trying to extract the first word from each cell in a range passed into the custom function. However, getting an error when using the function in the test spreadsheet.
/**
* @customfunction
*/
function test(alt_activities_range)
{
  var ss = SpreadsheetApp.getActive().getActiveCell();
  var sheet = SpreadsheetApp.getActive().getActiveSheet();
  var alt_activities_array = alt_activities_range[0];

  var alt_activities_array = alt_activities_range.map(str => {
    let arr = str.split(' ');
    return arr[0];
  });

  console.log(alt_activities_array);

}

The following error is produced:
TypeError: str.split is not a function.
Any help is greatly appreciated.
Answer: When I saw your provided Spreadsheet, it seems that the values of "B1:I1" of =test(B1:I1) are [["Chess - 6","Pilates - 6","Elevate - 6","Kundalini - 6","Scrabble - 6","Gardening - 6","Darning - 6","Crossword - 6"]]. So, in the case of your script, alt_activities_range is [["Chess - 6","Pilates - 6","Elevate - 6","Kundalini - 6","Scrabble - 6","Gardening - 6","Darning - 6","Crossword - 6"]].
In your script, the 1st element is retrieved by var alt_activities_array = alt_activities_range[0]. But, at var alt_activities_array = alt_activities_range.map(str => {, alt_activities_range is used. In this case, it is a 2-dimensional array. By this, str is an array. I guessed that this is the reason for your current issue of TypeError: str.split is not a function..
If you want to remove this issue, please modify it as follows.
From:
var alt_activities_array = alt_activities_range.map(str => {
  let arr = str.split(' ');
  return arr[0];
});

To:
var alt_activities_array = alt_activities_range[0].map(str => { // or alt_activities_array.map(str => {
  let arr = str.split(' ');
  return arr[0];
});

By this modification, alt_activities_array is ["Chess","Pilates","Elevate","Kundalini","Scrabble","Gardening","Darning","Crossword"].
Comment: @Drew254 Did my answer show you the result that you want? Would you please tell me about it? That is also useful for me to study. If this works, other people who have the same issue as you can also base your question as a question that can be solved. If you have issues with my answer yet, I apologize. At that time, can I ask you about your current situation? I would like to study to solve your issues.
Comment: Yes it did. Sorry for the delay in my response.


Django: Two fields, one valid

Question: I have two fields in one model, I want only one valid field in the Admin Form. If one field is valid then the other is not possible to insert data or vice versa. But is necessary put data in one of the two fields for save.
That is possible?
Thanks!
Answer: If you want this validation to happen on the backend, you would validate in clean method of the form. something like this:
class MyAdminForm(forms.ModelForm):
    def clean(self):
        cd = self.cleaned_data
        fields = [cd['field1'], cd['field2']]
        if all(fields):
            raise ValidationError('Please enter one or the other, not both')
        if not any(fields): #Means both are left empty
            raise ValidationError('Please enter either field1 or field2, but not both')

    return cd

Here is the documentation on using forms with django admin
If you want the validation to happen on the frontend, rather than on form submit, you might want to consider using a javascript solution for that.
Here is an answer for a javascript solution

Django: Two fields, one valid


What is the desired behavoir of a neural network?

Question: I tried a few neural networks and would like to know, when do I have a good trained model.
First, the training error goes down and stays constant at a certain number of epochs, the same with the validation error. Has it now converged?
Second, the training error goes down over all simulated epochs, and the validation error goes first down, but then increases after 10 epochs. I would have to stop there?
In which case do I have a better trained model? What is a desired behavior?
Thanks
Answer: Ideally, you would like both your training and validation error to decrease. But sometimes, if you train too much (i.e. your model tries too hard to learn your training dataset), it may lead to overfitting. That is the whole purpose behind using a validation set to keep a check on whether you are overfitting your dataset.
In the first case, since your error for both your training and validation set is going down nicely, it is possible that the model has trained well. But this does not mean that the model has found the global minimum (if that is what you were asking).
In the second case, after the point when your validation error starts increasing, your model has started to overfit the dataset. So you may want to stop your training at this point because training further will lead your model to overfit. This is also known as early stopping.
Hope this helps.
Comment: ok thanks, yes that helps.
Can you actually test if a network has reached a global minimum? I think in general not.
Comment: In my knowledge, there is no way to actually test if your network has reached a global minimum. But then again, most of the time you will still be able to land a sensible answer even with a local minimum (which may not be too far away from the global minimum). There are various optimization techniques you might want to look at, which will land you into a better local minimum (such as initialization techniques, activation functions, choice of the optimizer, etc).


response.sendRedirect replacing + with space in encrypted URL when receiving in app2?

Question: On a tomcat, I have two webapplications i.e app1 and app2. I send URL from app1 in encrypted form (using below program) to app2 . I send the URL through response.sendRedirect(encryptedURL).Then at app2 I get this encrypted URL. I see there are some extra characters like +,space( ) in this encrypted URL at app2. I want the exact same URL at app2. I am not getting why these extra characters getting inserted?
Here is the URL at app1 after encryption
 Rc9mgB+18chPk6nk1+gzpws6dO5/TSkcOYy8rbuVVTmjE9YjLt5w0EMpuhh+QBKzReYO34pAquf9
 kmYOiwl99jo2kDCCkYHMh/+nxEgs1yrLYagsc/0p5KdYeMy1eWeUQB8KqmNlhtYysrHhOYVuunUi
 dTaEKUTSWd8lPg9/wZfHdBoJgaF40aUW3FeRODVL

Here is the value of this encrypted URL at app2 when I get it with req.getParameter("encryptedURL");
 Rc9mgB 18chPk6nk1 gzpws6dO5/TSkcOYy8rbuVVTmjE9YjLt5w0EMpuhh QBKzReYO34pAquf9  kmYOiwl99jo2kDCCkYHMh/ nxEgs1yrLYagsc/0p5KdYeMy1eWeUQB8KqmNlhtYysrHhOYVuunUi  dTaEKUTSWd8lPg9/wZfHdBoJgaF40aUW3FeRODVL

Here is the program for encryption
 import java.security.Key;
 import javax.crypto.Cipher;
 import javax.crypto.spec.SecretKeySpec;
 import sun.misc.BASE64Decoder;
 import sun.misc.BASE64Encoder;

 public class AESEncryptionDecryptionTest {

   private static final String ALGORITHM       = "AES";
   private static final String myEncryptionKey = "ThisIsFoundation";
   private static final String UNICODE_FORMAT  = "UTF8";

   public static String encrypt(String valueToEnc) throws Exception {
 Key key = generateKey();
 Cipher c = Cipher.getInstance(ALGORITHM);
 c.init(Cipher.ENCRYPT_MODE, key);
 byte[] encValue = c.doFinal(valueToEnc.getBytes());
 String encryptedValue = new BASE64Encoder().encode(encValue);
 return encryptedValue;
   }

private static Key generateKey() throws Exception {
byte[] keyAsBytes;
keyAsBytes = myEncryptionKey.getBytes(UNICODE_FORMAT);
Key key = new SecretKeySpec(keyAsBytes, ALGORITHM);
return key;
}

}

EDIT:-Looks  like very close to it. here is my new code and finding
This is the parameter I am encrypting at app1
 mySession=84088586B45317C3600978DF9F52A699&securityTok=44a2e4dd89ed1aad438d5e3c16ff528&myurl=https://10.205.112.83:8443

// encrypted as you suggested at app1 and sending  encryptedParam as request parameter
//now getting the encryptedParam at app2 from request and decrypted  as per your suggestion . As you can see below
everything is decrypted fine at app2 except my URL part(i.e =https://10.205 replaced with ½‡è˜�Àg¸l½.µbO')
mySession=84088586B45317C3600978DF9F52A699&securityTok=44a2e4dd89ed1aad438d5e3c16ff528&myurl½‡è˜�Àg¸l½.µbO'112.83:8443

Code is
   public static String encrypt(String valueToEnc) throws Exception {
    Key key = generateKey();
    // Key key = buildKey();
    Cipher c = Cipher.getInstance(ALGORITHM);
    c.init(Cipher.ENCRYPT_MODE, key);
    byte[] encValue = c.doFinal(valueToEnc.getBytes(UNICODE_FORMAT));
    String encryptedValue1 = new BASE64Encoder().encode(encValue);
    String encryptedValue = URLEncoder.encode(encryptedValue1);
    return encryptedValue;
  }

  public static String decrypt(String encryptedValue) throws Exception {
    Key key = generateKey();
    // Key key = buildKey();
    Cipher c = Cipher.getInstance(ALGORITHM);
    c.init(Cipher.DECRYPT_MODE, key);
    String decordedValueStr = URLDecoder.decode(encryptedValue);
    byte[] decordedValue = new BASE64Decoder().decodeBuffer(decordedValueStr);
    byte[] decValue = c.doFinal(decordedValue);
    // String try1=new BASE64Encoder().encode(decValue);
    String decryptedValue = new String(decValue);
    return decryptedValue;
  }

Comment: You should not use `valueToEnc.getBytes()`. You should use `valueToEnc.getBytes(UNICODE_FORMAT)`. You were told this in another answer.
Comment: I have already mentioned in my answer that you should do decode. And why you should not do decode.
Answer: You have to use URLEncoding.

Use URLEncoder to encode the url in app1.
Use URLDecoder to decode the url in app2.

When server receives the redirected request, anyway it will do URL decode. So you do not have to do it. Just URLEncode in the app1 should solve your problem.
Comment: Hi ramesh if you lok at encrypt method i am doing encoding using BASE64Encoder not •URLEncoder. Simliarly doing decoding using BASE64Decoder(). Are using saying i shud use urlencoder and decoder instead of BASE64Encoder and BASE64Decoder?
Comment: @MSach:  Yes, that is what he is saying.
Comment: @MSach Yes should be doing URLEncoding and URLDecoding
Comment: Hi ramesh. tried that, but same issue. Please look at edited part.With urlencoder, i  encrypted the url at app1 and then decrypted at app1 itself, then also give it gives error
Comment: Did you try doing only URLEncode. Do not do URLDecode on the other side.
Comment: Hi ramesh, it would be really nice if you can provide inputs on stackoverflow.com/questions/10846901/… as i am bit confused about  encoding and decoding and when it requires?
Comment: http://stackoverflow.com/questions/10846901/some-questions-about-urlencoder-and-urldecoder
Answer: In your encrypt method instead of:
return encryptedValue;

use this code:
return URLEncoder.encode(encryptedValue);

then on receiving side call URLDecoder#decode:
String tmpUrl = URLDecoder.decode(encryptedURL);
// call BASE64Decoder on tmpUrl
// call decrypt on return value of BASE64Decoder

Comment: Thanks Anubhav it solved. At decrypt removed URLDecoder.decode(encryptedValue); Looks like it already decoded
Comment: Yes you're right: `coder.encode(encryptedValue,"UTF8");` is a preferred one. I will look into your other question and provide my input.
Comment: @MSach: I didn't suggest removing `BASE64Encoder.encode` method call. You should call `URLEncoder.encode` on the return value of `BASE64Encoder.encode` in your encrypt method. Likewise on receiving side call `URLDecoder.decode` first then `BASE64Decoder.decode` and finally use your decrypt code.
Comment: Hi Anubhava looks  like very close to it. See my new edit after your suggestion. Waiting for it eaglarly from last two days
Comment: Your new code looks good to me, are you still getting some problem with this approach?
Comment: Anubhava one more thing is that coder.encode(encryptedValue) is deprecated . I think i should go for coder.encode(encryptedValue,"UTF8"); Right?
Comment: also it would be really nice if you can provide inputs on http://stackoverflow.com/questions/10846901/some-questions-about-urlencoder-and-urldecoder as i am really looking some good points on encoding and decoding?


Joining three tables with 2 count function

Question: I've been at it for a day and couldn't really figure it out. I'm making a page where users can post and other users can reply and like.
I have these three tables: posts, replies, and likes. FYI that they all have a different number of rows, see full details below.
Posts table
post_id   message
-------   -------
1         This is post #1
2         This is post #2
3         This is post #3

Replies table
reply_id  post_id   message
-------   -------   -------
1         1        This is a reply to post #1
2         1        This is a reply to post #1
3         2        This is a reply to post #2
4         2        This is a reply to post #2
5         3        This is a reply to post #3

Likes table
like_id   post_id   liked
-------   -------   -------
1         1         Yes
2         1         Yes
3         1         Yes
4         2         Yes
5         2         Yes
6         3         Yes
7         3         Yes

Those are the structure of my tables. What I need to achieve is like this below:
All tables joined and tallied
post_id   total_replies   total_likes
-------   -------------   -----------
1         2               3
2         2               2
3         1               2

Basically, for the 1st post, it should show that it has 2 replies and 3 likes. I cannot seem to do it using two counts. It is giving me incorrect numbers.
select posts.post_id, count(replies.post_id) as total_replies, count(likes.post_id) as total_likes from posts
inner join replies on posts.post_id = replies.post_id
inner join likes on posts.post_id = likes.post_id
group by posts.post_id

Answer: I would suggest correlated subqueries:
select p.post_id,
       (select count(*)
        from replies r
        where r.post_id = p.post_id
       ) as total_replies,
       (select count(*)
        from likes l
        where l.post_id = p.post_id
       ) as total_likes
from posts p;

The problem with your query is that you are joining along two different dimensions, so you are getting a Cartesian product -- all likes and all replies for a given post.
Not only does this get rid of that problem, but with indexes on replies(post_id) and likes(post_id) this should have better performance than any solution that does an aggregation over all the data.
Answer: I took your query and made a small edit so that it produces desired output. However note that the query would not be efficient. Gordon's solution is more effective in terms of efficiency.
select
     posts.post_id,
     count(distinct replies.reply_id) as total_replies,
     count(distinct likes.like_id) as total_likes
from posts
 inner join replies on posts.post_id = replies.post_id
 inner join likes on posts.post_id = likes.post_id
group by
  posts.post_id;

Or would be better to pre-aggregate your metrics. That way it would be bit more efficient.
select
     posts.post_id,
     r.total_replies,
     L.total_likes
from posts
 inner join (Select post_id, count(reply_id) as total_replies from replies group by post_id) r on posts.post_id = r.post_id
 inner join (Select post_id, count(like_id) as total_likes from likes group by posts_id) L on posts.post_id = L.post_id;

The caveat is you won't get post that weren't liked or replied upon since you are doing inner join. To get all posts irrespective of likes or replies you have to do left join.


"Inverse" of an $n\times k$ matrix.

Question: I know that only square matrices can have inverses. Nevertheless, assume that we have an $n \times k$ matrix $A $ with $n\neq k$. Then it may still be possible to construct a matrix $B$ such that
$$BA=I$$
For example, assume that $B=(A^TA)^{-1}A^T$, then $BA=(A^TA)^{-1}(A^TA)=I$
I know that $B$ cannot be called an inverse, due to the definition of inverse requiring $A$ to be a square matrix. Nevertheless, it is sort of like an inverse, so do we have a name/theory about these kinds of "inverses"?
Comment: Look for "pseudoinverse" or "Moore-Penrose inverse".
Answer: If we see these matrices as representing linear maps, then your $B$ is called a left inverse of $A$. An $n\times k$ matrix $A$ has a left inverse iff $\operatorname{rank} A = k$, in other words, if all $k$ columns of $A$ are linearly independent. Similarily, a matrix has a right inverse iff it has linearly independent rows.
If a matrix has both a right and a left inverse, then both its rows and its columns must be linearly independent, so there must be equally many of them, and the matrix is therefore square. It also turns out that the left inverse and the right inverse must be the same matrix, and we call it the inverse.

"Inverse" of an $n\times k$ matrix.


Is there an advantage to single-ended LED replacement bulbs for fluorescent fixtures?

Question: I installed 100 dual-ended LED 4-foot replacements last year and noticed that my AMZN supplier (Sunco) has replaced the product with a single-ended version.  Naturally, I do not want to rewire the 100 units a second time and would like to continue with the dual-ended LEDs to maintain consistency (KISS principle).
QUESTIONS

Is there advantage to using a single-ended bulb?
Is there cause to believe that single-ended bulbs will phase out dual-ended?

I ask these questions because if there is a significant advantage to single-ended designs, then maybe I should stock up on whatever dual-ended supplies exist if they are to become extinct.
If the winds are blowing in the direction of single-ended devices, then it may make sense to give up on consistency and replace existing fluorescent devices with single-ended LEDs.
Comment: @isherwood not on many tombstones, no.
Comment: I speculate that the single-ended version is both simpler (less expensive) to manufacture and simpler to retrofit. Your hunch is probably right, and whether you should stock up is subjective. I'd probably forget about it and rewire (which I assume is fairly easy) when and if you need to replace them.
Comment: I will speculate you can but, not worth the trouble.  You would need to remove it from the fixture to snip it  and you might as well replace the it with a nonshunted.  Good video: https://www.youtube.com/watch?v=R6xe54orVNY
Comment: Do you expect your LEDs to expire in any significant timeframe?
Comment: Good question.  I'd like to think that they will last 10+ years in a storage facility, however, with the Florida heat its a crapshoot/
Comment: Single-Ended may be cheaper to manufacture, however, they require non shunted 'tombstones': if the fixture's tombstone is shunted, then a tombstone change is additional labor and cost.
Comment: You can't just snip the shunt?
Comment: The shunted ones I have the shiny is internal for the single ended retrofit the tombstones need to be replaced. On some earlier retrofits that were double ended shunted tombstones were ok but not on the lamps I use today
Answer: I have purchased hundreds of led tubes. I currently use a T8 that is ballast bypass single or double ended and ballast compatible, I love these lights and just ordered 4 more cases. With my T5 lights I cannot find the same specs yet but I prefer double ended because most of my T5 lamps are 277v and I don't like my 277v 20 amp circuits having the pins that close together because I lose at least 2 fixtures a year when chunks of wood hit the fixtures. In the past, the ballast controlled the max current but with direct wire lamps that are single ended a good hit would, and has in 1 case, burn a large hole in a very expensive fixture because no matter how good the fixture is the tombstones are all cheap so when the $1.20 tall tombstone broke on a single ended retrofit it burned a huge hole in the $380 fixture.
So I go with double ended when possible.
Comment: Good fire-safety insight.   I am now inclined to stay the course with double-ended.  I have low tolerance for fire-risk.  Post a link to your preferred T8?


Tooltip in FullCalendar

Question: I am trying to make a tooltip in my calendar,
 the calendar is working properly but I want to show more details of the patient, like
Description of patient on mouseover. I have no idea how to do it?
Can some one help me out?

ref link(https://fullcalendar.io/)

This is what I did

Javascript(ajax)
Data take from dynamic
<link href='jscss/fullcalendar.min.css' rel='stylesheet' />
    <link href='jscss/fullcalendar.print.min.css' rel='stylesheet' media='print' />

Method
    [WebMethod]
    public static IList GetEvents()
    {
        clsDBOperation obj = new clsDBOperation();
        DataTable dt1 = obj.GetDataTable("SELECT con.EDate as EDate ,  con.pfname , COUNT(*) OVER (PARTITION BY CAST(con.AppDate AS DATE)) Appointment, con.AppDate as Date, CAST(con.AppTime AS Time(0)) Time from Consultation as con inner join DoctorMaster as doc on con.DrCode=doc.id where con.DrCode='" + HttpContext.Current.Session["DrCode"] + "' ");
            IList events = new List<Event>();
            for (int i = 0; i < dt1.Rows.Count; i++)
            {
                DataRow dRow4 = dt1.Rows[i];
                events.Add(new Event
                {
                   start = Convert.ToDateTime(dRow4["Date"].ToString()).ToString("yyyy-MM-dd") + "T" + dRow4["Time"].ToString(),
                    end = Convert.ToDateTime(dRow4["Date"].ToString()).ToString("yyyy-MM-dd") + "T" + dRow4["Time"].ToString(),
                    title = dRow4["pfname"].ToString(),
                    Appointment = dRow4["Appointment"].ToString(),
                    Time = dRow4["Time"].ToString()

                });
            }
            return events;
    }
}
public class Event
{
    public string start { get; set; }
    public string end { get; set; }
    public string title { get; set; }
    public string Appointment { get; set; }
    public string Time { get; set; }
}

Comment: https://fullcalendar.io/docs/eventRender gives a basic example - it requires the "qtip" library which you can search for and download, or you can use any other way of displaying a popover in JavaScript, it doesn't matter.
Answer: You need to override eventRender property of full calendar.
 $('#calendar').fullCalendar({
    defaultView: 'month',
    defaultDate: '2018-10-12',

    eventRender: function(eventObj, $el) {
      $el.popover({
        title: eventObj.title,
        content: eventObj.description,
        trigger: 'hover',
        placement: 'top',
        container: 'body'
      });
    },

    events: [
      {
        title: 'All Day Event',
        description: 'description for All Day Event',
        start: '2018-10-01'
      },
      {
        title: 'Long Event',
        description: 'description for Long Event',
        start: '2018-10-07',
        end: '2018-10-10'
      },
      {
        id: 999,
        title: 'Repeating Event',
        description: 'description for Repeating Event',
        start: '2018-10-09T16:00:00'
      },
      {
        id: 999,
        title: 'Repeating Event',
        description: 'description for Repeating Event',
        start: '2018-10-16T16:00:00'
      },
      {
        title: 'Conference',
        description: 'description for Conference',
        start: '2018-10-11',
        end: '2018-10-13'
      },
      {
        title: 'Meeting',
        description: 'description for Meeting',
        start: '2018-10-12T10:30:00',
        end: '2018-10-12T12:30:00'
      },
      {
        title: 'Lunch',
        description: 'description for Lunch',
        start: '2018-10-12T12:00:00'
      },
      {
        title: 'Meeting',
        description: 'description for Meeting',
        start: '2018-10-12T14:30:00'
      },
      {
        title: 'Birthday Party',
        description: 'description for Birthday Party',
        start: '2018-10-13T07:00:00'
      },
      {
        title: 'Click for Google',
        description: 'description for Click for Google',
        url: 'http://google.com/',
        start: '2018-10-28'
      }
    ]
  });

working example is here
for more reference see this in fullcalendar docs

Tooltip in FullCalendar


Easiest way to attach this HDX inline filter to replace my American Plumber WICA inline filter

Question: I threw out this American Plimber inline filter:
[]
[]
It was over a decade old, and yes I can replace it, but I'd rather use this HDX one:
[
[
I have a torch and a hacksaw. I have plenty of slack in my copper line. I have the following collars and fittings:
[
[
[
Is the best thing to do just to saw off the plastic couplings and then soldier on the metal ones?
Comment: Doesn't that HDX filter have push on connectors on both sides?  So can't you just use a tubing cutter (not a saw) to cleanly cut the copper and push it into the filter?
Comment: @JPhi1618 yes once I realized that the plastic conectors were push to connect, I came to the conclusion that push to connect works for copper as well as flex line.
Comment: Yea, the pipes are clever because the _outside_ diameter is the same for all materials so the connectors work for various pipe types.
Answer: I was able to take off the plastic connectors on each end of copper. After that I realized since ther were push to connect then I could use push to connect on copper as well as flex line. At that point I cleaned the copper ends with a green 3m scouring pad, and installed the filter with no soldering and none of the brass parts.
Comment: Don't forget to secure it to something with strapping.
Comment: It might protect the 1/4 inch lines from pulling free.
Comment: @ojait the old filter had none and it lasted a decade.  I will put that on my todo though.
Comment: Wait. What? A decade? I believe water filters should be replaced every 3-6 months. Or it should be printed on the filter label.
Comment: @ojait yes the filter was installed longer than I owned the house. I got a new fridge so I decided it was time to deal with the matter. I bought the house from the estate of a widow. I assume when the husband died, the widow didn't know to have the filter in the ceiling of the basement changed.


How can I catch EPIPE in my NSFIleHandle handling?

Question: I'm having a problem with EPIPE in my iOS app, and it's not being caught in the @try/@catch/@finally block. How can I catch this signal (SIGPIPE, likely)...
I've built a "web proxy" into my app that will handle certain kinds of URLs - in this error case, it seems that the remote end (also in my app, but hiding in the iOS libraries) closes its end of the socket. I don't get a notification (should I? Is there something I should register for with the NSFileHandle that might help here?).
I've based this proxy on HTTPServer that Matt Gallagher put together (available here), and the problem is in a subclass of the HTTPRequestHandler class he put together. Here's the code (this code is the equivalent of the startResponse method in the base class):
-(void)proxyTS:(SSProxyTSResource *)proxyTS didReceiveResource:(NSData *)resource
{
    NSLog(@"[%@ %@]", NSStringFromClass([self class]), NSStringFromSelector(_cmd));

CFHTTPMessageRef response =
    CFHTTPMessageCreateResponse(kCFAllocatorDefault, 200, NULL, kCFHTTPVersion1_1);
    CFHTTPMessageSetHeaderFieldValue(response,
                                    (CFStringRef)@"Content-Type",
                                    (__bridge CFStringRef)s_MIMEtype);
    CFHTTPMessageSetHeaderFieldValue(response,
                                    (CFStringRef)@"Connection",
                                    (CFStringRef)@"close");
    CFHTTPMessageSetBody(response,
                        (__bridge CFDataRef)resource);

    CFDataRef headerData = CFHTTPMessageCopySerializedMessage(response);
    @try
    {
        NSLog(@" -> writing %u bytes to filehandle...",[((__bridge NSData *)headerData) length]);
        [self.fileHandle writeData:(__bridge NSData *)headerData];
    }
    @catch (NSException *exception)
    {
        // Ignore the exception, it normally just means the client
        // closed the connection from the other end.
    }
    @finally
    {
        NSLog(@" *ding*");
        CFRelease(headerData);
        CFRelease(response);
        [self.server closeHandler:self];
    }
}

And here's what shows up in the console log when it crashes:
Jan 15 14:55:10 AWT-NoTouch-iPhone-1 Streamer[1788] <Warning>: [SSProxyTSResponseHandler proxyTS:didReceiveResource:]
Jan 15 14:55:10 iPhone-1 Streamer[1788] <Warning>:  -> writing 261760 bytes to filehandle...
Jan 15 14:55:11 iPhone-1 com.apple.launchd[1] (UIKitApplication:com.XXX.Streamer[0xf58][1788]) <Warning>: (UIKitApplication:com.XXX.Streamer[0xf58]) Exited abnormally: Broken pipe: 13

It seems that because the other end closed the pipe the write() fails, so if someone can point me at how I can either discover that it's already closed and not try to write data to it OR whatever will make it not crash my program that would be very helpful.
Comment: Ok, the simple solution is to ignore SIGPIPE (via `signal(SIGPIPE,SIG_IGN)`) in `application:didFinishLaunchingWithOptions:` and restoring it in `applicationWillTerminate:`. A more detailed version is below in my answer to my own question...
Answer: The immediate problem of crashing with SIGPIPE is solved. I'm not entirely giggly about this solution, but at least the app doesn't crash. It's not clear that it's working 100% correctly, but it does seem to be behaving quite a bit better.
I've resolved this issue by examining further what's going on. In doing some research, I found that perhaps I should be using NSFileHandle's writeabilityHandler property to install a block to do the writing. I'm not fully sold on that approach (it felt convoluted to me), but it might help.
Writability-handler solution:
In doing some web searching on writeabilityHandler, I stumbled on Bert Leung's blog entry on some issues he was having in a similar area. I took his code and modified it as follows, replacing the @try/@catch/@finally block above with this code:
self.pendingData = [NSMutableData dataWithData:(__bridge NSData *)(headerData)];

CFRelease(headerData);
CFRelease(response);

self.fileHandle.writeabilityHandler = ^(NSFileHandle* thisFileHandle)
    {
        int amountSent = send([thisFileHandle fileDescriptor],
                              [self.pendingData bytes],
                              [self.pendingData length],
                              MSG_DONTWAIT);
        if (amountSent < 0) {
            // errno is provided by system
            NSLog(@"[%@ %@] Error while sending response: %d", NSStringFromClass([self class]), NSStringFromSelector(_cmd), errno);
            // Setting the length to 0 will cause this handler to complete processing.
            self.pendingData.length = 0;
        } else {
            [self.pendingData replaceBytesInRange:NSMakeRange(0, amountSent)
                                   withBytes:NULL
                                      length:0];
        }

        if ([self.pendingData length] == 0) {
            thisFileHandle.writeabilityHandler = nil;
            // Hack to avoid ARC cycle with self. I don't like this, but...
            [[NSNotificationCenter defaultCenter] postNotification:self.myNotification];
        }
    };

That worked fine but it didn't solve the problem. I was still getting SIGPIPE/EPIPE.
SIGPIPE be gone!
This wasn't a surprise, exactly, as this does pretty much the same thing as the former writeData: did but does it using send() instead. The key difference though is that using send() allows errno to be set. This was quite helpful, actually - I was getting a couple of error codes (in errno), such as 54 (Connection reset by peer) and 32 (Broken pipe). The 54's were fine, but the 32's resulted in the SIGPIPE/EPIPE. Then it dawned on me - perhaps I should just ignore SIGPIPE.
Given that thought, I added a couple of hooks into my UIApplicationDelegate in application:didFinishLaunchingWithOptions:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    // Override point for customization after application launch.
    [self installSignalHandlers];

    if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad) {

    ...

and applicationWillTerminate::
- (void)applicationWillTerminate:(UIApplication *)application
{
    // Saves changes in the application's managed object context before the application terminates.

    [self removeSignalHandlers];

    [self saveContext];
}

-(void)installSignalHandlers
{
    signal(SIGPIPE,SIG_IGN);
}

-(void)removeSignalHandlers
{
    signal(SIGPIPE, SIG_DFL);
}

Now at least the app doesn't crash. It's not clear that it's working 100% correctly, but it does seem to be behaving.
I also switched back to the @try/@catch/@finally structure because it's more direct. Further, after ignoring SIGPIPE, the @catch block does get triggered. Right now, I'm logging the exception, but only so I can see that it's working. In the released code, that log will be disabled.


Does $4b^3pq=2a^2+b$ has a solution for non-zero integers $a,b$ and odd primes $p<q$?

Question: Just recently, I had an equation on my hands that I thought had no solutions:
Why $4b^3p=2a^2+qb$ has no solutions for integers $a,b$ and two odd primes $p<q$?
I was on a wrong path and now have an equation $4b^3pq=2a^2+b$ that really do not brings me any non-zero integer solution $a,b$ where $2<p<q$ are odd primes. What I see is that $b$ must be even and when I substitute $b=2t$ I have to solve $0=16t^3pq-t-a^2$ for $t$ (quadratic equation) and analyze the discriminant?
Comment: Have you considered the possibility that the solutions would be bigger than your brute force range?
Comment: Is this your original equation, or should I trust that the steps leading to this equation are arithmetically correct?
Comment: I really run the brute force program (python) supporting big integers. If there is a solution, I would be very interested in this one.
Comment: I did a minor mistake which I just fixed (in compliance with your answer) - the equation after substitution is $0=16t^2pq-a^2-t$. Your proof in your answer is very helpful - thank you very much!
Answer: The correct resulting equation is of substituting $b=2t$ is:
$$16t^3pq=a^2+t$$
We transform our equation to:
$$(16t^2pq-1)t = a^2$$
Let $\ell$ be any prime factor of $t$, and let $\ell^n$ be the highest power of $\ell$ that divides $\color{red}{a}$. Then $\ell^{2n}$ is the highest power of $\ell$ that divides $a^2$; now $\ell$ does not divide $16t^2pq - 1$ at all, so $\ell^{2n}$ must also be the highest power of $\ell$ that divides $t$.
Since $\ell$ is arbitrary, we conclude that $t$ is in fact a square, say $t = g^2$. Then our equation becomes:
$$(16g^4pq-1)g^2 = a^2$$
which gives:
$$16g^4pq-1 = \left(\frac ag\right)^2$$
which is impossible, since the squares mod $16$ are $0, 1, 4, 9$.
Comment: Since $t$ is prime to $16t^2pq - 1$, one concludes directly that $16t^2pq - 1$ is a perfect square, which is impossible by an argument mod $4$.
Comment: Indeed, your method is quicker.
Answer: More generally, the equation
$$
2b^3c=2a^2+b
\qquad\;\;\;\;
$$
has no integer solutions with $c > 0$ and $a,b\ne 0$.

Suppose otherwise.
\begin{align*}
\text{Then}\;\;&
2b^3c=2a^2+b
\qquad\qquad\qquad\;
\\[4pt]
\implies\;&
2b^3c-b=2a^2
\\[4pt]
\implies\;&
b(2b^2c-1)=2a^2
\\[4pt]
\implies\;&
b(2b^2c-1) > 0
\\[4pt]
\implies\;&
b > 0\;\;\text{(since $2b^2c-1 > 0)$}
\end{align*}
Next let $d=\gcd(a,b)$.

Then
$$
\left\lbrace
\begin{align*}
a&=da_1\\[4pt]
b&=db_1\\[4pt]
\end{align*}
\right.
\qquad\qquad\qquad\;\;\;
$$
for some integers $a_1,b_1$ with $b_1 > 0$ and $\gcd(a_1,b_1)=1$.
\begin{align*}
\text{Then}\;\;&
2b^3c=2a^2+b
\qquad\qquad\qquad\;\;\;\;
\\[4pt]
\implies\;&
2(db_1)^3c=2(da_1)^2+db_1
\\[4pt]
\implies\;&
2d^3b_1^3c=2d^2a_1^2+db_1
\\[4pt]
\implies\;&
2d^2b_1^3c=2da_1^2+b_1
\\[4pt]
\implies\;&
2d{\,\mid\,}b_1
\\[4pt]
\end{align*}
hence $b_1=2db_2$ for some positive integer $b_2$.

Then since $\gcd(a_1,b_1)=1$ and $b_2{\,\mid\,}b_1$, it follows that $\gcd(a_1,b_2)=1$.
\begin{align*}
\text{Then}\;\;&
2d^2b_1^3c=2da_1^2+b_1
\qquad\qquad\qquad
\\[4pt]
\implies\;&
2d^2(2db_2)^3c=2da_1^2+2db_2
\\[4pt]
\implies\;&
16d^5b_2^3c=2da_1^2+2db_2
\\[4pt]
\implies\;&
8d^4b_2^3c=a_1^2+b_2
\\[4pt]
\implies\;&
b_2{\,\mid\,}a_1^2\
\\[4pt]
\implies\;&
b_2=1\;\;\text{(since $\gcd(a_1,b_2)=1$)}
\\[4pt]
\implies\;&
8d^4c=a_1^2+1
\\[4pt]
\implies\;&
a_1^2\equiv -1\;(\text{mod}\;4)
\\[4pt]
\end{align*}
which is not possible.


download Zip file which is formed by multiple files in PHP

Question: I have some pdf files...I want to just download them as a collection and not one by one.
For that , I am trying to zip all pdf files and download. But I don't know why when in my code I am changing ZipArchive file name, it is saying damaged and corrupt.
My code is below:-
 function zipFilesAndDownload($file_names,$archive_file_name,$file_path)
{
    $zip = new ZipArchive();
    //create the file and throw the error if unsuccessful
    if ($zip->open($archive_file_name, ZIPARCHIVE::CREATE | ZIPARCHIVE::OVERWRITE )!==TRUE) {
        exit("cannot open <$archive_file_name>\n");
    }
    //add each files of $file_name array to archive
    foreach($file_names as $files)
    {
        $zip->addFile($file_path.$files,$files);

    }
    $zip->close();
    //then send the headers to foce download the zip file
    header("Content-type: application/zip");
    header("Content-Disposition: attachment; filename=$archive_file_name");
    header("Pragma: no-cache");
    header("Expires: 0");
    readfile("$archive_file_name");
    exit;
}

if($button=="Save as pdf")
{
$file_names = array();
foreach($a as $key=>$as)
{
 $file_names[] = $key.'.pdf';
}
}
$archive_file_name='zipped.zip';
$file_path='/resume/';
zipFilesAndDownload($file_names,$archive_file_name,$file_path);

?>

Can anybody help me out? Thanks in advance.
Its working fine but still i am facing 2 problems,1. I am getting error that Archive is corrupted if I change the name of archive_file_name to something other than given above. I don't why its happening    2.If I have got a zip file of say, 2 pdfs and then i again download a zip of only 1 pdf which was not same as earlier ones. But when I am downloading the zip of 1 pdf, then i am getting 3 pdfs......I don't know why ........please help me.
Comment: Which name have you tried? Which one is ok?
Comment: i have tried zipper1.zip and its not working. Its working with only zipper.zip name.
Answer: I tested your zipFilesAndDownload function and it works well. So at first you should check your script, whether you have no characters or blank spaces sent before the <?php starting tag.
In the case that your script is running inside a CMS, you should also clear all output buffers: while (@ob_end_clean()); (and if gzip headers was already sent, then also turn gz compression on again ob_start('ob_gzhandler');)
Also you can also check, if you have correctly set the $file_path and all your files exists, for example:
$file_path='resume/';
if (!file_exists($file_path) || !is_dir($file_path)) {
    die("Invalid directory $file_path in ".getcwd());
}
// you can test the existence of your problematic files:
foreach ($file_names as $file) {
    if (!file_exists($file_path.$file)) {
        echo "$file not found.";
    } else {
        echo "$file is ok.";
    }
}
exit;
// end of test
zipFilesAndDownload($file_names,$archive_file_name,$file_path);

In Windows is also problem with UTF-16/UTF-8/international character encoding, see here: PHP detecting filesystem encoding, How do I use filesystem functions in PHP, using UTF-8 strings?.
Comment: Its working fine but still i am facing 2 problems,1. I am getting error that Archive is corrupted if I change the name of archive_file_name to something other than given above. I don't why its happening    2.If I have got a zip file of say, 2 pdfs and then i again download a zip of only 1 pdf which was not same as earlier ones. But when I am downloading the zip of 1 pdf, then i am getting 3 pdfs......I don't know why ........please help me.
Comment: Hi, I also don't know why. But you can check the zipped file in some hexaviewer to see whether it begins correctly with PK letters or not. Other than that I dunno.


Mansfied Toilet Compatibale bowls?

Question: Are there compatible bowls for a Mansfield tank, I have a Mansfield Model 148 tank and no bowl?
Comment: VTC - This question is seeking product recommendations regarding specific brands -- basically a shopping question. This type is not a good fit for this site because it will outdate quickly and not likely be of use to the general user here even if an answer were to come forward.
Comment: In short, as Jimmy's answer goes into more detail, a new toilet is almost always going to be cheaper and much easier to find - and all of its parts will work together properly (or you can complain to the seller until they do...) Put it out in the yard as a porcelain planter, that's pretty much what they are good for once separated.
Answer: I will answer by using this question as a platform to address the difficulty and expense, at least in the U.S.A., of procuring one replacement piece (tank or bowl) for a 2-piece toilet.
There are numerous manufacturers of toilets from many countries and locales, most offering (at least) several designs and several colors of each design.
The primary reason is financial. Supply and demand dictates that sales of complete toilets would dwarf sales of just a tank or bowl. With essentially zero demand there would simply be no financial incentive to ship, wholesale, then retail the individual components for separate sale. If they did, the cost would likely be very near the cost of buying a complete toilet, which would undoubtedly rankle most consumers.
That being said, there are exceptions. A good plumbing shop may very well have just a tank or bowl available for the basic top seller at their shop and in the most common color (white). You also may be able to order a replacement from the manufacturer, through a distributer. What you are not likely to find is replacements for anything no longer manufactured (designs change frequently, for many reasons); anything in a color that is not white; anything not originally sold in large quantities; anything from a distant land.

Mansfied Toilet Compatibale bowls?


differentiability with complex numbers

Question: Let $f:\mathbb{C}\rightarrow \mathbb{C}$ defined by $f(z)=z^{3}$. Prove that does not exist a point $z_0$ for the line segment that joins $z_1=1$ and $z_2=i$ such that
$f(z_2)-f(z_1)=f'(z_0)(z_2-z_1)$
...any idea how to start, please?
Answer: Hint: This is really equivalent to asking whether there exists a $z_0$ on this line segment for which
$$-i - 1 = f'(z_0) (i - 1)$$
or even better,
$$f'(z_0) = i$$
Now try showing that for any $z_0$ on this line segment, $3z_0^2 \ne i$. Try considering absolute values.

differentiability with complex numbers


Need to add data returned from api to List, but can only post to LiveData?

Question: From my fragment I call: videoViewModel.fetchContentSections();
From my vm I call: public void fetchContentSections(){repository.getContent();}
From my repo I do this:
apiService.getContent(request).enqueue(new Callback<Content>() {
        @Override
        public void onResponse(Call<Content> call, Response<Content> response) {
            List
 sections = response.body() != null ? response.body().getSections() : null;
            if (sections != null && !sections.isEmpty()) {
                final List
 sectionList = new ArrayList<>();
                for (Section section : sections) {
                    sectionList.add(section);
                }
            }
        }
        @Override
        public void onFailure(Call<Content> call, Throwable t) {
            Log.d(TAG, "onFailure" + Thread.currentThread().getName());
        }
    });

Data is returned, but in this scenario the list is null.
If I substitute the if statement for: sectionsMutableLiveList.postValue(response.body().getSections());
...everything works fine. But I need to use a non-LiveData list so I can then write the sectionList to a file. I'm hoping to then read the list from the file and post the value to a LiveData list to my vm.
Does anyone know what I've done wrong?
Answer: To receive a result in a synchronous way from Retrofit you must use "execute".
   /**
   * Synchronously send the request and return its response.
   *
   * @throws IOException if a problem occurred talking to the server.
   * @throws RuntimeException (and subclasses) if an unexpected error occurs creating the request or
   *     decoding the response.
   */
  Response<T> execute() throws IOException;

This allows you to return the result and write it to the file. So something like this:
try {
   Response<Content> response = apiService.getContent(request).execute();
   List
 sections = response.body() != null ? response.body().getSections() : null;
            if (sections != null && !sections.isEmpty()) {
                final List
 sectionList = new ArrayList<>();
                for (Section section : sections) {
                    sectionList.add(section);
                }
            }
} catch(IOException) {
   Log.d(TAG, "onFailure" + Thread.currentThread().getName());
}

The problem is that you then execute the call on the MainThread and your app will freeze until the call is finished. With enqueue and a callback, the request is performed asynchronously and your MainThread is not blocked.


php update radio button state in db

Question: I am new in php, I just starting learn php and have some problems.
In admin panel I have some form for adding info, after that in output I have radio buttons for selecting which row show into website. The problem is in update function the query is ok but it doesn't work, and I need you help.
thanks.
submit if.
 if(isset($_POST['update_info'])){
        $selected_info=$_POST['selected'];
        $selected_id = $_POST['id'];
        updateHomeInfo($selected_info, $selected_id);
    }

output added rows.

        <form action="/admin/" method="post">

                        #
                        slected
                        title
                        descriptiom

                    <?php foreach($homeInfo as $row) { ?>

                        <?php echo $row['id']; ?><input type="hidden" name="id" value="<?php echo $row['id']; ?>">
                        <input type="radio" name="selected" value="home-info" <?php if($row['selected'] == 1) echo "checked"; ?> />
                        <?php echo $row['title']; ?>
                        <?php echo $row['description']; ?>

                    <?php } ?>

                            <input type="submit" class="btn btn-default" name="clear_info" value="delete all">

                            <input type="submit" class="btn btn-default" name="update_info" value="update">

        </form>

and update function.
function updateHomeInfo($selected_info, $selected_id) {
    global $db;
    $db->exec("UPDATE home SET selected = '$selected_info' where id = '$selected_id'");
}

Comment: What's in the `selected` column? The `UPDATE` query sets it to the string `home-info` because that comes from the form, but the loop that displays the `checked` attribute looks for `$row['selected'] == 1`. So is it a string or a number?
Comment: @Barmar it's boolean true or false(1 or 0)
Comment: Then what's going on in the `UPDATE` statement? Why is it setting it to `$selected_info`?
Comment: Also, when you set it to 1 in the selected row, shouldn't you also set it to 0 in all the other rows?
Comment: yes  and how to do that?
Comment: LIke I showed in my answer.
Answer: All your hidden inputs have the same name; they'll all be submitted, and the value of $_POST['id'] will just be the last one, not the one next to the selected radio button. And all the radio buttons have the same value as well.
You should put the ID into the value of the radio button. You only need one copy of the hidden input, and it can contain the selected info.
<form action="/admin/" method="post">
    <input type="hidden" name="selected" value="home-info">

        ...
        <?php echo $row['id']; ?>
        <input type="radio" name="id" value="<?php echo $row['id']; ?>" <?php if($row['selected'] == 1) echo "checked"; ?> />
        ...

Actually, it seems like you don't need the selected input at all, if selected is a boolean. It should just be:
function updateHomeInfo($selected_id) {
    $db->exec("UPDATE home SET selected = (id = '$selected_id')");
}

This will set selected to 1 for the selected ID, and 0 for all the other IDs.
Comment: Thank you very much it's work, and also if no hard can you explain the query how it works because I didn't understand it :)
Comment: `id = '$selected_id'` is true on the row that matches `$selected_id`, false on all other rows. `true = 1` and `false = 0`, so it sets the `selected` field to those values.
Comment: then we didn't need hidden input yes?
Comment: That's what I said in my answer.

php update radio button state in db


Spring Social /connect return HTTP 404

Question: Spring can't find html views and im getting 404 while i'm trying to open /connect/linkedin. In referece to that post I double checked my paths in webapp folder. Here is my SpringSocialConfig
@Configuration
@EnableSocial
public class SocialConfig implements SocialConfigurer {

    @Inject
    private DataSource dataSource;

    @Override
    public void addConnectionFactories(ConnectionFactoryConfigurer connectionFactoryConfigurer, Environment environment) {
        connectionFactoryConfigurer.addConnectionFactory(new LinkedInConnectionFactory("xxxxxx", "xxxxxx"));
    }

    @Override
    public UserIdSource getUserIdSource() {
        return new UserIdSource() {
            @Override
            public String getUserId() {
                Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
                if (authentication == null) {
                    throw new IllegalStateException("Unable to get a ConnectionRepository: no user signed in");
                }
                return authentication.getName();
            }
        };
    }

    @Bean
    public ConnectController connectController(ConnectionFactoryLocator connectionFactoryLocator, ConnectionRepository connectionRepository) {
        return new ConnectController(connectionFactoryLocator, connectionRepository);
    }

    @Bean
    @Scope(value = "request", proxyMode = ScopedProxyMode.INTERFACES)
    public LinkedIn linkedin(ConnectionRepository repository) {
        Connection<LinkedIn> connection = repository.findPrimaryConnection(LinkedIn.class);
        return connection != null ? connection.getApi() : null;
    }

    @Override
    public UsersConnectionRepository getUsersConnectionRepository(ConnectionFactoryLocator connectionFactoryLocator) {
        return new JdbcUsersConnectionRepository(dataSource, connectionFactoryLocator, Encryptors.noOpText());
    }
}

My HomeController with /linkedin mapping handler
@Inject
private ConnectionRepository connectionRepository;

@Inject
private LinkedIn linkedIn;

@Inject
public HomeController(LinkedIn linkedIn) {
    this.linkedIn = linkedIn;
}

@RequestMapping(value = "/linkedin", method = RequestMethod.GET)
public String home(Principal currentUser, Model model) {
    Connection<LinkedIn> connection = connectionRepository.findPrimaryConnection(LinkedIn.class);
    if (connection == null) {
        return "redirect:/connect/linkedin";
    }
    model.addAttribute("profile", connection.getApi().profileOperations().getUserProfileFull());
    return "linkedin/profile";
}

And my WEBAPP folder with views

As I see in logs, something happen and /connect/* mappings were discovered.
[localhost-startStop-1] INFO org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Mapped "{[/connect/{providerId}],methods=[POST]}" onto public org.springframework.web.servlet.view.RedirectView org.springframework.social.connect.web.ConnectController.connect(java.lang.String,org.springframework.web.context.request.NativeWebRequest)
[localhost-startStop-1] INFO org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Mapped "{[/connect/{providerId}],methods=[GET]}" onto public java.lang.String org.springframework.social.connect.web.ConnectController.connectionStatus(java.lang.String,org.springframework.web.context.request.NativeWebRequest,org.springframework.ui.Model)
[localhost-startStop-1] INFO org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Mapped "{[/connect],methods=[GET]}" onto public java.lang.String org.springframework.social.connect.web.ConnectController.connectionStatus(org.springframework.web.context.request.NativeWebRequest,org.springframework.ui.Model)
[localhost-startStop-1] INFO org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Mapped "{[/connect/{providerId}],methods=[GET],params=[oauth_token]}" onto public org.springframework.web.servlet.view.RedirectView org.springframework.social.connect.web.ConnectController.oauth1Callback(java.lang.String,org.springframework.web.context.request.NativeWebRequest)
[localhost-startStop-1] INFO org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Mapped "{[/connect/{providerId}],methods=[GET],params=[code]}" onto public org.springframework.web.servlet.view.RedirectView org.springframework.social.connect.web.ConnectController.oauth2Callback(java.lang.String,org.springframework.web.context.request.NativeWebRequest)
[localhost-startStop-1] INFO org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Mapped "{[/connect/{providerId}],methods=[GET],params=[error]}" onto public org.springframework.web.servlet.view.RedirectView org.springframework.social.connect.web.ConnectController.oauth2ErrorCallback(java.lang.String,java.lang.String,java.lang.String,java.lang.String,org.springframework.web.context.request.NativeWebRequest)
[localhost-startStop-1] INFO org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Mapped "{[/connect/{providerId}],methods=[DELETE]}" onto public org.springframework.web.servlet.view.RedirectView org.springframework.social.connect.web.ConnectController.removeConnections(java.lang.String,org.springframework.web.context.request.NativeWebRequest)
[localhost-startStop-1] INFO org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Mapped "{[/connect/{providerId}/{providerUserId}],methods=[DELETE]}" onto public org.springframework.web.servlet.view.RedirectView org.springframework.social.connect.web.ConnectController.removeConnection(java.lang.String,java.lang.String,org.springframework.web.context.request.NativeWebRequest)
[local

I'm using Thymeleaf 3.0
@Bean
public ViewResolver viewResolver() {
    ThymeleafViewResolver resolver = new ThymeleafViewResolver();
    resolver.setTemplateEngine(templateEngine());
    resolver.setCharacterEncoding("UTF-8");
    resolver.setContentType("text/html; charset=UTF-8");
    return resolver;
}

@Bean
public TemplateEngine templateEngine() {
    SpringTemplateEngine engine = new SpringTemplateEngine();
    engine.setEnableSpringELCompiler(true);
    engine.setTemplateResolver(templateResolver());
    engine.addDialect(new SpringSecurityDialect());
    return engine;
}

 private ITemplateResolver templateResolver() {
        SpringResourceTemplateResolver resolver = new SpringResourceTemplateResolver();
        resolver.setApplicationContext(applicationContext);
        resolver.setPrefix("/views/");
        resolver.setSuffix(".html");
        resolver.setTemplateMode(TemplateMode.HTML);
        resolver.setCharacterEncoding("UTF-8");
        resolver.setCacheable(Boolean.parseBoolean(THYMELEAF_CACHE));
        return resolver;
    }

Dispatcher configuration
public class WebAppInitializer implements WebApplicationInitializer {

    private final String APP_SERVLET_NAME = "x";
    private final String DISPLAY_NAME = "App";

    @Override
    public void onStartup(ServletContext container) {
        container.addListener(new ContextLoaderListener(getContext()));
        CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter();
        characterEncodingFilter.setEncoding("utf-8");
        characterEncodingFilter.setForceEncoding(true);

        container.addFilter("charEncodingFilter", characterEncodingFilter).addMappingForUrlPatterns(null, false, "/*");
        container.addFilter("securityFilter", new DelegatingFilterProxy("springSecurityFilterChain")).addMappingForUrlPatterns(null, false, "/*");
        container.addFilter("apiFilter", new DelegatingFilterProxy("apiExceptionHandler"));
        container.addFilter("hidden", new HiddenHttpMethodFilter());

        AnnotationConfigWebApplicationContext dispatcherServlet = new AnnotationConfigWebApplicationContext();
        dispatcherServlet.register(ServletConfig.class);

        ServletRegistration.Dynamic dispatcher = container.addServlet(APP_SERVLET_NAME, new DispatcherServlet(dispatcherServlet));
        dispatcher.setLoadOnStartup(1);
        dispatcher.addMapping("/");
    }

    private AnnotationConfigWebApplicationContext getContext() {
        AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
        rootContext.register(JPARepositoryConfig.class,
                ThymeleafConfig.class,
                WebSecurityConfig.class,
                SocialConfig.class,
                MailConfig.class,
                MongoRepositoryConfig.class,
                ServiceConfig.class,
                CacheConfig.class);

        rootContext.setDisplayName(DISPLAY_NAME);
        return rootContext;
    }

I set breakpoints in Connection Controller from Spring Social and non of mapped method was invoked. So I think that app configuration is mess up.
EDIT
I had wrong spring servlet configuration. I registered spring social controllers as root servlet.
Comment: Hey @Jakub, can you try to set `debug log level` for `spring controller`? log4j.logger.controller=DEBUG,console
Comment: could you create a simple project on GitHub to replicate this error? It will be easier to help you.
Answer: I think the problem is the location of your views.
You have it under src/main/webapp and spring is searching for views under src/main/resources.
Either move all your html files to src/main/resources/views or change the config so that spring searches under src/main/webapp/views.
Check this Example the config is similar to what you have but the views are under src/main/resources folder.
Answer: My guess is that you might need spring.social.auto-connection-views=true in your application.properties file
Comment: I don't have application.properties File at all. Im using Spring MVC, not Boot.
Comment: well "redirect:/connect/linkedin" in general redirects to those views if set to true, if you don't have this flag set up I guess you need to provide your own view to make connection or somehow set this flag to true (I'm not Spring MVC user so cannot help there)
Comment: pretty sure you just need to provide your own view to redirect to your social media to login since this redirects like that shouldn't work (it supposed to work only in boot with flag which provides some hidden views and configurations).
Comment: As you see I provided custom views (`webapp/views/connect/*`) maybe I should move these files somewhere else?
Comment: You redirect to "connect/linkedin" but in (webapp/views/connect/*) you dont have view "linkedin" that's why you get 404 imo.
Comment: I added `linkedin.html` and nothing changed.
Answer: I know it's been long time, but I think I found solution for this problem.
The issue is, that your spring configuration found 'ConnectController' as bean, but it was not mapped as Controller. Also, I've checked source of ConnectController class. It turned out that it builds view names based on prefix and providerId.
Following this answer: https://stackoverflow.com/a/19699607/4544269
I've inherited ConnectController, and overrided both 'connectView' and 'connectedView', now pointing to Freemarkers templates in WEB-INF folder.
@Controller
public class CustomConnectController extends ConnectController{

    @Autowired
    public CustomConnectController(
            ConnectionFactoryLocator connectionFactoryLocator,
            ConnectionRepository connectionRepository) {
        super(connectionFactoryLocator, connectionRepository);
    }

    @Override
    protected String connectedView(String providerId){
        return "connect/facebookConnected";
    }

    @Override
    protected String connectView(String providerId) {
        return "connect/facebookConnect";
    }

   }

Spring Social /connect return HTTP 404


Load a 16-bit DLL into a 32-bit Process on Windows 7 64-bit

Question: I wrote a 32-bit application that launches a 16-bit executable, which loads some 16-bit DLLs to perform some of the application's functions.  It runs fine on Windows 7 32-bit, but not on Windows 7 64-bit since that version of the OS does not include the NTVDM.
The 16-bit portion of the code is pretty extensive and would be pretty expensive to port to 32-bit.  Also, it uses some 3rd-party 16-bit APIs from a company that is no longer in business; therefore, that code would have to be recreated completely, thereby increasing the cost.
Is there any possible way to simply load the existing 16-bit DLLs directly from the 32-bit application, removing the 16-bit executable completely?
I've looked into thunking, but it doesn't appear that is supported in Windows 7 either.
Comment: Even if you could load it, how do you plan on executing it? The 16-bit code expects a different processor architecture, and none of the support DLLs will be there, and even if they were, they would try to communicate with a kernel that isn't there.
Comment: if the program's extensive then it'll take advantage when recompile to 32 or 64-bit code, especially in 64-bit mode where there are double the registers. You should look for or write an alternative API, which may be much more powerful than the old one. Only in the case there's really isn't possible then use an emulator
Answer: You have to use an emulator or a virtual machine.
Or, if that is not an option then you can write a primitive emulator yourself, read the machinecode instruction-by-instruction and modify fake-registers and memory accordingly, and when the program calls outward then you will have to generate responses.
Answer: No. This is not possible in Windows.


Show that the Mean Value Theorem does not apply to $f(x)=x^{-2}$ on $(-1,1)$

Question: Show that the Mean Value Theorem does not apply to $f(x)=x^{-2}$ on $(-1,1)$. Is this a contradiction to the Mean Value Theorem?
My solution so far:
$$f(1)-f(-1)=f'(c)(1-(-1)) \Leftrightarrow 1-1=2f'(c) \Leftrightarrow f'(c)=0$$
Since $ f'(x)=-2x^{-3} \Rightarrow f'(c)=-2c^{-3}$
$$f'(c)=-2c^{-3}=0.$$
This is not satisfied by any value $c$ so I think I've now got the first part of the task. However, I'm not quite sure how do I figure if this contradicts with the Mean Value Theorem. I know that the MVT tells us that if $f$ is continuous on $[a, b]$ and differentiable on $(a, b)$, there is a point $c\in (a,b )$ such that $f(b)-f(a)=f'(c)(b-a)$ but I don't know how to apply it here.
Comment: You already proved, indeed you already know that you cannot apply the Mean Value thorem since the function is not defined on a closed bounded interval. Then if you assume by contradiction that the theorem holds anyway, you find that $f'(c) = -2c^{3}=0$ which is impossible. Therefore, you conclude that the fact that the function has to be defined (and continuous) on a bounded closed interval is a necessary condition to apply the theorem.
Answer: The mean-value theorem only applies for continous functions. But $x^{-2}=\frac{1}{x^2}$ is not defined at $x=0$ , the singularity is not even removeable.
Comment: It would be better to show directly that it fails for some endpoints, indeed this is not a clear evidence that the theorem could not be extended to cover this function (even if it can't)
Answer: I think your idea is correct, maybe I would phrase it differently:
If MVT did apply to $f$, it would be that
$$\frac{f(-1) - f(1)}{2} = 0 = f'(c)$$
would hold for some $c$, but, as you say, $f'(c) = \frac{1}{-2c^3}$, so no such $c$ can be found, contradicting MVT.


Java: Running DAO class in multithreaded and transactional environment

Question: I am calling a DAO class from multithreaded environment that fires a select query to get a row ( get a ticketId) from the table and then update the same row (with a customerId). This happens in the same transaction. My database is SQL Server. When I fire the select query I try to put a row level lock (WITH ROWLOCK) so that the other threads don't get the same row. My DAO class is as follows (Only the important piece of code is shown here):
public void saveCustomerTicketUsingJDBC(String customerId) {
  Session session = getSession();
  //Session session = SessionFactoryUtils.getSession(getSessionFactory(), true);// Have tried this too
  try {
         session.getTransaction().begin();

        Query query1 = session.createSQLQuery("select TOP 1 * from CustomerTicket WITH (ROWLOCK) where customerId is null");
        Object[] customerTicket = (Object[])query1.uniqueResult();

             Integer id = (Integer)customerTicket[0];
             ticketId = (String)customerTicket[1];
             logger.debug("Got ticket id -->"+ticketId);

        Query query2 = session.createSQLQuery("update CustomerTicket " +
                                                "set customerId = :customerId " +
                                                "where ticketId = :ticketId");
        query2.setParameter("customerId", customerId);
        query2.setParameter("ticketId", ticketId);
        logger.debug("QUery 2 executeUpdate : customerId : "+customerId+", ticketId :"+ticketId);
        int result = query2.executeUpdate();
        logger.debug("result >"+result +", customerTicketId ----------->"+customerId+", ticketId ------------>"+ticketId);
        //session.flush();
        //session.clear();
        session.getTransaction().commit();
  } catch (Exception e) {
        logger.error("Exception while saving customer ticket-->"+e,e);
    } finally {
        if (session != null) {
            session.close();
        }
    }
}

I spawn 4 threads. What I see in the log file is that all the four threads get to the same record in the database table.
2014-02-26 22:41:29.183 DEBUG [pool-3-thread-2] CustomerTicketDAO.java:83 Got ticket id -->4
2014-02-26 22:41:29.183 DEBUG [pool-3-thread-4] CustomerTicketDAO.java:83 Got ticket id -->4
2014-02-26 22:41:29.184 DEBUG [pool-3-thread-3] CustomerTicketDAO.java:83 Got ticket id -->4
2014-02-26 22:41:29.184 DEBUG [pool-3-thread-1] CustomerTicketDAO.java:83 Got ticket id -->4

First of all this shouldn't happen, correct? I am expecting to see that each thread should get different row.
Then I see that only one thread is able to successfully update the database.
2014-02-26 22:41:29.408 DEBUG [pool-3-thread-1] CustomerTicketDAO.java:93 result >1, customerTicketId ----------->CustomerId_0, ticketId ------------>4

The other three thread dies at the line:
int result = query2.executeUpdate();

I don't understand what happens to the other three threads as I don't see anything in my log file.
Someone please help me here.
Thanks
Raj
Comment: How is your `getSession()` implemented?
Comment: My DAO class extends HibernateDaoSupport. So I get the getSession() from there. BTW, I have also tried the other one: Session session = SessionFactoryUtils.getSession(getSessionFactory(), true); Still the same result.
Comment: When you say the thread _die_, what do you mean? Turn your log levels down if anything. Do the threads block?
Comment: May be they are blocking but the log file is not clear. But lets say if they are blocking isn't the "WITH (ROWLOCK)" in the first query should not allow all the threads to access the same row?
Answer: It's unclear (at least to me), exactly what error Sql Server and hibernate are returning in the case of the 3 failed tx's.  But it's not surprising that they failed.
(Row) Locks are not queues, and nor are they filters.  It's not surprising that the four select queries will return the same row because the presence of the lock does not change the data, and therefore also doesn't change the query results - it merely guards access to the data.  I suspect, but do not know, that the lock might be bypassed here by hibernate caching the query.
The root problem is that you have four processes all contending for a single resource (the first unassigned ticket).  While a properly implemented row locking scheme would work, it's a poor choice because it doesn't scale as well as the alternatives.
You'd be better off writing your dao with a synchronization block.  This will handle the case where multiple threads in the appserver are contending for the resource at the same time.  The simplest way would be to do this:
public synchronized void saveCustomerTicketUsingJDBC(String customerId) {
    Session session = getSession();
    ...
}

This handles the single appserver case nicely, although you need to be aware that there's no guarantee as to the order in which the threads are executed.  I suspect, based on your variable names, that that might be a problem for you, but even if so, this solution doesn't make the problem any worse.
In the case where you have multiple appservers, then you can still have multiple processes contending for the same resource.  Again, this could be solved with a (pessimistic) row lock, but I suspect you'd be better off with an optimistic locking solution.  The optimistic lock would look something like this:
while (true) {
  session.getTransaction().begin();

  try {
    Query query1 = session.createSQLQuery("select TOP 1 * from CustomerTicket where customerId is null");
    Object[] customerTicket = (Object[])query1.uniqueResult();

    Integer id = (Integer)customerTicket[0];
    ticketId = (String)customerTicket[1];
    logger.debug("Got ticket id -->"+ticketId);

    Query query2 = session.createSQLQuery("update CustomerTicket " +
                                            "set customerId = :customerId " +
                                            "where ticketId = :ticketId AND customerId is NULL");
                                            // Notice the AND clause!!!
    query2.setParameter("customerId", customerId);
    query2.setParameter("ticketId", ticketId);
    logger.debug("QUery 2 executeUpdate : customerId : "+customerId+", ticketId :"+ticketId);
    int updateCount = query2.executeUpdate();
    logger.debug("updateCount >"+updateCount +", customerTicketId ----------->"+customerId+", ticketId ------------>"+ticketId);

    //  Did someone beat us to it?
    if (updateCount == 0) {
        session.getTransaction().rollback();
        continue;
    }

    // Nope - we're winning so far, but the race isn't over yet...
    session.getTransaction().commit();
  } catch (OptimisticLockException ex) {
      logger.debug("Darn, someone DID beat us to it");
      session.getTransaction().rollback();
      continue;
  } catch (Exception ex) {
      ...
  }

  break;
}

Comment: Thank you Jeff. I will try the synchronization and let you know how it goes.
Comment: Jeff, appreciate you response. I have marked it as an answer. It was really helpful to me. Thank you once again:)


how to safely remove granite counter top

Question: is it possible to re-use granite countertop when i am replacing cabinets in my kitchen? or is there a high chance of breaking it?
Thanks
Comment: I'd recommend getting a labor estimate from a local granite installer.  THey'll know how to separate the top from the cabinets safely.
Answer: Yes, it's possible & common. Cut any caulking clean through with a knife & slide it free, never pry up to free it. For solid sections you can just move those around carefully as-is. For sections that have a sink or cooktop cut-out, you'll want to sandwich the front edge by clamps or screws with 2x4's or wider. Slide the front edge out enough to sandwich that in place, then you can tip it up & move it to another room where you'll store it tipped up & not flat.
Comment: Possible and common, but still with a high chance of failure, especially around the sink. The adhesive used will have an impact on your success. It also varies widely with the type of stone. Have a backup $$ fund in the budget.
Comment: If you have any difficulties removing it, it would be more cost effective to have a professional countertop installer remove it for you. It would be much cheaper than having to replace the entire thing since you probably would not be able to match it up perfectly with a new piece if it broke. They have specialty tools which can brace the weak parts i.e. the sink cutouts when it is removed. They can also reinstall the countertop when you get your new cabinets, and make any adjustments necessary for a professional looking installation.


no suitable constructor found for AttributedString(java.util.List)

Question: You guys on this forum have been a great help so far, and i have a learnt a lot, i do however have one (hopefully) final issue, my code does not compile, i get an error of :
 no suitable constructor found for AttributedString(java.util.List<java.lang.String>)
constructor java.text.ArributedString(java.text.AttributedCharacterator,int,int,java.text.AttributedCharacterator.Attribute[]) is not applicable (actual and formal argument lists differ in length

When i get the above error is highlights the following line of code:
AttributedString mStyledText = new AttributedString(list);

with help from another thread someone suggested it is because i am passing the entire list of strings instead of a single string.
What is causing this error? and more importantly how do i overcome it
code is below
import java.awt.*;
import java.awt.font.*;
import java.awt.geom.*;
import java.awt.print.*;
import java.text.*;
import java.io.*;
import javax.swing.*;
import java.util.List;
import java.util.ArrayList;

public class PrintText implements Printable {

    private String text; // Constructor argument for AttributedString.

    // Below the code will allow the user to select a file and then print out the contents of the file
    public static void main(String[] args) throws IOException {
        new PrintText();
    }

    public PrintText() {
        EventQueue.invokeLater(new Runnable() {
                @Override
                public void run() {
                    try {
                        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                    } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    }

                    //selects the file
                    JFileChooser chooser = new JFileChooser();
                    chooser.showOpenDialog(null);
                    File file = chooser.getSelectedFile();
                    String filename = file.getName();
                    //System.out.println("You have selected: " + filename);  testing to see if file seleected was right
                    String path = file.getAbsolutePath();

                    //Reads contents of file into terminal
                    //FileReader fr = new FileReader("filename");
                    // FileReader fr = new FileReader("D:/Documents/" + "filename"));

                    BufferedReader br = null;
                    try {
                        br = new BufferedReader(new FileReader(path));
                        StringBuilder stringBuilder = new StringBuilder();
                        String line;
                        while ((line = br.readLine()) != null) {
                            System.out.println(line);
                            stringBuilder.append(line).append("\n");
                        }
                        text = stringBuilder.toString();;

                        printer();
                    } catch (IOException exp) {
                        exp.printStackTrace();
                    } finally {
                        try {
                            br.close();
                        } catch (Exception e) {
                        }
                    }
                    //fr.close();
                }
            });
    }
    //private static final String mText =
    //    "This is a test to see if this text will be printed "; //This works perfectly fine
    //AttributedString mStyledText = new AttributedString(mText);
    /**
     * Print a single page containing some sample text.
     */
    public void printer() {

        /* Get the representation of the current printer and
         * the current print job.
         */
        PrinterJob printerJob = PrinterJob.getPrinterJob();
        /* Build a book containing pairs of page painters (Printables)
         * and PageFormats. This example has a single page containing
         * text.
         */
        Book book = new Book();
        book.append(this, new PageFormat());
        /* Set the object to be printed (the Book) into the PrinterJob.
         * Doing this before bringing up the print dialog allows the
         * print dialog to correctly display the page range to be printed
         * and to dissallow any print settings not appropriate for the
         * pages to be printed.
         */
        printerJob.setPageable(book);
        /* Show the print dialog to the user. This is an optional step
         * and need not be done if the application wants to perform
         * 'quiet' printing. If the user cancels the print dialog then false
         * is returned. If true is returned we go ahead and print.
         */
        boolean doPrint = printerJob.printDialog();
        if (doPrint) {
            try {
                printerJob.print();
            } catch (PrinterException exception) {
                System.err.println("Printing error: " + exception);
            }
        }
    }

    /**
     * Print a page of text.
     */
    public int print(Graphics g, PageFormat format, int pageIndex) {

        AttributedString mStyledText = new AttributedString();
        Graphics2D g2d = (Graphics2D) g;
        g2d.translate(format.getImageableX(), format.getImageableY());
        g2d.setPaint(Color.black);// Sets text colour
        Point2D.Float pen = new Point2D.Float();
        AttributedCharacterIterator charIterator = mStyledText.getIterator();
        LineBreakMeasurer measurer = new LineBreakMeasurer(charIterator, g2d.getFontRenderContext());
        float wrappingWidth = (float) format.getImageableWidth();
        while (measurer.getPosition() < charIterator.getEndIndex()) {
            TextLayout layout = measurer.nextLayout(wrappingWidth);
            pen.y += layout.getAscent();
            float dx = layout.isLeftToRight() ? 0 : (wrappingWidth - layout.getAdvance());
            layout.draw(g2d, pen.x + dx, pen.y);
            pen.y += layout.getDescent() + layout.getLeading();
        }
        return Printable.PAGE_EXISTS;
    }
}

Updated the code above to what i am running now
Comment: ..which the code will ignore with things like `catch (Exception e) {
                        }` - Change those to `catch (Exception e) {
e.printStackTrace();  }`
Comment: Got the code working fine, runs and even prints out exactly what i want it to :D thank you guys for all your help, you have made this possible !
Comment: If no suitible contructor is found obviously it means your not using the object parameters right. Let me find out more about this object and see how it's properly done.
Comment: You should make a habit of using the API as all of this is answered there, including what constructors are valid for this class, if you take a look.
Comment: *" have one (hopefully) final issue, my code does not compile,.."*  After clean compilation, then come 'run-time errors & exceptions'.  :)
Comment: Thank you have done that
Comment: Glad you got it sorted.  :)
Answer: These are the valid constructors for the class:
AttributedString(AttributedCharacterIterator text)
AttributedString(AttributedCharacterIterator text, int beginIndex, int endIndex)
AttributedString(AttributedCharacterIterator text, int beginIndex, int endIndex, AttributedCharacterIterator.Attribute[] attributes)
AttributedString(String text)
AttributedString(String text, Map<? extends AttributedCharacterIterator.Attribute,?> attributes)

None of them takes a list of strings, so you need to rethink what you are passing to it.  Possibly:
list.get(0);

Answer: If you look at the API of AttributedString there is no constructor which takes a List as an argument. Thus you get a compile time error when you try to pass it an List.
AttributedString mStyledText = new AttributedString(list);

The below are the only allowed constructors in AttributedString class
AttributedString(AttributedCharacterIterator text)
AttributedString(AttributedCharacterIterator text, int beginIndex, int endIndex)
AttributedString(AttributedCharacterIterator text, int beginIndex, int endIndex, AttributedCharacterIterator.Attribute[] attributes)
AttributedString(String text)
AttributedString(String text, Map<? extends AttributedCharacterIterator.Attribute,?> attributes)

Answer: There is no constructor that accepts a List<String>.
Considering that AttributedString deals with a single string value, passing a list to it doesn't make sense.
Perhaps you want a list, ie List<AttributedString>? In which case, loop over the List<String> calling the String constructor and add to a List<AttributedString>.
Answer: Use a StringBuilder to build one single String.
Replace
private List<String> list;

...
                    // Wrong: List<String> list = new ArrayList<String>();
                    list = new ArrayList<String>(); //
                    String line;
                    while ((line = br.readLine()) != null) {
                        System.out.println(line);
                        list.add(line);
                    }

by
private String text; // Constructor argument for AttributedString.

...
                    StringBuilder stringBuilder = new StringBuilder();
                    String line;
                    while ((line = br.readLine()) != null) {
                        System.out.println(line);
                        stringBuilder.append(line).append("\n");
                    }
                    text = stringBuilder.toString();

Comment: Thank you, i have just tried this however on compiling i get the error incompatible types and it highlights String stringBuilder = new StringBuilder();
Comment: Copy error; should have been `StringBuilder stringBuilder ...`