How can I run "Command & Conquer: Generals – Zero Hour" on Windows 7?

Question: I have Windows 7 64-bit, and I'm trying to run Command & Conquer: Generals – Zero Hour on it. Generals itself works fine, but Zero Hour just quits after the splash screen.
I have the latest version (1.04) and made sure I have the latest Nvidia drivers, etc. I have tried all the .INI file tricks and running it in XP compatibility mode, but those don't seem to work.
I've also tried the following:

Install DirectX 9.0c
Run as administrator
Set compatibility to Windows XP SP2/SP3
Change the options.ini for Zero Hour; this is in a different folder than the normal Generals options.ini
Answer: The reason that this game no longer works is outlined by the other answer and this other question on Arqade.  Basically there was a security hole in Windows 7 and 8 that Microsoft patched that makes certain write protection not work anymore.  There is a simpler and safer solution to the problem than the one outlined in the other answer though (note that there is no workaround for Windows 10).  First, open a command prompt as an administrator:

Windows button -> cmd.exe -> right-click -> Run as administrator

Run this command (with the exact spaces) to reenable the driver's service:

sc config secdrv start= demand

You should get a [SC] ChangeServiceConfig SUCCESS message.  Then run this command to start the service:

sc start secdrv

Then open the game and it should work!  You'll have to start the service every time you want to run this or any other CD-based game with SafeDisc or SecuROM, and you'll probably want to stop it when you're done to reduce security risks.
Comment: This definitely brought me closer to a solution than anything else I've seen before, the game launched but a serious error occurred afterwards. I think this solution ought to work out for most people though, and might just require doing the things others have suggested too.
Comment: worked for me, windows 8.1 64 bit c&c general with daemon tools lite
Answer: Some things to try if you haven't already (according to: http://forums.cncnz.com/index.php?showtopic=12319)

Install DirectX 9.0C
Run as administrator
Set compatibility to Windows XP SP3
Change the options.ini for Zero Hour, this is in a different folder than the normal generals options.ini.
Comment: I've tried all of that already.
Answer: I guess that if you have a good machine you could set up a virtual machine with XP and try it from there... it will have a perf hit.. but generals is a little old, so it might be ok..
Comment: I think I'll try the XP compatibility mode next.
Answer: Following the instructions on forums.cncnz.com worked for me. I already had the latest drivers and I installed C&C Generals and Zero Hour. Then (these are I think the most important parts):

Try to run C&C. It will not work but it will create this directory: C:\Users\<your user name>\Documents\Command and Conquer Generals Zero Hour Data.
In this directory, create an empty file called options.ini.
Copy these contents to the file:

AntiAliasing = 1
BuildingOcclusion = yes
CampaignDifficulty = 0
DynamicLOD = yes
ExtraAnimations = yes
GameSpyIPAddress = 0.0.0.0
Gamma = 50
HeatEffects = yes
IPAddress = 0.0.0.0
IdealStaticGameLOD = Low
LanguageFilter = false
MaxParticleCount = 5000
MusicVolume = 55
Resolution = 1366 768
Retaliation = yes
SFX3DVolume = 79
SFXVolume = 71
ScrollFactor = 60
SendDelay = no
ShowSoftWaterEdge = yes
ShowTrees = yes
StaticGameLOD = Custom
TextureReduction = 0
UseAlternateMouse = yes
UseCloudMap = yes
UseDoubleClickAttackMove = no
UseLightMap = yes
UseShadowDecals = yes
UseShadowVolumes = yes
VoiceVolume = 70

In Windows Explorer, go to C:\Program Files (x86)\EA Games\Command & Conquer Generals Zero Hour.
Right-click on generals.exe. Select Properties.
On the Compatibility tab, check Run this program in compatibility mode for and in the drop down select Windows XP (Service Pack 3).
On the same tab, under Privilege Level check the Run this program as administrator check box.
Press OK and then run the program.

So far this crashed once (with a "serious error" when I changed the settings in game) - apart from that it has worked fine.
Answer: I have Windows 7 64-bit as well. Generals did work on my computer at some point but no longer worked for a while. I did try all the fixes you mentioned, and I eventually found out that my problem was caused by a Windows update, specifically, Update KB3086255.  Here's a link to show you how to uninstall the aforementioned update:
Comment: @Texenox What relevant information could he possible have added? how to remove a windows update from your update history?
Comment: @Texenox This question is not "How to uninstall a Windows update", though. They can look that up somewhere else.
Answer: You can also try XP mode inside of windows 7
It's a free download from Microsoft
Download Windows XP mode for Windows 7


Updates of async methods are lost in Vue.js components

Question: I have a component that saves a message to the server on every blur. See full example here: https://jsfiddle.net/ob3rhsqp/
My async update method
async saveAsync($event) {
  const value = $event.target.value;
  this.message.state = `saving ${value}...`;
  this.message.text = await new Promise((resolve, reject) => {
    setTimeout(() => resolve(value + value.length), 1000)
  });
  this.message.state = "saved";
}

won't work if the bound prop message has changed in the meantime. message.text is still updated but message.state is not!
[
  {
    "text": "1#ChangedMessage16", // Correct.
    "state": "saving 1#ChangedMessage..." // Wrong, should be "saved".
  },
  {
    "text": "2#Message",
    "state": "saved"
  },
  {
    "text": "3#Message",
    "state": "saved"
  }
]

Answer: this.message.state is updated, but this.message refers to the new object, so you won't see the update when old an new state are the same (you can see it when switching to a message with a "saving 1#ChangedMessage..." state).
this.message.text = await ... still updates the old message, probably because the whole line is evaluated together, when this.message.text still refers to the old message.
Technically, you can think of it like this:
this.message.state = `saving ${value}...`;
const target = this.message.state
await new Promise(resolve => setTimeout(resolve, 1000)) // <--- this.message changes while waiting
target.text = value + value.length // <--- sets the old object's text
this.message.state = "saved " // <--- sets the new object's state

A simple way to avoid it is to store a local copy of message:
    async saveAsync($event) {
      const value = $event.target.value;
      const message = this.message // <--- create reference to current message
      message.state = `saving ${value}...`;
      message.text = await new Promise((resolve, reject) => {
        setTimeout(() => resolve(value + value.length), 1000)
      });
      message.state = "saved ";
    }


Nginx except root, all others are redirected to 404 error

Question: My goal is to put two or more(in future) Laravel applications under single domain and do the aliasing eg: http://domain-name/Lara-1  and http://domain-name/Lara-2.
I had trouble in aliasing and finally was able to do it by using locations but now, Except the root Laravel index.php of both apps, all other uris result in 404 error.
Followed is my sites-available/default file:
server {
    listen 80 default_server;
    listen [::]:80 default_server;

   index index.php index.html index.htm;
   try_files $uri $uri/ /index.php?$query_string;

    server_name Domain-IP;

     location ^~ /Lara-1/ {
        alias /var/www/Lara-1/public/;

        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/run/php/php5.6-fpm.sock;
        fastcgi_param SCRIPT_FILENAME $request_filename;
        include fastcgi_params;
         }

     location ^~ /Lara-2/ {
     alias /var/www/Lara-2/public/;
    include snippets/fastcgi-php.conf;
    fastcgi_pass unix:/run/php/php5.6-fpm.sock;
    fastcgi_param SCRIPT_FILENAME $request_filename;
    include fastcgi_params;
    }

  location ~ /\.ht {
            deny all;
    }
 }

In-case of single app instead of two i.e. only Lara-1, when I put the root as
/var/www/Lara-1/public/; everything works fine. Above situation happens only in case of app alias. May be, i may have configured it wrong.
Followed is my fastcgi_params file:

fastcgi_param  QUERY_STRING       $query_string;
fastcgi_param  REQUEST_METHOD     $request_method;
fastcgi_param  CONTENT_TYPE       $content_type;
fastcgi_param  CONTENT_LENGTH     $content_length;

fastcgi_param  SCRIPT_NAME        $fastcgi_script_name;
fastcgi_param  REQUEST_URI        $request_uri;
fastcgi_param  DOCUMENT_URI       $document_uri;
fastcgi_param  DOCUMENT_ROOT      $document_root;
fastcgi_param  SERVER_PROTOCOL    $server_protocol;
fastcgi_param  REQUEST_SCHEME     $scheme;
fastcgi_param  HTTPS              $https if_not_empty;

fastcgi_param  GATEWAY_INTERFACE  CGI/1.1;
fastcgi_param  SERVER_SOFTWARE    nginx/$nginx_version;

fastcgi_param  REMOTE_ADDR        $remote_addr;
fastcgi_param  REMOTE_PORT        $remote_port;
fastcgi_param  SERVER_ADDR        $server_addr;
fastcgi_param  SERVER_PORT        $server_port;
fastcgi_param  SERVER_NAME        $server_name;

# PHP only, required if PHP was built with --enable-force-cgi-redirect
fastcgi_param  REDIRECT_STATUS    200;

I am a newbie to Nginx and Laravel. Appreciate your help!
Comment: What is in the `fastcgi_params` include file?
Comment: @RichardSmith: Modified above with fastcgi_params content. Thnx.
Comment: @usernamehidden Can you share your solution?
Comment: @BhargavMehta: I updated with an answer, please check. Thanks.
Answer: Got this apps working after trials and errors. Following is how my Nginx default file looks like with 2 Laravel apps placed under webroot dir.
Happened to use Nginx Url Rewrites.    Hope it helps!
server {
    listen 80 default_server;
    listen [::]:80 default_server;
    index index.php index.html index.htm;

    server_name 126.96.36.199;
    root /var/www/webroot/;

location /projectdev {
        rewrite ^/projectdev/(.*)$ /projectdev/public/index.php?$1 last;
    }

location /projectqa {
        rewrite ^/projectqa/(.*)$ /projectqa/public/index.php?$1 last;
    }
    error_page 401 403 404 /404.html;

location / {
        try_files $uri $uri/ /index.php?$query_string;
    }

     location ~ \.php$ {
            include snippets/fastcgi-php.conf;
            fastcgi_pass unix:/var/run/php/php5.6-fpm.sock;
    }

    location ~* .(woff|eot|ttf|svg|mp4|webm|jpg|jpeg|png|gif|ico|css|js)$ {
               expires 365d;
    }
    # deny access to .htaccess files, if Apache's document root
    # concurs with nginx's one
    #
    location ~ /\.ht {
            deny all;
    }
    # Block web attacks
    location ~* (roundcube|webdav|smtp|http\:|soap|w00tw00t)
    {
    return 444;
    }

    # Protect .ini files
    location ~ /\.ini
    {
    access_log off;
    log_not_found off;
    deny all;
    }
     location ~ /\.xml {
            deny all;
    }
}


