Ссылки о веб-разработке за апрель 2009

django-piston

django-piston. Promising looking Django mini-framework for creating RESTful APIs, from the bitbucket team. Ticks all of Jacob’s boxes, even including built-in pluggable authentication support with HTTP Basic, Digest and OAuth out of the box.

Building a Better JavaScript Profiler with WebKit

Building a Better JavaScript Profiler with WebKit. Clever hack from Francisco Tolmasky which solves the problem of JavaScript profilers showing ? as the name of any anonymous functions. He patched the WebKit profiler to look for a displayName attribute on a function and show that as the function name instead.

With YQL Execute, the Internet becomes your database

With YQL Execute, the Internet becomes your database. This is nuts (in a good way). Yahoo!’s intriguing universal SQL-style XML/JSONP web service interface now supports JavaScript as a kind of stored procedure language, meaning you can use JavaScript and E4X to screen-scrape web pages, then query the results with YQL.

Ubuntu brings advanced Screen features to the masses

Ubuntu brings advanced Screen features to the masses. Ubuntu 9.04’s screen-profiles package adds a taskbar to screen and emulates the gnome panel. You can even add a widget showing the cost of your current EC2 session.

python-sqlparse

python-sqlparse (via). Python library for re-identing SQL statements. This could make debugging Django’s generated SQL a whole lot easier. You can try the library out using an App Engine hosted application (complete with an API).

Canvas в разных браузерах

Сегодня с утра, порадовавшись выходу Mozilla Firefox 3.5beta4, решил погонять её на JS-эмуляторе «Спектрума», о котором я упоминал. По скорости выходит где-то на уровне или впереди Safari4beta.

Canvas (3.77Kb)


Плохо то, что Firefox, как оказывается, сильно размывает Canvas. Когда я играл на эмуляторе в одну из игр, мне казалось, что у меня что-то со зрением — до того размытая картинка. На скриншоте видно (слева направо): Opera 10 alpha 1456, Safari 3.2.2, Firefox 3.5beta4.

Получаем ещё один «стандарт», который ведёт себя во всех браузерах по-разному. Приехали.

питон: генераторы и сопрограммы

я почти не пишу на питоне, но имею его в виду, в том числе почитываю разные интересные вещи о нём. Сейчас только что закончил читать пару презентаций David M. Beazley с PyCon. В первой из них он интересно рассказывает про генераторы в питоне, справедливо ругая обычные примеры про числа Фибоначи. Его собственные примеры про реализацию почти-unix-pipes на генераторах намного интереснее.

честно скажу, что вторую презентацию я не осилил до конца, но даже прочитанная часть стоила того. Сопрограммы (coroutines) — недавно введённая в питон фича, теоретические разработки которой делались в 60-70 годы, но почти забытая потом. Это нечто похожее на генераторы, но более мощное. В принципе, сам автор пишет про них:

I think a reasonable programmer could claim that programming with coroutines is just too diabolical to use in production software

тем не менее, ознакомиться с обоими презентациями полезно, особенно с учётом прихода генераторов в яваскрипт:

вечная проблема с полноэкранным флеш-видео

я понимаю, что ещё немногие люди дошли до того, чтобы подключать к компу более одного монитора. Очень зря, конечно, они многое теряют, но никого заставлять я не буду. Хотя некоторых программистов стоило бы, в особенности это касается флешеров

мне на глаза попадалось только несколько видеохостингов, но на каждом втором из них есть проблемы при разворачивании видео на весь экран. Я не знаю, какую математику применяют при этом, и какие возможности даёт флеш для определения доступных размеров, но многие делают одну и ту же ошибку. Люди! Флешеры! Вам отдаётся не весь рабочий стол, а только один монитор. Исходите из размеров монитора, а не рабочего стола! А то получится, как на ютюбе, или — не дай бог — яндекс-видео. Первый, хотя и кладёт картинку в конверт с соотношением сторон десктопа, но показывает её целиком на одном мониторе. Конечно, видео при этом увеличивается совсем немного, но его видно. А вот плеер яндекс-видео ошибается куда неприятнее

наверное, нужно затачивать очеловечиватель и под другие хостинги

уязвимость в спеке oauth

последние несколько дней в списке рассылки OAuth шло обсуждение недавно открытой уязвимости. Что характерно, проблема заключается не в технической части, а в социальной. Вся криптография по-прежнему надёжна (сюрприз!), но есть способ получить доверенность на данные другого человека.

если коротко, то процесс OAuth состоит из трёх частей. Вначале вы говорите сервису-потребителю, что сейчас дадите ему доверенность использовать свои данные с другого сервиса. Потом вы отправляетесь на другой сервис и подписываете доверенность. И в конце отправляетесь назад с готовыми документами.

проблема здесь в том, что нет никакой гарантии, что сервису-потребителю вы дадите доверенность именно на свои данные. Образно говоря, можно подготовить пакет документов и подсунуть их на подпись ничего не подозревающему человеку. Если тот незнаком с процессом, он спокойно может доверить свои данные постороннему.

