View Category

Check your language appears on the langref.org site

Your language name should appear within the HTML found at the http://langreg.org main page.
ruby
Net::HTTP.start(URL, 80) do |http|
status = if http.get('/').body =~ /#{SRCHEXP}/ then "offers" else "does not offer" end
puts "http:\/\/#{URL} #{status} #{LANGUAGE}"
end
java
String url = "http://langref.org/", language = "java", line = null, regexp = ".*" + url + language + ".*";

BufferedReader in = new BufferedReader(new InputStreamReader((new URL(url)).openStream()));
while ((line = in.readLine()) != null)
if (line.matches(regexp)) { System.out.printf("Language %s exists @ %s\n", language, url); break; }

in.close();
perl
# requires libwww-perl
use LWP::Simple;

if (grep /perl/, get('http://langref.org/')) {
print 'perl appears on langref.org';
} else {
print 'perl does not appear on langref.org';
}
groovy
assert new URL('http://langref.org').text.contains('groovy')
scala
val url = "http://langref.org/" ; val language = "scala" ; val srchexp = url + language;

val source = Source.fromURL(url).getLines

while (source.hasNext) if (source.next.contains(srchexp)) printf("Language %s exists @ %s\n", language, url)
python
from urllib import urlopen
print urlopen('http://langref.org').read().find('python') >= 0 and 'found' or 'not found'
cpp
HttpWebRequest^ httpReq = safe_cast<HttpWebRequest^>(WebRequest::Create(url)); httpReq->KeepAlive = false;
StreamReader^ httpStream = gcnew StreamReader(httpReq->GetResponse()->GetResponseStream());
String^ htmlPage = httpStream->ReadToEnd(); httpStream->Close();

Console::WriteLine("{0} {1} {2}", url, (htmlPage->IndexOf(url + language) > 0 ? "offers" : "does not offer"), language);
fsharp
let httpReq = (WebRequest.Create(url) :?> HttpWebRequest)
httpReq.KeepAlive <- false
let httpStream = new StreamReader(httpReq.GetResponse().GetResponseStream())
let htmlPage = httpStream.ReadToEnd()
httpStream.Close()

let offerStatus = (if (htmlPage.IndexOf(url ^ language) > 0) then "offers" ; else "does not offer")
Console.WriteLine("{0} {1} {2}", url, offerStatus, language)
erlang
URL = "http://langref.org/", Language = "erlang", Regexp = ".*" ++ URL ++ Language ++ ".*",

