Hello There, Guest!

Thread Rating:
  • 1 Vote(s) - 3 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Snippet Sharing
Hey all, this is an idea from an age old coders forum, snippet sharing.

Since many of this community show an interest in coding in one way or another, I thought it might be nice for us to help others learn (whilst also showing off our coding skills).

The idea is, you post a code comment, or hell a thread if you think it's a broader snippet. In this comment you provide a snippet of code (small section of useful code). 
The snippet should be well commented and a documentation/walk-through is always a nice touch. Any terminology that might escape some people, such as "variable", "boolean", or "ternary" might need a key to explain the meaning and function of them. Or we can make a reference thread for this.

Weather it's a simple snippet or something truly mind-bogglingly fan-dabby-dozey I'm sure someone here would appreciate seeing it. It's a great way to earn respect and reputations, so get snippet sharing, peeps!
[-] The following 3 users Like LKD70 's post:
  • Eden, MadMan YT, Voakie
Wow, great idea! I always wanted to learn coding actually, but just never seemed to understand the language. This might actually help me. Big Grin Can't wait to see others skills and or code.
[-] The following 1 user Likes Apix 's post:
  • LKD70
Here's one for people more familiar with the .NET framework and languages that rely on it, specifically in this case C#.

This is an extension of the 'RichTextBox' class that redefines 'AppendText' to include a colour option. Somewhat simple but very useful.

   // Define a class 'RichTextBoxExtensions'. Make sure to put this in yuor namespace and not in another class.
   public static class RichTextBoxExtensions
       // define the AppedText void. This accepts 'this' (RichTextBox object) which will be referred to as '
                                                // text (string type) which is the contents to append to the RichTextBox.
                                                // and colour (Color object) used to define the texts colour.
       public static void AppendText(this RichTextBox box, string text, Color colour)
            // Most of this is standard from the default RTB, assuming you're reading into this I'll imagine you know what that does...
           box.SelectionStart = box.TextLength;
           box.SelectionLength = 0;

           box.SelectionColor = colour; // Change the colour, simples.
           box.SelectionColor = box.ForeColor;
           box.ScrollToCaret(); // Also, scroll to caret (scroll to the bottom of the RichtextBox). Nice for keeping new appended text always on top ;)
[-] The following 1 user Likes LKD70 's post:
  • Apix
What is a ping? In short, the Ping is a method in networking to determine the status of connectivity between two devices. For example, I imagine you're sat at a PC now, and you have a phone next to you, if they're both on the same network, you could ping your phone from your PC to check if it's connected. Of course to do this you'd need the local IP of the phone. And to get this you'd probably go through the router or to the phone, so rather pointless, but meh. Another usage is to ping things on a larger network, like the internet. You can ping a website such as google to check if 1. the site is up and 2. you can connect to the site. 

Pretty much all (if not all) operating systems have a standard ping command in their console. For example in Windows, you can use ping from cmd like so:
These methods can be used in some coding languages too, ones that allow execution of these command line commands.

Php examples:

using cURL:

PHP Code:
//cURL method: cURL is a common cli-based lib that allows the sending/getting of files from/to a URL.
function ping($url=NULL // Define a function with one param '$url' which defaults to 'NULL' (a blank value)
                         // Functions are a way to predefine reusable code in Php (and many other langauges)
                         // This function returns a boolean type (true or false) meaning it can be used in 
                         // an 'if' without extracting any information from it...
                         // in Php this function could be called like so: echo ping("");
                         // Or, in an if like so:  if (ping("")) {} else {}
($url == NULL) return false // Check if the $url was left as "NULL" (programmer forgot to send ...
                                    // a URL into the function, perhaps?) if so, return false, as we couldn't ping.

   $ch curl_init($url);           // Initialize cURL for usage. Assign it to a variable called ($ch) this means we can
                                    // reference this curl as $ch.

   // curl_setopt is somewhat like defining rules to the cURL before executing.
   curl_setopt($chCURLOPT_TIMEOUT5);               // CURLOPT_TIMEOUT = max time allowed to load (seconds). 
   curl_setopt($chCURLOPT_CONNECTTIMEOUT5);        // CURLOPT_CONNECTTIMEOUT = max time to try to connect (seconds).
   curl_setopt($chCURLOPT_RETURNTRANSFERtrue);     // CURLOPT_RETURNTRANSFER = if true, will return output from the site
                                                       // instead of outputting it straight away.

   $data curl_exec($ch);                             // Simply execute (run) the cURL we've created in '$ch'.
   $httpcode curl_getinfo($chCURLINFO_HTTP_CODE);  // Get the HTTP code in var $httpcode, know that 404 error? That's a HTTP error code.
   curl_close($ch);                                    // Close the cURL session, memory saving is always good, tie up loose ends.

   // Return sends the information out of the function back to what ever triggered the function.
   // This will return true if the httpcode was positive (good), false if it was negative (bad).
   return ($httpcode>=200 && $httpcode<300) ? true false

Code without comments:
PHP Code:
function ping($url=NULL)
($url == NULL) return false 
   $httpcode curl_getinfo($chCURLINFO_HTTP_CODE);
($httpcode>=200 && $httpcode<300) ? true false

As I mentioned, some languages allow execution of OS commands, Php has this ability using the exec() command.
PHP Code:
$loc=""// url/ip whatever you wish to ping. Stored as a variable called $loc
exec("ping " $loc$output$result); // exec allows you to execute command line code.
                                            // in this example it will execute "ping" as if you would do so in cmd.exe
                                            // The output of this is stored in $output, this is an array (list) one line per element...
                                            // Example $output (the output I got from 'print_r($output);' ):
                                                        [0] =>
                                                        [1] => Pinging with 32 bytes of data:
                                                        [2] => Reply from bytes=32 time<1ms TTL=64
                                                        [3] => Reply from bytes=32 time<1ms TTL=64
                                                        [4] => Reply from bytes=32 time<1ms TTL=64
                                                        [5] => Reply from bytes=32 time<1ms TTL=64
                                                        [6] =>
                                                        [7] => Ping statistics for
                                                        [8] =>     Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
                                                        [9] => Approximate round trip times in milli-seconds:
                                                        [10] =>     Minimum = 0ms, Maximum = 0ms, Average = 0ms

print_r($output); // Output the example seen above. print_r is used to show a readable output from an Array. 

echo ($result==0) ? "Success" "Failed"// Ternary operator. if $result is 0, echo Success, otherwise, echo Failed. 

Here's the same code in a function that will return a boolean:
PHP Code:
function ping($url) { // Call like so: echo ping("");
exec("ping " $loc$output$result); 
   return ($result==0) ? true false;

C# Example:

public static bool PingHost(string nameOrAddress)   // Define a static boolean (function) named PingHost.
                                                           // Send in a string 'nameOrAddress'.
                                                           // Example usage: if (PingHost('')) {}
                                                           // Another example:
                           // MessageBox.Show(PingHost('') ? "Pinged Google successfully" : "Failed to ping Google")
           bool pingable = false; // Define a boolean variable called pingable. This can only be true/false.
           Ping pinger = new Ping(); // Create a new instance of the Ping class, name it pinger
                                     // This requires the ' System.Net.NetworkInformation' namespace.

           try // Try allows us to attempt code, but catch any errors that occur in it.
               PingReply reply = pinger.Send(nameOrAddress); // PingReply dataType, variable name: reply. use the
                                                             // Ping classes Send() function to send a Ping to 'nameOrAddress'.
               pingable = reply.Status == IPStatus.Success;  // Check the status attribute of the reply. if it's equal to 'IPStatus.Success'
                                                             // Then the ping was successful, save the boolean result to pingable.
           catch (PingException)                             // catch is the sub of the 'try' method, it will catch any errors thrown.
                                                             // Here we're catching specifically PingException errors, these are errors
                                                             // thrown from the Ping class.
               // Here we'll do nothing, we just added the catch so when an error occurs, it stops progressing through
               // the lines in the try {} block. Meaning pingable was never redefined (still false).
           return pingable; // return pingble out of the function.

Stripped the comments:

public static bool PingHost(string nameOrAddress)
           bool pingable = false;
           Ping pinger = new Ping();
               PingReply reply = pinger.Send(nameOrAddress);
               pingable = reply.Status == IPStatus.Success;
           catch (PingException)
               // Discard PingExceptions and return false;
           return pingable;
[-] The following 3 users Like LKD70 's post:
  • Apix , dARe, Voakie
Wow! Nice to know someone here loves coding! I, myself learn coding as well. Great idea too, good luck!
Have A Nice Day! d(・ω・)b

[-] The following 1 user Likes CantREKTMe 's post:
  • LKD70
Nice to see fellow coders around here! Where have you guys been hiding Wink
Lifetime supporter & Lifetime member for:  

Special Thanks to, @Sora & @retslac

[Image: agmalogo_a.png]
(04-26-2018, 06:57 PM)Owl Wrote: Nice to see fellow coders around here! Where have you guys been hiding Wink

They’ve been hiding in 2016!

[Image: giphy.gif] [Image: giphy.gif][Image: giphy.gif]
Well they need to be in 2018
Lifetime supporter & Lifetime member for:  

Special Thanks to, @Sora & @retslac

[Image: agmalogo_a.png]
might need a key to explain the meaning and function of them. Or we can make a reference thread for this.

Forum Jump:

Users browsing this thread: 1 Guest(s)