ниже следует более техническое описание.

регистрируемся на сервисе-потребителе данных. Говорим, что сейчас можно будет получить, например, свою адресную книжку от гугла. Сервис пытается отправить нас на гугл за подтверждением. Но мы на гугл не идём, мы берём этот урл и даём в блоге ссылку на него со словами типа «какие чудеса сервис ХХХ делает с адресной книжкой».

читатель блога заинтересовывается и переходит по ссылке. При необходимости логинится в гугл. Видит там запрос «сервис ХХХ хочет вашу адресную книжку». Всё кажется нормальным, и человек подписывает доверенность.

вот и всё: злонамеренному пользователю сервиса ХХХ выдана доверенность на пользование адресной книжкой другого человека.

окончательное решение этой проблемы ещё не придумано. Пока что есть несколько рекомендаций, которые уменьшают вероятность использования такой уязвимости. Например, сервис ХХХ должен сохранять у себя эту доверенность не на того человека, который начал процесс, а на того, кто пришёл по редиректу с доверенностью. Кроме того, поскольку злодею неизвестен момент выдачи доверенности, сервис может аннулировать ключи тогда, когда злодей проверяет наличие ещё не существующей доверенности.

более подробно и с картинками проблема под названием «OAuth Session Fixation Attack» описана в блоге со смешным названием

Системы управления версиями / В Google Code добавлена поддержка Mercurial

Как сообщает Google Code Blog, в скором времени хостинг для опенсорсных проектов от гугла будет поддерживать Mercurial наряду с Subversion для контроля версий.

Разработчики тщательно выбирали между разными распределенными системами, и в конце концов остановили выбор именно на mercurial, а процессу выбора между mercurial и git посвящен этот интересный документ. Mercurial победил в «конкурсе», поскольку:


Гуглоразработчикам пришлось частично переписать mercurial, вместо стандартного дискового хранилища у них используется BigTable.

What you can write in Perl 6 today

«новое» в гуглокартах

только что обнаружил две клёвых фичи!

во-первых, можно избавиться от всего того мусора, что гуглокарты кладут в глобальную область видимости: достаточно вместо параметра скрипта file=api писать file=googleapionly, и все нужные объекты насовсем переедут в google.maps.*

во-вторых, можно динамически подключать скрипты к странице: если передать скрипту параметр async=2, то он не будет использовать document.write

обидно, правда, что приходится так глубоко зарываться, чтобы найти эти фичи

Timed compatibility tables for features in HTML5, CSS3, SVG and other upcoming web technologies

Timed compatibility tables for features in HTML5, CSS3, SVG and other upcoming web technologies

Fuck the font foundries

The more I read about embedded web fonts, the more I crystalize my thinking. Take, for example, this latest “A List Apart” article where Jeffrey Zeldman interviews David Berlow:

Zeldman: Let me put it another way. I want to use your ITC Franklin in a site I’m designing, but I’m not willing to violate my end user licensing agreement. How do we resolve this impasse, from your perspective?

Berlow: The next step is for those who control the font format(s) to define and document a permissions table to be added with all due haste to the OpenType, CoolType, TrueType, and FreeType formats. …

Zeldman: How can type designers and web designers work together to persuade the engineers who control the formats to modify the code to include a permissions table?

Berlow: [W]eb designers flat-out refused to part with real type, which has filled the web with type as graphic files, scaring the bejesus out of a lot of engineering people. … How important dynamically rendered type is to design and use on the web must now be clear. In addition, the only other option — that the type industry cede its intellectual property to the public without permission — is not going to happen. With no upgrade penalty to any applications, or change in usage by the public, the permissions table is the only invisible (type-like) solution.

I like how he focuses on the publisher’s end of the problem — “gee, all we have to do is define this permissions table, that sounds easy.” What he fails to mention is that every font-consuming application on every platform on every computer on Earth will need to be “upgraded” to “respect” this permissions table. Because otherwise they’re not really permissions, are they? They’re just useless bits taking valuable chunks out of my metered bandwidth plan. Like the bozo bit without the bozo.

This, then, is my current thinking about embedded web fonts:

FUCK THE FOUNDRIES

Seriously. Fuck them. They still think they’re in the business of shuffling little bits of metal around. You want to use a super-cool ultra-awesome totally-not-one-of-the-11-web-safe-fonts? Pick an open source font and get on with your life.

I know what you’re going to say. I can hear it in my head already. It sounds like the voice of the comic book guy from The Simpsons. You’re going to say, “Typography is by professionals, for professionals. Free fonts are worth less than you pay for them. They don’t have good hinting. They don’t come in different weights. They don’t have anything near complete Unicode coverage. They don’t, they don’t, they don’t…”