case http:request(URL) of
{ok, {_, _, Body}} ->
case regexp:first_match(Body, Regexp) of
{match, _, _} -> io:format("Language ~s exists @ ~s~n", [Language, URL]);
_ -> false
end;
{error, ErrorInfo} -> throw("Error: " ++ http:format_error(ErrorInfo))
end,
php
if (preg_match("/PHP/i", file_get_contents("http://langref.org/"))) {
echo "PHP appears on langref.org";
} else {
echo "PHP doesn't appear on langref.org";
}
haskell
{-# LANGUAGE OverloadedStrings #-}
import Control.Lens ((^.))
import Control.Monad (liftM)
import qualified Data.Text.Lazy as T
import qualified Data.Text.Lazy.Encoding as TL
import Network.Wreq (get, responseBody)

main = do
hasHaskell <- liftM
(\r -> (T.isInfixOf "haskell") . TL.decodeUtf8 $ r ^. responseBody)
(get "http://langref.org")

if hasHaskell then do
putStrLn "Haskell found"
else do
putStrLn "Haskell not found"
{-# LANGUAGE OverloadedStrings #-}
import Control.Monad (liftM)
import Data.Char (toLower)
import Data.List (isInfixOf)
import Network.HTTP (getRequest, getResponseBody, simpleHTTP)

main = do
hasHaskell <- liftM
(\body -> "haskell" `isInfixOf` (map toLower body))
(getResponseBody =<< simpleHTTP (getRequest "http://langref.org"))

if hasHaskell then do
putStrLn "Haskell found"
else do
putStrLn "Haskell not found"
clojure
(def *url* "http://langref.org/")
(def *lang* "clojure")

(with-open [ stream (.openStream (URL. *url*)) ]
(let [ body (str (line-seq (BufferedReader. (InputStreamReader. stream)))) ]
(str "Language " *lang* " does "
(if-not (re-matches (re-pattern (str ".*" *url* *lang* ".*")) body) "not ")
"exist")))
fantom
language := "Fantom"
url := `http://langref.org/`

response := WebClient(url).getStr
if (Regex.fromStr("\\b$language.lower\\b").matcher(response).find)
echo("Language $language appears at ${url}.")
go
resp, err := http.Get(url)
if err != nil {
fmt.Println("Error", err)
}

defer resp.Body.Close()

bodyBytes, err := ioutil.ReadAll(resp.Body)
if err != nil {
fmt.Println("Read Error", err)
}
matched, _ := regexp.Match(lang,bodyBytes)
if matched {
fmt.Println("Go is in the page")
} else {
fmt.Println("Go isn't in the page")
}

Send an email

Use library functions, classes or objects to create a short email addressed to your own email address. The subject should be, "Greetings from langref.org", and the user should be prompted for the message body, and whether to cancel or proceed with sending the email.
ruby
require 'net/smtp'
require 'webrick/utils'

body = <<END_OF_MESSAGE
This is a message from langref.org
END_OF_MESSAGE

SMTPSRV = 'smtp.somewhere.com'
USER = 'me' ; DOMAIN = 'somewhere.com' ; FROM = USER + '@' + DOMAIN
TO = 'dest@somewhereelse.com'
SUBJECT = 'Greetings from langref.org'
DATE = Time.now.rfc2822()
MSGID = '<' + WEBrick::Utils.random_string(21) + '.' + WEBrick::Utils.random_string(21) + '@' + SMTPSRV + '>'

Net::SMTP.start(SMTPSRV, 25) do |smtp|
smtp.open_message_stream(FROM, [TO]) do |msg|
msg.puts "From: #{FROM}"
msg.puts "To: #{TO}"
msg.puts "Subject: #{SUBJECT}"
msg.puts "Date: #{DATE}"
msg.puts "Message-ID: #{MSGID}"
msg.puts
msg.puts body
end
end
java
// requires Java Mail API (mail.jar), which must be in classpath
try {
Properties props = System.getProperties();
props.put("mail.smtp.host", "smtp.sampledomain.com");
Session session = Session.getDefaultInstance(props, null);
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress("gaylord.focker@hollywood.com"));
msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse("father@family.com"));
msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse("mother@family.com"));
msg.setSubject("subject");
msg.setText("message body");
msg.setHeader("X-Mailer", "jAVAmAILER");
msg.setSentDate(new Date());
Transport.send(msg);
} catch (AddressException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
}
perl
#SendSimpleEmail.pl
#
# Uses NET::SMTP to send an email to a specific email address
#Modification History
# 2009-MAR-17: GGARIEPY: [creation] (note: geoff.gariepy@gmail.com)

use strict;
use Net::SMTP; # See http://search.cpan.org/~gbarr/libnet-1.22/Net/SMTP.pm

my $smtpserver = 'some.smtp.server.fqdn.com'; # FQDN of SMTP server
my $fromaddress = 'somebody.surname@someemail.com';# Authorized user of SMTP server
my $subject = 'Greetings from langref.org'; # Subject of the message
my $recipient = 'geoff.gariepy@gmail.com'; # Recipient address
my @now;

# Prompt user for the message body to send
print "Enter the body of the message to send, then press Enter >";
my $message = <STDIN>; # String containing the body of the email

# Prompt user to see if execution should continue
print "Open connection to SMTP server [$smtpserver] to send your message? y/N [N] >";
my $yesorno = <STDIN>;
unless ($yesorno =~ /y/i ) {
print "Aborting send of message\n";
exit;
}


my $smtp = Net::SMTP->new($smtpserver, Debug => 1);# Connect to the SMTP server, and
# output diagnostics to STDOUT (DEBUG mode)

# Check to make sure connection was established; die if not.
if (!ref($smtp)) {
die("SENDMAIL: Couldn't establish session with $smtpserver! Message not sent!\n");
}

# Start the communication with the SMTP server by telling it we want
# to mail something.
$smtp->mail($fromaddress);

# Perl's NET::SMTP interface specifies the recipient(s) of the message by
# calls to the recipient method.
# Note that the method should be called once for each separate recipient
# (set up a loop to do this.)
# We're only going to do it once, however, since we only have one recipient.
$smtp->recipient($recipient);