Why getting NAN when i try to add index in end of the field?

Question: good morning everyone
why I'm getting a NAN error when I try to add index value to the field.it supposes to return myForm.user0 and myForm.user1 inside the loop right? kindly please advise here

var users=['a','b'];
var myForm ={

        $name:"testform",
        user0: {
            $dirty: false,
            $invalid: true,
            $name: "user0"
        },
        user1: {
            $dirty: false,
            $invalid: true,
            $name: "user1"
        }
        };

        for (var i = 0; i < users.length; i++) {
                console.log(i)
                var s = myForm.user+i;
                console.log(s);

            }

the expected output is in the console log: it should return myForm.user0 and myForm.user1 in console
{$dirty: false,$invalid: true,$name: "user0"}
{$dirty: false, $invalid: true, $name: "user1"}

Comment: `myForm.user` is `undefined`, and `undefined + 1` is `NaN`. You need `myForm["user" + i]` However you should use an array instead, not consecutively numbered keys.
Comment: Great, but still: consider using `users: [{ ... }, { ... }]` instead.
Comment: `NaN` is not an error, it's a value.
Comment: ok I will consider your suggestion
Answer: myForm.user+1 is not accessing a member of the object. try using the following syntax: myForm['user' + i]


Custom URL Scheme with BroadcastReceiver not working (ERR_UKNOWN_URL_SCHEME)

Question: I'm trying to use a custom url scheme, myapp://recv in order to receive logins. I figured I would use a BroadcastReceiver for this and an intent-filter. I went ahead and did this, but no matter what I do, I get the error ERR_UNKNOWN_URL_SCHEME. Googling showed that this used to be a Chromium bug (which has apparently been resolved), and I can't figure out how to solve this. This is my registration of the Broadcast receiver. Thanks!
<receiver
            android:name=".LoginReceiver">
            <intent-filter>
                <data android:scheme="myapp"/>
                <data android:host="recv"/>
                <data android:pathPattern=".*"/>
                <action android:name="android.intent.action.VIEW"/>
                <category android:name="android.intent.category.DEFAULT"/>
                <category android:name="android.intent.category.BROWSABLE"/>
            </intent-filter>
        </receiver>

Comment: You don't usually use schemes, or `Uri` patterns, with a receiver. Who is actually supposed to be sending this broadcast?
Comment: The Twitter API would be redirecting the user to that URI scheme, but whenever it redirects (or I go to it manually), it fails.

In addition, even if I move this intent filter to an activity, it fails.
Comment: "The Twitter API would be redirecting the user to that URI scheme" -- not via a broadcast, they wouldn't. "In addition, even if I move this intent filter to an activity, it fails" -- I'd start by getting rid of your `pathPattern`, since you are not using it. Beyond that, please explain **completely and precisely** what you are doing that causes you to "get the error `ERR_UNKNOWN_URL_SCHEME`". Saying "no matter what I do" is not especially helpful, as we have no idea what you tried, what sort of Java stack trace was generated, etc.
Comment: I apologize. There was no stack trace generated. I set myapp://recv as my callback for Twitter, and when it logs in, it should redirect to myapp://recv. Chrome tells me it could not load the page for the reason ERR_UNKNOWN_URL_SCHEME.
Comment: If I had to guess, they're not expecting a redirect to be anything other than a regular Web URL.
Comment: No, they allow custom URIs. It's just failing to register.
Answer: The issue seems to be that you can't have a URI scheme intent-filter going to a BroadcastReceiver. It must be an Activity.


Is this a doorbell transformer? How to test if faulty?

Question: My doorbell has stopped working.  I am trying to test each of the components using a multi-meter.
However, the wires seem to go through the ceiling etc, so I can't trace where they are going or what they are for.
I have identified a box which I think may be the transformer though:

Using the multi-meter, I measured voltage AC by connecting the red lead to the screw and the black lead to ground.  I got:

(2) having 250V AC
(3) having 18V AC
(4) having 10V AC
Between (1) and (2), I got a reaching of 250V AC
Between (3) and (4), I got a reading of 12.5V AC.

Is this enough to establish that (a) this is the transformer, and (b) it is working?
Answer: Yes, your method is sound.
Another method is to momentarily touch the line 3 and 4 together, and if good will have a tiny arc. This can be done easily at the door bell button. Once you remove the button off the wall undo one of the lines and momentarily touch it to the other line.
Usually the button will go bad or the chime.  By bypassing the button as described above, you're one step closer.
Comment: Basically by momentarily touching the 12v lines together will create a tiny arc. (Spelling)
Comment: Hi.  Thanks for your answer. What do you mean "have a tiny arch"?
Comment: Oh, I see, like a spark, I understand now.
Comment: Hi, I use a foil and joined the two 12v lines together.  There was a spark (arc).  However, when I touch the two button wires, nothing happens.
Comment: Sounds like a bad chime
Comment: Buttons and chimes are easy to replace.  Hopefully you do not have a bad wire in the wall.


Is it possible to switch back to a previous difficulty?

Question: I've just finished the first playthrough and unlocked the Cruel difficulty mode.  Now I'd like to help a friend who is stuck at the final boss of act 3, Normal difficulty.  Is it even possible ?
I can't find how, but it seems weird to me: how can I even trade with a player from another difficulty (without creating a new level 1 caracter) ?
Answer: When selecting a waypoint, you can change the difficulty by selecting an alternate difficulty displayed above the map waypoint list.

In the picture, the difficult you are on is shown. Once you have completed Normal Difficulty, Cruel Difficulty will appear next to it.


gmp value into char*

Question: I don't understand how I can get mpz_t type variable into char*. I've tried many functions, but my char* stays empty.
I can output my B variable:

mpz_t B;
gmp_printf("B: %Zx\n", B);