And you’re right. You’re absolutely, completely, totally, 100% right. “Your Fonts” are professionally designed, traditionally licensed, aggressively marketed, and bought by professional designers who know a professional typeface when they see it. “Our Fonts” are nothing more than toys, and I’m the guy showing up at the Philadelphia Orchestra auditions with a tin drum and a kazoo. “Ha ha, look at the freetard with his little toy fonts, that he wants to put on his little toy web page, where they can be seen by 2 billion people ha h… wait, what?”

Let me put it another way. Your Fonts are superior to Our Fonts in every conceivable way, except one:

WE CAN’T FUCKING USE THEM

Soon — and I mean really fucking soon, like “this year” soon — there will be enough different browsers in the hands of enough different people that can use any possible font on any possible web page. And then a whole lotta people will start noticing fonts again — not just Your People, just also Our People. People who couldn’t tell a serif from a hole in their head, but they’re gonna be looking for new fonts. People who are just savvy enough to be tired of Comic Sans will be looking for a new font to “spruce up” their elementary school newsletter, which, in an effort to Love Our Mother (Earth), they now publish exclusively online.

And maybe, just maybe, they’ll stumble across Jeffrey Zeldman’s excellent interview with highly talented David Berlow and think, “Wow, this guy has over 300 fonts! That’s awesome! Where can I download them?” And boy, won’t they be surprised to learn that those 300 fonts can only be used offline. Epic fail.

Dynamic web fonts are coming. Actually they’re already here, but most of Our People haven’t noticed yet. But they will, and that’s going to be a huge boon to somebody. I see you’ve decided that it won’t be you. Well, have fun shuffling your little bits of metal around. The rest of us will be over here, using the only fonts we’re allowed to use: Everything But Yours.

Some Notes on Distributed Key Stores

Some Notes on Distributed Key Stores. Another ringing endorsement for Tokyo Cabinet, this time from Leonard Lin.

pubsubhubbub - OS realtime feed update

pubsubhubbub. From Brad Fitzpatrick, a simple but clever way of using web hooks (HTTP callbacks) to inform subscribers that an Atom feed has updated in almost real-time—solving the constant polling problem and making it easier for small sites to offer publish-subscribe APIs. Any Atom feed can delegate subscriber updates to a “hub” server. An example hub server implementation is provided running on App Engine.

Introduction to W3C Widgets

As I said before, I’m currently working for Vodafone on mobile browser compatibility and W3C Widgets. I’ve discussed some mobile browser problems, and you can look over my shoulder while I’m at work dissecting their odd behaviours. If you want the latest scoops on my mobile adventures, you can follow me on Twitter.

The time has come to talk about the W3C Widgets part of my job. Exactly what is a widget, how do you create one, why would you want to, and which systems support them?

Personally I firmly believe that widgets are the future of the mobile web. They are easy to create, they’re based on open standards, they save the end user quite a bit of network traffic, and many people around the world already know how to create them.

In contrast to other recent publications about widgets, I’ll tell you the whole story — or rather, a condensed version thereof.

IBM, Nokia, Sun and others join EU antitrust case against Microsoft

The European Committee for Interoperable Systems (ECIS), has joined Opera's antitrust complaint against Microsoft. ECIS members include IBM, Sun, Nokia, Adobe, Oracle, and others. Opera is also a member of ECIS
Opera Software initially took a lot of heat for reporting Microsoft to the authorities. However, contrary to what one might believe from reading some of the knee-jerk reactions from people around the Web, Opera did not sue Microsoft, nor did it demand any money from Microsoft. Like any concerned and responsible citizen, Opera Software reported that it considered Microsoft's actions to be illegal, and asked the authorities to look into it.

After the flames had mostly subsided, Mozilla joined the complaint, followed by Google, and now several major and well known companies through ECIS. The reasoning is:

This case is about the future of the Web and maintaining an open and dynamic internet. Key
business, e-commerce, public service and social networking applications are moving to the internet, which is rapidly becoming the backbone of economic life and social interaction. By tying IE to the Windows desktop monopoly, by using proprietary IE standards and making internet applications and content dependent on other Microsoft proprietary technologies, such as Silverlight and .NET, Microsoft seeks to establish itself as gatekeeper to the internet.


ECIS has also released a paper titled "A History of Anticompetitive Behavior and Consumer Harm", where it makes its case against Microsoft. The Table of Contents lists, among other things, Microsoft's actions against DR-DOS, Word Perfect, Intel, Netscape, Java, and so on. It's a powerful reminder for those who are unaware of Microsoft history of anti-competitive practices.

There is also a history lesson regarding browsers:

During Microsoft's push to destroy Netscape, it released four major new versions of Internet Explorer in two years. But after it successfully excluded Netscape from the market, Microsoft slowed browser development, releasing only two new versions between 1998 and 2001, neither of which was a major upgrade. After 2001, Microsoft "effectively disbanded the Internet Explorer group after killing Netscape."
Microsoft did not introduce a new version of Internet Explorer for Windows until 2006, and even
then reviewers labeled the new version as an underwhelming catch-up release.
One of Microsoft's .NET program managers acknowledged that "[i]t simply doesn’t make business
sense for Microsoft to invest in a technology that d[is]intermediates [its] most popular platform, the Windows operating system.