# Figure out current date/time for the message date stamp
# Date stamp format is DD Monthname YY HH:MM:SS TIMEZONE
my @monthnames = qw(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec);
@now = gmtime(time);
for (0..$#now) {
# Make single-digit date/time elements two digits
if (length($now[$_]) lt 2) {$now[$_] = '0'.$now[$_];} # (i.e. prefix with '0')
}

# Slice off just the time and date elements we need from the output of gmtime()
my($YY, $MON, $DD, $HH, $MM, $SS) = @now[5,4,3,2,1,0];
$YY += 1900; # gmtime() epoch starts at 1900

my $monthname = $monthnames[$MON]; # Get the name of the month

# Finally build the silly date stamp!
my $datestring = "Date: $DD $monthname $YY $HH:$MM:$SS GMT";

# Tell the SMTP server we're about to send a block of message data
$smtp->data();
$smtp->datasend("$datestring"); # Give it the message date stamp
$smtp->datasend("From: $fromaddress\n"); # Send from address
$smtp->datasend("To: $recipient\n"); # Build the *display* list of 'to:' addresses
$smtp->datasend("Subject: $subject\n\n"); # Send subject delimited by two CRLFs
$smtp->datasend($message); # Send the message body
$smtp->dataend(); # Actually sends the message!!
$smtp->quit(); # Close the link to the SMTP server

__END__

groovy
// numerous libraries exist, this uses ant
// needs these jars: mailapi.jar, smtp.jar, ant-javamail.jar, ant-nodeps.jar
new AntBuilder().with {
input(message:'Message to send:', addproperty:'body')
input(message:'Send email?', validargs:'y,n,Y,N', addproperty:'confirm')
condition(property:'abort') { matches(string:'${confirm}', pattern:'n|N') }
fail(if:'abort', 'Email send aborted by user')
mail(mailhost:'smtp.gmail.com', mailport:'465', ssl:'on', user:'you@gmail.com',
subject:'Greetings from langref.org', password:'your_password'){
from(address:'you@gmail.com')
to(address:'rob@langref.org')
message('${body}')
}
}
scala
// requires Java Mail API (mail.jar), which must be in classpath

import javax.mail._
import javax.mail.internet._
import java.util.Properties._

// Get the user's message
println("Enter the text you wish to send in the message (hit Ctrl-D to finish):")
var bodyText = ""
var line = readLine
while (line != null) {
bodyText += line
line = readLine
}

// Confirm they want to send
println("Are you sure you want to send the message? [y/N]")
val yesOrNo = readLine
if (yesOrNo != "y" && yesOrNo != "Y") {
println("Aborted")
exit
}

// Set up the mail object
val properties = System.getProperties
properties.put("mail.smtp.host", "localhost")
val session = Session.getDefaultInstance(properties)
val message = new MimeMessage(session)

// Set the from, to, subject, body text
message.setFrom(new InternetAddress("test@example.org"))
message.setRecipients(Message.RecipientType.TO, "spam@mopoke.co.uk")
message.setSubject("Greetings from langref.org")
message.setText(bodyText)

// And send it
Transport.send(message)
Need a code t send email from smtp server in scala
python
import smtplib
import locale

from email.mime.text import MIMEText

encoding = locale.getpreferredencoding()

def main():
smtp_servername = "smtp.example.com"

from_addr = "ernie@example.com"
to_addr = "cookie.monster@mailinator.com"

body = raw_input("Enter the email message ")
if not raw_input("Send email? y/N ") in ["y", "Y"]:
print "aborting"
return

message = MIMEText(body, _charset=encoding)

message["From"] = from_addr
message["To"] = to_addr
message["Subject"] = "Greetings from langref.org"

server = smtplib.SMTP(smtp_servername)
server.sendmail(from_addr, to_addr, message.as_string())


if __name__ == "__main__":
main()
fsharp
open System
open System.Net
open System.Net.Mail
open System.Net.Mime

let subject = "Greetings from langref.org"
let from = "username@gmail.com"
let destination = "username@gmail.com"

printfn "Write mail body (press 'Enter' when finished):"
let mutable body = Console.ReadLine()
if body = null || body.Length = 0 then
body <- "Hello World"

