Thursday, 3 October 2013

UITextField UITextBorderStyleNone has lines everywhere in iOS7

UITextField UITextBorderStyleNone has lines everywhere in iOS7

I added a UITextField in Interface builder and selected
UITextBorderStyleNone. However the text field has lines in it and
partially around the border. See Image, the textfield in question is on
the left:

Prior to iOS7 I would have expected no border and no lines in that text
field.
I tried setting the border in code
[self.textFieldXX setBorderStyle:UITextBorderStyleNone];
but no change.
When I set a red border (as a test) I see this

[self.textFieldXX.layer setBorderColor:[[UIColor redColor] CGColor]];
[self.textFieldXX.layer setBorderWidth:1.0];
Qn. What gives?
Qn. What are those vertical lines in the text fields?
Qn. How to fix?

Wednesday, 2 October 2013

WPF MVVM Case: ItemsControl contains hyperlink and command to update property in ViewModel

WPF MVVM Case: ItemsControl contains hyperlink and command to update
property in ViewModel

I have a case, a little bit more complex but I try to illustrate and do
some modification to show the point in a simple way.
Let's say I have a Window1 as view and a Window1ViewModel as its
viewmodel. I also have a SubMenuViewModel class to represent submenu in
the window. I want to make an ItemsControl in Window1 which contains many
submenus. Every time user clicks one of the submenu, the property
CurrentSubMenu updates to the corresponding submenu. This is the problem,
I can't manage to update the CurrentSubMenu in the Window1ViewModel
SubMenuViewModel :
public class SubMenuViewModel : INPC
{
private string _submenuname;
public string SubMenuName
{
get
{ return _submenuname; }
set
{
_submenuname = value;
RaisePropertyChanged("SubMenuName");
}
}
private string _displayname;
public string DisplayName
{
get
{ return _displayname; }
set
{
_displayname = value;
RaisePropertyChanged("DisplayName");
}
}
// Command for Hyperlink in ItemsControl //
private RelayCommand _commandSubmenu;
public RelayCommand CommandSubMenu
{
get
{ return _commandSubmenu; }
set
{
_commandSubmenu = value;
RaisePropertyChanged("CommandSubMenu");
}
}
// end of command
public SubMenuViewModel(string Submenu_name, string Display_name)
{
_submenuname = Submenu_name;
_displayname = Display_name;
}
}
Window1 :
<Window x:Class="SomeProject.Window1"
xmlns:vm="clr-namespace:SomeProject.ViewModel"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="This is Some Project" WindowState="Maximized">
<Window.DataContext>
<vm:Window1ViewModel/>
</Window.DataContext>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="250" />
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Border Name="SubMenuPanelBorder"
Grid.Column="0"
Grid.Row="1"
HorizontalAlignment="Stretch"
VerticalAlignment="Stretch"
Margin="15 0 15 0"
BorderThickness="2"
BorderBrush="Black"
Padding="10 10">
<HeaderedContentControl Content="{Binding Path=SubMenus}"
Header="Panel Submenu :">
<HeaderedContentControl.ContentTemplate>
<DataTemplate>
<ItemsControl ItemsSource="{Binding}"
Foreground="White" Background="Transparent"
Margin="0 15">
<ItemsControl.ItemTemplate>
<DataTemplate>
<TextBlock>
<Hyperlink Command="{Binding
Path=CommandSubMenu}">
<TextBlock Margin="0 5"
Text="{Binding
Path=DisplayName}"/>
</Hyperlink>
</TextBlock>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</DataTemplate>
</HeaderedContentControl.ContentTemplate>
</HeaderedContentControl>
</Border>
.......
.......
</Grid>
</Window>
Window1ViewModel :
class Window1ViewModel : INPC
{
private List<SubMenuViewModel> _submenus;
public List<SubMenuViewModel> SubMenus
{
get
{ return _submenus; }
set
{
_submenus = value;
RaisePropertyChanged("SubMenus");
}
}
private SubMenuViewModel _currentSubMenu;
public SubMenuViewModel CurrentSubMenu
{
get
{ return _currentSubMenu; }
set
{
_currentSubMenu = value;
RaisePropertyChanged("CurrentSubMenu");
}
}
public Window1ViewModel()
{
SubMenus = MenuDefinition.GetSubMenus();
/***
Set the SubMenus's command to update the CurrentSubMenu,
and == HERE IS WHERE I GOT LOST ==.
The CurrentSubMenu is always point to the last submenu in the
loop.
By the way, the reason I use loop is because the submenu in
the Menu definition sometimes changed and there are many
number of submenus there, and there are some other reasons (I
use Menu-submenu mechanism, but it's not essential to show it
here because it's not the main point I want to show). So,
finally I use loop instead of specifying each command one by
one.
***/
foreach(SubMenuViewModel submenu in SubMenus){
submenu.CommandSubMenu=new
RelayCommand(()=>clickedSubMenu(submenu.SubMenuName));
}
}
public void clickedSubMenu(string submenu_name)
{
CurrentSubMenu = SubMenus.Find(sub => sub.SubMenuName ==
submenu_name);
}
}
MenuDefinition :
public static List<SubMenuViewModel> GetSubMenus()
{
return new List<SubMenuViewModel>
{
new SubMenuViewModel("overview_product", "Overview
Products"),
new SubMenuViewModel("search_product","Search
Products"),
new SubMenuViewModel("update_product","Update Data
Products"),
new SubMenuViewModel("order_product","Order
Products"),
new SubMenuViewModel("supplier_product","Products
Supplier"),
.................
.................
.................
};
}
}

Plotting square() and sawtooth() in Octave

Plotting square() and sawtooth() in Octave

I was trying to plot a square wave and a saw-tooth wave in Octave, but it
gave an error saying
>>>error: 'sawtooth' undefined near line 17 column 6
error: 'square' undefined near line 17 column 6
>>>error: 'x1' undefined near line 17 column 21
error: evaluating argument list element number 2
>>>error: 'x2' undefined near line 18 column 21
error: evaluating argument list element number 2
Then I read up on internet, and came to know that I have to install some
packages. I installed the necessary packages and also their respective
dependencies. In spite of doing that, it did not make a difference. The
same error persisted. I then installed all the packages from the online
repositories. Again that made no difference.
I ran the same code in Matlab and it worked! (I know it comes bundled with
all the packages).
But I don't really get the problem I am facing in Octave. I use the
QtOctave interface and there is a option there to install packages. Is
there some way to check for installed packages? Are they actually getting
installed?
I tried the same code in FreeMat and it gave some error there too.
Here is my code:
% program to plot a saw tooth and square wave
fs = 10000;
t = 0:1/fs:1.5;
x1 = sawtooth(2*pi*50*t);
x2 = square(2*pi*50*t);
subplot(211);plot(t,x1);axis([0 0.2 -1.2 1.2]);
xlabel('Time (sec)');ylabel('Amplitude');title('Sawtooth Periodic Wave');
subplot(212);plot(t,x2);axis([0 0.2 -1.2 1.2]);
xlabel('Time (sec)');ylabel('Amplitude');title('Square Periodic Wave');
set(gcf,'Color',[1 1 1]);
Please help me to get this code to work on Octave.

Receiving memory warning when downloading files and playing video at the same time

Receiving memory warning when downloading files and playing video at the
same time

I have an app something like a media player.User can purchase video items
and play single or multiple items.
I download files with this code :
NSMutableURLRequest* rq = [[APIClient sharedClient]
requestWithMethod:@"GET" path:[[self item] downloadUrl] parameters:nil];
[rq setTimeoutInterval:5000];
_downloadOperation = [[AFHTTPRequestOperation alloc]
initWithRequest:rq] ;
_downloadOperation.outputStream = [NSOutputStream
outputStreamToFileAtPath:[[self item] localUrl] append:NO];
[_downloadOperation
setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id
responseObject) {
NSLog(@"Successfully downloaded file to %@", [_item localUrl]);
success();
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Error: %@", error);
errorBlock(error);
}];
__weak typeof(self) weakSelf = self;
[_downloadOperation setDownloadProgressBlock:^(NSUInteger bytesRead,
long long totalBytesRead, long long totalBytesExpectedToRead) {
float progress = totalBytesRead / (float)totalBytesExpectedToRead;
weakSelf.progressOverlayView.progress = progress;
}];
[_downloadOperation
setShouldExecuteAsBackgroundTaskWithExpirationHandler:^{
}];
[[APIClient sharedClient]
enqueueHTTPRequestOperation:_downloadOperation];
Nearly 10 items are in the download queue.
When 2-3 of items are downloaded, I open the custom media player
(AVPlayerQueue)
-(VideoPlayerViewController*)playMoviesForItems:(NSArray*)items{
[SharedAppDelegate pauseBackgroundMusic];
playerItems = [[NSMutableArray alloc] init];
for (ShopItem* item in items) {
NSURL *url = [NSURL fileURLWithPath:item.localUrl];
AVPlayerItem *videoItem = [AVPlayerItem playerItemWithURL:url];
[playerItems addObject:videoItem];
}
currentIndex = 0;
[self initScrubberTimer];
[self playAtIndex:currentIndex];
}
After some more files are downloaded, it starts to give memory warning,
and stops working with this error:
Terminated due to Memory Pressure
Where am I wrong? What should I release from the memory?

Tuesday, 1 October 2013

Django: ImproperlyConfigured: The SECRET_KEY setting must not be empty

Django: ImproperlyConfigured: The SECRET_KEY setting must not be empty

I am trying to setup multiple setting files (development, production, ..)
that include some base settings. Cannot succeed though. When I try to run
./manage.py runserver I am getting the following error:
(cb)clime@den /srv/www/cb $ ./manage.py runserver
ImproperlyConfigured: The SECRET_KEY setting must not be empty.
Here is my settings module:
(cb)clime@den /srv/www/cb/cb/settings $ ll
total 24
-rw-rw-r--. 1 clime clime 8230 Oct 2 02:56 base.py
-rw-rw-r--. 1 clime clime 489 Oct 2 03:09 development.py
-rw-rw-r--. 1 clime clime 24 Oct 2 02:34 __init__.py
-rw-rw-r--. 1 clime clime 471 Oct 2 02:51 production.py
Base settings (contain SECRET_KEY)
(cb)clime@den /srv/www/cb/cb/settings $ cat base.py:
# Django base settings for cb project.
import django.conf.global_settings as defaults
DEBUG = False
TEMPLATE_DEBUG = False
INTERNAL_IPS = ('127.0.0.1',)
ADMINS = (
('clime', 'clime7@gmail.com'),
)
MANAGERS = ADMINS
DATABASES = {
'default': {
#'ENGINE': 'django.db.backends.postgresql_psycopg2', # Add
'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'cwu', # Or path to database file if
using sqlite3.
'USER': 'clime', # Not used with sqlite3.
'PASSWORD': '', # Not used with sqlite3.
'HOST': '', # Set to empty string for
localhost. Not used with sqlite3.
'PORT': '', # Set to empty string for
default. Not used with sqlite3.
}
}
# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# In a Windows environment this must be set to your system time zone.
TIME_ZONE = 'Europe/Prague'
# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'en-us'
SITE_ID = 1
# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = False
# If you set this to False, Django will not format dates, numbers and
# calendars according to the current locale.
USE_L10N = False # TODO: make this true and accustom date time input
DATE_INPUT_FORMATS = defaults.DATE_INPUT_FORMATS + ('%d %b %y', '%d %b,
%y') # + ('25 Oct 13', '25 Oct, 13')
# If you set this to False, Django will not use timezone-aware datetimes.
USE_TZ = True
# Absolute filesystem path to the directory that will hold user-uploaded
files.
# Example: "/home/media/media.lawrence.com/media/"
MEDIA_ROOT = '/srv/www/cb/media'
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://media.lawrence.com/media/", "http://example.com/media/"
MEDIA_URL = '/media/'
# Absolute path to the directory static files should be collected to.
# Don't put anything in this directory yourself; store your static files
# in apps' "static/" subdirectories and in STATICFILES_DIRS.
# Example: "/home/media/media.lawrence.com/static/"
STATIC_ROOT = '/srv/www/cb/static'
# URL prefix for static files.
# Example: "http://media.lawrence.com/static/"
STATIC_URL = '/static/'
# Additional locations of static files
STATICFILES_DIRS = (
# Put strings here, like "/home/html/static" or "C:/www/django/static".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
)
# List of finder classes that know how to find static files in
# various locations.
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
# 'django.contrib.staticfiles.finders.DefaultStorageFinder',
)
# Make this unique, and don't share it with anybody.
SECRET_KEY = '8lu*6g0lg)9z!ba+a$ehk)xt)x%rxgb$i1&amp;022shmi1jcgihi*'
# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
# 'django.template.loaders.eggs.Loader',
)
TEMPLATE_CONTEXT_PROCESSORS = (
'django.contrib.auth.context_processors.auth',
'django.core.context_processors.request',
'django.core.context_processors.debug',
'django.core.context_processors.i18n',
'django.core.context_processors.media',
'django.core.context_processors.static',
'django.core.context_processors.tz',
'django.contrib.messages.context_processors.messages',
'web.context.inbox',
'web.context.base',
'web.context.main_search',
'web.context.enums',
)
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'watson.middleware.SearchContextMiddleware',
'debug_toolbar.middleware.DebugToolbarMiddleware',
'middleware.UserMemberMiddleware',
'middleware.ProfilerMiddleware',
'middleware.VaryOnAcceptMiddleware',
# Uncomment the next line for simple clickjacking protection:
# 'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
ROOT_URLCONF = 'cb.urls'
# Python dotted path to the WSGI application used by Django's runserver.
WSGI_APPLICATION = 'cb.wsgi.application'
TEMPLATE_DIRS = (
# Put strings here, like "/home/html/django_templates" or
"C:/www/django/templates".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
'/srv/www/cb/web/templates',
'/srv/www/cb/templates',
)
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'south',
'grappelli', # must be before admin
'django.contrib.admin',
'django.contrib.admindocs',
'endless_pagination',
'debug_toolbar',
'djangoratings',
'watson',
'web',
)
AUTH_USER_MODEL = 'web.User'
# A sample logging configuration. The only tangible logging
# performed by this configuration is to send an email to
# the site admins on every HTTP 500 error when DEBUG=False.
# See http://docs.djangoproject.com/en/dev/topics/logging for
# more details on how to customize your logging configuration.
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'filters': {
'require_debug_false': {
'()': 'django.utils.log.RequireDebugFalse'
}
},
'formatters': {
'standard': {
'format' : "[%(asctime)s] %(levelname)s [%(name)s:%(lineno)s]
%(message)s",
'datefmt' : "%d/%b/%Y %H:%M:%S"
},
},
'handlers': {
'mail_admins': {
'level': 'ERROR',
'filters': ['require_debug_false'],
'class': 'django.utils.log.AdminEmailHandler'
},
'null': {
'level':'DEBUG',
'class':'django.utils.log.NullHandler',
},
'logfile': {
'level':'DEBUG',
'class':'logging.handlers.RotatingFileHandler',
'filename': "/srv/www/cb/logs/application.log",
'maxBytes': 50000,
'backupCount': 2,
'formatter': 'standard',
},
'console':{
'level':'INFO',
'class':'logging.StreamHandler',
'formatter': 'standard'
},
},
'loggers': {
'django.request': {
'handlers': ['mail_admins'],
'level': 'ERROR',
'propagate': True,
},
'django': {
'handlers':['console'],
'propagate': True,
'level':'WARN',
},
'django.db.backends': {
'handlers': ['console'],
'level': 'DEBUG',
'propagate': False,
},
'web': {
'handlers': ['console', 'logfile'],
'level': 'DEBUG',
},
},
}
LOGIN_URL = 'login'
LOGOUT_URL = 'logout'
#ENDLESS_PAGINATION_LOADING = """
# <img src="/static/web/img/preloader.gif" alt="loading"
style="margin:auto"/>
#"""
ENDLESS_PAGINATION_LOADING = """
<div class="spinner small" style="margin:auto">
<div class="block_1 spinner_block small"></div>
<div class="block_2 spinner_block small"></div>
<div class="block_3 spinner_block small"></div>
</div>
"""
DEBUG_TOOLBAR_CONFIG = {
'INTERCEPT_REDIRECTS': False,
}
import django.template.loader
django.template.loader.add_to_builtins('web.templatetags.cb_tags')
django.template.loader.add_to_builtins('web.templatetags.tag_library')
WATSON_POSTGRESQL_SEARCH_CONFIG = 'public.english_nostop'
One of the setting files:
(cb)clime@den /srv/www/cb/cb/settings $ cat development.py
from base import *
DEBUG = True
TEMPLATE_DEBUG = True
ALLOWED_HOSTS = ['127.0.0.1', '31.31.78.149']
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'cwu',
'USER': 'clime',
'PASSWORD': '',
'HOST': '',
'PORT': '',
}
}
MEDIA_ROOT = '/srv/www/cb/media/'
STATIC_ROOT = '/srv/www/cb/static/'
TEMPLATE_DIRS = (
'/srv/www/cb/web/templates',
'/srv/www/cb/templates',
)
Code in /manage.py
(cb)clime@den /srv/www/cb $ cat manage.py
#!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE",
"cb.settings.development")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
If I add from base import * into /srv/www/cb/cb/settings/__init__.py
(which is otherwise empty), it magically starts to work but I don't
understand why. Anyone could explain to me what's going on here?

Why ubuntu uses base 10 for calculating file sizes?

Why ubuntu uses base 10 for calculating file sizes?

I understand that hard drive companies do it to market a 900GB HD as an
1TB one, but what is the reason that Nautilus uses base 10 as well?
Shouldn't we try to be right rather than handy?

Are there other commands like scp but for deleting files and folders=?iso-8859-1?Q?=3F_=96_superuser.com?=

Are there other commands like scp but for deleting files and folders? –
superuser.com

He there, I am using scp to copy stuff to a remote location. But sometimes
scp does not work as expected, I have found that sometimes the copy does
not complete properly (possibly when I have added …

Cannonical Homomorphisms

Cannonical Homomorphisms

Let $G$ be a group and let $N$ be a normal subgroup. Let $\pi\colon G \to
G/N$ denote the canonical homomorphism. Prove that if $H$ is a subgroup of
$G$ then $\pi(H) = \pi(HN)$. Then prove that if $H$ and $K$ are subgroups
of $G$, then $\pi(H) = \pi(K)$ if and only if $HN = KN$.
I have been able to show that if $H$ is any subgroup of $G$ then $HN$ is
also a subgroup. But I am not really sure where to go to from there.