Yes, Microsoft apparently disbanded its Internet Explorer team when it achieved its goal of total dominance.

I strongly recommend that people read the document before commenting on this issue. A lot of comments around the Web so far show a worrying lack of knowledge of Microsoft's anti-competitive history.

Despite what some people are trying to turn this into, it is not about EU vs. US. This is not about Capitalism vs. Communism. Americans and Europeans, including several highly successful companies and organizations, are together on this one. It is about how a company which breaks the law should be held accountable for that. Contrary to what some seem to think, the United States does have antitrust laws, as do most countries on this planet, and it is not afraid to use them. Antitrust laws help to ensure that harmful practices do not undermine competition.

So Microsoft is not being investigated because it is an American company, nor is it because it is successful. It is being investigated because there is reason to believe that it has once again broken the law, and breaking the law should have consequences.

10 Cool Things We'll Be Able To Do Once IE6 Is Dead

10 Cool Things We’ll Be Able To Do Once IE6 Is Dead. Highlights include child and attribute selectors, 24bit PNGs and max-width and min-width. Simple pleasures, but I can hardly wait.

Making accessibility more real

To some web professionals, accessibility means nothing because they aren’t aware it exists. To others it is a checklist of items that need to be ticked off because their boss or client tells them to. Others yet may use the same checklist as a guide that helps them understand accessibility and how people with disabilities use the web.

But most of us don't go further than that unless we have a disability. So let's follow the advice given by Rob Foster in Accessibility to the Face and really try to imagine what it would be like to use the web with a disability:

For the next hour or so, I’d like you to imagine you don’t have any hands. All you have are elbows and forearms. How would you scroll down on this article? How would you close the window or switch applications?

Here are some other things you can do to help yourself understand some disabilities better:

It’s obviously not the real thing since you have the option to stop being “disabled”. But it will help you better understand why accessibility is important.

Posted in .

Counting the ways that rev="canonical" hurts the Web

Counting the ways that rev=“canonical” hurts the Web. Mark Nottingham complains about misapplied trust (a page can falsely claim to be the canonical URL for another page), the easy confusion between rev and rel and the lack of discussion with relevant communities.

Creating widgets for T-Mobile handsets: The T-Mobile Developer SDK and more

Opera has just released its T-Mobile developer SDK, an optimized version of the widgets SDK for creating and deploying advanced widgets on T-Mobile handsets, along with some other exciting new T-Mobile functionality. This article gives you an overview of all the available new functionality.

Security with string APIs

Один их трёх вчерашних блиц-докладов Андрея Пантюхина про rsync-based backup

Reducing XSS by way of Automatic Context-Aware Escaping in Template Systems

Reducing XSS by way of Automatic Context-Aware Escaping in Template Systems (via). The Google Online Security Blog reminds us that simply HTML-escaping everything isn’t enough—the type of escaping needed depends on the current markup context, for example variables inside JavaScript blocks should be escaped differently. Google’s open source Ctemplate library uses an HTML parser to keep track of the current context and apply the correct escaping function automatically.

отступы в textarea

некоторые вещи в текстовых редакторах настолько привычны, что кажутся естественными. Одна из них — увеличение отступа строки по Tab. Выделяешь кусок текста, и табом сдвигаешь его вправо, или шифт-табом влево. Наверное, каждый программист регулярно этим занимается : )

веб традиционно в отстающих. Да, есть проекты типа недавнего webIDE от мозиллы, но в миллионах textarea по всему миру юзеры делают форматирование руками или копируют текст из ворда. Дело упрощают всякие lightweight markup lanugages, но и в них цитировать код неудобно

хех, что-то меня занесло в космические корабли на просторах Большого театра % ) В общем, сегодняшний пост — про юзерскрипт, добавляющий поддержку Tab/Shift+Tab в каждую textarea. Выделите строчку или несколько, и меняйте ей отступ в своё удовольствие : )

Visualising Sorting Algorithms

Visualising Sorting Algorithms. Aldo Cortesi dislikes animations of sorting algorithms, so he designed a beautiful technique for statically visualising them instead (using Python and Cairo to generate the images).

"Welcome to 2002, when lots of us had more spare time than employment and we deployed new crap like..."

“Welcome to 2002, when lots of us had more spare time than employment and we deployed new crap like this on our blogs and sites daily. Back in those olden days, we manipulated raw HTML with our bare hands and deployed radioactive code using our teeth—all without benefit of protective change control. We probably all have cancer of the access logs now, but it was all in the name of Web Science!”

- 0xDECAFBAD

Updates API - YDN

Microsoft / Ссылка IE8 — в Windows Update

В официальном блоге Internet Explorer появилась запись о том, что до конца апреля (начиная с третьей недели) IE8 будет доступен через Windows Update как высокоприоритетное (для Vista — важное) обновление.
Решит ли это все проблемы — неизвестно, но то что это будет важный шаг в деле "борьбы против IE6" — ясно уже сейчас.