let mail = new MailMessage(from, destination, subject, body)

let smtpHost = "smtp.gmail.com"
let clientCredentials = new NetworkCredential("username@gmail.com", "password")
let smtpClient = new SmtpClient(smtpHost,587)
smtpClient.EnableSsl <- true
smtpClient.UseDefaultCredentials <- false
smtpClient.Credentials <- clientCredentials

printfn "Send email? y/n"
match Console.ReadLine() with
| "y" -> smtpClient.Send(mail);mail.Dispose();printfn "email delivered"
| "n" -> smtpClient.Dispose()
| _ -> smtpClient.Dispose()
ocaml
(* Using the library smtp-mail-0.1.3:
http://www.linux-nantes.org/%7Efmonnier/OCaml/smtp-mail/ *)

let () =
let h = Smtp.connect "smtp.example.com" in
Smtp.helo h "hostname";
Smtp.mail h "<john.smith@example.com>";
Smtp.rcpt h "<jane.smith@example.com>";
let email_header = "\
From: John Smith <john.smith@example.com>\r\n\
To: Jane Smith <jane.smith@example.com>\r\n\
Subject: Greetings from langref.org" in
let email_msg = "Hi,\n\nHow are you?" in
Smtp.data h (email_header ^ "\r\n\r\n" ^ email_msg);
Smtp.quit h;
;;
php
/* This is a version without any prompt – use it for a website */
$to = "mail@domain.tld";
$subject = "Greetings from langref.org";
$body = "Hi,\n\nHow are you?";
$headers = "From: sender@domain.tld\n"; // you can comment this out and delete it from below
if (mail($to, $subject, $body, $headers)) {
echo "Success";
}

/****
* For some (security)reason I couldn't
* submit this without adding a space to
* the functionnames. Please remove it :)
* in this case, only "f write" and "f gets"
****/

$to = "mail@domain.tld";
f write(STDOUT, "Mail: ".$to."\n");
$subject = "Greetings from langref.org";
f write(STDOUT, "Subject: ".$subject."\n");
f write(STDOUT, "Please type the body. Use \\n for newlines: \n");
$body = trim(f gets(STDIN)); // we get input
if ($body == "") { // if empty input
$body = "Hi! How are you?";
f write(STDOUT, "Using standard body: ".$body."\n");
}
f write(STDOUT, "Would you like to send the mail? [y/n]: ");
if (trim(f gets(STDIN)) == "y") {
if (mail($to, $subject, $body)) {
f write(STDOUT, "Success\n");
} else { // fallback
f write(STDOUT, "Failed to mail\n");
}
} else { // fallback
f write(STDOUT, "I'm sorry :(\n");
}
haskell
-- cabal install smtp-mail

host = "gmail.google.com"

from = Address Nothing "email@domain.com"
to = [Address (Just "John Doe") "email@domain.com"]
cc = []
bcc = []
subject = "Greetings from langref.org"

mail body = simpleMail from to cc bcc subject [body]

main = getContents >>= sendMail host mail
-- cabal install smtp-mail

import Network.Mail.SMTP
import qualified Data.Text as T
import qualified Data.Text.Lazy as L

host = "smtp.example.com"

from = Address Nothing (T.pack "toto@example.com")
to = [Address Nothing (T.pack "jdoe@domain.com")]
cc = []
bcc = []
subject = T.pack "Greetings from langref.org"

mail body = simpleMail from to cc bcc subject [plainTextPart (L.pack body)]

main = getContents >>= (sendMail host . mail)
fantom
// read message body
echo("Enter message body. End the message with '.' character on a separate line:")
in := Env.cur.in
buf := StrBuf()
line := in.readLine;
while (line != null)
{
if (line.trim == ".")
break;
buf.add(line)
line = in.readLine
}

// construct email
email := Email
{
to = [ "someone@somewhere" ]
from = "me@mydomain"
subject = "Greetings from langref.org"
body = TextPart { text = buf.toStr }
}
mailClient := SmtpClient
{
host = "smtp.somewhere.net"
username = "me"
password = "my password"
log.level = LogLevel.debug
}

// send or abort
echo("Send email '$email.subject' to $email.to?: ");
line = in.readLine
echo("response=$line")
if (line?.trim.compareIgnoreCase("y") == 0)
mailClient.send(email)
else
echo("Aborted!")