السبت، 16 مايو 2020

how to fix "A previous program installation created pending file operations on the installation machine. You must restart the computer before running setup."


My machine had SQL Server 7 installed, so I removed it, but the problem persisted. I restarted my machine many times, checked the registry for a pending file entry, and searched the local drive for a pending file, but I still haven't found the solution. Do you have any ideas? SQL Server issues this error message when Setup detects that some files need updating and that the registry has operations pending to update those files on the next reboot. You can see this scenario
 in the registry key :HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SessionManager\pendingfilerenameoperations. One way to eliminate this error message is to delete the registry's pending file rename or delete keys. Note that deleting either of these keys might prevent a necessary file update from occurring, perhaps causing an incomplete operation. Renaming the keys might be safer; then, you can restore the names after your SQL Server installation is complete.

الأحد، 24 سبتمبر 2017

Microsoft InfoPath 2013 Encountered an error during setup

The problem started when I decided to uninstall Office 2013. I noticed InfoPath 2013 had disappeared a few weeks later when I needed to use it. No problems I thought - I downloaded InfoPath 2013 from the O365 Portal (Other Installs - infopath_4753-1001_x86_en-us.exe). However - every install attempt resulted in "Microsoft InfoPath 2013 Encountered an error during setup". Install bar gets to near end and reverses. So - much googling - many false leads - etc etc. eventually resorted to removing all office applications using O15-ctrremove.cab. Tried installing InfoPath 2013 first - same error. Ran the remove office app O15-ctrremove.cab again. Restart. Re installed Microsoft Office 365 ProPlus - another nightmare but eventually got it all working and authenticating properly. Now I'm stuck with not being able to reinstall SharePoint Designer 2013 (from O365 Portal) and InfoPath 2013.

الأربعاء، 11 سبتمبر 2013

Hacking IRC


1. What is IRC, and how does it work? 

 IRC (Internet Relay Chat) provides a way of communicating in real time with people from all over the world. It consists of various separate networks (or "nets") of IRC servers, machines that allow users to connect to IRC. The largest nets are EFnet (the original IRC net, often having more than 32,000 people at once), Undernet, IRCnet, DALnet, and NewNet. Generally, the user (such as you) runs a program (called a "client") to connect to a server on one of the IRC nets. The server relays information to and from other servers on the same net. Recommended clients: 

  •  UNIX/shell: ircII 
  • Windows: mIRC 
  • Macintosh clients

 Be sure to read the documentation for your client! Once connected to an IRC server on an IRC network, you will usually join one or more "channels" and converse with others there. On EFnet, there often are more than 12,000 channels, each devoted to a different topic. Conversations may be public (where everyone in a channel can see what you type) or private (messages between only two people, who may or may not be on the same channel). IRC is not a "game", and I highly recommend you treat people you meet on IRC with the same courtesy as if you were talking in person or on the phone, or there may be serious consequences.

2. Some details


Channel names usually begin with a #, as in #irchelp . The same channels are shared among all IRC servers on the same net, so you do not have to be on the same IRC server as your friends. (There are also channels with names beginning with a & instead of a #. These channels are not shared by all servers on the net but exist locally on that server only.) Each user is known on IRC by a "nick", such as smartgal or FunGuy. To avoid conflicts with other users, it is best to use a nick that is not too common, e.g., "john" is a poor choice. On some nets, nicks do not belong to anyone, nor do channels. This can lead to conflict, so, if you feel strongly about ownership of such things, you may prefer networks with "services" like Undernet, DALnet, or other smaller networks.
Channels are run by channel operators, or just "ops" for short, who can control the channel by choosing who may join (by "banning" some users), who must leave (by "kicking" them out), and even who may speak (by making the channel "moderated")! Channel ops have complete control over their channel, and their decisions are final. If you are banned from a channel, send a /msg to a channel op and ask nicely to be let in (see the /who command in the next section to learn how to find ops). If they ignore you or /who gives no response because the channel is in secret mode (+s), just go somewhere else where you are more welcome. IRC servers are run by IRC admins and by IRC operators, or "IRC ops". IRC ops manage the servers themselves and, on EFnet and many other networks, do not get involved in personal disputes, channel takeovers, restoring lost ops, etc. They are not "IRC cops."