Running Rhino and Helma NG on Google App Engine

Running Rhino and Helma NG on Google App Engine. Helma NG is a JavaScript web app framework, which now works on App Engine out of the box.

rev=canonical bookmarklet and designing shorter URLs

I’ve watched the proliferation of URL shortening services over the past year with a certain amount of dismay. I care about the health of the web and try to ensure that URLs I am responsible will last for as long as possible, and I think it’s very unlikely that all of these new services will still be around in twenty years time. Last month I suggested that the Internet Archive start mirroring redirect databases, and last week I was pleased to hear that Archiveteam, a different organisation, had already started crawling.

The most recent discussion was kicked off by Joshua Schachter and Dave Winer, and a solution has emerged driven by some lightning fast hacking by Kellan Elliott-McCrea. The idea is simple: sites get to chose their preferred source of shortened URLs (including self-hosted solutions) and specify it from individual pages using <link rev="canonical" href="... shorter URL here ...">.

By hosting their own shorteners, the reliability should match that of the host site—and the amount of damage caused by a major shortener going missing can be dramatically reduced.

I’ve been experimenting with this new pattern today. Here are a few small contributions to the wider discussion.

A URL shortening bookmarklet

Kellan’s rev=canonical service exposes rev=canonical links using a server-side script running on App Engine. An obvious next step is to distil that logic in to a bookmarklet. I decided to combine the rev=canonical logic with my json-tinyurl web service (also on App Engine), which allows browsers to lookup or create TinyURLs using a cross-domain JSONP request. The resulting bookmarklet will display the site’s rev=canonical link if it exists, or create and display a TinyURL link otherwise:

Bookmarklet: Shorten (drag to your browser toolbar)

You can also grab the uncompressed source code.

Designing short URLs

I’ve also implemented rev=canonical on this site. I ended up buying a new domain for this, since simonwillison.net is both difficult to spell and 17 characters long. I ended up going with swtiny.eu—9 characters, and keeping tiny in the domain helps people guess the nature of the site from just the URLs it generates. Be warned: the DNS doesn’t appear to have finished resolving yet.

For the path component, I turned to a variant of base 62 encoding. Decimal integers are represented using 10 digits (0-9), but base 62 uses those digits plus the letters of the alphabet in both lower and upper case. A 13 character integer such as 7250397214971 compresses down to just 8 characters (CDeIPpOD) using base62. My baseconv.py module implements base62, among others. I considered using base 57 by excluding o, O, 0, 1 and l as being too easily confused but decided against it.

This site has three key types of content: entries, blogmarks and quotations. Each one is a separate Django model, and hence each has its own underlying database table and individual ID sequence. Since the IDs overlap, I need a way of separating out the shortened URLs for each content type.

I decided to spend a byte on namespacing my shortened URLs. A prefix of E means an entry, Q means a quotation and B means a blogmark. For example:

By using upper case letters for the prefixes, I can later define custom paths starting with a lower case letter. I also have another 23 upper case prefix letters reserved in case I need them.

I asked on Twitter and consensus opinion was that a 301 permanent redirect was the right thing to do (as opposed to a 302), both for SEO reasons and because the content will never exist at the shorter URL.

Implementation using Django and nginx

I run all of my Django sites using Apache and mod_wsgi, proxied behind nginx. Each site gets an Apache running on a high port, and nginx deals with virtual host configuration (proxying each domain to a different Apache backend) and static file serving. I didn’t want to set up a full Django site just to run swtiny.eu, especially since my existing blog engine was required in order to resolve the shortened URLs.

Instead, I implemented the shortened URL direction as just another view within my existing site: http://simonwillison.net/shorter/EZ8. I then configured nginx to invisibly requests to swtiny.eu through to that URL. The correct incantation took a while to figure out, so here’s the relevant section of my nginx.conf:

server {
    listen 80;
    server_name www.swtiny.eu swtiny.eu;
    location / {
        rewrite (.*) /shorter$1 break;
        proxy_pass http://simonwillison.net;
        proxy_redirect off;
    }
}

proxy_redirect off is needed to prevent nginx from replacing simonwillison.net in the resulting location header with swtiny.eu. My Django view code is relatively shonky, but if you’re interested you can find it here.

The nice thing about this approach is that it makes it trivial to add custom URL shortening domains to other projects—a quick view function and a few lines of nginx configuration are all that is needed.

Update: The bookmarklet now supports the rev attribute on A elements as well—thanks for the suggestion, Jeremy.

javascript 5

ух ты! позавчера вышел Candidate Specification для ECMAScript, Fifth Edition

ECMAScript, Fifth Edition Candidate Specification Announced

Yesterday was a significant milestone in the web’s continuing evolution—the announcement of ECMAScript, Fifth Edition Candidate Specification (formerly known as ECMAScript 3.1 back when I last mentioned it); the “Candidate Specification” stage is the last stop on the road to becoming a final standard. Read more about it on the Jscript blog!