But how to convert that B variable into char*?
Answer: Looks like mybuffer = mpz_get_str(NULL, /*base*/10, B); does what you want. (It allocates the returned buffer. You can have it write to an existing buffer if you prefer - see the manual for how to compute the size required.)
Answer:
gmp_sprintf(array, "%Zx", B);
Comment: Note that this function is not recommended, since there is no protection against writing past the end of the buffer ( http://gmplib.org/manual/Formatted-Output-Functions.html#Formatted-Output-Functions )

gmp value into char*


laptop overheat after update/install of 18.04 lts from 16.04 lts

Question: I had tried to update my 16.04lts to 18.04lts successfully, but right after it requested for a reboot my laptop (Dell Inspiron N5010) simply turned off. I tried turning it on, but right after it tells me of some "OVERHEAT/TEMPERATURE..." it turns off again. I had tried it more than 10x. After a while, I waited for an hour and it turned on. But the weird thing is the laptop becomes literally hot, starting from the touch pad. The fan was also noisy, the sound is very audible, as compare to normal fan noise. To think that there was no open program or files, as I was doing nothing. I never had this issue before in windows and even in 16.04 LTS. What I did is I had re-installed 18.04LTS and overwrite the existing installation. Afterwards, the scenario was still the same. I tried it 2x, to no avail. Now, I am back to 16.04 LTS, and everything is fine. What can I do to use 18.04 LTS without overheat issues?
Answer: Please install Ubuntu 18.04.1. It is more stable compared to 18.04. Also, rather than installing on top of 16.04, have backup of needed items and install 18.04.1 after wiping the hard drive completely. I am sure it will work.
Recently , I upgraded my 16.04.5 to 18.04.1 using sudo updata-manager -d and it works like a charm after installation completed.
My Laptop is HCL Me XITE L55, 7 years old!
Comment: I may have made a mistake in writing. What I installed is 18.04.1 LTS Version. I did an upgrade from 16.04.4 LTS, but it overheats. I did an overwrite install but it overheats. I did a "something else" installation and deleted all partition and installed 18.04.1 LTS but still it overheats. My laptop is a Dell Inspiron N5010 i3, 3Gb RAM, and I bought it way back 2010. It overheats without doing anything. The fan has a very audible noise.
Comment: My laptop has i3 1st gen processor, x86. Your case seems strange. I tried in AMD platforms also, worked fine.
Comment: I tried "googling" this overheat issue and had found this - " https://bugs.launchpad.net/ubuntu/+source/linux/+bug/1768976 " . I was reading a lot this thread but the terminologies used are not for me. I will just be waiting for a simplified solutions here.
Comment: okay, the bug is confirmed. Lets hope it gets fixed asap.
Comment: any fix for this issue?
Comment: A kind follow up, please. Just now, I had received an 18.04LTS Upgrade warning, I just neglected it, since I am not sure if this overheat issue is already solved or not. Please advise.
Comment: If you want to test again then got for it. If you rolled back to 16.04, then do `sudo update-manager -d` but it will take more than an hour despite good internet connection. Take the backup of your important files before doing so.
Comment: Guess 18.04.1LTS is really not for my laptop. I did an upgrade again,but the laptop fan is continuously running to a point it makes an irritating sound. There is still overheat issues.
Comment: again, I tried an upgrade,but still the fan is really noisy, and the laptop still overheats. any fix yet?


Can you tell how these cupboards are attached?

Question: Yesterday I was walking in the room above the one in the picture, and I heard a booming type noise. I eventually realized the tops of these cupboards are starting to come away from the wall.
(I apologize in advance - I know it is difficult to see what is going on from these photos).
Current image, with arrows pointing to new gaps:

Here is an old photo from when we were originally looking at the house:

Here is a final photo, showing the inside of the cabinet - looking above the top shelf, behind which should be the 90° angle between wall and ceiling:

You can see that the back of the cabinet is just a very thin sheet, nothing that looks structural. I assume that the screw attaching the back of the cabinet to the wall here was just done to stop the back from rattling or something.
Can you wager a guess how these cabinets are attached to the wall, and how I might fix this situation?
More photos, with the cabinet open and empty: https://i.stack.imgur.com/dDMxO.jpg
Comment: It looks to me like the cabinets were not attached to the wall properly, like the screw through the thin back wall was doing more of the work than it should have been doing, the cabinet came away from its backing, and is now leaning on the ceiling which is why it isn't falling.   Doesn't answer your question about how to get it off the wall but might help a little.
Comment: The only way I know to determine this is by direct inspection looking for hardware alternated with trying to move the cabinet to get an idea where it's fastened, possiblyplus trying to slide a piece of cardboard behind them to feel what's going on. There are multiple possibilities not resolvable from a distance.
Answer: I'm not a professional cabinet installer, but all the ones I've seen are screwed through the back and into the wall, just like yours. Some might be hung with a French cleat, but might still be screwed through the cleat for a "belt and suspenders" approach.
Generally, there would be a band of wood (might be plywood, particle board, MDF or similar) attached to the carcass, just under the top, and the screws would go through the finished back (the part you see from in your last pic), through this band, and into a stud.
It appears that this is probably how your cabinets are constructed, but that the cabinet carcass is pulling away from the back, allowing the tops to pull down from the walls.
I'd suggest that you unload all the cabinets of anything that might break, or anything that would increase the load on the cabinet itself. i.e. completely unload the cabinets!
If you're comfortable with DIY, look at the faces of the cabinets for screws that hold the faces together (these screws might be hidden behind the door hinges). Pick one cabinet as a test and remove any screws that are holding the front of it to its neighbors/the wall. Then, with assistance from someone holding the cabinet up for you (or build a temporary support to take the weight of the cabinet), unscrew it from the wall behind.
Note that you're looking for screws that attach the frames to each other at the front of the cabinet. It will be something like this drawing (pretend the red is a screw):

If you don't see an obvious screw head in this portion of the frame, look for a plug of wood or some wood filler or a sticker. These would be ways of hiding the screw head. When I installed my cabinets, I put the screws behind the hinges, though I used a different style of hinge. Try removing the portion of the hing pointed at by the green arrow to see if there's a screw behind that.
Once you've got it off the wall, you can look at the back of the cabinet and the wall to see what's going on and how or even if you could go about repairing them.
Comment: You do _not_ want to remove the faces! That will deconstruct the cabinets. Usually there will be a screw or two through the edge of the face of the cabinet shown in the first pic to the face of the cabinet next to it. You want to remove the screws, but that will _not_ remove the faces - it will simply detach one from the other so you can remove a single cabinet and not have to take down the entire wall at once.
Comment: Cabinets are unloaded :) What I can't see is any way to remove the faces - [this image](https://i.imgur.com/uMucOsY.jpeg) shows it a bit, but it looks like there are pieces of sharp metal connecting the cabinet to the face, and that the whole thing might have been hammered in.
Comment: [This image](https://i.imgur.com/8EKjDYQ.jpeg) shows a close up of the top rear of cabinet where it is pulling away from the wall - it looks like that thin board at back might be stapled in.
Comment: Thank you - I removed the doors, and I understand what you mean now. I think the those screws in what I assumed was decorative wood at the back of the cabinet are actually fastening the cabinet to the wall. The problem seems to be that this piece of wood is secured to the cabinet with staples, and those staples are pulling out. At least, [with the doors and trim removed](https://imgur.com/DyKsbo4) I can see no other method of attaching them to the wall.
Comment: I know that the former owner of this house did these cabinets himself. I wonder what the chances are that there is no French cleat or anything else - that the [four screws visible at the top and bottom](https://imgur.com/DyKsbo4) are the only thing securing the cabinet to the wall, and my problem is now that the rest of cabinet is pulling away from this stapled on back.
Comment: If the previous owner _built_ the cabinets, all bets are off. If he simply hung store bought cabinets, then it looks to me like this is standard cabinet construction and this is the standard way of hanging them. I can't tell from your 2 latest pics if there is anything through the face frame to the wall, left, or other cabinet, right. I see _something_ toward the back, but those could be shelf brackets.
Answer: There are usually brackets with "hooks" that catch on plates that are fixed to the wall. Fixing methods vary by country and region so check what you have.
These are fitted on the insides of the cupboards up close to the top corners.
They have two functions:

to secure the cabinet to the wall,

to provide a height adjustment to level the cabinets.

If cabinets are joined together, then often there is only one bracket at that point so two cupboards can be fixed with 3 brackets instead of 4.
Comment: I would say, "there are _occasionally_...". In many years of building and remodeling I never encountered what you describe here.
Comment: @isherwood in every kitchen I have worked on those brackets have always been there... And that is in 3 different countries... Makes it easy to adjust heights etc
Comment: I would say that this is probably a pretty common solution where `[Country] <> 'USA'`, but that it's a pretty rare solution for a US installation. OP hasn't specified, but the pictures do seem to indicate a large, American style kitchen.
Comment: @FreeMan perhaps it comes back to the (false) idea that for StackExchange [Country] = 'USA' ...
Comment: Is there any chance such brackets might be concealed somewhere? I am updating my question with more photos as soon as they upload, but I can't see anything like that for the life of me.
Comment: @negacao I have fitted several kitchens, one I removed, rebuilt and refitted with new doors (just married ie no money...) and that was the method used for the cabinets. Those brackets are about 2" long, 0.5" wide and 1" deep with the hook protruding toweards the back. If they were there you WOULD see them. If not then the other answers give other possibilities.
Comment: Thanks! I guess that method was not used here - there's nothing like that visible anywhere.
Comment: They sound handy, but I still think they're fairly rare.
Comment: I agree on the rarity—I've never seen them...sounds like some kind of french cleat type of system.
Comment: That _is_ a false assumption, however, I felt it was a fair guess in this case, based on the evidence provided, as I noted. Also, I fully acknowledge that your suggestion is a likely candidate for those not in the US.
Comment: @FreeMan I'm in several communities on here and it has reared its head often, more in the past though but still. And I did put (false)....
Comment: I think this is a case where, because of different use practices, multiple European countries have a better system than we in the US. If I understand correctly, in Germany, as an example, renters install their own stoves and kitchen cabinets and take them away when they vacate. So it would make sense that they would have a hanging system that would facilitate that. In the US kitchen cabinets are not intended to be removed without demolition.
Comment: Well, based on the Decora outlets in the kitchen, it's the US, Canada, or *maybe* someplace overseas built using American electrical stuff, like maybe a military base.
Answer: Wall cabinets are usually screwed to each other through the face frame, or the side of the cabinet if frameless.  Good cabinets also have a mounting strip on the inside of the back, top and bottom.  Bottom is a little bit less important, but top is very important if your cabinet backs are thin MDF or ply (≤1/4").  The mounting strip provides strength against the top of the cabinet being pulled from the wall, which is what is happening with your cabinets.  Since your cabinets are up against the ceiling, the installer could have shot some screws into the joists too (the top of the cabinet is likely thicker than the back).
But you are where you are.  It looks like the backs of your cabinets are just stapled to the carcass, and that the staples are pulling out.  It may not be too late to put some screws into the joists.  You'd want to empty the cabinets and wedge the bottoms up back into the expected position.  Hopefully the joists run perpendicular to this wall.  Locate their positions, and run 2-3 screws along that line inside the cabinet ceiling.
It might also be worth cutting some 2x2 or 2x3 lumber and retrofitting some mounting strips to the top of the cabinet.  You could screw the strip to the cabinet sides using pocket screws.  Then screw through the strip to the stud behind.
Comment: This is exactly what I am thinking at the moment - the cabinet is secured to the wall only by the visible screws, and the rest of the cabinet is pulling away from the back due to the staples.
Comment: @negacao that could be an option, if you can secure the top leg of the bracket to the top of the cabinet.  YMMV if it's particle board construction.  If it's plywood it should work OK.
Comment: What do you think about getting two metal L brackets, to secure the (interior) top of  the cabinet to the screws going into the studs?
Answer: Other than some rare specialty cabinets that may have a hanging rail, all cabinets are screwed to the wall or ceiling and can be screwed to each other.
That screw you are showing is most likely an anchoring screw. Look in the other cabinets for screws.
The 3rd pic shows separation between the back of the cabinet and the box. However for upper cabinets there is a reinforcing "bar" of thicker wood at the top and bottom used for mounting. This is under the thin backing material. I would be concerned about that gap and explore more.
You can try to tighten any screws by hand to see if there is an issue of screws becoming loose.  Also see if the cabinet box is coming apart by applying a bit of force to the sides and seeing if there is any movement.  If there is I would remove all the cabinets and look into reassembly. If not and the screws are all tight the gaps are expansion and contraction differential of the cabinets and the walls
Comment: @negacao this "reinforcing bar" is what I referred to as the "band of wood" and is often between the finished back of the cabinet and the wall precisely so you _don't_ see it from the inside.
Comment: They are definitely screwed into each other. I do not see any reinforcing bar like you mention - I wonder if there is some possibility it is above the (interior) top of the cabinet - there is an inch or two of space between the interior top of the cabinet, and the ceiling. It seems to be covered by this [decorative wood](https://i.imgur.com/HdehMWi.jpeg).


How do I install bidet T-valve here?

Question:
How do I install a bidet T-valve here?
I'm trying to install a handheld bidet on the toilet. This is the one I'd like to install

Unlike other toilets, there isn't much space to install the T-valve. Any ideas on what I can do here? How do i make more space for the T-valve there, is there some extension pipe that I can get?
The pipe in the pic reads 7/8" ballcock, 3/8" comp, 12" length
Answer: Yes you buy the 7/8 ballcock extension hose.
Comment: I would think this would normally be called a "pipe" or "hose", not a "cord"... Usually "cord" is for electricity or trussing up your prisoner, not running water through. ;)

How do I install bidet T-valve here?


Diameter of an 11' foot high, 3" (2&7/8) steel post footer hole

Question: I know that the general standard for post footers is to make the diameter of the footer hole 3 times wider than the post itself. However, I want to make sure that even in an 11' foot post (which seems kind of high to me), that this rule is still ok. Or should the footer hole be a bit wider for such a high post? The questions regards the corner post of an 11' foot high chainlink fence. Thanks in advance!
Comment: the post must surely be more than 11 feet if the fence is 11 feet high
Answer: I have always gone down minimum 1/3 of what you have above ground. Diameter off twice the post the top 6" opening out to 4 times the diameter.if your post is not long enough to give you the minimum amount below ground weld or bolt something to extend it
Comment: Hello, and welcome to Home Improvement. Your first sentence doesn't answer the original question; the second sentence is very confusing, and the third sentence seems dubious. Would you edit to clarify? Thanks.


Optimum Mazing Path (by Length)

Question: Assuming an N by N square playing space, with both towers and enemies taking up a 1x1 area, what is the optimum mazing setup to force enemies to spend the most overall distance pathing within the N by N square maze?
Comment: Not sure if it makes a difference, but where are the entrance and exit in this hypothetical scenario?
Comment: Should be posted on math or programming puzzles :)
Comment: I think it'd be useful to both consider entrances at the middle of the square, and at the corners, though those are, admittedly, two separate cases.
Comment: Cool question; I wonder if a TD "solver" app would be doable?
Comment: This question might get a better response over at http://math.stackexchange.com/ since the answer involves finding the longest path of a graph. Placing your towers removes vertices and edges, altering the current longest path. Check out http://en.wikipedia.org/wiki/Directed_acyclic_graph for more info.
Comment: @Crag - unfortunately, I lack the math vocabulary to ask the question appropriately on that site. Thanks for the link though!
Comment: How do enemies handle corners? Do they hit the center of each block or do they cut the corner?
Comment: @Arkive it depends on how the game is coded; it varies from Defense to Defense.
Comment: @Arkive I was going to ask a similar question to yours yesterday, but I think it is implied that there are no corners to handle. Enemies only can travel up/down/left/right. No Diagonal movement. @Raven_Dreamer can correct me and edit the question if I'm assuming too much.
Comment: I think that most tower defense games don't have the AI programmed to go through corners, but splitters often go through them anyway, and can really mess up your designs.
Comment: @RavenDreamer Really... No tag? Shame on you!
Comment: @Josefvz It had been tagged "Tower-Defense". If questions only have a single tag, however, they lose it and the tag gets auto-deleted after 6 months.
Answer: Well, assuming you start in the top left corner and end in the bottom right corner, the longest possible path will be one that zig/zags along the entire map from north to south or east to west.  I wrote the following recursive program for fun to find the longest path and produce an output and it comes out with this solution no matter what size for height,weight you input:
Note though, this does not mean the longest path is actually an optimal strategy in turret defence type games, because you have to factor in things like tower costs and upgrades.  More often than not, the best situation is simply to force units to congregate as much as possible in a kill zone.  It gets even more convoluted when you factor in things like slowing towers.
Here is some sample outputs:
<code># = wall
. = path
N = start
O = end

Width = 10, Height = 5
N#...#....
.#.#.#.##.
.#.#.#.#..
.#.#.#.#.#
...#...#.O

Width = 10, Height = 10
N#...#....
.#.#.#.##.
.#.#.#.#..
.#.#.#.#.#
.#.#.#.#..
.#.#.#.##.
.#.#.#.#..
.#.#.#.#.#
.#.#.#.#.#
...#...#.O
</code>
@Raven Dreamer
Yes, I realize that last edge case, I am unsure why its not doing that last optimization just yet, but I did modify my code to include a movable entrance/exit.  Here is a sample generation of a middle entrance:
<code>...#...#...#...##...
.#.#.#.#.#.#.#.##.#.
.#.#.#.#.#.#.#.##.#.
.#.#.#.#.#.#.#.##.#.
.#.#.#.#.#.#.#.##.#.
.#.#.#.#.#.#.#.##.#.
.#.#.#.#.#.#.#.##.#.
.#.#.#.#.#.#.#.##.#.
.#.#.#.#.#.#.#.##.#.
.#.#.#.#.#.#.#.##.#.
N#.#.#.#.#.#.#.##.#O
#..#.#.#.#.#.#.##.##
..#..#.#.#.#.#.##.## <---
.#..#..#.#.#.#.##.## <---
.#.#..#..#.#.#.##.## <---
.#.#.#..#..#.#.##.## <--- need optimization here
.#.#.#.#..#..#.##.## <---
.#.#.#.#.#..##..#.## <---
.#.#.#.#.#.####.#.## <---
...#...#...####...## <---
</code>
I removed my program since I figured out the source of error, I'll put up a working version later, but its going to take some rewriting.  The answer remains unchanged though, the longest path is not that interesting, but it was a fun programming exercise.
Comment: "...this does not mean the longest path is actually an optimal strategy in turret defence type games..." - wonderful point. For example, if one tower gave AoE damage, you might instead construct a "room" with the tower centered in it to maximize damage.
Comment: Ah, this is disappointing. I had hoped the optimal maze would be a little more interesting than this. What happens when you move N into the middle of the side?
Comment: @yx_ you might want to double-check your code; the final graph does not have the longest path; One or two length could be gained by forcing the path down to the bottom right corner instead of cutting across one row early.
Comment: @Kevin: or a maze where the enemies pass by your strongest tower(s) more than twice.  Also note that this won't work in games with specialized enemies eg. Sanctum has an enemy that moves *really* fast on long straightaways.
Comment: @MarkTrapp - That looks much better.
Comment: @yx_ How did you calculate length? # of blocks in path? I think I have a better solution than your program yielded for the 10x10 case. I use less towers too.
Comment: @Arkive yes, its simply by number of blocks '.' in the path, feel free to post yours :)  I didn't have time to give this problem another shot today, maybe tomorrow.
Comment: @yx_ Can I convince you two write a blog post about this answer?
Comment: @yx_  im jsut so impressed by this, unless you have some object, may i have a look at the script you used to gen then?
Comment: Any news on the new version?
Answer: <code>N = 10
Path Length = 61
Towers = 30
N#...#....
...#.#.#..
..#..#..#.
.#..#..#..
#..#..#..#
..#..#..#.
.#..#..#..
.#.#..#...
.#.#.#..#.
...#...#.O
</code>
This diagonal design, uses fewer towers than the traditional vertical design and yields a slightly longer path length for N = 10. For N = 9, I was unable to produce a longer path than the vertical approach.
I haven't tested cases other than N = 9, 10, and 12 , but I suspect that for N = 1 + 4x, where x is an integer > 0 the vertical approach will yield the maximum path length, but not necissarily the lowest tower number.
More investigation:

Entry/exit in middle
What values of N is this diagonal approach more effective
Identification of combinational strategies

The above approach uses diagonal walls with vertical segments in the NE and SW corners.
Answer: This is my favourite build. It is spiral build.
it is 190x. and 156x# Main strenght of this is that creeps are circling around middle so you can invest all your money in few strong tower and put them in the middle of your maze.
<code>..................#O
.################.#.
.#..............#.#.
.#.############.#.#.
.#.#..........#.#.#.
.#.#.########.#.#.#.
.#.#.#......#.#.#.#.
.#.#.#.####.#.#.#.#.
.#.#.#.#....#.#.#.#.
.#.#.#.#.####.#.#.#.
.#.#.#.#......#.#.#.
.#.#.#.########.#.#.
.#.#.#..........#.#.
.#.#.############.#.
.#.#..............#.
.#.################.
N#..................
</code>
Answer: On games like desktop tower defence where there is an entrance on the top and left, a diagonal line from top left to bottom right with a gap at bottom right, with lines on each side parallel with a gap at the top left repeated is the best, as all creeps go past every tower, and by upgrading the center few all flying creeps will go past the best towers.
Answer: Is there an assumption that the walls/towers/obstacles are permanently placed? If not, then you can try juggling.
Comment: I think "Mazing" implies permanence.

Optimum Mazing Path (by Length)


Cannot import user in Django 1.9

Question: I'm using Django 1.9 and following along on this tutorial:
https://www.youtube.com/watch?v=6WkQOlYgkHM&index=15&list=PLEsfXFp6DpzQFqfCur9CJ4QnKQTVXUsRy
When I put in the following code as recommended:
def post_list(request):
    # return HttpResponse("
Update
")

    if request.user.is_authenticated():
        context = {
        "title": "My User List"
        }
    else:
        context = {
            "title": "List"
        }
    return render(request, "index.html", context)

I get the following error message:
AttributeError: 'WSGIRequest' object has no attribute 'user'

I looked up the documentation and tried doing this:
from django.contrib.auth.models import user

But user is underlined on my pycharm and now the error message I'm getting is
ImportError: cannot import name 'user'

Comment: https://stackoverflow.com/questions/37949198/wsgirequest-object-has-no-attribute-user-django-admin check here.
Comment: It's User, not user.
Answer: You probably forgot to add some required middleware items to your MIDDLEWARE setting.
As explained in the documentation for User authentication in Django, you must add SessionMiddleware and AuthenticationMiddleware to the MIDDLEWARE setting in your settings.py file.
That will make sure the user attribute is set on your request objects.
Note that the above is true for the current state of Django (1.10 and later), Django 1.9 is not supported anymore and should not be used.
If you still want to use it, instructions for using django.contrib.auth with django 1.9 can be found here
Comment: Thanks @Jieter but I'm pretty sure I have those: `MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',`
Comment: Also, how do you make a line break in the comment section?  If I hit return then that ends my comment.
Comment: @fredrussell, you need to change MIDDLEWARE to MIDDLEWARE_CLASSES. Check links in comments by @neverwalkaloner and @aashu. And importing `user` doesn't work, because model is called `User`.
Comment: Thanks, that did it.
Comment: I'd suggest not changing `MIDDLEWARE` to `MIDDLEWARE_CLASSES`, but rather upgrade to a supported version of Django (1.11 or 2.0). Especially when you are learning, there is no point in using an old version, apart from the specific tutorial you are working from.
Comment: yes, there is.  I tried using the most updated version while following along in this tutorial which uses 1.9 and I confronted a lot of bugs because I was using a 1.11 version on a 1.9 tutorial.  And since I am new I have to call my personal tutor in order to remove the bugs. Switching back to 1.9 has made things a lot easier.

Cannot import user in Django 1.9


Which TCP/IP layer provides QoS?

Question: Which layer in TCP/IP model provides Quality of Service (QoS)? I am confused between Layer 2 and Layer 3?
Answer: According to Computer Networks, by Andrew S. Tanenbaum, Quality of Service is provided by the Network Layer (Layer 3).

A stream of packets from a source to a destination is called a flow (Clark, 1988). A flow might be all the packets of a connection in a connection-oriented network, or all the packets sent from one process to another process in a connectionless network. The needs of each flow can be characterized by four primary parameters: bandwidth, delay, jitter, and loss. Together, these determine the QoS (Quality of Service) the flow requires.
Computer Networks - Andrew S. Tanenbaum, 5th Edition, Chapter 5 (The Network Layer), Section 5.4 (Quality of Service), p. 404
Answer: Any layer can distinguish between different qualities of service. Layers 2 & 3 offer "best effort" delivery, where QoS can influence relative amount of effort. There are many layer-2 technologies, but ethernet is certainly a popular one. Ether standards committees have published various QoS specs, including IEEE P802.1p. There have been many others. Sometimes queuing discipline (packet drop policy) is of interest, and sometimes a reservation of committed bit-rate is the goal.
A QoS field has been baked into layer-3 IP headers since the beginning -- see Type of Service in https://www.rfc-editor.org/rfc/rfc791#page-12

Which TCP/IP layer provides QoS?


Stuck on a small Ajax with JQuery script

Question: Been a while since I asked a qustion about uncharted waters again (Ajax with JQuery). I've been doing a little website for a local charity group. On the website I have a small form were people can ask for help. But I am stuck. Probably staring at the error but can't see it. ;)
ajax.js
function submitApplication()
{
    $.ajax({
        url: 'db/submitApplication.inc.php',
        type:'POST',
        dataType: 'json',
        data: { name: $("#name").val() },
        success: function(output_string){  },
        error: function (xhr, ajaxOptions, thrownError) { alert(xhr.status); alert(thrownError); }
    });
}

submitApplication.inc.php
<?php
include('../inc/conn.inc.php');

$query = "INSERT INTO ljusimorker_applications (ljusimorker_applications_name) VALUES ('" . $_POST['name'] . "')";
$writeData = mysql_query($query) or die(mysql_error());

mysql_close();
?>

I know that the mysql statements are of the deprected variant but it's only for testing the script. I will add the security aspect later before putting the website live. The HTML I'm fetching is below.
HTML

Namn (visas ej):
	<input type="text" id="name" class="input-box">

The error I get is:
Chrome: SyntaxError: Unexpected end of input
Firefox: SyntaxError: JSON.parse: unexpected end of data
Firebug says this under NET -> XHR
Response Headers
Connection  Keep-Alive
Content-Length  0
Content-Type    text/html
Date    Thu, 15 Aug 2013 11:19:14 GMT
Keep-Alive  timeout=3, max=100
Server  Apache/2.2.24 (FreeBSD) PHP/5.4.15 mod_ssl/2.2.24 OpenSSL/0.9.8y
X-Powered-By    PHP/5.4.15

Request Headers
Accept  application/json, text/javascript, */*; q=0.01
Accept-Encoding gzip, deflate
Accept-Language sv-SE,sv;q=0.8,en-US;q=0.5,en;q=0.3
Cache-Control   no-cache
Connection  keep-alive
Content-Length  23
Content-Type    application/x-www-form-urlencoded; charset=UTF-8
Host    xxx.xxx.xxx
Pragma  no-cache
Referer http://xxx.xxx.xxx/
User-Agent  Mozilla/5.0 (Windows NT 6.2; WOW64; rv:22.0) Gecko/20100101 Firefox/22.0
X-Requested-With    XMLHttpRequest

Thanks in advance. :)
Comment: You are using [an **obsolete** database API](http://stackoverflow.com/q/12859942/19068) and should use a [modern replacement](http://php.net/manual/en/mysqlinfo.api.choosing.php).  You are also **vulnerable to [SQL injection attacks](http://bobby-tables.com/)** that a modern API would make it easier to [defend](http://stackoverflow.com/questions/60174/best-way-to-prevent-sql-injection-in-php) yourself from.
Comment: "I know that the mysql statements are of the deprected variant but it's only for testing the script. I will add the security aspect later before putting the website live." — Why write code that you know you will have to throw away?
Comment: As I said in the question. I know it's absolete but only for testing. I will probably use mysqli or pdo when the client-side script works.
Comment: I wanted to get the Ajax part done as I've always got stuck on that in the past. It's going to be the only script on the site. And for me at the moment the old mysql style api is easier to read.
Answer: Your PHP makes an SQL query and then never outputs anything back to the browser. If you want to parse some JSON then you need to send some JSON.
Comment: Thanks, it's working now. As I said in the question I was probably looking at the error but did not see it. When I read your answer my first thought was "Duh... Why did i not see that...".
Answer: Your data type is 'json'  but your dont return anything.
http://api.jquery.com/jQuery.ajax/


Issue with XML via XSL StyleSheet

Question: I'm really hoping you can help here... When i transform the XML response against the XSL Stylesheet using XSLTProcessor transformToFragment it seems to be creating some data outside of the XML structure, right at the end:-
    123456782

        JohnSmith
        TNTExpress
        TNTHouse
        ATHERSTONE
        Warks
        CV91TT
        GB

        TNTCorporateHeadOffice
        Neptunusstraat41-63
        Taurusavenue111
        HOOFDDORP

        2132LS
        NL

        8783802
        GB

    3
    Express (ND)
    PR
    2016-11-15
    INT
    AIR

    2

        CVT

            EMA

            LGG
            8
            SP8

        SP8
        17
        2016-11-17

    63

    GBP 12.34

    BSH

I've included the XML, XSL and the result below, please could you take a look perhaps you've seen something like this happening before?
This online tool is useful for quick testing http://www.utilities-online.info/xsltransformation/
I cant see whats causing this data at the end to be generated, i'm assuming its something in the XSL template?
Thanks for any help whatsoever.
EDIT: it looks like someone had the same issue here but no actual specific answer Converting XML into HTML using XSL?
Paul
XML Here:-
<?xml version="1.0" encoding="UTF-8"?>
<labelResponse>
    <consignment key="CON1">
        <pieceLabelData>
            <pieceNumber>1</pieceNumber>
            <weightDisplay code="1.11" renderInstructions="yes">1.11kg</weightDisplay>
            <pieceReference><![CDATA[piece1]]></pieceReference>
            <barcode symbology="128C">1100123456782011641424002132</barcode>
            <twoDBarcode symbology="pdf417"><![CDATA[123456782|123456782||1||JohnSmith|TNTExpress|ATHERSTONE|CV91TT|GB|S||TNTCorporateHeadOffice|Neptunusstraat41-63|HOOFDDORP|2132LS|NL||EX|N|PR||||0|12.34|GBP|N|||piecelinegoodsdesc|3|1.11|1.3676310000000003|N|15 Nov 2016|17:58:00]]></twoDBarcode>
        </pieceLabelData>
        <pieceLabelData>
            <pieceNumber>2</pieceNumber>
            <weightDisplay code="1.11" renderInstructions="yes">1.11kg</weightDisplay>
            <pieceReference><![CDATA[piece1]]></pieceReference>
            <barcode symbology="128C">1100123456782021641424002132</barcode>
            <twoDBarcode symbology="pdf417"><![CDATA[123456782|123456782||2||JohnSmith|TNTExpress|ATHERSTONE|CV91TT|GB|S||TNTCorporateHeadOffice|Neptunusstraat41-63|HOOFDDORP|2132LS|NL||EX|N|PR||||0|12.34|GBP|N|||piecelinegoodsdesc|3|1.11|1.3676310000000003|N|15 Nov 2016|17:58:00]]></twoDBarcode>
        </pieceLabelData>
        <pieceLabelData>
            <pieceNumber>3</pieceNumber>
            <weightDisplay code="1.11" renderInstructions="yes">1.11kg</weightDisplay>
            <pieceReference><![CDATA[piece3]]></pieceReference>
            <barcode symbology="128C">1100123456782031641424002132</barcode>
            <twoDBarcode symbology="pdf417"><![CDATA[123456782|123456782||3||JohnSmith|TNTExpress|ATHERSTONE|CV91TT|GB|S||TNTCorporateHeadOffice|Neptunusstraat41-63|HOOFDDORP|2132LS|NL||EX|N|PR||||0|12.34|GBP|N|||piecelinegoodsdesc|3|1.11|1.3676310000000003|N|15 Nov 2016|17:58:00]]></twoDBarcode>
        </pieceLabelData>
        <consignmentLabelData>
            <consignmentNumber>123456782</consignmentNumber>
            <sender>
                <name><![CDATA[JohnSmith]]></name>
                <addressLine1><![CDATA[TNTExpress]]></addressLine1>
                <addressLine2><![CDATA[TNTHouse]]></addressLine2>
                <town><![CDATA[ATHERSTONE]]></town>
                <province><![CDATA[Warks]]></province>
                <postcode><![CDATA[CV91TT]]></postcode>
                <country><![CDATA[GB]]></country>
            </sender>
            <delivery>
                <name><![CDATA[TNTCorporateHeadOffice]]></name>
                <addressLine1><![CDATA[Neptunusstraat41-63]]></addressLine1>
                <addressLine2><![CDATA[Taurusavenue111]]></addressLine2>
                <town><![CDATA[HOOFDDORP]]></town>
                <province><![CDATA[]]></province>
                <postcode><![CDATA[2132LS]]></postcode>
                <country><![CDATA[NL]]></country>
            </delivery>
            <account>
                <accountNumber>8783802</accountNumber>
                <accountCountry>GB</accountCountry>
            </account>
            <totalNumberOfPieces>3</totalNumberOfPieces>
            <product id="EX">Express (ND)</product>
            <option id="PR"><![CDATA[PR]]></option>
            <collectionDate>2016-11-15</collectionDate>
            <marketDisplay code="2" renderInstructions="yes"><![CDATA[INT]]></marketDisplay>
            <transportDisplay code="1" renderInstructions="yes"><![CDATA[AIR]]></transportDisplay>
            <freeCirculationDisplay code="" renderInstructions="no"/>
            <sortSplitText><![CDATA[2]]></sortSplitText>
            <xrayDisplay code="" renderInstructions="no"/>
            <originDepot>
                <depotCode>CVT</depotCode>
            </originDepot>
            <transitDepots>
                <transitDepot>
                    <depotCode>EMA</depotCode>
                </transitDepot>
                <sortDepot>
                    <depotCode>LGG</depotCode>
                    <sortCellIndicator code="" renderInstructions="yes">8</sortCellIndicator>
                    <sortLocationCode>SP8</sortLocationCode>
                </sortDepot>
            </transitDepots>
            <destinationDepot>
                <depotCode>SP8</depotCode>
                <dueDayOfMonth>17</dueDayOfMonth>
                <dueDate>2016-11-17</dueDate>
            </destinationDepot>
            <microzone code="" renderInstructions="no"/>
            <clusterCode>63</clusterCode>
            <legalComments/>
            <cashAmount code="12.34" renderInstructions="yes">GBP 12.34</cashAmount>
            <specialInstructions/>
            <bulkShipment code="Y" renderInstructions="yes">BSH</bulkShipment>
        </consignmentLabelData>
    </consignment>
</labelResponse>

XSL Here:-
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:template name="RestOfWorldHtml" match="pieceLabelData">

    <xsl:value-of select="../consignmentLabelData/marketDisplay"/>
    <xsl:text>/</xsl:text>
    <xsl:value-of select="../consignmentLabelData/transportDisplay"/>

.
      <xsl:for-each select="../consignmentLabelData/option">
          <xsl:if test="@id='HZ'">
             <xsl:text>HAZARDOUS</xsl:text>
          </xsl:if>
      </xsl:for-each>

  <xsl:if test="string-length(../consignmentLabelData/xrayDisplay)>0">

      <xsl:value-of select="../consignmentLabelData/xrayDisplay"/>

  </xsl:if>

  <xsl:choose>
    <xsl:when test="string-length(../consignmentLabelData/freeCirculationDisplay)>0">

        <xsl:value-of select="../consignmentLabelData/freeCirculationDisplay"/>

    </xsl:when>
    <xsl:otherwise>

      <xsl:text> </xsl:text>

    </xsl:otherwise>
  </xsl:choose>

  <xsl:choose>
    <xsl:when test="string-length(../consignmentLabelData/sortSplitText)>0">

            <xsl:value-of select="../consignmentLabelData/sortSplitText" />

    </xsl:when>
    <xsl:otherwise>

            <xsl:text> </xsl:text>

    </xsl:otherwise>
  </xsl:choose>

Con No.

<xsl:value-of select="../consignmentLabelData/consignmentNumber"/>

Service

    <xsl:choose>
        <xsl:when test="string-length(../consignmentLabelData/product)>15">

                <xsl:value-of select="../consignmentLabelData/product" />

        </xsl:when>
        <xsl:otherwise>

                <xsl:value-of select="../consignmentLabelData/product" />

        </xsl:otherwise>
    </xsl:choose>

        Piece

<xsl:value-of select="pieceNumber"/> of <xsl:value-of select="../consignmentLabelData/totalNumberOfPieces"/>

        Weight

    <xsl:choose>
        <xsl:when test="weightDisplay/@renderInstructions='highlighted'">

                <xsl:value-of select="weightDisplay" />

        </xsl:when>
        <xsl:otherwise>

                <xsl:value-of select="weightDisplay" />

        </xsl:otherwise>
    </xsl:choose>
    <xsl:text> </xsl:text>

Option

    <xsl:variable name="numberOptions" select="count(../consignmentLabelData/option)" />
        <xsl:choose>

            <xsl:when test="$numberOptions >1">
              <xsl:for-each select="../consignmentLabelData/option">

                    <xsl:value-of select="@id" />
                    <xsl:text>  </xsl:text>

              </xsl:for-each>
            </xsl:when>

            <xsl:otherwise>
                <xsl:choose>
                    <xsl:when test="string-length(../consignmentLabelData/option)>0">

                        <xsl:value-of select="../consignmentLabelData/option" />

                    </xsl:when>
                    <xsl:otherwise>

                            <xsl:text> </xsl:text>

                    </xsl:otherwise>
                </xsl:choose>
            </xsl:otherwise>
        </xsl:choose>

Customer Reference

<xsl:value-of select="pieceReference" disable-output-escaping="yes" />

      S/R Account No
      <xsl:value-of select="../consignmentLabelData/account/accountNumber" />

    Origin
    <xsl:value-of select="../consignmentLabelData/originDepot/depotCode" />

Pickup Date

      <xsl:call-template name="FormatDate">
                <xsl:with-param name="DateTime" select="../consignmentLabelData/collectionDate"/>
        </xsl:call-template>

Sender Address

      <xsl:value-of select="../consignmentLabelData/sender/name" disable-output-escaping="yes"/>

      <xsl:value-of select="../consignmentLabelData/sender/addressLine1" disable-output-escaping="yes"/>

      <xsl:value-of select="../consignmentLabelData/sender/addressLine2" disable-output-escaping="yes"/>

      <xsl:value-of select="../consignmentLabelData/sender/town" disable-output-escaping="yes"/><xsl:text>  </xsl:text>
      <xsl:value-of select="../consignmentLabelData/sender/postcode"/>

      <xsl:value-of select="../consignmentLabelData/sender/country"/>

Delivery Address

      <xsl:value-of select="../consignmentLabelData/delivery/name" disable-output-escaping="yes"/>

      <xsl:value-of select="../consignmentLabelData/delivery/addressLine1" disable-output-escaping="yes"/>

      <xsl:value-of select="../consignmentLabelData/delivery/addressLine2" disable-output-escaping="yes"/>

      <xsl:value-of select="../consignmentLabelData/delivery/town" disable-output-escaping="yes"/><xsl:text>  </xsl:text>
      <xsl:value-of select="../consignmentLabelData/delivery/postcode"/>

      <xsl:value-of select="../consignmentLabelData/delivery/country"/>

    Routing

         <xsl:if test="count(../consignmentLabelData/transitDepots/*)=0">
             <xsl:text> </xsl:text>
         </xsl:if>

        <xsl:for-each select="../consignmentLabelData/transitDepots/*">

            <xsl:if test="name(self::node()[position()])='transitDepot'">
                <xsl:value-of select="depotCode" />

            </xsl:if>

            <xsl:if test="name(self::node()[position()])='actionDepot'">
                <xsl:value-of select="depotCode" />
                <xsl:text>-</xsl:text>
                <xsl:value-of select="actionDayOfWeek" />

            </xsl:if>

            <xsl:if test="name(self::node()[position()])='sortDepot'">
                <xsl:value-of select="depotCode" />
                <xsl:text>-</xsl:text>
                <xsl:value-of select="sortCellIndicator" />

            </xsl:if>

        </xsl:for-each>

      Sort

        <xsl:value-of select="../consignmentLabelData/transitDepots/sortDepot/depotCode" />
        <xsl:text> </xsl:text>

Postcode /

      Cluster Code

    <xsl:choose>

      <xsl:when test="string-length(../consignmentLabelData/clusterCode)>3">
        <xsl:value-of select="../consignmentLabelData/delivery/postcode"/>
      </xsl:when>
      <xsl:otherwise>
        <xsl:value-of select="../consignmentLabelData/clusterCode"/>
      </xsl:otherwise>
    </xsl:choose>

      Dest

      Depot

    <xsl:choose>
      <xsl:when test="../consignmentLabelData/destinationDepot/dueDayOfWeek/@renderInstructions='highlighted'">
        <xsl:value-of select="../consignmentLabelData/destinationDepot/depotCode"/>
        <xsl:text>-</xsl:text>
        <xsl:value-of select="../consignmentLabelData/destinationDepot/dueDayOfMonth"/>
      </xsl:when>
      <xsl:otherwise>
        <xsl:value-of select="../consignmentLabelData/destinationDepot/depotCode"/>
        <xsl:text>-</xsl:text>
        <xsl:value-of select="../consignmentLabelData/destinationDepot/dueDayOfMonth"/>
      </xsl:otherwise>
    </xsl:choose>

  <xsl:variable name="barcode_url" select='"https://express.tnt.com/barbecue/barcode?type=Code128C&height=140&width=2&data="' />

       <xsl:attribute name="src">
         <xsl:value-of select="concat($barcode_url,barcode)" />
       </xsl:attribute>

     <xsl:value-of select="barcode" />

</xsl:template>

<xsl:template name="FormatDate">

    <xsl:param name="DateTime" />

    <xsl:variable name="year">
        <xsl:value-of select="substring-before($DateTime,'-')" />
    </xsl:variable>
    <xsl:variable name="mo-temp">
        <xsl:value-of select="substring-after($DateTime,'-')" />
    </xsl:variable>
    <xsl:variable name="mo">
        <xsl:value-of select="substring-before($mo-temp,'-')" />
    </xsl:variable>
    <xsl:variable name="day">
        <xsl:value-of select="substring-after($mo-temp,'-')" />
    </xsl:variable>

    <xsl:value-of select="$day" />
    <xsl:text> </xsl:text>
    <xsl:choose>
        <xsl:when test="$mo = '1' or $mo = '01'">Jan</xsl:when>
        <xsl:when test="$mo = '2' or $mo = '02'">Feb</xsl:when>
        <xsl:when test="$mo = '3' or $mo = '03'">Mar</xsl:when>
        <xsl:when test="$mo = '4' or $mo = '04'">Apr</xsl:when>
        <xsl:when test="$mo = '5' or $mo = '05'">May</xsl:when>
        <xsl:when test="$mo = '6' or $mo = '06'">Jun</xsl:when>
        <xsl:when test="$mo = '7' or $mo = '07'">Jul</xsl:when>
        <xsl:when test="$mo = '8' or $mo = '08'">Aug</xsl:when>
        <xsl:when test="$mo = '9' or $mo = '09'">Sep</xsl:when>
        <xsl:when test="$mo = '10'">Oct</xsl:when>
        <xsl:when test="$mo = '11'">Nov</xsl:when>
        <xsl:when test="$mo = '12'">Dec</xsl:when>
    </xsl:choose>
    <xsl:text> </xsl:text>
    <xsl:value-of select="$year" />
</xsl:template>

</xsl:stylesheet>

Result after transform:-
<?xml version="1.0" encoding="UTF-8"?>

INT/AIR

.

2

Con No.

123456782

Service
Express (ND)

        Piece

1 of 3

        Weight

1.11kg

Option

PR

Customer Reference

piece1

S/R Account No8783802

OriginCVT

Pickup Date

15 Nov 2016

Sender Address

JohnSmith
TNTExpress
TNTHouse
ATHERSTONE  CV91TT
GB

Delivery Address

TNTCorporateHeadOffice
Neptunusstraat41-63
Taurusavenue111
HOOFDDORP  2132LS
NL

Routing
EMA
LGG-8

SortLGG

Postcode /

      Cluster Code

63

      Dest

      Depot

SP8-17

1100123456782011641424002132

INT/AIR

.

2

Con No.

123456782

Service
Express (ND)

        Piece

2 of 3

        Weight

1.11kg

Option

PR

Customer Reference

piece1

S/R Account No8783802

OriginCVT

Pickup Date

15 Nov 2016

Sender Address

JohnSmith
TNTExpress
TNTHouse
ATHERSTONE  CV91TT
GB

Delivery Address

TNTCorporateHeadOffice
Neptunusstraat41-63
Taurusavenue111
HOOFDDORP  2132LS
NL

Routing
EMA
LGG-8

SortLGG

Postcode /

      Cluster Code

63

      Dest

      Depot

SP8-17

1100123456782021641424002132

INT/AIR

.

2

Con No.

123456782

Service
Express (ND)

        Piece

3 of 3

        Weight

1.11kg

Option

PR

Customer Reference

piece3

S/R Account No8783802

OriginCVT

Pickup Date

15 Nov 2016

Sender Address

JohnSmith
TNTExpress
TNTHouse
ATHERSTONE  CV91TT
GB

Delivery Address

TNTCorporateHeadOffice
Neptunusstraat41-63
Taurusavenue111
HOOFDDORP  2132LS
NL

Routing
EMA
LGG-8

SortLGG

Postcode /

      Cluster Code

63

      Dest

      Depot

SP8-17

1100123456782031641424002132

            123456782

                JohnSmith
                TNTExpress
                TNTHouse
                ATHERSTONE
                Warks
                CV91TT
                GB

                TNTCorporateHeadOffice
                Neptunusstraat41-63
                Taurusavenue111
                HOOFDDORP

                2132LS
                NL

                8783802
                GB

            3
            Express (ND)
            PR
            2016-11-15
            INT
            AIR

            2

                CVT

                    EMA

                    LGG
                    8
                    SP8

                SP8
                17
                2016-11-17

            63

            GBP 12.34

            BSH

Answer: You seem to have written a single matching template so the other elements are handled by the built-in templates which copy any text node children through to the result. Either add <xsl:template match="text()"/> to prevent that in general or at the entry point use <xsl:template match="/"><xsl:apply-templates select="//pieceLabelData"/></xsl:template>. I hope that suffices, you have posted that long snippets that I have not checked all code, so I think the diagnostic and explanation is fine, hopefully the suggested fix suffices as well.
So you need
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:output method="html" indent="yes"/>

<xsl:template name="RestOfWorldHtml" match="pieceLabelData">

    <xsl:value-of select="../consignmentLabelData/marketDisplay"/>
    <xsl:text>/</xsl:text>
    <xsl:value-of select="../consignmentLabelData/transportDisplay"/>

.
      <xsl:for-each select="../consignmentLabelData/option">
          <xsl:if test="@id='HZ'">
             <xsl:text>HAZARDOUS</xsl:text>
          </xsl:if>
      </xsl:for-each>

  <xsl:if test="string-length(../consignmentLabelData/xrayDisplay)>0">

      <xsl:value-of select="../consignmentLabelData/xrayDisplay"/>

  </xsl:if>

  <xsl:choose>
    <xsl:when test="string-length(../consignmentLabelData/freeCirculationDisplay)>0">

        <xsl:value-of select="../consignmentLabelData/freeCirculationDisplay"/>

    </xsl:when>
    <xsl:otherwise>

      <xsl:text> </xsl:text>

    </xsl:otherwise>
  </xsl:choose>

  <xsl:choose>
    <xsl:when test="string-length(../consignmentLabelData/sortSplitText)>0">

            <xsl:value-of select="../consignmentLabelData/sortSplitText" />

    </xsl:when>
    <xsl:otherwise>

            <xsl:text> </xsl:text>

    </xsl:otherwise>
  </xsl:choose>

Con No.

<xsl:value-of select="../consignmentLabelData/consignmentNumber"/>

Service

    <xsl:choose>
        <xsl:when test="string-length(../consignmentLabelData/product)>15">

                <xsl:value-of select="../consignmentLabelData/product" />

        </xsl:when>
        <xsl:otherwise>

                <xsl:value-of select="../consignmentLabelData/product" />

        </xsl:otherwise>
    </xsl:choose>

        Piece

<xsl:value-of select="pieceNumber"/> of <xsl:value-of select="../consignmentLabelData/totalNumberOfPieces"/>

        Weight

    <xsl:choose>
        <xsl:when test="weightDisplay/@renderInstructions='highlighted'">

                <xsl:value-of select="weightDisplay" />

        </xsl:when>
        <xsl:otherwise>

                <xsl:value-of select="weightDisplay" />

        </xsl:otherwise>
    </xsl:choose>
    <xsl:text> </xsl:text>

Option

    <xsl:variable name="numberOptions" select="count(../consignmentLabelData/option)" />
        <xsl:choose>

            <xsl:when test="$numberOptions >1">
              <xsl:for-each select="../consignmentLabelData/option">

                    <xsl:value-of select="@id" />
                    <xsl:text>  </xsl:text>

              </xsl:for-each>
            </xsl:when>

            <xsl:otherwise>
                <xsl:choose>
                    <xsl:when test="string-length(../consignmentLabelData/option)>0">

                        <xsl:value-of select="../consignmentLabelData/option" />

                    </xsl:when>
                    <xsl:otherwise>

                            <xsl:text> </xsl:text>

                    </xsl:otherwise>
                </xsl:choose>
            </xsl:otherwise>
        </xsl:choose>

Customer Reference

<xsl:value-of select="pieceReference" disable-output-escaping="yes" />

      S/R Account No
      <xsl:value-of select="../consignmentLabelData/account/accountNumber" />

    Origin
    <xsl:value-of select="../consignmentLabelData/originDepot/depotCode" />

Pickup Date

      <xsl:call-template name="FormatDate">
                <xsl:with-param name="DateTime" select="../consignmentLabelData/collectionDate"/>
        </xsl:call-template>

Sender Address

      <xsl:value-of select="../consignmentLabelData/sender/name" disable-output-escaping="yes"/>

      <xsl:value-of select="../consignmentLabelData/sender/addressLine1" disable-output-escaping="yes"/>

      <xsl:value-of select="../consignmentLabelData/sender/addressLine2" disable-output-escaping="yes"/>

      <xsl:value-of select="../consignmentLabelData/sender/town" disable-output-escaping="yes"/><xsl:text>  </xsl:text>
      <xsl:value-of select="../consignmentLabelData/sender/postcode"/>

      <xsl:value-of select="../consignmentLabelData/sender/country"/>

Delivery Address

      <xsl:value-of select="../consignmentLabelData/delivery/name" disable-output-escaping="yes"/>

      <xsl:value-of select="../consignmentLabelData/delivery/addressLine1" disable-output-escaping="yes"/>

      <xsl:value-of select="../consignmentLabelData/delivery/addressLine2" disable-output-escaping="yes"/>

      <xsl:value-of select="../consignmentLabelData/delivery/town" disable-output-escaping="yes"/><xsl:text>  </xsl:text>
      <xsl:value-of select="../consignmentLabelData/delivery/postcode"/>

      <xsl:value-of select="../consignmentLabelData/delivery/country"/>

    Routing

         <xsl:if test="count(../consignmentLabelData/transitDepots/*)=0">
             <xsl:text> </xsl:text>
         </xsl:if>

        <xsl:for-each select="../consignmentLabelData/transitDepots/*">

            <xsl:if test="name(self::node()[position()])='transitDepot'">
                <xsl:value-of select="depotCode" />

            </xsl:if>

            <xsl:if test="name(self::node()[position()])='actionDepot'">
                <xsl:value-of select="depotCode" />
                <xsl:text>-</xsl:text>
                <xsl:value-of select="actionDayOfWeek" />

            </xsl:if>

            <xsl:if test="name(self::node()[position()])='sortDepot'">
                <xsl:value-of select="depotCode" />
                <xsl:text>-</xsl:text>
                <xsl:value-of select="sortCellIndicator" />

            </xsl:if>

        </xsl:for-each>

      Sort

        <xsl:value-of select="../consignmentLabelData/transitDepots/sortDepot/depotCode" />
        <xsl:text> </xsl:text>

Postcode /

      Cluster Code

    <xsl:choose>

      <xsl:when test="string-length(../consignmentLabelData/clusterCode)>3">
        <xsl:value-of select="../consignmentLabelData/delivery/postcode"/>
      </xsl:when>
      <xsl:otherwise>
        <xsl:value-of select="../consignmentLabelData/clusterCode"/>
      </xsl:otherwise>
    </xsl:choose>

      Dest

      Depot

    <xsl:choose>
      <xsl:when test="../consignmentLabelData/destinationDepot/dueDayOfWeek/@renderInstructions='highlighted'">
        <xsl:value-of select="../consignmentLabelData/destinationDepot/depotCode"/>
        <xsl:text>-</xsl:text>
        <xsl:value-of select="../consignmentLabelData/destinationDepot/dueDayOfMonth"/>
      </xsl:when>
      <xsl:otherwise>
        <xsl:value-of select="../consignmentLabelData/destinationDepot/depotCode"/>
        <xsl:text>-</xsl:text>
        <xsl:value-of select="../consignmentLabelData/destinationDepot/dueDayOfMonth"/>
      </xsl:otherwise>
    </xsl:choose>

  <xsl:variable name="barcode_url" select='"https://express.tnt.com/barbecue/barcode?type=Code128C&height=140&width=2&data="' />

       <xsl:attribute name="src">
         <xsl:value-of select="concat($barcode_url,barcode)" />
       </xsl:attribute>

     <xsl:value-of select="barcode" />

</xsl:template>

<xsl:template name="FormatDate">

    <xsl:param name="DateTime" />

    <xsl:variable name="year">
        <xsl:value-of select="substring-before($DateTime,'-')" />
    </xsl:variable>
    <xsl:variable name="mo-temp">
        <xsl:value-of select="substring-after($DateTime,'-')" />
    </xsl:variable>
    <xsl:variable name="mo">
        <xsl:value-of select="substring-before($mo-temp,'-')" />
    </xsl:variable>
    <xsl:variable name="day">
        <xsl:value-of select="substring-after($mo-temp,'-')" />
    </xsl:variable>

    <xsl:value-of select="$day" />
    <xsl:text> </xsl:text>
    <xsl:choose>
        <xsl:when test="$mo = '1' or $mo = '01'">Jan</xsl:when>
        <xsl:when test="$mo = '2' or $mo = '02'">Feb</xsl:when>
        <xsl:when test="$mo = '3' or $mo = '03'">Mar</xsl:when>
        <xsl:when test="$mo = '4' or $mo = '04'">Apr</xsl:when>
        <xsl:when test="$mo = '5' or $mo = '05'">May</xsl:when>
        <xsl:when test="$mo = '6' or $mo = '06'">Jun</xsl:when>
        <xsl:when test="$mo = '7' or $mo = '07'">Jul</xsl:when>
        <xsl:when test="$mo = '8' or $mo = '08'">Aug</xsl:when>
        <xsl:when test="$mo = '9' or $mo = '09'">Sep</xsl:when>
        <xsl:when test="$mo = '10'">Oct</xsl:when>
        <xsl:when test="$mo = '11'">Nov</xsl:when>
        <xsl:when test="$mo = '12'">Dec</xsl:when>
    </xsl:choose>
    <xsl:text> </xsl:text>
    <xsl:value-of select="$year" />
</xsl:template>

<xsl:template match="text()"/>

</xsl:stylesheet>

Online at http://www.utilities-online.info/xsltransformation/?save=85366593-91a7-4c00-95ca-1677c2e9a84b-xsltransformation.
Comment: Thanks for your reply,  i've found an old topic here, looks like someone was having the exact same issue http://stackoverflow.com/questions/8911558/converting-xml-into-html-using-xsl  i think it is a problem with knowing what match="" criteria to use.  I still cant get it to produce 3 labels... :(
Comment: Start with adding ``, that can help when creating fragments of HTML in client-side script. If you still have problems then edit the question as to what you have now and where you are stuck, I think the problem about the unwanted content is solved.

Issue with XML via XSL StyleSheet


Android AIDL support "short" type?

Question: Does AIDL support short type ?
http://developer.android.com/guide/developing/tools/aidl.html
It said "All primitive types in the Java programming language (such as int, long, char, boolean, and so on)"
But it seems cannot use short in AIDL.
thanks !
Comment: Out of interest, why do you require a short? Will a char, byte[] or int not suffice?
Answer: I think it does not :/ so use an int and cast it back to short afterwards

Android AIDL support "short" type?


jQuery Ajax and AddThis social bookmark application

Question: I am developing a website that has an AddThis Integration
Here's my situation right now,
Every time a user inputs an RSS Feed in a text input, it will display the results in the same page since I'm using an AJAX on fetching the data. Together with the result is the AddThis code that has javascripts in it.
My problem here is the AddThis button is not appearing when I started using AJAX. But before using that one, it works perfectly.
Here's the code.

                Insert RSS Feed Here:
                <input type="text" name="url" id="url" style='width:300px;' />

    <input type='button' name='submit' value='Submit' class='submit' />

When the user clicks on the button it runs on this jQuery script:
jQuery('.submit').click(function() {
        if( jQuery('#url').val() == "" )
            return false;
        jQuery.ajax({
            type:   "POST",
            url:    "parse.php",
            data:   "url="+jQuery('#url').val(),
            success: function(data) {
                jQuery(".urlResult").html(data);
            }
        });
    });

This is the parse.php file/code:
<?php
$file = $_POST['url'];

$xml = simplexml_load_file($file,'SimpleXMLElement',LIBXML_NOCDATA);

foreach($xml as $key)
{

    $links = $key->item;

    for($x=0; $x<count($links); $x++)
    {
        echo "
";
        echo $links[$x]->link;
        echo "
";
?>

    <?php
    }
}
    ?>

The problem here is that this code is not appearing since I started to use jquery-ajax:
This code allows the display of the addThis buttons.

The javascript files that were embedded on my site is only the jQuery script.
Comment: I am having a similar issue where the script tag loads in the addthis__[blah].js only once, and never does it again unless you refresh the page. I'll post a solution when I figure it out.
Answer: This post solved my issue -- you need to dynamically load in the script via $.getScript():
http://kb.jaxara.com/how-initialize-addthis-social-sharing-widgets-loaded-ajax


Django serialization validation optimization for bulk create

Question: I am trying to write an api to process large number of rows of data using bulk_create on zipped csv records. but when serializer.is_valid() is called to validate the data before calling serializer.save(), it takes a long time to validate due to the foreign key constraint for device_id(sensorReading_device).
I've tried prefetch_related() & select_related() and nested serializer and the performance is similar or worse as i suspect the modelserializer is committing the n+1 DB roundtripping problem for validation due to the foreign key. The only method which worked is to remove the foreign key in my model and implement as charfield and it became blazingly fast but it means there will be no more foreign key constraint. Is the removal of foreign key the way forward or am I missing something?
heres my code and any advice is greatly appreciated!
serializer.py
class SensorReadingListSerializer(serializers.ListSerializer):
    def create(self, validated_data):
        sensor_readings = [SensorReading(**item) for item in validated_data]
        return SensorReading.objects.bulk_create(sensor_readings)

class SensorReadingSerializer(serializers.ModelSerializer)
    device_qs = Device.objects.all()
    sensorReading_device = PrimaryKeyRelatedField(label='SensorReading device', many=True, queryset=device_qs)

    class Meta:
        model = ReadingsModel.SensorReading
        fields = ('id', 'device_timestamp', 'server_timestamp', 'payload', 'sensorReading_device')
        list_serializer_class = SensorReadingListSerializer

model.py
class Device(models.Model):
    device_id = models.CharField(primary_key=True, max_length=120)
    device_deviceType = models.ForeignKey(DeviceType, on_delete=models.CASCADE)
    device_softwareVersion = models.ForeignKey(SoftwareVersion, on_delete=models.CASCADE)

class SensorReading(models.Model):
    device_timestamp = models.DateTimeField(default=datetime.today)
    server_timestamp = models.DateTimeField(default=datetime.today)
    payload = JSONField()
    sensorReading_device = models.ForeignKey(Device, on_delete=models.CASCADE)
    # sensorReading_device = models.CharField(max_length=120)

view.py
class SensorReadingViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows SensorReading to be viewed or edited.
    """

    serializer_class = SensorReadingSerializer
    # queryset = SensorReading.objects.all().select_related('device')
    # queryset = SensorReading.objects.prefetch_related('sensorReading_device').all()
    queryset = SensorReading.objects.all()
    parser_classes = (MultiPartParser, FormParser,)

    @list_route(methods=['post'])
    def post_readings_zip(self, request):
        if not sys.warnoptions:
            warnings.simplefilter("ignore")

        # print(self.queryset.len())
        request_file = request.FILES['zipped_file']
        device_id = request.data['device_id']
        # server_timestamp = datetime.datetime.today

        if Device.objects.filter(device_id=device_id).exists():
            print('device exist')
            if zipfile.is_zipfile(request_file):
                print('file is zip')
                zf = zipfile.ZipFile(request_file)
                filelist = zf.namelist()
                data = []
                print("Processing data: " + str(datetime.datetime.now()))
                for csv_file_name in filelist:
                    with zf.open(csv_file_name) as reading_csv:
                        rc = reading_csv.read()
                        c = csv.StringIO(rc.decode())
                        for row in c:
                            row = row.rstrip()
                            data.append({'payload': {'data': row}, 'sensorReading_device': device_id})
                print("Done processing csvs: " + str(datetime.datetime.now()))
                # data = [{'payload': {'data': 'hello world payload 01'}, 'sensorReading_device': '001'},
                #         {'payload': {'data': 'hello world payload 02'}, 'sensorReading_device': '001'}]
                # qs = SensorReadingSerializer.setup_eager_loading(self.queryset)
                serializer = SensorReadingSerializer(data=data, many=True)
                # print(repr(serializer))
                print("Validating serializer: " + str(datetime.datetime.now()))
                if serializer.is_valid():
                    print("Saving: " + str(datetime.datetime.now()))
                    serializer.save()
                    print("Done: " + str(datetime.datetime.now()))
                    # return JsonResponse(serializer.data, status=201, safe=False)
                    return JsonResponse({'status':serializer.data}, status=201, safe=False)
                return JsonResponse(serializer.errors, status=400, safe=False)
            else:
                return JsonResponse(
                    {'status': status.HTTP_400_BAD_REQUEST, 'message': 'Bad Request: Uploaded file is not a zip'})
        else:
            return JsonResponse({'status': status.HTTP_400_BAD_REQUEST,'message': 'Device ID does not exist, please register'})

Answer: Have you tried to add index_db? Have a quick read at Django Doc. Have you analysed your querys with django-toolbar or anything similar?


How do I add a left button item to a UINavigationController on iOS?

Question: I am trying to add a Reload button to the top bar of a navigation controller with no success.
Here is the header:
<code>@interface PropertyViewController : UINavigationController {

}
</code>
Here is how I am trying to add it:
<code>- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
        UIBarButtonItem *reload = [[UIBarButtonItem alloc] initWithTitle:@"Show" style:UIBarButtonItemStylePlain
                                          target:self action:@selector(reloadPropertyList:)];
        self.navigationItem.leftBarButtonItem = reload;
    }
    return self;
}
</code>
Comment: Why are you subclassing navigation controller here?
Comment: then how to add and where?
Comment: You haven't explained what all your view controllers are, but view controllers specify the items to show and the navigation controller deals with showing them
Answer: You should use custom navigation bar. hide navigation bar and made your custom. Drag UIView and and add button to it.
If you wantto keep navigation bar than you can use tool bar like,
here
Answer: The method initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil is not called automatically so you need to create an instance of PropertyViewController class like below
<code>PropertyViewController *propertyVC = [[PropertyViewController alloc] initWithNibName:@"your_nib_if_exist" bundle:nil];
//pass nib name if nib exist otherwise pass nil
</code>


Can we add two columns when we are selecting them directly from a dataframe

Question: I created a dataframe
'df1=spark.read.format("csv").option("delimiter","|").load(file)'

Now I want to select columns from that dataframe
df1.select("col1","col2","col3")

This works fine. But can I concat two columns in the same statement. consider col1 as age,col2 as firstname and col3 as lastname. I am looking for output as mentioned below combined first and last name. I know it can be done using sparksql. I want to know this can be done in the above df1.select() statement.Thanks
col1  col2col3
23    JohnHarper
20    MarshallMathers

Answer: You can try something like this
df1.select("col1",concat("col2","col3"))

Comment: Got an error concat is not defined. Do I need to import anything?
Comment: Can you post the snapshot of the error here
Comment: in pyspark you would need `from pyspark.sql.functions import *` or for specific `from pyspark.sql.functions import concat`
Answer: You can use concat function as
from pyspark.sql.functions import *
df1.select("col1",concat("col2","col3").alias("col2col3")).show(truncate=False)

or use concat_ws as
df1.select("col1",concat_ws("", "col2","col3").alias("col2col3")).show(truncate=False)

or you can use a udf function as
from pyspark.sql.functions import *
from pyspark.sql.types import *

@udf(StringType())
def concatenating(x, y):
    return "".join([x,y])

df1.select("col1", concatenating(col("col2"),col("col3")).alias("col2col3")).show(truncate=False)

Comment: Thanks @Ramesh Maharjan. I totally forgot to import the function. Its a silly mistake.Thanks
Comment: happy to hear that its helpful :) you can upvote both mine and madhu's answer too ;) its the up button