3. Talking, and entering commands



 Commands and text are typed in the same place. By default, commands begin with the character / . If you have a graphical client such as mIRC for Windows, many commands can be executed by clicking on icons with the mouse pointer. It is, however, highly recommended that you learn to type in the basic IRC commands first. When entering commands, pay close attention to spacing and capitalization. The basic commands work on all the good clients.Some examples are given below. In these, suppose your nick is "yournick", and that you are on the channel #coolness.
Your friend "MaryN" is in #coolness with you, and your friend "Tomm" is on IRC but is not on a channel with you. You can apply these examples in general by substituting the relevant nick or channel names.

What you typeWhat happens
/join #coolnessYou join the channel #coolness.
/who #coolnessGives some info on users in the channel.
@ = channel op, while * means IRC op.
hello everyoneEveryone on #coolness sees <yournick> hello everyone. (You need not type in your own nick.)
/me is a pink bunnyEveryone in #coolness sees * yournick is a pink bunny
/part #coolnessYou leave the channel.
/whois TommYou get some info about Tomm or whatever nickname you entered.
/whois yournickThis is some info others see about you.
/nick newnickChanges your nick to "newnick"
/msg Tomm hi there.Only Tomm sees your message (you don't need to be on the same channel for this to work).
/ping #coolnessGives information on the delay (round-trip) between you and everybody on #coolness.
/ping TommGives information on the delay (round-trip) between you and just Tomm.
/dcc chat MaryNThis sends MaryN a request for a dcc chat session. MaryN types /dcc chat yournick to complete the connection. DCC chat is faster (lag free) and more secure than /msg.
/msg =MaryN Hi there!Once a DCC connection has been established, use the /msg =nick message format to exchange messages (note the = sign). DCC does not go through servers, so it are unaffected by server lag, net splits, etc.
/helpThis works in many clients. Try it!
/quit good night!You quit IRC completely, with the parting comment so that others see "*** Signoff: yournick (good night!)".
NOTE: When you are not in a named channel, lines not beginning with a / have no effect, and many commands work differently or fail to work altogether.

4. Where to go

 You can learn a lot by joining a channel and just listening and talking for a while. For starters, try these channels: #new2irc, #newuser, #newbies, or #chatback. Busier alternatives include: #chat, and #ircbar. For help with the mIRC client, try joining #new2mirc or #mirchelp. For help with general IRC questions, join #irchelp. To form your own channel with the name #mychannel (if #mychannel does not already exist), type /join #mychannel. The channel is created and you are automatically made an op.


5. Some smileys and jargon


 :-) is a smiley face, tilt your head to the left to see it. Likewise, :-( is a frown. ;-) is a wink. :~~( is crying, while :-P is someone sticking their tongue out. :-P ~~ is drooling. (-: a lefty's smile, etc. There are hundreds of these faces.Here are some common acronyms used in IRC:
brb =  be right back                     bbiaf = be back in a flash
bbl =  be back later                     ttfn = ta ta for now
np  =  no problem                        imho = in my humble opinion
lol =  laughing out loud                 j/k = just kidding
re  =  hi again, as in 're hi'           wb = welcome back
wtf =  what the f--k                     rtfm = read the f--king manual
rofl = rolling on the floor laughing

6. Some advice

 Etiquette

 Typing in all caps, LIKE THIS, is considered "shouting" and should be avoided. Likewise, do not repeat yourself or otherwise "flood" the channel with many lines of text at once. Be sure to use correct terminology, e.g., "channel", not "chat room", and "nick", not "handle". While in a channel, follow the lead of the channel ops there. If you antagonize them, you may be "kicked" off the channel forcibly and possibly "banned" from returning. On the other hand, some channel ops are power-hungry and may kick or ban for no good reason. If this happens, or if someone on a channel is bothering you, simply leave the channel -- there are thousands of others.

 Disconnected by /list? 

If you get disconnected when using the /list command, try switching servers, or else recent channel lists are available on the WWW at .

 Harassment and attacks 

If someone starts harassing or flooding you, leave the channel or use the /ignore command. For more details, mIRC users see our flood protection page, ircII users type /help ignore. It is a good idea to set your user mode to +i (invisible) to avoid unsolicited messages and harrassment -- if you are "invisible" generally only users on a channel with you can determine what nick you are using. If somebody else is crashing or disconnecting you, see our Denial of Service or "Nuke" Attacks page. You can also log and report abuse when it violates server rules, which you can read by typing /motd.


7. IRC server problems, and choosing a server 

 At this point, you are ready to "chat" on IRC. For the most part, the commands above should suffice for beginners, but things can go wrong in IRC. 

Net splits

 Networks can become divided (called a "net split"), thus separating you from users you had been speaking with. These splits are often relatively short, though common some days.

 Lag

 A more frequent problem is "lag", where there is a noticeable delay between the time you type something in and someone else reads it. Choosing a server near you is one way to try to lessen lag. Lag can be measured by using the /ping command (see the commands section above). Once you find a better server, the command for changing servers is /server server.name.here. 

Server Lists 

On most clients, typing /links gives a list of servers on your current net. Use this command sparingly, no more than a couple times in a row, or you may mistaken for a "link looking" troublemaker. 

Ping? Pong!

 mIRC users: Ping? Pong! in the status window just means your server pinged you to make sure you were still connected, and your client automatically replied with a pong. Don't worry about these. 

Reminder about DCC chat 

The /dcc chat command can be used to establish a one-on-one connection that avoids lag and will not be broken by a net split! Check your docs for usage info. In most clients, you can set up a DCC chat connection by both typing /dcc chat nick_of_other_person. To talk through that connection, type /msg =nick whatever (note the = sign). In mIRC, you can also start a DCC chat session by selecting DCC and then Chat from the menu and then entering the nick of the user with whom you wish to chat. A window opens for that dcc chat session.



9. A word of warning

 IRC scripts are sets of commands that your client will run. Many otherwise good scripts have been hacked so that if you load them, you can seriously compromise your security (someone can get into your account, delete all of your files, read your mail, etc.). There are also evildoers who try to send people viruses and other bad things. Just like in real life, don't accept anything from a stranger. There have been many incidents of this type, not just a few. Do not ever run a script unless you know what each line does, not even if it is given to you by a friend, as your friend may not have the expertise to detect well-hidden "trojans". Automatic DCC get is a very bad idea! Once it is on, you are susceptible to dangers ranging from disconnection from your server to giving someone else control of your computer. Quite a few people have run into serious problems because of the DCC autoget setting.

Shout it

How to Hack Gmail Password or Account


Things That you Need for Hacking Gmail Account Password:
1. Gmail Phisher
2. Free Web hosting  Site
3. Little bit of manual Work :P

Introduction to Phishing
If you know little bit of Hacking then Its must for you know About Phishing i.e What is Phishing and how it works and most important How you can protect yourself from getting into the Trap. I will try to explain all of these in my article. 
First of all What are Phish pages and what is phishing?? Phish pages are basically the fake pages or virtual pages that looks similar to the original website Page. The only difference is the batch program running in the background i.e Original Webpage sends requests to Gmail server while Phish Page sends request to hacker's php server. Now Phishing is a password hacking technique commonly used by hackers using phish pages that looks similar to original web page. The only difference is the URL in the address bar so Guys One Important Tip for you all always check the Address bar while going to any website .
Now What is Smart Phishing, Normal phishing page sends the password to hacker but it doesn't redirects the page to original website but smart phishing does. Means victim can never know what really happened and his account is got hacked. He will only think that he has entered the wrong password as in second attempt the web page is original and he will be able to login and the most fantastic thing is that the original redirected page has username already entered in it that makes it even smarter. 
Now lets come to how it works?? When a user types a Username Password in the the text box,The info is sent to "login.php" which acts as a password logger and redirects the page to "LoginFrame2.htm" which shows "There has been a temporary error Please Try Again" in it . So when the person clicks on try again it redirects to the actual URL so that the victim does not know that your site is a fake site and gets his gmail.com password hacked.
 HACKING GMAIL ACCOUNT STEPWISE:
1. First of all download the Gmail Phisher.
2. Extract the rar file now you will get three files as given below:
  •       gmail.html
  •       log.txt
  •       mail.php
3. Upload all the Three files to any of the free Web hosting server. Remember while creating the  account on these servers try the username as nearer as possible to the original URL like mail.gmaile or maile.gmall etc.. As its the most crucial step. Some Free Web hosting servers are given below you can also find few more for yourself.
  • www.yourfreehosting.net
  • www.esmartstart.com
  • www.110mb.com
  • www.drivehq.com
  • www.t35.com
4. Once you have uploaded all the three files to web hosting server now you have to send these to your victim. This is the most important step regarding smart phishing technique.
Most People use same password for orkut and gmail and here is the main hack lies. What you have to do you have to send the HTML email to the victim which looks similar to the Orkut scrap to his email you can easily do this using simple editing to the existing mail. Just you have to change the link with your phish link and content according to the person likings so that he will surely come inside the trap. 
Another technique is that you can send him a request to join a particular community in the format orkut does.
And Last but the most important one Send him mail from Gmail Admin such that "We have seen illegal activity from your account and you need to verify your account and your account is temporarily disabled after this login. To unlock your account Verify your Email and in that link put your Phish link. Now Guys you all will came to know How it works. If you want to Protect yourself its must that you should know what techniques a Hacker can use to hack your Gmail Account.
5. Now After sending phisher to victim, once the user logs in to his Gmail account using your Phisher, his user ID and password are ours..And these are stored in log.txt What you have to do is just refresh your Web hosting account files. 
6. The Log.txt file will contain the passwords and look like this:
 

Thats all Now you have hacked the password of victim. I hope you all have Liked It. 

How to Protect Your Gmail Account From Phisher??
1. Always check the URL in the address bar before entering username and password.
2. Never follow any link from your email and any website until u have confirmed the Address bar URL.
3. Never Follow spam mails and "Win lottery or Cash" mails.


الاثنين، 12 أغسطس 2013

writing SMS Gateway Apps with clickatell ruby scripts


Update: After contacting the guys from Clickatell they sorted out my billing issues and were friendly enough to throw in some free credits. Very nice of them, thanks guys!

I’m always a big fan of interfacing with as many possible data inputs and outputs when i’m working on projects. So much so, that sometimes I do a project purely to plan with novel ways to interact with people. After being introduces to the CEO of Clickatell, a international messaging company that runs a very nifty SMS (Text Message) API, I figured I’d better build something with it.
Two interesting problems came up almost simultaneously that I attacked with a little text messaging scripts in both cases – server monitoring and, well, roommate monitoring!
As one of the development members on 2draw.net, an online art community started by Marcello Bastae-Forte, I’ve been dealing with keeping the server alive and running. Since we’re a team of only 4 at the moment, there is the distinct possibility that the server can go down, and without adequate monitoring utilities, none of us will realize this for a significant amount of time. Thus, what could be better than a text message crying for help if something goes wrong! In the same gist, I would like to remind my roommates (and myself) to go take out the trash and run the dishwasher according to our very intricate schedule we posted on the fridge. Thus, I registered a Clickatell account to start playing with text gateways.
Clickatell gave me a great initial impression. Their website is clean and informative, and their API is great to use. Once you’ve registered, you request an application ID and corresponding secret ID. Using these numbers for authentication you can send batch message jobs easily and securely. Most attractive to my problem at hand was their, as I call it, “one request, one message” API call. With one HTTP POST I can send all the necessary information to get a text message sent to multiple phone numbers. This allowed me to write a total of 12 lines of Ruby to wrap their API in a simple Ruby object.
Unfortunately, I hit quite a snag in trying to procure some text message credits from them. For some strange reason, I kept getting a message saying “Required Field” next to the State form field on their billing page. I did, quite naturally, fill out the form multiple times and made sure to fill out every field I could find, but to no avail. Their customer service response was prompt, but unfortunately did not help to solve my problem. Being slightly confused about how to continue using their service, I shopped around to see what else is out there. (I did manage to fix this issue, so keep reading!) I gave Ez TextingUpsideWireless and CellTrust a try to compare. Unfortunately, each of these services has caveats that, if I had some credit on Clickatell, I would not have bothered to register. Since I did not, I pressed on and gave them all a try.
Ez Texting is, as their name suggests, super easy. Register, and you get 10 messages to use. They have the cheapest rates going (over half the price of Clickatell – $12 for 500 credits versus $12 for 200 credits on Clickatell), and their site indicates this strongly with a design that doesn’t exactly spell professional. I was here for the API, though, and it was a big disappointment when I was notified that I needed special permission to use the API, and to please send an email to their customer support group. Seriously, I don’t want to waste the time waiting for them. I did send them an email though, but have yet to hear back. They do have the same feature as Clickatell to send a text message with a single HTTP call, but since they do not support HTTPS your password will be floating along the lines in cleartext. Need I say more about security. Their messages also contain “Subject: ” and “Message: ” parts that you cannot get rid of, which looks stupid and annoyed me to no end. As an easy to use, online text center, they work well though.
UpsideWireless and CellTrust both looked like strong competitors to Clickatell, and probably are in the business world. Neither catered to the hackers out there, though, and to buy credit or get access to the API you had to get quotes from their sales department and access rights to their APIs. (I’m generalizing now, and each has their own process, but lets get to the code shall we?)
By now, 2 days later, I hoped that whatever bug was in Clickatell’s billing script would be sorted out by now. Alas, it wasn’t, but in filling out all my details on both the Administrative and Billing profile sections, and filling out their billing page that forms part of the buying process, I made it to the checkout screen. I was taken aback that they required a phone call to verify my credit card (for a total of $13), but they called within 10 minutes after filling out the form, so I did not complain too loudly! With such a prompt response, I applaud them for taking the security measures.
Once I had my credits and my ruby code, I could finally start doing some cool stuff.
To wrap the Clickatell API, I put together a Notify object and, with some Monkey-patching to the URI class, I was all set:
<br />require 'net/http'<br />require 'uri'<br />require 'cgi'<br /><br />#Slight modification to the URI class:<br />class URI::Generic<br /> #appends more data to the current query.<br /> def append_query(param, arg)<br /> if self.query<br /> self.query += "&#{param.to_s}=#{arg.to_s}"<br /> else<br /> self.query = "#{param.to_s}=#{arg.to_s}"<br /> end<br /> return self<br /> end<br />end<br /> <br />class Notifier<br />public<br /> #Takes a YAML object that contains the <br /> #hashes "phones" and "emails" to notify people<br /> def initialize(yaml_conf)<br /> @yaml_conf = yaml_conf<br /> end<br /> <br /> #see https://www.clickatell.com/downloads/http/Clickatell_HTTP.pdf<br /> def clickatell_text(message, phonenrs)<br /> if (message == false)<br /> message = "_hmm, nothing's up. _is the script buggy?"<br /> end<br /> url = URI.parse(@yaml_conf["clickatell"]["send_uri"].to_s)<br /> url.append_query("api_id", CGI::escape(@yaml_conf["clickatell"]["api_id"].to_s))<br /> url.append_query("user", CGI::escape(@yaml_conf["clickatell"]["user"].to_s))<br /> url.append_query("password", CGI::escape(@yaml_conf["clickatell"]["password"].to_s))<br /> nrs = ""<br /> phonenrs.each do |value| <br /> nrs += value.to_s + "," <br /> end<br /> nrs[-1] = ''<br /> url.append_query("to", CGI::escape(nrs.to_s))<br /> url.append_query("text", CGI::escape(message))<br /> response = Net::HTTP.get_response(url)<br /> puts " code = #{response.code}"<br /> puts " message = #{response.message}"<br /> puts " response = #{response.body}"<br /> return (response.code.to_i == 200 && response.body.to_s.include?("id: "))<br /> end<br />end<br />
I tend to use YAML to store my config files, which is exactly what I did in this case. My config.yml file looked something like this:

<br />clickatell:<br />&nbsp&nbsp user: user<br />&nbsp&nbsp password: pass<br />&nbsp&nbsp api_id: appid<br />&nbsp&nbsp send_uri: http://api.clickatell.com/http/sendmsg?<br /> <br />phones:<br />&nbsp&nbsp person1: 19999999999<br />&nbsp&nbsp person2: 19999999999<br />
The script to remind my roommates and I of our daily duties was a simple couple of lines on top of this:
<br />require 'notifier.rb'<br />require 'yaml'<br /><br />$LOAD_PATH.unshift(File.dirname(__FILE__)) <br />CHECKERCONF_FILE = "dutiesconf.yml"<br /><br />yaml_conf = YAML.load_file("#{File.dirname(__FILE__)}/#{CHECKERCONF_FILE}")<br />notify = Notifier.new(yaml_conf)<br />message = "Yo " + yaml_conf["people"][Time.now.wday].to_s + "! Letting you know that House Duties is yours today. Aiight peace! -KitchenBot"<br /><br />notify.clickatell_text(message, [yaml_conf["phones"][Time.now.wday]]).to_s<br />
I added a “people” and “phones” field, and indexed both of these by the day of the week, thus sending personalized text messages to whoever is the lucky person that day. A simple cron job entry on my little home server, and I was all set for a blissfully clean kitchen. (I’ll have to let you guys know how that works out though…)
Overall, Clickatell is easy to use once you have it set up, their response time if fast, and their service works great. Once their initial process of buying credits is more streamlined, they will undoubtedly be the top choice for anyone wanting to do some text message hacking. I haven’t yet tried using their 2-way text messaging, but if this is as easy to use as their one-way API, I’m sold.

الأربعاء، 19 يونيو 2013

JavaScript Tips And Tricks For JavaScript Developers

If you are doing lot of JavaScript programming, you might find below list of code snippets very useful. Keep it handy (bookmark it) and save it for future reference.
Here are 20 very useful JavaScript tips and tricks for you.

1. Converting JavaScript Array to CSV

First one goes like this. You have a javascript array of strings (or numbers) and you want to convert it to comma separated values (csv). We’ll below is the code snippet:
Reference: Array to CSV in JavaScript
var fruits = ['apple', 'peaches', 'oranges', 'mangoes'];
  
var str = fruits.valueOf();
  
//print str: apple,peaches,oranges,mangoes
The valueOf() method will convert an array in javascript to a comma separated string.
Now what if you want to use pipe (|) as delimeter instead of comma. You can convert a js array into a delimeted string using join() method. See below:
var fruits = ['apple', 'peaches', 'oranges', 'mangoes'];
  
var str = fruits.join("|");
  
//print str: apple|peaches|oranges|mangoes
The join() method will convert the array into a pipe separated string.

2. Convert CSV to Array in JavaScript

Now what if you want to convert a comma seprated string into a JavaScript array? We’ll there is a method for that too. You can use split() method to split a string using any token (for instance comma) and create an array.
In below example we split string str on comma (,) and create a fruitsArray array.
var str = "apple, peaches, oranges, mangoes";
  
var fruitsArray = str.split(",");
  
//print fruitsArray[0]: apple

3. Remove Array element by Index

You have an array. You want to remove a perticular element from array based on its index. We’ll you can do so using splice() method. This method can add as well as removes element from an array. We will stick to its removal usage.
Reference: Remove element by array index
function removeByIndex(arr, index) {
    arr.splice(index, 1);
}
test = new Array();
test[0] = 'Apple';
test[1] = 'Ball';
test[2] = 'Cat';
test[3] = 'Dog';
alert("Array before removing elements: "+test);
removeByIndex(test, 2);
alert("Array after removing elements: "+test);

4. Remove Array element by Value

This one is very useful. You have an array and you want to remove an element based on its value (instead of index).
Reference: Remove element by array index
function removeByValue(arr, val) {
    for(var i=0; i<arr.length; i++) {
        if(arr[i] == val) {
            arr.splice(i, 1);
            break;
        }
    }
}
var somearray = ["mon", "tue", "wed", "thur"]
removeByValue(somearray, "tue");
//somearray will now have "mon", "wed", "thur"
See how in above code we defined a method removeByValue that takes serves the purpose. In JavaScript you can define new functions to classes at runtime (although this is discourage) usingprototypes.
In below code snippet, we create a new method removeByValue() within Array class. So now you can call this method as any other arrays method.
Array.prototype.removeByValue = function(val) {
    for(var i=0; i<this.length; i++) {
        if(this[i] == val) {
            this.splice(i, 1);
            break;
        }
    }
}
//..
var somearray = ["mon", "tue", "wed", "thur"]
somearray.removeByValue("tue");
//somearray will now have "mon", "wed", "thur"

5. Calling JavaScript function from String

Sometime you want to call a Javascript method at runtime whos name you know. Let say there is a method “foo()” which you want to call at runtime. Below is a small JS snippet that helps you calling a method just by its name.
var strFun = "someFunction"; //Name of the function to be called
var strParam = "this is the parameter"; //Parameters to be passed in function
  
//Create the function
var fn = window[strFun];
  
//Call the function
fn(strParam);

6. Generate Random number from 1 to N

Below little snippet helps you in generating random number between 1 to N. Might come handy for your next JS game.
//random number from 1 to N
var random = Math.floor(Math.random() * N + 1);
//random number from 1 to 10
var random = Math.floor(Math.random() * 10 + 1);
//random number from 1 to 100
var random = Math.floor(Math.random() * 100 + 1);

7. Capture browser close button event or exiting the page in JavaScript

This is a common use case. You want to capture the browsers close event so that you can alert user if there is any unsaved data on webpage that should be saved. Below javascript snippet will help you in that.
<script language="javascript">
function fnUnloadHandler() {
       // Add your code here
       alert("Unload event.. Do something to invalidate users session..");
}
</script>
<body onbeforeunload="fnUnloadHandler()">
    <!-- Your page content -->
</body>

8. Warn user if Back is pressed

This is same as above. Difference is instead of capturing close event here we capture back button event. So that we know if user is moving awaw from this webpage.
Reference: Capture Browser Back Button
window.onbeforeunload = function() {
    return "You work will be lost.";
};

9. Check if Form is Dirty

A common usecase. You need to check if user changed anything in an HTML form. Below functionformIsDirty returns a boolean value true or false depending on weather user modified something within the form.
/**
 * Determines if a form is dirty by comparing the current value of each element
 * with its default value.
 *
 * @param {Form} form the form to be checked.
 * @return {Boolean} <code>true</code> if the form is dirty, <code>false</code>
 *                   otherwise.
 */
function formIsDirty(form) {
  for (var i = 0; i < form.elements.length; i++) {
    var element = form.elements[i];
    var type = element.type;
    if (type == "checkbox" || type == "radio") {
      if (element.checked != element.defaultChecked) {
        return true;
      }
    }
    else if (type == "hidden" || type == "password" ||
             type == "text" || type == "textarea") {
      if (element.value != element.defaultValue) {
        return true;
      }
    }
    else if (type == "select-one" || type == "select-multiple") {
      for (var j = 0; j < element.options.length; j++) {
        if (element.options[j].selected !=
            element.options[j].defaultSelected) {
          return true;
        }
      }
    }
  }
  return false;
}
window.onbeforeunload = function(e) {
  e = e || window.event; 
  if (formIsDirty(document.forms["someForm"])) {
    // For IE and Firefox
    if (e) {
      e.returnValue = "You have unsaved changes.";
    }
    // For Safari
    return "You have unsaved changes.";
  }
};

10. Disable Back button using JavaScript

This one is tricky. You want to disable the browsers back button (Dont ask me why!!). Below code snippet will let you do this. The only catch here is that you need to put this code in page where you dont want user to come back. See below reference for more details.
Reference: Disable Browsers Back Button
<SCRIPT type="text/javascript">
    window.history.forward();
    function noBack() { window.history.forward(); }
</SCRIPT>
</HEAD>
<BODY onload="noBack();"
    onpageshow="if (event.persisted) noBack();" onunload="">

11. Deleting Multiple Values From Listbox in JavaScript

You have a SELECT box. User can select multiple OPTIONS from this SELECT box and remove them. Below Javascript function selectBoxRemove let you do this. Just pass ID of SELECT object you want to remove OPTIONS in.
function selectBoxRemove(sourceID) {
  
    //get the listbox object from id.
    var src = document.getElementById(sourceID);
   
    //iterate through each option of the listbox
    for(var count= src.options.length-1; count >= 0; count--) {
  
         //if the option is selected, delete the option
        if(src.options[count].selected == true) {
   
                try {
                         src.remove(count, null);
                          
                 } catch(error) {
                          
                         src.remove(count);
                }
        }
    }
}

12. Listbox Select All/Deselect All using JavaScript

You can use below JS snippet to select/deselect all the OPTIONS from a SELECT box. Just pass the ID of select box you want to perform this operation on and also a boolean value isSelect specifying what operation you want to perform.
Reference: Select All/None using Javascript
function listboxSelectDeselect(listID, isSelect) {
    var listbox = document.getElementById(listID);
    for(var count=0; count < listbox.options.length; count++) {
            listbox.options[count].selected = isSelect;
    }
}

13. Listbox Move selected items Up / Down

This one is useful if you are playing a lot with multi options select box in your application. This function let you move select OPTIONS in a SELECT box to UP or DOWN. See below reference for more details.
Reference: Move Up/Down Selected Items in a Listbox
function listbox_move(listID, direction) {
  
    var listbox = document.getElementById(listID);
    var selIndex = listbox.selectedIndex;
  
    if(-1 == selIndex) {
        alert("Please select an option to move.");
        return;
    }
  
    var increment = -1;
    if(direction == 'up')
        increment = -1;
    else
        increment = 1;
  
    if((selIndex + increment) < 0 ||
        (selIndex + increment) > (listbox.options.length-1)) {
        return;
    }
  
    var selValue = listbox.options[selIndex].value;
    var selText = listbox.options[selIndex].text;
    listbox.options[selIndex].value = listbox.options[selIndex + increment].value
    listbox.options[selIndex].text = listbox.options[selIndex + increment].text
  
    listbox.options[selIndex + increment].value = selValue;
    listbox.options[selIndex + increment].text = selText;
  
    listbox.selectedIndex = selIndex + increment;
}
//..
//..
listbox_move('countryList', 'up'); //move up the selected option
listbox_move('countryList', 'down'); //move down the selected option

14. Listbox Move Left/Right Options

This javascript function lets you move selected OPTIONS between two SELECT boxes. Check below reference for details.
Reference: Move Options Left/Right between two SELECT boxes
function listbox_moveacross(sourceID, destID) {
    var src = document.getElementById(sourceID);
    var dest = document.getElementById(destID);
  
    for(var count=0; count < src.options.length; count++) {
  
        if(src.options[count].selected == true) {
                var option = src.options[count];
  
                var newOption = document.createElement("option");
                newOption.value = option.value;
                newOption.text = option.text;
                newOption.selected = true;
                try {
                         dest.add(newOption, null); //Standard
                         src.remove(count, null);
                 }catch(error) {
                         dest.add(newOption); // IE only
                         src.remove(count);
                 }
                count--;
        }
    }
}
//..
//..
listbox_moveacross('countryList', 'selectedCountryList');

15. Initialize JavaScript Array with series of numbers

Sometime you want to initialize a Javascript array with series of numbers. Below code snippet will let you achieve this. This will initialiaze array numbers with numbers 1 to 100.
var numbers = [];
for(var i=1; numbers.push(i++)<100;);
//numbers = [0,1,2,3 ... 100]

16. Rounding Numbers to ‘N’ Decimals

This one is quite useful. It will let you round off a number to ‘N’ decimal places. Here in below example we are rounding of a number to 2 decimal places.
var num = 2.443242342;
alert(num.toFixed(2)); // 2.44
Note that we use toFixed() method here. toFixed(n) provides n length after the decimal point; whereastoPrecision(x) provides x total length.
num = 500.2349;
result = num.toPrecision(4); // result will equal 500.2

17. Check if String contains another substring in JavaScript

Below code snippet (courtesy Stackoverflow) let you check if a given string contains another substring.
Reference: stackoverflow
if (!Array.prototype.indexOf) {
    Array.prototype.indexOf = function(obj, start) {
         for (var i = (start || 0), j = this.length; i < j; i++) {
             if (this[i] === obj) { return i; }
         }
         return -1;
    }
}
if (!String.prototype.contains) {
    String.prototype.contains = function (arg) {
        return !!~this.indexOf(arg);
    };
}
The code will add two new methods to String, indexOf and contains. Once this is done, you can use contains method to check weather a substring is present in a given string.
var hay = "a quick brown fox jumps over lazy dog";
var needle = "jumps";
alert(hay.contains(needle));

18. Remove Duplicates from JavaScript Array

Aha!! You know this one comes quite handy. Just call removeDuplicates method and pass the array, it should remove all duplicate elements from the array.
function removeDuplicates(arr) {
    var temp = {};
    for (var i = 0; i < arr.length; i++)
        temp[arr[i]] = true;
    var r = [];
    for (var k in temp)
        r.push(k);
    return r;
}
//Usage
var fruits = ['apple', 'orange', 'peach', 'apple', 'strawberry', 'orange'];
var uniquefruits = removeDuplicates(fruits);
//print uniquefruits ['apple', 'orange', 'peach', 'strawberry'];

19. Trim a String in JavaScript

Below code will add a method trim() to String which can be used to remove spaces from both sides of a string.
if (!String.prototype.trim) {
   String.prototype.trim=function() {
    return this.replace(/^\s+|\s+$/g, '');
   };
}
//usage
var str = "  some string    ";
str.trim();
//print str = "some string"

20. Redirect webpage in JavaScript

This javascript code should perform http redirect on a given URL.
window.location.href = "http://viralpatel.net";

21. Encode a URL in JavaScript

Whenever you are making an http request and passing some parameters. You should encode the URL string. Use encodeURIComponent function for encoding a url parameter.
Reference: w3scools
var myOtherUrl =
       "http://example.com/index.html?url=" + encodeURIComponent(myUrl);