This is a great achievement and paves the way for enhanced web programming scenarios in all browsers. I’d also like to personally thank Allen and Pratap for their contribution to the TC-39 effort, as well as their assistance in delivering a few of the ES 5 features to our customers in IE8.

-Travis Leithead

каскадные таблицы стилей

так называется блог про CSS на хабре. Таблицы, ага. Я бы посмотрел на таблицу в самом css-файле : )

есть здесь какой-то тонкий намёк на Семантичные Войны

Protovis

Protovis. JavaScript graphing library based on canvas, with an elegant chaining style API.

Блог компании Opera Software / Перевод Как Opera «ремонтирует» веб-сайты

image

Пожалуй, чаще всего разработчиков браузера Opera обвиняют в их принципиальности, когда дело касается соблюдения веб-стандартов. Как это ни странно. Основной довод при этом звучит примерно так: «Ну вот другие же могут подстраиваться под несовершенство интернета, чем вы лучше?». На самом деле — почти ничем. Правда, за этим «почти» скрывается такая простая вещь, как желание сделать интернет-мир лучше. Обычная житейская логика подсказывает, что идя на поводу у недобросовестных веб-разработчиков изменить ситуацию вряд ли получится, но и слишком принципиальный подход делу особо не поможет. Выход один — искать золотую середину. И нужно сказать, что норвежские программисты оказались, наверное, ближе всех к этому компромиссному решению. Более того, их метод по многим статьям идёт на голову впереди всех остальных участников рынка. Как такое может быть? Читаем перевод статьи Холлворда Стеена.
Читать дальше →

Google / Google Chrome и Linux

image

Пользователи Ubuntu (или пользователи дистрибутивов, основанных на этой системе), которые терпеливо ждали появления Google Chrome для Linux теперь имеют такую возможность. Пре альфа Chromium доступна в репозиториях:
deb ppa.launchpad.net/chromium-daily/ppa/ubuntu intrepid main
deb-src ppa.launchpad.net/chromium-daily/ppa/ubuntu intrepid main


Затем sudo apt-get install chromium-browser и chromium-browser

Хотя это ещё очень ранняя версия, Хром работает на удивление гладко и шустро. Некоторых важных функций и фич нет, но ведь мы вроде бы никуда не торопимся? =)

Скриншоты можно посмотреть примерно тут

Vector country borders for Google Maps

Друзья, скажите, а может быть кто-то видел в открытом доступе выборку стран для Google Maps API — точно так же как это сделано в Google AdWords (см. картику)

http://dl.getdropbox.com/u/788671/stuff/gmaps1.jpg
[ Оригинал @ dull.ru ]

js-hotkeys - Google Code

Web Trend Map 4

Web Trend Map 4

Opera's site patching: smart+omnipotent


You know the complexity of web technology is getting out of hand when every website needs some special treatment. Imagine driving a car if you had to change the engine slightly or replace wheels every time you turned a corner and entered a new street? Browser development is a lot like that these days.

Nearly every modern browser has site patching features, to grease the wheels where the nuts and bolts of standards are exposed to the unpredictable elements of the web:

Treating every site differently? That sounds insane. It's clearly impossible. For starters, there are billions of websites, all different. And they keep changing with millions of lines of code being added or changed every day. Who can possibly keep up with that? Besides, aren't standards supposed to be the answer?

Standards

I commend the standardisation efforts and the evangelists at The Web Standards Project and elsewhere. Without you we would be far, far worse off. The future might even be on your side - more and more sites validating and cleaning up their standards story. Power to you!

Various Opera teams take part in the standards work too, including doing education and outreach. Our Open The Web team contacts web sites with advice on cross-browser compatibility and standards compliance.

But the browser is the user's agent. Across all sites breaking the rules and standards in different ways, we owe the user to do anything we can to make them all work whenever possible. Often a broken site is not our fault, but it's most definitely our problem. And we must make it work today. Not in 2022..

Hence, we patch.

Since we see various more or less ad-hoc approaches to site patching develop among our fellow browser vendors, it seems like a good time to share some of our experiences - what I think are the strengths and constraints of our particular implementation.

Strengths

Experience

Opera has more experience with site-specific patches than other browser vendors, since we've been patching the web since Opera 8.01. I believe our solution is also by far the most advanced one. Special commands available to User JavaScripts make up a simple yet powerful API for modifying and correcting a website. With getters and setters and DOM interfaces we can change Opera's behaviour to match most standard deviations the script expects. Sometimes we add a specific missing style or even remove some object or policy that gets in the way. And when a web site uses browser sniffing we can often dig in and repair the exact line of code that is broken! Some random examples:

We can also override settings like what browser we identify as and what rendering mode (quirks or standards) we should use for a specific site through downloadable preferences.

Bugfixes

Given the power to change websites and change Opera, we can sometimes even work around our own bugs.

