Dive Into Python
This book lives at http://diveintopython.org/. If you're reading it somewhere else, you may not have the latest version.
Permission is granted to copy, distribute, and/or modify this document under the terms of the GNU Free Documentation License, Version 1.1 or any later version published by the Free Software Foundation; with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts. A copy of the license is included in Appendix G, GNU Free Documentation License.
Read more: Dive Into Python
Three locks for your SSH door
Posted by
jasper22
at
16:08
|
Introduction
If you require remote access to your computer and you enable Secure Shell (SSH) connections, you must accept that you will automatically attract hackers who will try to break your defenses and take command of your machine. Although there's no guarantee that your machine won't be "0wn3d" by a "h4x0r," a few simple solutions can help reinforce your SSH door and make life a bit more difficult for anybody trying to break in. This article considers three such techniques:
- Changing SSH's standard port to an unusual value and reinforcing SSH configuration so that simple-minded attacks just bounce back.
- Defining a restricted list of users who are allowed to log in.
- Completely hiding the fact that you even allow SSH access and requiring a special "knock" sequence to be recognized as a possible user.
To apply these techniques, you need to access the root account. Also, you'll probably have to install some packages, and you'll need to configure your firewall and your router—if you have one—to open and close specific ports and forward them to your machine.
Reinforcing the door
The concept "security through obscurity" is well known—and well derided—because doing things in an obscure way, hoping that no one will get wise to your method, is just asking for problems. However, in some contexts, a bit of obscurity can help. Although simple measures cannot stop determined hackers, at least you can be better defended against "script kiddies", whose scripts usually aren't that thorough.
Everybody knows that the standard port for SSH connections is 22. So, the first step you should take to make your machine more secure is simply to change the port to another unused and nonstandard port number—say, 22960. Numbers above 1024 are usually safe, but check the references to avoid possible problems. This change simply means that you have to use this command line to connect to your computer:
ssh -p 22960 your.machine.url
To effect this bit of subterfuge, make a simple change in the /etc/ssh/sshd_config file. Edit it (you must work as root for this), look for the line that reads Port 22, and change the number to whatever you have chosen (If the line is commented out because it starts with a pound sign [#], remember to uncomment it). Save the file, and restart SSH with the command /etc/init.d/sshd restart. You should also open the chosen port in your firewall and close port 22.
But you can do even more. Fiddle with the configuration file so that it includes the lines shown in Listing 1. Note that some of these lines may already exist, but they could be commented out.
Listing 1. Some changes to your SSH configuration file enhance security at little cost
Port 22960
LoginGraceTime 30
MaxAuthTries 3
Protocol 2
PermitRootLogin no
Read more: IBM
Working with the Managed Extensibility Framework (TOC)
This post is simply a table of contents for posts that I'm creating to help others learn about the Managed Extensibility Framework (MEF). As new posts get published, I'll be updating the links to this page. In addition, as I work more with MEF, I'll be adding more entries to this series to hopefully cover a wide range of scenarios while using such. An Introduction to MEF A Deeper Look at MEF's Imports and Exports LINQing to MEF Imports Playing Nice with Other Assemblies using MEF Catalogs Looking Around at Circular References in MEF Managing Composition Through Lazy Loading Parts Using MEF and Custom Configuration Sections A Configurable Type Catalog for MEF Making Part Declarations Easier with InheritedExports Hiding Parts From InheritedExport Using MEF with Signed Part Assemblies
Read more: Random Acts of Coding
Managed Extensibility Framework Overview
Posted by
jasper22
at
11:26
|
This topic provides an overview of the Managed Extensibility Framework introduced in the .NET Framework 4.
This topic contains the following sections.
- What is MEF?
- The Problem of Extensibility
- What MEF Provides
- Where Is MEF Available?
- MEF and MAF
- SimpleCalculator: An Example Application
- Composition Container and Catalogs
- Imports and Exports with Attributes
- Further Imports and ImportMany
- Calculator Logic
- Extending SimpleCalculator Using A New Class
- Extending SimpleCalculator Using A New Assembly
- Conclusion
- Where Do I Go Now?
What is MEF?
The Managed Extensibility Framework or MEF is a library for creating lightweight, extensible applications. It allows application developers to discover and use extensions with no configuration required. It also lets extension developers easily encapsulate code and avoid fragile hard dependencies. MEF not only allows extensions to be reused within applications, but across applications as well.
The Problem of Extensibility
Imagine that you are the architect of a large application that must provide support for extensibility. Your application has to include a potentially large number of smaller components, and is responsible for creating and running them.
The simplest approach to the problem is to include the components as source code in your application, and call them directly from your code. This has a number of obvious drawbacks. Most importantly, you cannot add new components without modifying the source code, a restriction that might be acceptable in, for example, a Web application, but is unworkable in a client application. Equally problematic, you may not have access to the source code for the components, because they might be developed by third parties, and for the same reason you cannot allow them to access yours.
A slightly more sophisticated approach would be to provide an extension point or interface, to permit decoupling between the application and its components. Under this model, you might provide an interface that a component can implement, and an API to enable it to interact with your application. This solves the problem of requiring source code access, but it still has its own difficulties.
Because the application lacks any capacity for discovering components on its own, it must still be explicitly told which components are available and should be loaded. This is typically accomplished by explicitly registering the available components in a configuration file. This means that assuring that the components are correct becomes a maintenance issue, particularly if it is the end user and not the developer who is expected to do the updating.
In addition, components are incapable of communicating with one another, except through the rigidly defined channels of the application itself. If the application architect has not anticipated the need for a particular communication, it is usually impossible.
Finally, the component developers must accept a hard dependency on what assembly contains the interface they implement. This makes it difficult for a component to be used in more than one application, and can also create problems when you create a test framework for components.
What MEF Provides
Instead of this explicit registration of available components, MEF provides a way to discover them implicitly, via composition. A MEF component, called a part, declaratively specifies both its dependencies (known as imports) and what capabilities (known as exports) it makes available. When a part is created, the MEF composition engine satisfies its imports with what is available from other parts.
This approach solves the problems discussed in the previous section. Because MEF parts declaratively specify their capabilities, they are discoverable at runtime, which means an application can make use of parts without either hard-coded references or fragile configuration files. MEF allows applications to discover and examine parts by their metadata, without instantiating them or even loading their assemblies. As a result, there is no need to carefully specify when and how extensions should be loaded.
In addition to its provided exports, a part can specify its imports, which will be filled by other parts. This makes communication among parts not only possible, but easy, and allows for good factoring of code. For example, services common to many components can be factored into a separate part and easily modified or replaced.
Because the MEF model requires no hard dependency on a particular application assembly, it allows extensions to be reused from application to application. This also makes it easy to develop a test harness, independent of the application, to test extension components.
An extensible application written by using MEF declares an import that can be filled by extension components, and may also declare exports in order to expose application services to extensions. Each extension component declares an export, and may also declare imports. In this way, extension components themselves are automatically extensible.
Where Is MEF Available?
MEF is an integral part of the .NET Framework 4, and is available wherever the .NET Framework is used. You can use MEF in your client applications, whether they use Windows Forms, WPF, or any other technology, or in server applications that use ASP.NET.
MEF and MAF
Previous versions of the .NET Framework introduced the Managed Add-in Framework (MAF), designed to allow applications to isolate and manage extensions. The focus of MAF is slightly higher-level then MEF, concentrating on extension isolation and assembly loading and unloading, while MEF's focus is on discoverability, extensibility, and portability. The two frameworks interoperate smoothly, and a single application can take advantage of both.
Read more: MSDN
Communication between C++ Silverlight Host and Silverlight Application
Posted by
jasper22
at
11:01
|
Things to Do in a Silverlight Application
using System.Windows.Browser;
Use the above mentioned namespace for communication. We will use HTML communication bridge to communicate with the C++ host.
Use the following statement to register the Communicator object. We will get this communicator object in C++ Silverlight host using IDispath.
HtmlPage.RegisterScriptableObject("Communicator", this);
Write another function in Silverlight application which we will call from C++ Silverlight host.
[ScriptableMember]
public void SetDataInTextBox(string strData)
{
txtData.Text = strData;
}
The complete code for the Silverlight page is as follows:
using System.Windows.Browser;
namespace SilverlightTestApp
{
public partial class MainPage : UserControl
{
public MainPage()
{
HtmlPage.RegisterScriptableObject("Communicator", this);
InitializeComponent();
}
private void ClickMe_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show("Button click handler is in Silverlight :)",
"SilverlightTestApp", MessageBoxButton.OK);
}
[ScriptableMember]
public void SetDataInTextBox(string strData)
{
txtData.Text = strData;
}
}
}
I am not trying to explain Silverlight development issues here but I would like to say the same things we do for Silverlight and JavaScript interaction. If someone is not familiar with the above code, Google Silverlight and JavaScript interaction. Almost every Silverlight book covers this topic.
C++ Silverlight Host
Add an edit box and a button in your dialog box in ATL application. We will enter some test in the edit box and write some code in the click handler of the button we just added.
Handler function for button click. Getting the user input in strData...
LRESULT CCMainDlg::OnBnClickedBtnSendDataToSilverlight
(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
CAtlStringW strData;
GetDlgItem(IDC_EDIT_DATA).GetWindowTextW(strData);
Now coming to the main point - getting DISPID of Communicator object we just registered in Silverlight app.
IDispatch *pContent;
HRESULT hr = CXcpControlHost::GetXcpControlPtr()->get_Content(&pContent);
CComBSTR bstrMember(L"Communicator");
DISPID dispIDCommunicator = NULL;
hr = pContent->GetIDsOfNames(IID_NULL, &bstrMember, 1,
LOCALE_SYSTEM_DEFAULT, &dispIDCommunicator);
if(FAILED(hr))
{
::MessageBox(NULL, L"Failed to get the DISPID for Communicator",
L"Error :(", 0);
return 0;
}
Once we have a valid dispID for Communicator object, we are ready to get the IDispatch* for Communicator object. It's a bit tricky here, we will make an invoke call with DISPATCH_PROPERTYGET.
Read more: Codeproject
Localizing Silverlight-based Applications
Posted by
jasper22
at
10:29
|
Localization is the customization of applications for a given culture or locale. Localization consists primarily of translating the user interface into the language of a particular culture or locale. Localizing an application involves creating a separate set of resources (such as strings and images) that are appropriate for the users of each targeted culture or locale and that can be retrieved dynamically depending on the culture and locale.
This topic contains the following sections:
Localization and Resource Files
Localizing Out-of-Browser Applications
Localization and String Size
Displaying Chinese, Japanese, and Korean Text
Deploying a Targeted Localized Application
Retrieving Specific Localized Resources
Localization and Resource Files
The .NET Framework for Silverlight uses a hub-and-spoke model to package and deploy resources. The hub is the main assembly that contains the nonlocalizable executable code and the resources for a single culture, which is called the neutral or default culture. The default culture is the fallback culture for the application. It represents a region-neutral language such as "en" if the default language is English or "fr" if the default language is French. The spokes connect to satellite assemblies, and each satellite assembly contains the resources for a single supported culture, but does not contain any code. At run time, a resource is loaded from the appropriate resource file, depending on the value of the application's current user interface (UI) culture, which is defined by the CultureInfo.CurrentUICulture property.
Read more: MSDN
Thrift
Posted by
jasper22
at
10:26
|
Thrift is a software framework for scalable cross-language services development. It combines a software stack with a code generation engine to build services that work efficiently and seamlessly between C++, Java, Python, PHP, Ruby, Erlang, Perl, Haskell, C#, Cocoa, JavaScript, Node.js, Smalltalk, and OCaml.
Originally developed at Facebook, Thrift was open sourced in April 2007 and entered the Apache Incubator in May, 2008.
Read more: Apache Thrift
Шаблон проекта многоязычного WPF приложения
Posted by
jasper22
at
10:18
|
Введение
Локализация приложения на WPF — не легкое занятие. Практически любое пособие по локализации WPF изобилует деталями и ручными шагами для реализации локализованного приложения.
Существующие решения
Локализация с помощью утилиты LocBaml, описанная в руководстве по локализации от Microsoft имеет множество преимуществ, однако сложна для поддержки. André van heerwaarde, в своей статье предложил упростить это решение с помощью настроенного шага сборки, он же написал утилиты для слияния переведенных текстовых фрагментов. Однако, в его статье, так же много ручных шагов.
Шаблон проекта Visual Studio
Я предлагаю воспользоваться созданным мной шаблоном локализованного приложения, для начала работы над многоязычным WPF приложением. Проект, созданный с помощью этого шаблона, уже содержит все необходимые утилиты, для локализации, а так же максимально автоматизирует процедуры локализаци в процессе разработки.
В процессе разработки приложения вы добавляете новые XAML файлы, не заботясь о локализации. По завершению внесения изменений выполните сборку проекта.
Настроенный шаг перед сборкой вызовет msbuild /t:updateuid [Имя проекта].csproj. Этот шаг автоматически добавляет x:Uid в каждый элемент, содержащий текстовые элементы.
После чего в процессе сборки будет автоматически запущен LocBaml, который найдет все текстовые элементы в XAML файлах и создаст CSV файл, содержащий текстовые элементы.
Следующий шаг запустит утилиту MergeLocBamlCsv от André van heerwaarde. В результате чего предыдущие переведенные фрагменты будут объединены с новыми. Утилита StripLocBamlCsv вырежет неиспользуемые элементы из CSV файлов.
Единственное, что вам придется сделать вручную, это добавление новых языков и собственно сам перевод.
Добавление нового языка
Для добавления нового языка в проект вам придется:
скопировать локализацию нейтрального языка в новый CSV файл
copy Translation\Translate.csv Translation\Translate.ru-RU.csv
открыть файл проекта в текстовом редакторе и после строчек:
<LocBamlCsv Include="Translation\Translate.de-DE.csv">
<Culture>de-DE</Culture>
</LocBamlCsv>
добавить новый язык, например
<LocBamlCsv Include="Translation\Translate.ru-RU.csv">
<Culture>ru-RU</Culture>
</LocBamlCsv>
После этого нужно переоткрыть проект в Visual Studio, если проект уже был открыт, то среда разработки спросит, желаете ли вы переоткрыть проект, для отражения внесенных изменений, ответьте 'Да'.
Если вы не допустили ошибок, то во вновь открытом проекте в папке Translation появится новый файл Translate.ru-RU.csv
Read more: Habrahabr.ru
XAML И DATA BINDING: ЕЩЕ РАЗ ПРО STRINGFORMAT
Posted by
jasper22
at
10:17
|
STRINGFORMAT И СТРОКИ
Казалось бы, какие могут быть особенности при связывании строки в XAML. А ведь есть. Даже, по правде сказать, не столько “особенности”, сколько “полезности”. Итак, поехали. Давайте на форму поместим какой-нибудь контрол, как предмет для издевательств, а далее просто примеры применения.
<TextBlock x:Name="userControl" Text="Полезный параметр StringFormat"/>
Пример 1: Связывание произойдет и строка будет содержать как минимум 15 символов. Дополнительные (недостающие до 15) символы пробелов будут подставлены с начала и с конца строки.
<TextBlock Text="{Binding Text, StringFormat=\{0\,15\}, ElementName=userControl}"/>
Пример 2: Связывание произойдет и строка будет содержать как минимум 25 символов. Дополнительные (недостающие до 25) символы пробелов будут подставлены с начала и с конца строки.
<TextBlock Text="{Binding Text, StringFormat=\{0\,25\}, ElementName=userControl}"/>
Пример 3: Значение свойства Text контрола userControl будет являться цитатой, то есть будет отображено в кавычках.
<TextBlock Text="{Binding Text,
StringFormat='Цитата "\{0\}" в кавычках',
ElementName=userControl}"/>
STRINGFORMAT И ЦИФРЫ
Формат вывода цифр тоже можно контролировать. Опять же просто приведу примеры, потому как именно по этой причине мы тут и собрались. Итак, у нас есть:
<TextBlock x:Name="userControl" Text="[какое-то double значение]" />
Примечание
Если просто написать вместо [какое-то double значение], то оно воспримется как текст, поэтому важно именно привязать (через Binding) это значение.
Read more: МУЗЕЙ ЮМОРА
Threading recipes: the many ways of spawning background works in Silverlight
Posted by
jasper22
at
10:13
|
People often think at Silverlight like a beautiful toolset useful to create amazing interfaces on the web. Since it is true for sure that it does not exists a similar toolset that join power and simplicity like Silverlight does, it's already true that under the cover of the user interface it beats a tiger heart that is capable of features that are typically reserved to desktop frameworks. As an example, a respectful application framework can't play its role without the capability of processing background operations and from this point of view Silverlight is not second to any other.
Processing background operations is important for a number of reasons; first of all, since we are developing application that have an user interface it is important to process things without locking the UI. When you call the network this is implicitly done but there is many cases you have to do this by hand for your particular purposes. Secondary it is important to be able to optimize the computation when you have an huge number of elements process. From this point of view the threading helps you to improve the performances of the application balancing the work across multiple threads. Finally there is many times when you need to run scheduled operations - for instance when you need to poll the network - and being able to spawn a thread responsible of scheduling the activities is important to better organize the application.
Silverlight contains an huge set of threading tools and sometimes it is difficult to choose from one or the other, and also often at the way you chosen for your purpose, it corresponds another way that is better tailored for your needs.
Concurrency and Marshaling: the two edges of the threading blade
Before starting to explain some of the ways of spawning a background thread, is it required to spend some words about what you have to be strongly aware when you start writing in a multithreaded way. As you will see there is lot of opportunities for threading but the very difficult thing is not starting the background operation but usually dealing with concurrency and marshaling.
Concurrency is a concept so hard to deal with almost as simple it is to be explained. Imagine you have a resource shared by two persons that may access and change it, you need to be careful that the manipulation made by one of the two actors does not have impact with the work that is done by the other side. Explaining concurrency properly is out of the scope of this article since it probably will take lot of pages. Suffice is to understand that Silverlight has a number of tools that helps you to deal with concurrency. Lock, Monitor, Interlocked, ManualResetEvent, AutoResetEvent and WaitHandles are all types that in a way or in another can be used to manage access to shared resources. Someone is specifically drafted for the purpose of synchronizing threads (Lock, Monitor and Interlocked) and other are supporting tools that enable waiting across threads (events and WaitHandles). I suggest you to spent some time trying to understand how they works just a minute after the end of this reading and for sure before start writing a single line of code.
Read more: Silverlight show
MonoTouch/MonoDroid and Xamarin - what now?
Posted by
jasper22
at
10:12
|
If you are in the mono community then you'd have to be living under a rock not to have read that Novell was purchased by Attachmate then (first) heard the rumors that Attachmate Lets US Mono Developers Go and (second) seen Miguel's confirmation/announcement of the creation of Xamarin.
What I think this means is:
- Mono should be fine. It has always been open-source (see github.com/mono) and receives contributions from a variety or people regardless of who they work for.
- The MonoTouch and Mono for Android (aka MonoDroid) products published by Novell will effectively stop being supported "as of now". This is based on the fact that none of the devs work there any more.
- Attachmate hasn't announced any plans for those products - even whether they'll continue to be available for sale (along with the associated activation servers). It's impossible to predict what will happen here... various people are trying to get answers from Novell/Attachmate. Personally, even if Attachmate attempted to continue selling/supporting the products I would choose not to be their customer as soon as alternatives are available.
- Miguel and the team who built MonoTouch and MonoDroid have publicly announced they're working on comparable/compatible products to be sold by Xamarin (their new company). These new products are 3-4 months away, betas first prior to a real release. They've done it before, they can do it again!
Lots of people (myself included) have invested plenty of time and money purchasing, learning and using MonoTouch and MonoDroid. I even helped write a MonoTouch book (and some guys have been busy with a MonoDroid one too). We are all collectively upset, disappointed and angry (imagine how the devs themselves feel).
All of this uncertainty has provoked a number of reactions, among them suggestions that all the work done on MonoTouch/MonoDroid projects to-date has been wasted or that people should start learning the native SDKs for iOS and Android instead of committing to the Mono alternatives.
Read more: ConceptDev (Craig Dunn's blog)
Visual Studio vNext
Posted by
jasper22
at
10:11
|
На проходящей нынче конференции TechEd компания Microsoft наконец приоткрыла карты на счёт следующей версии Visual Studio (кодовое название пока — vNext). Были указаны основные векторы развития, оглашен пяток серьёзных фич и показано пару скриншотов. Если есть желание — можно почитать об этом большой или даже еще больший документ на английском, ну а я сделаю короткую выжимку на русском. А еще скоро будет видео, но пока нету.
Agile Planning
Microsoft окончательно прониклась мыслью, что будущее — за гибкими технологиями разработки. В веб-интерфейсе TFS можно увидеть backlog, деление на спринты и другие атрибуты Scrum. Выглядит симпатично. Насколько юзабельно — по скриншотам не понятно.
Быстрое прототипирование
Microsoft согласилась с мыслью, что быстренько набросать прототип приложения в Студии для демонстрации заказчику не так уж и просто и выпустила отдельный инструмент для этого. Правда, не обошлось без «Microsoft-way»: инструмент называется Storyboarding и представляет собой плагин к PowerPoint, добавляющий в него ряд компонентов, возможность разложить их на форме и привязать к ним некоторые события (например, чтобы показать, что клик вот по этой кнопке откроет вот эту форму).
Read more: Habrahabr.ru
How long do taskbar notification balloons appear on the screen?
Posted by
jasper22
at
10:02
|
We saw some time ago that taskbar notification balloons don't penalize you for being away from the computer. But how long does the balloon stay up when the user is there?
Originally, the balloon appeared for whatever amount of time the application specified in the uTimeout member of the NOTIFYICONDATA structure, subject to a system-imposed minimum of 10 seconds and maximum of 60 seconds.
In Windows XP, some animation was added to the balloon, adding 2 seconds of fade-in and fade-out animation to the display time.
Starting in Windows Vista, applications are no longer allowed to specify how long they wanted the balloon to appear; the uTimeout member is ignored. Instead, the display time is the amount of time specified by the SPI_GETMESSAGEDURATION system parameter, with 1 second devoted to fade-in and 5 seconds devoted to fade-out, with a minimum of 3 seconds of full visibility. In other words, if you set the message duration to less than 1+3+5=9 seconds, the taskbar behaves as if you had set it to 9 seconds.
The default message duration is 5 seconds, so in fact most systems are in the "shorted possible time" case. If you want to extend the time for which balloons notification appear, you can use the SystemParametersInfo function to change it:
BOOL SetMessageDuration(DWORD seconds, UINT flags)
{
return SystemParametersInfo(SPI_SETMESSAGEDURATION,
0, IntToPtr(seconds), flags);
}
Read more: The old new thing
Использование Protocol Buffers на платформе .Net (Часть 1)
Posted by
jasper22
at
10:01
|
Предлагаю вашему вниманию введение в использование Protocol Buffers на платформе .Net в формате дискуссии. Я расскажу и покажу что это такое и зачем оно нужно .Net разработчику. Топик требует от читателя начального владения языком C# и системой контроля версий SVN. Так как объем материала превышает среднестатистический объем топиков на хабре, которые не вгоняют хаброюзеров в тоску и не заставляют их скроллить до комментариев, было принято решение разбить его на две части. В первой части мы познакомимся с основами и даже напишем (не)много кода!
Здравствуйте, а что такое Protocol Buffers?
Согласно определению на официальной странице, Protocol Buffers (protobuf) – это способ кодирования структурированных данных в эффективном и расширяемом формате, применяемый корпорацией Google почти во всех своих продуктах. Для большинства платформ, включая .Net, такой процесс называется сериализацией.
Я пользуюсь сервисами Google, но как protobuf поможет мне в разработке .Net приложений?
Да вы правы, Google не занимается написанием специализированных библиотек для .Net разработчиков. Однако существует проект protobuf-net (одна из нескольких реализаций protobuf для платформы), который позволяет использовать protobuf в .Net. Им руководит Marc Gravell — завсегдатай stackoverflow.com и участник множества других отличных проектов. Так что вы всегда можете задать ему вопрос, и он с радостью ответит на него (чем и злоупотреблял автор топика).
Почему мне стоит использовать эту библиотеку вместо встроенных средств?
Когда речь заходит о сериализации в .Net, все обычно вспоминают о существовании бинарного форматера и xml сериализатора. Следующее, что отмечают разработчики, то, что первый быстрый и имеет высокую степень сжатия, но работает только в пределах .Net платформы; а второй представляет данные в человеко-читабельном формате и служит основой для SOAP, который в свою очередь обеспечивает кросс-платформенность. Фактически утверждение, что вам всегда нужно делать выбор между скоростью и переносимостью, принимается за аксиому! Но protobuf позволяет решить обе проблемы сразу.
Read more: Habrahabr.ru
Two for one day - A cool Kinect hack and open source 3D development platform for interactive real time 3D projects
Posted by
jasper22
at
09:59
|
OpenSpace3D is a free and Open Source development platform for interactive real time 3D projects. Its mains advantages are :
User friendly, you can create a whole interactive 3D scene, with great graphical quality, without writing any code.
Power, lots of functionality are directly included, realizing an OpenSpace3D application consist in linking functionalities together, and defining theirs mutual interactions.
Technological advance, our team keep searching for and integrates the last technologies in domains of virtual reality, speech recognition, and computer graphics.
Story:
As a demo, we had developed K’AndyNect, a small tunnel game, where the goal is to catch with your hand some gems coming front to you. The player got one minute at the beginning of the game, and everytime you catch a gems, you grab some points and a few more seconds to play. There’s also red colored gems which must be avoided by the player because they drops 5 seconds of the timer (this adds fun, some players were making great and fast movement to avoid them!).
...
Note that this game was created without writing any line of code: OpenSpace3D is an 3D editor which goal is to add some interactivity to a 3d scene without code. It works with logical blocks, which triggers events and receives actions.
We also package all kinect redist (OpenNi/driver/Nite), so it’s easier for end-user to use a Kinect on pc (it’s much more like clicking “next/next/next” on a unified setup instead of manually install those 3 setups, and configuring them by hand).
Read more: Greg's Cool [Insert Clever Name] of the Day
Read more: K’AndyNect Kinect game
Node.js on Android
Posted by
jasper22
at
09:58
|
I'm trying to make the recently popular (well, maybe not so recently) Node.js run on Android. So far, I've succeeded in getting it to run on the ISO1, a smartphone running Android 1.6, but only by doing the following.
Here are the basic steps:
Root the IS01
Use qemu to build a Linux on an ARM environment
Use the ARM Linux environment to build Node.js
Copy the Node.js binary to the IS01
Rooting the IS01
This step requires root permissions on Android to get Node.js running, since we need to create a lib directory in which to place shared libraries.
To root the device quickly, we'll follow the directions in the MobileHackerz Blog: Getting Root Permissions for the au IS01, build 01.00.09(Japanese).
Following the directions there is an easy way to get root.
Things to watch out for:
Turn USB debugging on.
Settings => Applications => Development => USB debugging
Install ChainsDD Superuser.
Install it from the Android Market
Try repeatedly until it works.
Using qemu to build Linux on an ARM environment
Using qemu allows us to emulate an ARM CPU, and build a virtual environment. We'll install debian on qemu, and from there build Node.js. This will get us a Node.js binary that can run on an ARM processor.
Read more: AMT blog
Memory Corruption, GC, and Overlapping Objects
Posted by
jasper22
at
09:57
|
Dima has brought to my attention a nasty bug probably attributed to a memory corruption. The bug’s manifestation is usually an access violation in a completely unrelated piece of code, oftentimes causing an ExecutionEngineException.
This is an example of an access violation of the above variety (some of the output was snipped for brevity):
0:004> .loadby sos clr
0:004> g
(510.c88): Access violation - code c0000005 (first chance)
First chance exceptions are reported before any exception handling.
This exception may be expected and handled.
00742a11 8b4028 mov eax,dword ptr [eax+28h] ds:002b:0000002c=????????
0:000> !CLRStack
OS Thread Id: 0xc88 (0)
Child SP IP Call Site
004bedb8 00742a11 OverlappingObjects.Program.Main(System.String[]) [\OverlappingObjects\Program.cs @ 51]
004beff0 724221bb [GCFrame: 004beff0]
0:000> k
ChildEBP RetAddr
WARNING: Frame IP not in any known module. Following frames may be wrong.
004bedc4 724221bb 0x742a11
004bedd4 72444be2 clr!CallDescrWorker+0x33
004bee50 72444d84 clr!CallDescrWorkerWithHandler+0x8e
Read more: All Your Base Are Belong To Us
netMonkey
Posted by
jasper22
at
09:56
|
Project Description
netMonkey is a .net wrapper around SpiderMonkey, Mozilla's javascript implementation.
It will let you embed javascript scripts in your app with ease.
It is written in C# 4 and will eventually run on both the .net framework and mono.
Features:
Run on .net framework and mono from any .net compliant language.
Call .net functions and use .net classes straight from javascript.
API looks like C# code as opposed to C code.
Read more: Codeplex
20 Linux Server Performance Tips
Posted by
jasper22
at
09:56
|
Below are some performance tips based on Linux features. These performance guidelines will enhance Linux’s efficiency.
1. Tuning of the Elevator Algorithm in Linux Kernel for Disk I/O
After choosing the file system, there are several kernel and mounting options that can affect it. One such kernel setting is the elevator algorithm. By tuning the elevator algorithm, the system can balance the need for low latency with the need to collect enough data to efficiently organize batches of read and write requests to the disk.
2. Disable Unnecessary Daemons for Saving Memory and CPU space
There are numerous daemons or background services which run on every server, and the ironic thing is that they’re usually not required. But services with no utility still utilize valuable RAM and CPU time. In addition, they may expose the server to be attacked remotely. So, you should discard them from the server. The best place to disable them is the startup scripts that start these services at boot time. Disabling these daemons free up memory and decreases startup time. In addition, you’ll cut the number of processes that the CPU has to handle. Another benefit of disabling them is increased security of the server because fewer daemons mean fewer exploitable processes.
3.Shutdown GUI
Broadly speaking, there is no requirement for a GUI on a Linux server. Hence, it is better to shut down GUI as all administration tasks can be achieved by the command line, redirecting the X display or through a Web browser interface. In order to disable GUI, “init level” should be set to 3 (command line login), rather than 5 (graphical login). If a GUI is needed, it can always be started manually with startx.
4.Clean up modules or features
There are number of features enabled in server software packages (such as Apache) that are not really required. Look at the configuration files for Apache and decide if FrontPage support or some of the other extra modules re required. If the answer is “no,” disable unnecessary modules from the server. It helps in increasing the system memory, and it lends more resources to the software that truly needs it to run fast!
5. Disable control panels
In Linux, there are a number of the more popular control panels, such as Cpanel, Plesk, Webmin, and phpMyAdmin which everyone loves. However, disabling these software packages can make as much as 120 MB of RAM free! Hence it is advised to disable these control panels until they are actually needed. They can be turned on via a PHP script (albeit somewhat insecure), or via a command entered at a shell prompt. By doing this, you can decrease the amount of RAM being used by as much as 30-40%.
Read more: Monitis part1, part2
How The Martha Graham Google Logo is Animated (Short Explanation)
Posted by
jasper22
at
09:53
|
Google’s logo was so cool today, I had to write something. Here’s a short explanation of how they did it:
First, start with an sprite image that contains every frame of the animation. Next, have in mind to create a whole lota <div>s, styled like so…
<div id="hplogo0" style="left: 307px; top: 48px; width: 88px; height: 89px; background: url(logos/2011/graham11-hp-sprite.png) no-repeat scroll 0px 0px transparent;"></div>
<div id="hplogo1" style="left: 307px; top: 48px; width: 89px; height: 89px; background: url(logos/2011/graham11-hp-sprite.png) no-repeat scroll -88px 0px transparent;"></div>
<div id="hplogo2" style="left: 307px; top: 48px; width: 91px; height: 89px; background: url(logos/2011/graham11-hp-sprite.png) no-repeat scroll -177px 0px transparent;"></div>
//...and so on, and so on
Firebug is a web develper's best friend
The best way to see how these <divs> will tie together is to use a tool like Firebug or the Webkit Inspector to inspect the Google logo after the animation is complete. Since the logo will only be for a single day, I’ve included a screen capture.
Read more: AcumenBrands
Integrating Security into Silverlight Applications
Posted by
jasper22
at
09:51
|
Security is a key component of applications and something that developers often struggle with to get right. How do you authenticate a user? How do you integrate roles and use them to show or hide different parts of a screen? These and other questions commonly come up as I talk with developers working on ASP.NET and Silverlight applications.
While I was presenting a workshop on Silverlight at the DevConnections conference in Orlando last March, an audience member asked me a question about how I handle security roles in Silverlight applications. Since I had just implemented a security mechanism for a customer, I gave a brief response but didn't have a sample application available to share to point people in the right direction. After the workshop was over, I put together a sample application to demonstrate one potential approach for accessing usernames and roles. I'll walk through the sample application in this article and highlight the key components.
The goal of the article isn't to dictate how to authenticate users, since every application has unique requirements. However, I will discuss general techniques for accessing usernames and working with roles to block access to views and show or hide controls.
Working with Security
Silverlight applications can take advantage of Windows and Forms authentication techniques and can integrate user roles into the mix as well. However, unless you use Windows Communication Foundation (WCF) RIA Services on the back end, you'll need to write the plumbing code to authenticate a user if you need to do so directly within the application. WCF RIA Services projects provide login and registration screens out of the box that leverage Forms authentication by default. You can view a walk-through of the WCF RIA Services authentication process.
WCF RIA Services also provides a means for accessing an authenticated user's username and roles by using a WebContext object. This isn't possible out of the box in a standard Silverlight application unless you write custom code to handle it. If WCF RIA Services is appropriate for your project, then it's a great way to go for handling data exchange and security tasks. If you won't be using WCF RIA Services, then this article will provide insight into other techniques that can be used.
Read more: DevProConnections
Ultimate Bashrc File 3.4
Posted by
jasper22
at
09:46
|
Description:
For those who love using the terminal, here is a '.bashrc' file I created, mainly for those who've had issues with their own. Hopefully it'll benefit those of whom love aliases, functions, and such. Probably more than you need, so modify all you want. I've organized it best I can to make it easier for using and modification. This is also for those many who've had a difficult time finding a good source for their own on the net, like it was for me.
Oh, and any modifications that others wish to share are always welcome.
Instructions:
Just extract the tar file and put in your home directory. You may have to overwrite the current one, so be sure to backup whatever beforehand. FYI, the default text in the '.bashrc' is included in this version so if you haven't modified it at all, you should have nothing to worry about.
To refresh it, just type in the terminal:
source ~/.bashrc
...or just close your terminal window and open it again.
Read more: Gnome-look
Четыре вида метаданных NTFS
Posted by
jasper22
at
09:46
|
В данной теме я рассмотрю четыре вида метаданных, которые могут быть прикреплены к файлу или каталогу средствами файловой системы NTFS. Я опишу, в каких целях можно использовать тот или иной тип метаданных, приведу пример его применения в какой-либо технологии Microsoft или стороннем программном обеспечении.
Речь пойдёт о точках повторной обработки (reparse points), идентификаторах объектов (object id) и о других типах данных, которые может содержать файл помимо своего основного содержимого.
Object Id
Идентификатор объекта это 64 байта, которые можно прикрепить к файлу или каталогу. Из них первые 16 байт позволяют однозначно идентифицировать файл в пределах тома и обращаться к нему не по имени, а по идентификатору. Остальные 48 байт могут содержать произвольные данные.
Идентификаторы объектов существуют в NTFS со времён Windows 2000. В самой системе они используются для отслеживания расположения файла, на который ссылается ярлык (.lnk). Допустим, файл, на который ссылается ярлык, был перемещён в пределах тома. При запуске ярлыка он всё равно откроется. Специальная служба Windows в случае, если файл не найден, произведёт попытку открыть файл не по его имени, а по заранее созданному и сохранённому идентификатору. Если файл не был удалён и не покидал пределы тома, он откроется, а ярлык снова будет указывать на файл.
Идентификаторы объектов использовались в технологии iSwift Антивируса Касперского 7-ой версии. Вот как описана эта технология: Технология разработана для файловой системы NTFS. В этой системе каждому объекту присваевается NTFS-индентификатор. Этот индентификатор сравнивается с значениями специальной базы данных iSwift. Если значения базы данных с NTFS-индентификатором не совпадают, то объект проверяется или перепроверяется, если он был изменен.
Впрочем, переизбыток созданных идентификаторов вызывал проблемы со сканированием диска стандартной утилитой проверки chkdsk, она происходила слишком долго. В следующих версиях Антивируса Касперского отказались от использования NTFS Object Id.
Reparse Point
В файловой системе NTFS файл или каталог может содержать в себе reparse point, что переводится на русский язык как «точка повторной обработки». В файл или каталог добавляются специальные данные, файл перестаёт быть обычным файлом и обработать его может только специальный драйвер фильтра файловой системы.
Read more: Habrahabr.ru
Microsoft Unity 2.1 for Silverlight
Posted by
jasper22
at
09:43
|
Overview
Unity is a dependency injection container. It is full-featured, with support for instance and type interception and custom extensions. This release is a port of Unity 2.1 to Microsoft Silverlight 3, 4 and 5 beta. Interception is now supported.
Read more: MS Download
NUnrar - Unrar in pure C#
Posted by
jasper22
at
09:42
|
Project Description
NUnrar is a native C# unrar library that supports forward-only (i.e. Network) streams and Silverlight. No intermediate buffering necessary. Random access is also available.
It was ported from the JUnrar version of unrar (http://java-unrar.sourceforge.net/) by Edmund Wagner.
SharpCompress is the future for NUnrar http://sharpcompress.codeplex.com/
Read more: Codeplex
Ubuntu Linux Satanic Edition (666.9) review
Getting ready to review a Linux distribution is usually pretty straightforward. After some background research into the distribution's history, you download the latest ISO and beseech the head of IT to lend you a netbook or scrounge up some moth-infested, aging desktop PC.
In the case of Ubuntu Linux Satanic Edition ("Linux for the Damned"), however, I had wondered whether I would require some kind of spiritual preparation: Perhaps a confession of my sins to the nearest religious authority. Deadline pressure meant that there was no time for me to unburden myself of my frequent and extensive contraventions of the moral codes of many major religions (and quite a few minor ones). My atheist soul would have to face the distribution unshriven.
Read more: TechWorld
How to eliminate tempuri.org from your service WSDL
Posted by
jasper22
at
11:37
|
tempuri.org is the default namespace applied to WCF Services and Workflow Services. You can and should specify your service namespace.
It is recommended that you explicitly specify a name and namespace for the service contract, and an action for each operation to avoid using "http://tempuri.org" and to prevent interface and method names from being exposed in the service’s contract
MSDN Library - Service Contract Versioning
Where is tempuri.org in the WSDL?
If you browse the service WSDL you will see tempuri.org all over the place. Here is a default WCF service WSDL.
Read more: The .NET Endpoint
If undecorated names are given in the DLL export table, why does link /dump /exports show me decorated names?
Posted by
jasper22
at
11:37
|
If you run the link /dump /exports command on a DLL which exports only undecorated names, you may find that in addition to showing those undecorated names, it also shows the fully-decorated names.
We're building a DLL and for some functions, we have chosen to suppress the names from the export table by using the NONAME keyword. When we dump the exports, we still see the names. And the functions which we did want to export by name are showing up with their decorated names even though we list them in the DEF file with undecorated names. Where is the decorated name coming from? Is it being stored in the DLL after all?
1 00004F1D [NONAME] _Function1@4
2 000078EF [NONAME] _Function2@12
3 00009063 [NONAME] _Function3@8
The original decorated names are not stored in the DLL. The link /dump /exports command is sneaky and looks for a matching PDB file and, if finds one, extracts the decorated names from there.
Read more: The old new thing
Android and Arduino pair up
Posted by
jasper22
at
11:21
|
Google has announced an SDK that allows the development of USB peripherals for all Android devices using an Arduino hardware component.
Many news sources are getting this confused with the bigger and more ambitious project that Google has in mind to make Android the universal home control system - Android@Home - but this isn't the case. The new facility solves a much more modest problem but it has the advantage of being with us now.
While other phone manufacturers are doing their best to keep you out of their hardware Google's ADK - Accessory Development Kit - aims at making it easy for you to connect almost anything to an Android. In short it is a way of creating Android hardware peripherals that connect to the device via USB. The ADK works on the latest Android 3.1 and it has been backported to work on Android 2.3.4.
A special Android Open Accessory mode has been introduced which allows the devices to communicate via USB. In this case, however, it is the remote device is the primary device, i.e. the host, and even charges up the Android as if it was an accessory.
Some Android devices are already capable of acting as a host, usually tablets with an additional host USB connector. In this case you can simply connect any standard USB device, a hard disk say or USB stick and use it in the standard way. However, most phones can't act as a host device and can't initiate a USB connection. You can plug them into a PC say and then the PC acts as the host and makes the Android storage available as local storage. It is reasonably safe to say that most Android devices have to have a non-host USB connector, however.
So to be clear, the ADK simply provides a way of creating USB peripherals to those devices that can't act as a host by allowing the peripheral to act as the host and use the Android device as an accessory. When an ADK based peripheral is connected to an Android device it first has to check that the Android can work in the required mode - if not it simply won't connect. So ADK based peripherals are not going to work until a significant number of devices are running Android 2.3.4 or later.
Read more: I Programmer
Silverlight 4: End-to-End Application using Prism 4, WCF 4 and DataGrid Custom Behavior
Posted by
jasper22
at
11:21
|
With the support for Prism 4 and the growing popularity of Silverlight 4 for line-of-business application development, there is a lot of buzz amongst developers to use the new features these technologies has to offer. So for example, I have observed that the demand for providing a simple and more interactive UX for developing DML UI using DataGrid is increasing. In this article, we will cover just that. I have explained the mechanism for performing CRUD operations using the Silverlight 4 DataGrid and have used SL 4, Prism 4 and WCF 4.0, along with DataGrid Custom behavior. The architecture is as below:
Read more: dot net curry
A Complete Guide to Expression Blend 4 Shortcut Keys
Posted by
jasper22
at
11:19
|
In this post, I will share you some important Shortcut keys of Microsoft Expression Blend 4. If you are working with Expression Blend 4, this will definitely help you to improve your daily productivity work. Keep the list with you always to best use of the Shortcut keys in Blend 4 while designing your XAML page.
If you have more shortcuts, please share those to me and I will include them here as the key resource. Thanks for your support. If you are a XAML developer and using Expression Blend 4, this post will really help you. You will be able to download the free eCopy of the List at the end. Here is the list of important shortcut keys which can improve your productivity while working in Blend 4:
Shortcut Key | Description |
F1 | Open Expression Blend User Guide (Help File) |
Ctrl + + | Zoom in designer screen |
Ctrl + - | Zoom out designer screen |
Ctrl + 0 | Fit entire page to designer screen |
Ctrl + 1 | Zoom to Actual Size |
Ctrl + 9 | Fit selection to the designer screen |
F9 | Show Handles |
Ctrl + Shift + H | Show object boundaries |
F11 | Switch Active document view |
F2 | Edit text or Rename the selected control |
Ctrl + E | Edit control |
Ctrl + Shift + ] | Bring control to Front |
Ctrl + ] | Bring control Forward |
Ctrl + Shift + [ | Send control to Back |
Ctrl + [ | Send control Backward |
Ctrl + G | Group into a Grid control |
Read more: Codeproject
Why is my SQL Server being slow... Top 10 PerfMon Counters for SQL Server Performance Monitoring
Posted by
jasper22
at
11:17
|
Do you have a list of SQL Server Counters you review when monitoring your SQL Server environment? Counters allow you a method to measure current performance, as well as performance over time. Identifying the metrics you like to use to measure SQL Server performance and collecting them over time gives you a quick and easy way to identify SQL Server problems, as well as graph your performance trend over time.
Below is my top 10 list of SQL Server counters in no particular order. For each counter I have described what it is, and in some cases I have described the ideal value of these counters. This list should give you a starting point for developing the metrics you want to use to measure database performance in your SQL Server environment.
Read more: Greg's Cool [Insert Clever Name] of the Day
How to implement Template Binding in Silverlight Custom Control?
Posted by
jasper22
at
11:17
|
Introduction
Continuing to our 2nd chapter of the series here on Silverlight Custom Control. In this chapter we will discuss on dynamically setting the Content and other properties to our Custom Control that we implemented earlier. After reading this article, you will be able to create properties and set content dynamically to your control.
So, lets start describing them and learn something again today. These series of posts are mainly targeted for beginners but anyone can read it to refresh their learning. Don't forget to leave your comment at the end of the post. Any queries, please drop a line. I will try to help you as early as I can. Don't Forget to support me by providing vote.
Background
I hope, you read my previous posts. Those will help you to understand this one very easily. If you didn't read them or want to brush up before starting this chapter, find them here:
How to create a Custom Control in Silverlight?
How to design a Custom Control by editing the Part Template?
Once you are familiar with the previous context, lets start with this one. We will use the same example here which will give you more visualization on the sample code.
Working with the Template Part
Template parts are defined in the XAML inside the style. In our example, we have three part called "PART_HeaderPanel", "PART_HeaderText" and "PART_Content". Those are already declared in the style and you can find them here:
Read more: Codeproject
Store credit card number using openssl rsa(Encryption & Decryption)
Posted by
jasper22
at
11:15
|
There are lots of ways to store credit card information in a datastore with the two way encryption method. I would like to share one with Openssl RSA-dse3 with 2048 bits. Lets start playing with it.
#Requirements:
1) Openssl (yum install openssl) # centos flavor
# Now if need to create public and private key. Public key to decrypt and private key to encrypt.
* Create private key(Details: http://www.openssl.org/docs/apps/genrsa.html)
[root@localhost sudhir]# openssl genrsa -des3 -out private.pem 2048
Generating RSA private key, 2048 bit long modulus
..........................+++
......+++
e is 65537 (0x10001)
Enter pass phrase for private.pem:
Verifying - Enter pass phrase for private.pem:
[root@localhost sudhir]#
* View generated file
[root@localhost sudhir]# ls -la
drwxr-xr-x 2 root root 4096 Nov 24 21:03 .
drwxr-x--- 16 root root 4096 Nov 24 21:03 ..
-rw-r--r-- 1 root root 1751 Nov 24 21:04 private.pem
[root@localhost sudhir]#
* Check whats in private.pem file
[root@localhost sudhir] rvim ./private.pem
-----BEGIN RSA PRIVATE KEY-----
Proc-Type: 4,ENCRYPTED
DEK-Info: DES-EDE3-CBC,88831CE47DB54B21
Read more: Sudhir Chauhan
How to access Control Template parts from Code Behind
Posted by
jasper22
at
11:13
|
Here is the last chapter of the series for Silverlight Custom Control. In this article, we will learn how to access the template parts from code behind to do various operations in the UI front.
Hope you read the previous three articles and are familiar with the Custom control as of now. This article will help you to understand accessibility of the template parts from the code. So, let's start discussing now. I appreciate your feedback as always.
Background
I hope you read my previous three articles. Those will help you to understand the context of this one very easily. If you didn't read them or want to brush up before starting this chapter, find them here:
How to create a Custom Control in Silverlight?
How to design a Custom Control by editing the Part Template?
How to implement Template Binding in Silverlight Custom Control?
Once you are familiar with the previous code, let's start with this one. We will use the same example here which will give you better visualization on the sample code.
Brush up Previous Chapter on Parts
In our previous article, we discussed about template parts. These are the UI elements available in your style of the custom control. Generally, we prefix their name with PART_. In the control's class, we initialize them with the attribute called TemplatePart as shown below. This is to make sure that the metadata of the class shows them properly and your user can easily understand which UI elements you used there. Also, this is beneficial for you to easily access the parts in the file.
Once you marked the template parts in the class, you can declare the member variables to store the instance of those parts, so that you can access them easily. Remember that only get the instance whenever required. If you need them multiple times, better declare them as member variable and use throughout the life of the control.
Declaring Private Members for Part Instance
We need to declare the member variables now to store the instance of the template parts. In this example, we used three parts called Border, TextBlock and ContentPresenter. Declare the private instances of them. This is simple enough. The below screenshot will help you to understand:
Read more: Codeproject
Subscribe to:
Posts (Atom)