Я тестировал это только для прямоугольных координат, но я думаю, что он должен обобщать на круглые или многоугольники
function wrap ( img, map ) {
var originalCoords = [ ],
test = new Image();
for ( var i = 0; i < map.areas.length; ++i ) {
var coords = map.areas[i].coords;
originalCoords.push( coords.split( "," ).map( parseFloat ) );
}
function resize () {
var ratio = img.width / test.width;
for ( var i = 0; i < map.areas.length; ++i ) {
map.areas[i].coords = originalCoords[i].map( function ( n ) {
return ratio * n;
} ).join( "," );
}
}
test.addEventListener( "load", function () {
window.addEventListener( "resize", resize, false );
resize();
}, false );
test.src = img.src;
}
var imgs = document.querySelectorAll( "img[usemap]" );
for ( var i = 0; i < imgs.length; ++i ) {
var map = document.querySelector( "map[name=" + imgs[i].useMap.substring( 1 ) + "]" );
wrap( imgs[i], map );
}
Я получил отличный отклик от моих детей с быстрым сценарием VB для управления персонажем Microsoft Agent. Для тех, кто не знаком с MS Agent, это серия анимированных экранных персонажей, которыми можно управлять через COM-интерфейс. Вы можете загрузить код и символы на странице загрузки Microsoft Agent .
Следующие несколько строк заставят персонажа Мерлина появляться на экране, летать, стучать по экрану, чтобы привлечь ваше внимание, и говорить привет.
agentName = "Merlin"
agentPath = "c:\windows\msagent\chars\" & agentName & ".acs"
Set agent = CreateObject("Agent.Control.2")
agent.Connected = TRUE
agent.Characters.Load agentName, agentPath
Set character = agent.Characters.Character(agentName)
character.Show
character.MoveTo 500, 400
character.Play "GetAttention"
character.Speak "Hello, how are you?"
Wscript.Sleep 15000
character.Stop
character.Play "Hide"
Вы можете использовать множество других команд. Для получения дополнительной информации см. http://www.microsoft.com/technet/scriptcenter/funzone/agent.mspx .
ИЗМЕНИТЬ 2011-09-02 Недавно я обнаружил, что Microsoft Agent изначально не установлен в Windows 7. Однако он предлагается как отдельная загрузка здесь . Я не проверял это, поэтому не могу проверить, работает ли он.
Я помню, когда я только начинал циклы кодирования, это всегда меня поражало. Вы пишете от 5 до 10 строк кода (или меньше) и распечатываются сотни (или сколько бы вы ни указали) строк. (Я изучил сначала на PHP и Java).
for( int i = 0; i < 200; i++ )
{
System.out.println( i );
}
In this day and age, JavaScript is an excellent way to show how you can program using some really basic tools e.g. notepad.
jQuery effects are great starting point for anyone wanting to wow their friends!
In this one, just click the white space of the page.
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script>
$(document.body).click(function () {
if ($("#pic").is(":hidden")) {
$("#pic").slideDown("slow");
} else {
$("#pic").slideUp();
}
});
</script>
</head>
<body><img id="pic" src="http://www.smidgy.com/smidgy/images/2007/07/26/lol_cat_icanhascheezburger.jpg"/>
</body>
</html>
Как и большинство других комментаторов, Я начал писать код для решения математических задач (или для создания графики для действительно ужасных игр, которые я бы разрабатывал - например, «Индиана Джонс против зомби»).
То, что действительно меня поразило (как в математике, так и в программировании), исходило из текста на основе, выберите свои собственные игры в стиле приключений ... для более графических игр. Я начал раскрашивать графическую бумагу и рисовать пиксели, пока не попал в геометрию ... и обнаружил, как использовать уравнения для построения кривых и линий, прямоугольников и т. Д.
Суть в том, что я мог бы получить действительно ] попал во что-то вроде обработки ( http: // processing.
One thing you might consider is something like Robocode, in which a lot of coding is abstracted away and you basically just tell a robot what to do. A simple 10-line function can make the robot do a great deal, and has a very visual and easy-to-follow result.
Perhaps Robocode itself isn't suited to the task, but this kind of thing is a good way to relate written code to visual actions on the computer, plus it's fun to watch for when you need to give examples.
public class MyFirstJuniorRobot extends JuniorRobot {
public void run() {
setColors(green, black, blue);
// Seesaw forever
while (true) {
ahead(100); // Move ahead 100
turnGunRight(360); // Spin gun around
back(100); // Move back 100
turnGunRight(360); // Spin gun around
}
}
public void onScannedRobot() {
turnGunTo(scannedAngle);
fire(1);
}
public void onHitByBullet() {
turnAheadLeft(100, 90 - hitByBulletBearing);
}
}
Вы может использовать сценарий, написанный с помощью AutoIt , который стирает грань между использованием традиционного приложения и программированием.
Например, сценарий, который открывает блокнот и заставляет их собственный компьютер оскорблять их в нем и через окно сообщения, и затем не оставляет никаких следов своих действий:
Run("notepad.exe")
WinWaitActive("Untitled - Notepad")
Send("You smell of human.")
Sleep(10000)
MsgBox(0, "Humans smell bad", "Yuck!")
WinClose("Untitled - Notepad")
WinWaitActive("Notepad", "Do you want to save")
Send("!n")
This is cheating, and not even remotely simple, but I once wrote a shoot'em up in 20 lines of C++, using the Allegro graphics library. No real criteria for what a line was, but it was a bit ago, and it was made purely for fun. It even had crude sound effects.
Here's what it looked like:
20 Lines http://img227.imageshack.us/img227/8770/20linesxx0.png
And here's the code (should compile):
bool inside(int x, int y, int x2, int y2) { return (x>x2&&x<x2+20&&y>y2&&y<y2+10); }
int main() {
BITMAP* buffer;
float px,shotx,shoty,monstars[8],first,rnd,pressed,points = 0, maxp = 0;
unsigned char midi[5] = {0xC0,127,0x90,25,0x54}, plgfx[] = {0,0,0,10,3,10,3,5,6,5,6,10,8,12,10,10,10,5,13,5,13,10,16,10,16,0,13,0,13,2,3,2,3,0,0,0}, mongfx[] = {0,0, 10,5, 20,0, 17,8, 15,6, 10,16, 5,6, 3,8, 0,0};
allegro_init(), set_color_depth(32), set_gfx_mode(GFX_AUTODETECT_WINDOWED,320,240,0,0), install_timer(), install_keyboard(), install_mouse(), buffer = create_bitmap(320,240),srand(time(NULL)),install_sound(DIGI_AUTODETECT, MIDI_AUTODETECT,""),clear_to_color(buffer,makecol32(100,100,255));
while ((pressed=(!key[KEY_Z]&&pressed)?0:pressed)?1:1&&(((shoty=key[KEY_Z]&&shoty<0&&pressed==0?(pressed=1?200:200):first==0?-1:shoty)==200?shotx=px+9:0)==9999?1:1) && 1+(px += key[KEY_LEFT]?-0.1:0 + key[KEY_RIGHT]?0.1:0) && 1+int(px=(px<0?0:(px>228?228:px))) && !key[KEY_ESC]) {
rectfill(buffer,0,0,244,240,makecol32(0,0,0));
for(int i=0;i<8;i++) if (inside(shotx,shoty,i*32,monstars[i])) midi_out(midi,5);
for (int i=0; i<8; monstars[i] += first++>8?(monstars[i]==-100?0:0.02):-100, points = monstars[i]>240?points-1:points, monstars[i]=monstars[i]>240?-100:monstars[i], points = inside(shotx,shoty,i*32,monstars[i])?points+1:points, (monstars[i] = inside(shotx,shoty,i*32,monstars[i])?shoty=-1?-100:-100:monstars[i]), maxp = maxp>points?maxp:points, i++) for (int j=1; j<9; j++) line(buffer,i*32+mongfx[j*2 - 2],monstars[i]+mongfx[j*2-1],i*32+mongfx[j*2],monstars[i]+mongfx[j*2+1],makecol32(255,0,0));
if (int(first)%2000 == 0 && int(rnd=float(rand()%8))) monstars[int(rnd)] = monstars[int(rnd)]==-100?-20:monstars[int(rnd)]; // randomowe pojawianie potworkow
if (shoty>0) rectfill(buffer,shotx,shoty-=0.1,shotx+2,shoty+2,makecol32(0,255,255)); // rysowanie strzalu
for (int i=1; i<18; i++) line(buffer,px+plgfx[i*2 - 2],200-plgfx[i*2-1],px+plgfx[i*2],200-plgfx[i*2+1],makecol32(255,255,0));
textprintf_ex(buffer,font,250,10,makecol32(255,255,255),makecol32(100,100,255),"$: %i ",int(points)*10);
textprintf_ex(buffer,font,250,20,makecol32(255,255,255),makecol32(100,100,255),"$$ %i ",int(maxp)*10);
blit(buffer, screen, 0, 0, 0, 0, 320,240);
}
} END_OF_MAIN()
Как насчет того, чтобы показать, что вы можете взять любой веб-браузер и ввести JavaScript в адресную строку и получить код для выполнения?
РЕДАКТИРОВАТЬ: перейдите на страницу с большим количеством изображений и попробуйте это в адресная строка:
javascript:R=0; x1=.1; y1=.05; x2=.25; y2=.24; x3=1.6; y3=.24; x4=300; y4=200; x5=300; y5=200; DI=document.images; DIL=DI.length; function A(){for(i=0; i<DIL; i++){DIS=DI[ i ].style; DIS.position='absolute'; DIS.left=Math.sin(R*x1+i*x2+x3)*x4+x5; DIS.top=Math.cos(R*y1+i*y2+y3)*y4+y5}R++ }setInterval('A()',5); void(0)
Back in computer class in high school, myself and a couple of friends taught the class how to program with Delphi. The class was mostly focused on programming with Pascal, so Delphi was a good next step. We demonstrated the event driven nature of Delphi and its RAD capabilities. At the end of the lesson we showed the class a sample application and asked them to reproduce it. The application asked "Are you drunk?" with two buttons Yes and No. ...I think you know what is coming next...the No button changed locations on mouse over and was almost impossible to click.
The students and teacher got a good kick out of it.
The program only required a few lines of user-written code with a simple equation to calculate where to move the button. I don't think any of the other students figured it out, but a few were close.
I've found a big favorite (in GWBASIC) is:
10 input "What is your name ";N$
20 i = int(rnd * 2)
30 if i = 0 print "Hello ";N$;". You are a <fill in insult number 1>"
40 if i = 1 print "Hello ";N$;". You are a <fill in insult number 2>"
I've found beginning students have a few conceptions that need to be fixed.
Good luck with your class. I'm sure you'll do well.
P.S. I'm sure you understand that, along with material and skill, you're also teaching an attitude, and that is just as important.
Я думаю, что в наши дни трудно быть компьютерным педагогом. Я. Мы сталкиваемся со все более и более крутым тяжелым сражением. Наши студенты невероятно искушенные пользователи , и для их впечатления требуется много времени. У них так много доступных инструментов, которые делают удивительные вещи.
Простой калькулятор из 10 строк кода? Почему? Для этого у меня есть TI-86.
Сценарий, который применяет специальные эффекты к изображению? Для этого и нужен Photoshop. А Photoshop сметает все, что вы можете сделать в 10 строк.
Как насчет копирования CD и преобразования файла в MP3? У меня уже есть 50 000 песен, которые я получил от BitTorrent. Они уже в формате MP3. Я играю их на своем iPhone. Кто в любом случае покупает компакт-диски?
Чтобы познакомить опытных пользователей с программированием, вам нужно найти что-то, что ' б) делает то, что они уже не могут.
Предположим, у ваших учеников уже есть доступ к самому дорогому программному обеспечению. Многие из них имеют полную версию Adobe CS5.5 (розничная цена: 2600 долларов США; фактическая цена: бесплатно) и могут легко получить любое приложение, которое обычно нарушало бы бюджет вашего отдела.
Но подавляющее большинство из них даже не подозревают как на самом деле работает любой из этих «компьютерных штучек».
Они невероятно креативны: им нравится создавать вещи. Они просто хотят иметь возможность делать или делать то, чего не могут их друзья. Они хотят чем-то похвастаться.
Вот некоторые вещи, которые я нашел, чтобы найти отклик у моих учеников:
Ни одна из них не связана с программированием в традиционный смысл Но они используют мощные библиотеки. Я думаю о них как о другом виде программирования.
картографирование и визуализация. Готовые виджеты в виде коллажей могут быть встроены в веб-страницы.Ни одна из них не связана с программированием в традиционный смысл Но они используют мощные библиотеки. Я думаю о них как о другом виде программирования.
картографирование и визуализация. Готовые виджеты в виде коллажей могут быть встроены в веб-страницы.Ни одна из них не связана с программированием в традиционный смысл Но они используют мощные библиотеки. Я думаю о них как о другом виде программирования.
С помощью простой в использовании среды трехмерного программирования, такой как Алиса , легко создавать высококачественные, увлекательные истории, используя не что иное, как перетаскивание.программирование в традиционном смысле. Но они используют мощные библиотеки. Я думаю о них как о другом виде программирования.
С помощью простой в использовании среды трехмерного программирования, такой как Алиса , легко создавать высококачественные, увлекательные истории, используя не что иное, как перетаскивание.программирование в традиционном смысле. Но они используют мощные библиотеки. Я думаю о них как о другом виде программирования.
Хорошо, это 15 строк кода, но результат потрясающий! Это то, что заставляло меня волноваться, когда я был ребенком. Это из руководства по PHP:
$x = 200;
$y = 200;
$gd = imagecreatetruecolor($x, $y);
$corners[0] = array('x' => 100, 'y' => 10);
$corners[1] = array('x' => 0, 'y' => 190);
$corners[2] = array('x' => 200, 'y' => 190);
$red = imagecolorallocate($gd, 255, 0, 0);
for ($i = 0; $i < 100000; $i++) {
imagesetpixel($gd, round($x),round($y), $red);
$a = rand(0, 2);
$x = ($x + $corners[$a]['x']) / 2;
$y = ($y + $corners[$a]['y']) / 2;
}
header('Content-Type: image/png');
imagepng($gd);
Microsoft имеет Small Basic , IDE для "детей".
pic = Flickr.GetRandomPicture("beach")
Desktop.SetWallpaper(pic)
Он специально разработан, чтобы показать, насколько классным является программирование.
This is a Python telnet server that will ask for the users name and say hello to them. This looks cool because you are communicating with your program from a different computer over the network.
from socket import *
s=socket(AF_INET, SOCK_STREAM)
s.bind(("", 3333))
s.listen(5)
while 1:
(c, a) = s.accept()
c.send("What is your name? ")
name = c.recv(100)
c.send("Hello "+name)
c.close()
Вы можете сделать приложение, которое выбирает случайное число. И ты должен угадать это. Если вы ошибаетесь, он говорит: выше или ниже. И если вы догадались, приятное сообщение.
Классно играть для студентов.
Простая версия Python без надлежащей проверки ошибок:
import random
while input('Want to play higher/lower? ').lower().startswith('y'):
n = random.randint(1, 100)
g = int(input('Guess: '))
while g != n:
print(' %ser!' % (g > n and 'low' or 'high'))
g = int(input('Guess: '))
print(' Correct! Congratulations!')
Эрик предлагает, чтобы компьютер угадал число. Это также может быть сделано в пределах 10 строк кода (хотя в настоящее время отсутствие надлежащей проверки ошибок еще более серьезно: допустимые числа вне диапазона вызывают бесконечный цикл):
while input('Want to let the pc play higher/lower? ').lower().startswith('y'):
n = int(input('Give a number between 1 and 100: '))
lo, hi, guess, tries = 1, 100, 50, 1
while guess != n:
tries += 1
lo, hi = (guess + 1, hi) if guess < n else (lo, guess - 1)
guess = (lo + hi) // 2
print('Computer guessed number in %d tries' % tries)
How about a bookmarklet? It would show them how to manipulate something that they use every day (the Internet) without requiring any development tools.
Когда я впервые написал это.
10 PRINT "What is your name?"
20 INPUT A$
30 PRINT "Hello " A$
40 GOTO 30
Это взорвало людей! Компьютер запомнил их имя!
РЕДАКТИРОВАТЬ: Просто чтобы добавить к этому. Если вы сможете убедить нового программиста, это самая крутая вещь, которую они могут сделать, они станут хорошими программистами. В наши дни вы можете делать практически все, что захотите, с помощью одной строки кода для запуска библиотеки, написанной кем-то другим. Лично я не получаю абсолютно никакого удовлетворения от этого и вижу небольшую пользу в обучении этому.
Это очень элементарная текстовая программа на c #, которая имитирует вращательное действие игрового автомата. Он не включает в себя различные шансы на выигрыш или денежные выплаты, но это может быть хорошим упражнением для студентов.
Извините, что это более 10 строк.
string[] symbols = new[] { "#", "?", "~" }; // The symbols on the reel
Random rand = new Random();
do
{
string a="",b="",c="";
for( int i = 0; i < 20; i++ )
{
Thread.Sleep( 50 + 25 * i ); // slow down more the longer the loop runs
if( i < 10 )
a = symbols[rand.Next( 0, symbols.Length )];
if( i < 15 )
b = symbols[rand.Next( 0, symbols.Length )];
c = symbols[rand.Next( 0, symbols.Length )];
Console.Clear();
Console.WriteLine( "Spin: " + a + b + c );
}
if( a == b && b == c )
Console.WriteLine( "You win. Press enter to play again or type \"exit\" to exit" );
else
Console.WriteLine( "You lose. Press enter to play again or type \"exit\" to exit" );
}
while( Console.ReadLine() != "exit" );
Интересно, что вы упомянули множество Мандельброта, поскольку создание фракталов с помощью GW-BASIC - это то, что пробудило мою любовь к программированию в старшей школе (примерно в 1993 году). Прежде чем мы начали изучать фракталы, мы написали скучные приложения со стандартными отклонениями, и я все еще планировал заняться журналистикой.
Но как только я увидел, что длинная, трудная для написания BASIC-программа генерирует «фрактальную местность», меня зацепили, и я никогда не оглядывался назад. Это изменило мой взгляд на математику, науку, компьютеры и способ обучения.
Надеюсь, вы найдете программу, которая оказывает такое же влияние на ваших учеников.
I'm sure it'd turn into more than 10 lines of code, but have you considered a form based app where pressing the buttons does things like changing the colour of the background or changes the size of the text? This would show them how interactive programs work. It would also show them that they, as programmer, are in complete control of what the computer (program) does.
Hopefully it would lead them to make suggestions for other things they could change and then onto other things they might want to do.
If you can afford the hardware, using an Arduino board + processing will produce some pretty cool things, though it may be a little advanced for people that may not be interested at all in programming.
С Tcl у вас есть простой текстовый редактор с кнопкой сохранения в примерно 12 строках кода (но без открытия, который занял бы еще 8 строк). Он работает на всех стандартных платформах:
pack [frame .toolbar] -side top -fill x
pack [button .save -text save -command save] -in .toolbar -side left
pack [scrollbar .vsb -orient vertical -command [list .text yview]] -side right -fill y
pack [text .text -wrap word -yscrollcommand [list .vsb set]] -side left -fill both -expand true
proc save {} {
set filename [tk_getSaveFile]
if {$filename ne ""} {
set f [open $filename w]
puts $f [.text get 1.0 end-1c]
close $f
}
}
Я понимаю, что цель была в 10 строк, поэтому, если вы хотите, чтобы придерживались 10 или менее строк, простой текстовый редактор без загрузки или сохранения - это всего две строки. Это не так уж и плохо.
pack [scrollbar .vsb -orient vertical -command [list .text yview]] -side left -fill y
pack [text .text -wrap word -yscrollcommand [list .vsb set]] -side left -fill both -expand true
Выполните любой из вышеперечисленных блоков кода с «wish filename » на выбранной вами платформе. Желание приходит с большинством * nix и Mac, но вам придется установить его вручную для Windows.
Чтобы продвинуться дальше, этот двухстрочный сценарий также может быть написан на python, хотя он занимает восемь строк, все еще под 10-строчной целью:
from Tkinter import *
root=Tk()
text = Text(wrap="word")
sb = Scrollbar(orient="vertical", command=text.yview)
text.configure(yscrollcommand=sb.set)
sb.pack(side="right", fill="y")
text.pack(side="left", fill="both", expand=True)
root.mainloop()
Я думаю, что хорошим местом для начала обучения может быть Greasemonkey . На userscripts.org есть тысячи примеров сценариев, очень хороший материал для чтения, некоторые из которых очень маленькие. Скрипты Greasemonkey влияют на веб-страницы, с которыми студенты уже знакомы, если не манипулируют ими. Greasemonkey сам по себе предлагает очень простой способ редактировать и включать / отключать скрипты во время тестирования.
В качестве примера, вот скрипт «Два столбца Google»:
result2 = '<table width="100%" align="center" cellpadding="10" style="font-size:12px">';
gEntry = document.evaluate("//li[@class='g'] | //div[@class='g'] | //li[@class='g w0'] | //li[@class='g s w0']",document,null,XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE,null);
for (var i = 0; i < gEntry.snapshotLength; i++) {
if (i==0) { var sDiv = gEntry.snapshotItem(i).parentNode.parentNode; }
if(i%2 == 0) { result2 += '<tr><td width="50%" valign="top">'+gEntry.snapshotItem(i).innerHTML+'</td>'; }
if(i%2 == 1) { result2 += '<td width="50%" valign="top">'+gEntry.snapshotItem(i).innerHTML+'</td></tr>'; }
}
sDiv.innerHTML = result2+'</table>';
if (document.getElementById('mbEnd') !== null) { document.getElementById('mbEnd').style.display = 'none'; }
Я склонен думать, что люди впечатлены вещами, к которым они могут относиться или которые имеют отношение к их жизни. Я бы попытался основать свои 10 строк кода на том, что они знают и понимают. Взять, к примеру, Twitter и его API. Почему бы не использовать этот API для создания чего-то классного. Следующие 10 строк кода вернут «общедоступную временную шкалу» из Twitter и отобразят ее в консольном приложении ...
using (var xmlr = XmlReader.Create("http://twitter.com/statuses/public_timeline.rss"))
{
SyndicationFeed
.Load(xmlr)
.GetRss20Formatter()
.Feed
.Items
.ToList()
.ForEach( x => Console.WriteLine(x.Title.Text));
}
Мой пример кода может быть не лучшим для ваших студентов. Он написан на C # и использует .NET 3.5. Так что, если вы собираетесь учить их PHP, Java или C ++, это будет бесполезно. Тем не менее, я хочу сказать, что, связывая ваши 10 строк кода с чем-то «крутым, интересным и актуальным для студентов», ваш образец также становится крутым, интересным и актуальным.
Удачи!
[Да, я знаю, что пропустил несколько строк использования операторов и метода Main, но я предполагаю, что эти 10 строк не должны были быть буквально 10 строками]
Введите этот код в адресную строку (в браузере) и нажмите клавишу ввода.
Когда я впервые подумал я подумал, что это действительно мило. Такой простой, но изящный в том, что он может делать:
:(){ :|:& };:
So one day, I decided that I'd had enough. I would learn piano. Seeing people like Elton John command such mastery of the keyboard assured me that this was what I wanted to do.
Actually learning piano was a huge letdown. Even after completing eight grades of piano lessons, I was still not impressed with how my mental image of playing piano was so different from my original vision of enjoying the activity.
However, what I thoroughly enjoyed was my mere three grades of rudiments of music theory. I learned about the construction of music. I was finally able to step from the world of performing written music to writing my own music. Subsequently, I was able to start playing what I wanted to play.
Don't try to dazzle new programmers, especially young programmers. The whole notion of "less than ten lines of simple code" seems to elicit a mood of "Show me something clever".
You can show a new programmer something clever. You can then teach that same programmer how to replicate this "performance". But this is not what gets them hooked on programming. Teach them the rudiments, and let them synthesize their own clever ten lines of code.
I would show a new programmer the following Python code:
input = open("input.txt", "r")
output = open("output.txt", "w")
for line in input:
edited_line = line
edited_line = edited_line.replace("EDTA", "ethylenediaminetetraacetic acid")
edited_line = edited_line.replace("ATP", "adenosine triphosphate")
output.write(edited_line)
I realize that I don't need to assign line
to edited_line
. However, that's just to keep things clear, and to show that I'm not editing the original document.
In less than ten lines, I've verbosified a document. Of course, also be sure to show the new programmer all the string methods that are available. More importantly, I've showed three fundamentally interesting things I can do: variable assignment, a loop, file IO, and use of the standard library.
I think you'll agree that this code doesn't dazzle. In fact, it's a little boring. No - actually, it's very boring. But show that code to a new programmer and see if that programmer can't repurpose every part of that script to something much more interesting within the week, if not the day. Sure, it'll be distasteful to you (maybe using this script to make a simple HTML parser), but everything else just takes time and experience.
Я недавно писал об этом в статье «Самая короткая, самая полезная программа, которую я когда-либо писал».
Резюме: я написал 3-строчное приложение VB6 еще в 1996 году, которое Я до сих пор использую каждый божий день. После того, как exe закинулся в папку «Отправить». Он позволяет вам щелкнуть правой кнопкой мыши файл в проводнике и отправить полный путь к этому файлу в буфер обмена.
Public Sub Main()
Clipboard.SetText Command$
End Sub
import wx
app = wx.App()
wx.Frame(None, -1, 'simple.py').Show()
app.MainLoop()
simple.py frame http://zetcode.com/wxpython/images/simple.jpg[12111 impression
Этот C-код может быть запутан, но я нашел его очень мощным
#include <unistd.h>
float o=0.075,h=1.5,T,r,O,l,I;int _,L=80,s=3200;main(){for(;s%L||
(h-=o,T= -2),s;4 -(r=O*O)<(l=I*I)|++ _==L&&write(1,(--s%L?_<L?--_
%6:6:7)+"World! \n",1)&&(O=I=l=_=r=0,T+=o /2))O=I*2*O+h,I=l+T-r;}
И вот результат ... Всего в 3 строках ...
Своего рода фрактал Hello World
...
WWWWWWWWWWWWWWWWooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
WWWWWWWWWWWWWWooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
WWWWWWWWWWWWWooooooooooooooooorrrrrrrrrrrrrrrrrrrrroooooooooooooooooooooooooooo
WWWWWWWWWWWoooooooooooorrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrooooooooooooooooooooo
WWWWWWWWWWooooooooorrrrrrrrrrrrrrrrrrrrrrrllllld!!ddllllrrrrrrooooooooooooooooo
WWWWWWWWoooooooorrrrrrrrrrrrrrrrrrrrrrllllllldd!oWW!!dllllllrrrrroooooooooooooo
WWWWWWWoooooorrrrrrrrrrrrrrrrrrrrrrlllllllldddd!orro!o!dllllllrrrrrrooooooooooo
WWWWWWooooorrrrrrrrrrrrrrrrrrrrrllllllllldddd!WorddddoW!ddllllllrrrrrrooooooooo
WWWWWoooorrrrrrrrrrrrrrrrrrrrrlllllllllddd!!!o!!! !dWW!ddddllllrrrrrrrooooooo
WWWWooorrrrrrrrrrrrrrrrrrrrllllllllldd!!!!WWWoo WloW!!!ddddllrrrrrrrrooooo
WWWWoorrrrrrrrrrrrrrrrrrrlllllllddddWldolrrlo!Wl r!dlooWWWoW!dllrrrrrrroooo
WWWoorrrrrrrrrrrrrrrrrlllllddddddd!!Wdo l! rdo!l!r!dlrrrrrrrrooo
WWoorrrrrrrrrrrrrrrlllddddddddd!!!!oolWW lW!ddlrrrrrrrroo
WWorrrrrrrrrrrrllld!!!!!dddd!!!!WWrd ! rlW!ddllrrrrrrrro
Worrrrrrrllllllddd!oooWWWoloWWWWoodr drrWdlllrrrrrrrr
Worrrlllllllldddd!WolWrr!!dWWWlrrldr ro!dlllrrrrrrrr
Wrrllllllllddddd!WWolWr oWoo r!dllllrrrrrrr
Wlllllllldddd!!odrrdW o lWddllllrrrrrrr
Wlddddd!!!!!WWordlWrd oW!ddllllrrrrrrr
olddddd!!!!!WWordlWrd oW!ddllllrrrrrrr
Wlllllllldddd!!odrrdW o lWddllllrrrrrrr
Wrrllllllllddddd!WWolWr oWoo r!dllllrrrrrrr
Worrrlllllllldddd!WolWrr!!dWWWlrrldr ro!dlllrrrrrrrr
Worrrrrrrllllllddd!oooWWWoloWWWWoodr droWdlllrrrrrrrr
WWorrrrrrrrrrrrllld!!!!!dddd!!!!WWrd ! rlW!ddllrrrrrrrro
WWoorrrrrrrrrrrrrrrlllddddddddd!!!!oolWW lW!ddlrrrrrrrroo
WWWoorrrrrrrrrrrrrrrrrlllllddddddd!!Wdo l! rdo!l!r!dlrrrrrrrrooo
WWWWoorrrrrrrrrrrrrrrrrrrlllllllddddWldolrrlo!Wl r!dlooWWWoW!dllrrrrrrroooo
WWWWooorrrrrrrrrrrrrrrrrrrrllllllllldd!!!!WWWoo WloW!!!ddddllrrrrrrrrooooo
WWWWWoooorrrrrrrrrrrrrrrrrrrrrlllllllllddd!!!o!!! WdWW!ddddllllrrrrrrrooooooo
WWWWWWooooorrrrrrrrrrrrrrrrrrrrrllllllllldddd!WorddddoW!ddllllllrrrrrrooooooooo
WWWWWWWoooooorrrrrrrrrrrrrrrrrrrrrrlllllllldddd!orro!o!dllllllrrrrrrooooooooooo
WWWWWWWWoooooooorrrrrrrrrrrrrrrrrrrrrrllllllldd!oWW!!dllllllrrrrroooooooooooooo
WWWWWWWWWWooooooooorrrrrrrrrrrrrrrrrrrrrrrllllld!!ddllllrrrrrrooooooooooooooooo
WWWWWWWWWWWoooooooooooorrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrooooooooooooooooooooo
WWWWWWWWWWWWWooooooooooooooooorrrrrrrrrrrrrrrrrrrrroooooooooooooooooooooooooooo
WWWWWWWWWWWWWWooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
WWWWWWWWWWWWWWWWooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
WWWWWWWWWWWWWWWWWWWoooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
WWWWWWWWWWWWWWWWWWWWWoooooooooooooooooooooooooooooooooooooooooooooooooooooooooo