Now there's a thought. Opera - the browser that works around its bugs so you don't have to? This is like a time machine - we can fix our past sins for already released versions.

In the long term, this is a very important and subtle effect of browser.js: there will be less Opera-specific hacks to worry about. Both IE8's upgrade woes and our own experience tells us that workarounds against our own old bugs are among our worst problems. We did the wrong thing, sites did the wrong thing in response. We fixed it on our side, but the web never forgets your old bugs.

The difference with browser.js? When we release a new version with bug fixes, corresponding browser.js patches are secretly dropped as obsolete. What used to work because of browser.js hacks keeps working because the new version supports it, making the upgrade experience smoother for users and web developers alike, and a lot simpler for us. I can almost feel the envy of the IE8 team across the Atlantic.

Another interesting effect is that we can implement new standards with less worries. When HTML5's <input required> feature breaks Barnes & Noble because the user name field in the login form isn't really required input after all when you click the "create account" button - we can first patch it, and later tell the spec editor about our problems and discuss if the spec can be made more web-compatible.

Transparency

From the very beginning, one of the main concerns was that our fixes would prevent webmasters from finding and correcting problems. We might even end up creating problems if our patches linger on while the site changes.

To make things as transparent as possible, the patches are documented, we try to keep the file itself readable and reasonably well commented (though we also try to avoid unnecessary download bloat). And every patch applied will output a message in Opera's error console trying to make it obvious what is going on.

Scope

Site patching is cross-platform. Actually, that's an understatement. Did you know we have site patches for Nintendo Wii? And for the DSi? For Opera on Windows Mobile, Symbian, BREW and Archos's portable media players? Heck, we even have patches for Opera Mini!

It's an ambitious scope, probably much more ambitious than it might seem from the outside. The devices and platforms have very different requirements and problems. For example:

When dealing with such a range of problems the true and magic potential of browser.js becomes apparent.

Infrastructure

To support all this, we need some nifty download servers picking the correct file for any client that asks for one. We have a database of patches and meta data like what versions and platforms a patch applies to. But did you know we also have a script spidering sites to check if broken parts are still there? When a patched site changes a relevant piece of code, I want to know about it. I love the sound patches make when they hit the virtual "obsolete" bin.

Constraints

Time

So much power, so little time.. Analysing sites and developing patches takes a lot of time. We are nowhere near IE8's overwhelming list of 2400+ sites. (Actually, browsing the IE8 list is a Déjà vu experience. Many familiar names, many sites we need to patch or contact for various reasons too.)

Nevertheless, our list is shorter - fortunately! Technical analysis with the level of detail required to support our site patching can be very time consuming, so I hope we'll remain smaller and more focused than the IE list. We will however scale the efforts up - we're at 600+ entries in the database and there is room for plenty of more - and we welcome contributions.

Performance

I just said there is room for plenty of more patches. But how far can we scale site patching before performance suffers too much?

Apparently we can keep going for quite a while. Some profiling work we did recently indicates that we can patch upwards of 10 000 specific sites without slowing Opera down by more than a couple of percentage points. And frankly, by the time we've written patches for 10 000 sites you've probably bought a more powerful computer..

Security

Isn't it unsafe? Can't a virus or malicious server fake your browser.js file and gain instant control of your Opera browsing?

The short answer is: no.

The longer answer is that this would be possible without our security precautions, but it is in fact all taken care of. Every file is signed, so Opera can check that it is a genuine file and that it has not been tampered with. Such a signature is very, very hard to fake. If a malicious server or virus alters the file, Opera will stop using it and try to download a fresh version from the server.

Conclusions

One of the things that surprised me most about browser.js work is how quickly the web changes. By paying such close attention to specific sites we see the web as a whole evolve, and it's iterating faster than I would have dared to expect. And contrary to what you might expect, we do see sites change to become more Opera-friendly after we've patched them!

That means site patcing works. It works because it improves compatibility, thereby giving users a real choice in browsers and - as weird as it may sound - as a direct effect of that, it gives webmasters incentives to make sure their sites are Opera- and cross-browser-compatible.

Welcome to the future - made of and with standards, openness and site patching.


About the author

Hallvord R. M. Steen works for Opera's core team on quality assurance, testing and web compatibility. He maintains the browser.js file and can break all websites worldwide with a minor typo.

Google App Engine With Java

The Google App Engine allows developers to create websites on Google’s server infrastructure. So far, only Python was supported as programming language, but Google now announced support for Java as well (this was foreshadowed by TechCrunch last month). Google in their announcement post also mentions that the App Engine now supports Cron jobs – i.e. scheduled events running for your app –, though I’m not sure how new that is.

My friend and I had been setting up one of our sites using the App Engine (we have our own domain and front-end but the front-end communicates with the App Engine back-end via Json). Our experiences in the past months were very mixed. It’s a nice framework to develop in, if you don’t mind getting your head around the pros and cons of accessing data with the scalable datastore approach I guess, but the outages were quite heavy. For several weeks, the scheduled maintenance downtime alerts (as well as the alerts related to non-scheduled problems) kept piling up, so this wouldn’t have been a realistic option for a hugely important site. Even for our smaller fun project, it caused headaches... imagine you’re being linked from a newsletter or a popular website or so and then there’s a one-hour downtime. On the other hand, the App Engine is of course also completely free for starters, until you want to buy into additional quota.

[Thanks Manoj, KMB and Steffi. Via Google blog and App Engine blog.]

[By Philipp Lenssen | Origin: Google App Engine With Java | Comments]


[Advertisement] Want to advertise here? Your ad will show in the blog and feed.

FAIL



FAIL

CSS-кружка

"Слушайте, если у человека отключен JS, он уже привык к, скажем так, альтернативному экспириенсу."

“Слушайте, если у человека отключен JS, он уже привык к, скажем так, альтернативному экспириенсу.”

- berkgaut

cufon

cufon. A promising alternative to sIFR, cufon uses VML on IE and canvas on other browsers to render custom fonts in the browser. You have to convert your font to JavaScript first, either using their free hosted tool or by installing the FontForge based server-side script yourself. The JavaScript encoded font file uses VML primitives to improve IE performance; the JavaScript library converts that to canvas calls for other, faster browsers.

Mapreduce Bash Script

local-openid: Single User, Ephemeral OpenID Provider

Лента новостей / IBM купит Sun Microsystems за $7млрд.

К сожалению, то, чего я так боялся, произошло. 1 апреля давно прошло и New York Times не шутит. Что это может означать для нас? Обрисую ситуацию так, как её вижу я.

1. IBM или продаст (кому???) MySQL или постепенно убъет его, проталкивая в Сообщество свою DB2
2. Будущее Solaris вообще под вопросом. Зачем он IBM'у
3. Тоже самое для NetBeans. Думаю версия 7 будет последней :(
4. Большое давление на Java сообщество с целью протаскивания своих решений. Советую уже поиграться с ВебСферой… Привыкайте

У IBM очень строгий и жесткий процесс. Sun Microsystems контора, в общем-то, раздолбайская с довольно демократичным микроклиматом. Такое поглощение явно вызовет недовольство у некоторых топ-инженеров компании Sun и… они пойдут по стопам Джошуа Блоха.

Меня больше всего беспокоит судьба Java и NetBeans. Что думаете Вы?

UPD: таки не договорились пока http://lenta.ru/news/2009/04/06/ibm/

«//» в ссылках

Как известно, в вебе, в подавляющем большинстве случаев, для адресации ресурсов применяются HTTP или HTTPS протоколы. Как вы понимаете, я не Капитан Очевидность, так что за этим последует какая-то интрига.

Бывает так, что одна и так же страница должна быть видна по обоим протоколам (например, у нас в интранетах такое бывает часто). В зависимости от того как пользователь зайдёт.

То, что я скажу дальше NDA не является, например, об этом рассказывал Олег Оболенский на РИТ-2007: все сервисы состоят из кусочков, кусочки грузятся с какого-то сервера. На практике это означает, что часть CSS и картинок, которые используются в нашем интранет-хозяйстве лежат на другом сервере и их ковыряют совсем другие люди.

В итоге, когда человек заходит на страницу, ему грузится ещё и CSS с другого сайта, внутри которых могут быть абсолютные (с протоколом) пути, которые подгружают картинки. Если человек зашёл по HTTPS, то и всё остальное должно отдаться по HTTPS (иначе, например, Internet Explorer заругается), если он зашёл по HTTP, то всё должно отдаваться по HTTP (HTTPS нагружает сервер и вообще отдаётся по шифрованному протоколу всё заметно медленее).

Как это реализовать? Как менять протокол, в зависимости от протокола страницы, если CSS, который грузится статичен и менять пути внутри него не получится? Делать два отдельных CSS?

Есть способ проще.

Откуда я о нём узнал, я не помню. Что-то смутно вспоминаю, что, кажется, прочитал у Кукуца много лет назад, с тех пор и использую. Впрочем, память меня тут, вероятно, подводит, потому что до моего прихода в «Яндекс» способа там этого, похоже, не знали.

Способ заключается в том, чтобы не указывать протокол. Выглядит такой URL вот так: «//example.net/picture.jpg» и описан в RFC 1738 как «Common Internet Scheme Syntax»:

While the syntax for the rest of the URL may vary depending on the particular scheme selected, URL schemes that involve the direct use of an IP-based protocol to a specified host on the Internet use a common syntax for the scheme-specific data:

//<user>:<password>@<host>:<port>/<url-path>
Смысл в том, что в таком указания без протокола должен использоваться текущий тип протокола. Таким образом, хорошее решение — просто всегда указывать полный URL в таком виде.
комментировать тут

on url shorteners

POP and IMAP Troubleshooter

Firefox 3 becomes top browser in Europe -study | Reuters

← предыдущий месяц