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.

Monday, 30 September 2013

Cause for not being able to login?

Cause for not being able to login?

Before Ubuntu 12.04 LTS login screen I get this message and was wondering
if this could be the cause for the login screen returning after entering
my password and hitting enter; "The disk drive for /dev/mapper/cryptswap1
is not ready yet or not present."
When I login to my main user account it tries to load something but then
after a time just comes back to the login screen.
I am not able to login with Guest either, same kick back to login screen
after about 20-seconds.
This is a clean install.
When the Login to Guest window disappears I get a black screen with the
following message (after some OKs);
947.796019] nouveau E[ 1007] failed to idle channel 0xcccc0000
[1254.824019] """"" " [ 3136] " " " " """""""" [2417.180016] """"" " [
4086] " " " " """""" [2420.276016] """" " [ 4361] " " " " """"""
[3007.796018] """" " [ 6094] " " " " """"""

Can INSERT (x) VALUES (@x) WHERE NOT EXISTS ( SELECT * FROM WHERE x = @x) cause duplicates?

Can INSERT (x) VALUES (@x) WHERE NOT EXISTS ( SELECT * FROM WHERE x = @x)
cause duplicates?

While browsing SO I found the following Question/Discussion about the
"best" approach for inserting records that don't exist yet. One of the
statements that struck me was one of [Remus Rusanu] stating:
Both variants are incorrect. You will insert pairs of duplicate @value1,
@value2, guaranteed.
Although I do agree about this for the syntax where the check is
'separated' from the INSERT (and no explicit locking/transaction mgmt is
present); I'm having a hard time understanding why and when this would be
true for the other proposed syntax that looks like this
INSERT INTO mytable (x)
SELECT @x WHERE NOT EXISTS (SELECT * FROM mytable WHERE x = @x);
I do NOT want to start (another) what's best/fastest discussion, nor do I
think the syntax can 'replace' a unique index/constraint (or PK) but I
really need to know in what situations this construction could cause
doubles as I've been using this syntax in the past and wonder if it is
unsafe to continue doing so in the future.
What I think that happens is that the INSERT & SELECT are both in the same
(implicit) transaction. The query will take an IX lock on the related
record (key) and not release it until the entire query has finished, thus
only AFTER the record has been inserted. This lock blocks all other
connections from making the same INSERT as they can't get a lock
themselves until after our insert has finished; only then they get the
lock and will start verifying for themselves if the record already exists
or not.
As IMHO the best way to find out is by testing, I've been running the
following code for a while on my laptop:
-- (create table once, run below on many, many connections in parallel)
CREATE TABLE t_test (x int NOT NULL PRIMARY KEY (x))
GO
SET NOCOUNT ON
WHILE 1 = 1
BEGIN
INSERT t_test (x)
SELECT x = DatePart(ms, CURRENT_TIMESTAMP)
WHERE NOT EXISTS ( SELECT *
FROM t_test old
WHERE old.x = DatePart(ms, CURRENT_TIMESTAMP) )
END
So far the only things to note are:
No errors encountered (yet)
CPU is running quite hot =)
table held 300 records quickly (due to 3ms 'precision' of datetime) after
that no actual inserts are happening any more, as expected.

How to capture/store a users answer to something and determine if it's true after a certain peroid of time.

How to capture/store a users answer to something and determine if it's
true after a certain peroid of time.

I'm trying to figure out how I could accomplish something.I'm having a
hard time thinking how to exactly word this so I apologize but lets take
this for example.. Say if you had a site that you could predict the
winners of basketball/football games. When someone is on their account on
the site, how can I capture their prediction and after a certain period of
time (When the game is over) it will update the account and tell me if I
was right or wrong and maybe put some kind of points on their account or
something...
Even if the site was as basic as two teams. Who will win, A or B? When you
choose A or B it's going to be before the game.. You can only choose
before the game begins, so you're not going to know the winner.. So it's
going to save your choice you've made and when the game is over it's going
to tell you if you were right or not. The hardest part I see is the time
delay.. Also what if the game goes into over time?
I'm not sure if Javascript/Jquery or PHP would be the best language for
the job so any suggestions would be helpful. I really appreciate taking
the time and read and answer my question.
Thank you

Android: (if) not working properly

Android: (if) not working properly

I am trying to set one message in toast. My idea is when the GPS is turn
on and the Latitude and Longitude is not "0" then to receive message like
this "gps is connected to satellites". But it's look this method is not
working. If I say to if- GPS turn off or the Latitude and Longitude is
equals to "0" then everything work properly. Just whyyy! I dont't get it.
Here is the code
Thanks in advance.
LocationListener Loclist = new LocationListener(){
@Override
public void onLocationChanged(Location lc){
// TODO Auto-generated method stub
//not working but with right logic
//GPS is turn on and the Latitude and Longitude is not "0"
if(lc != null && lastLat != 0 && lastLon != 0){
Context context = getApplicationContext();
CharSequence text = "GPS is connected to satellites.";
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
//working but with wrong logic
//GPS turn off or the Latitude and Longitude is equals to "0"
if(lc == null || lastLat == 0 && lastLon == 0){
Context context = getApplicationContext();
CharSequence text = "GPS is connected to satellites.";
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
}

Sunday, 29 September 2013

String.Split Method optimize way in vb.net

String.Split Method optimize way in vb.net

I have a string xxx1-0.1/1 yyy,ccc1,1. I used split and substring. All i
want to get is the 0.1/1 only. Is there any optimize way to do this?
Thank you in advance!

How To Make Page To Interact With Background Page?

How To Make Page To Interact With Background Page?

My Chrome extension has a background page that execute script on current tab.
The script change elements on current tab by adding code to existing
elements to call function 'myFunction' defined at background page when
'onClick' events occur. The problem is that exception is thrown that
'myFunction' is not defined on current tab.
what is the best way to enable this interaction? to enable current page to
go to function defined on background page?
Thanks in advance!

What does the %= operator do?

What does the %= operator do?

What does the %= operator do, as shown in this example:
if (a > b)
{
a %= b;
}
What are its uses and is it commonly used?

iggrid page size drop down list showed and disappeared, it cannot be selected on IE10 and IE11

iggrid page size drop down list showed and disappeared, it cannot be
selected on IE10 and IE11

The iggrid shows up correctly. But it cannot be changed page size because
the drop down list showed after mouse click and disappeared when mouse
move to select.
I am using iggrid 13.1.20131.2217.
My feature code :
.Features( features =>
{
features.Sorting().Type(OpType.Local);
features.Paging().Type(OpType.Local).Inherit(true).PageSize(10);
features.Selection().Mode(SelectionMode.Row);
features.Filtering();
features.ColumnMoving().Mode(MovingMode.Deferred).AddMovingDropdown(true).MoveType(MovingType.Render);
})
IE shows error when mouse move over button and text box of page size change:
SCRIPT28: Out of stack space
File: infragistics.ui.editors.js, Line: 3307, Column: 13
Thanks in advance
Wilson

Saturday, 28 September 2013

nhibernate one-to-one mapping and not-null="false"?

nhibernate one-to-one mapping and not-null="false"?

How to create one-to-one relation using NHibernate where other side could
be a NULL? For example, I have a Banner entity that has a relation to
Image entity like this:
<class name="Banner" table="Banner">
<id name="Id" type="Int64" unsaved-value="0">
<generator class="native" />
</id>
<many-to-one name="Image" unique="true" column="ImageId"
not-null="false"/>
<!-- check: In the example this property was without inverse attribute
-->
<set name ="BannerSlideSet" fetch="subselect" inverse="true">
<key column="Banner_ID" foreign-key="FK_Banner_BannerSlide"
not-null="false" />
<one-to-many class="BannerSlide"/>
</set>
</class>
So, Image can be null for a Banner entity. I create one banner entity with
no image without any issues. In DB I have
--------------
ID | ImageId
--------------
1 | NULL
After that, I'm trying to create second Banner instance with no Image as
well and get the following error:
NHibernate.Exceptions.GenericADOException: could not insert:
[Domain.Entities.Banner][SQL: INSERT INTO Banner (ImageId) VALUES (?);
select SCOPE_IDENTITY()] ---> System.Data.SqlClient.SqlException:
Violation of UNIQUE KEY constraint 'UQ_Banner_7516F70DE6141471'. Cannot
insert duplicate key in object 'dbo.Banner'. The duplicate key value is
().
I guess, it happens because I have unique constraint on one-to-many
relation between banner and image entities and several Banner instances
can't have several NULL values in ImageId field. Question: how I would
achieve one-to-nullableone relation with in NHinerbate?
Thanks!

Pandas dataframe: drop columns whose name contains a specific string

Pandas dataframe: drop columns whose name contains a specific string

I have a pandas dataframe with the following column names:
Result1, Test1, Result2, Test2, Result3, Test3, etc...
I want to drop all the columns whose name contains the word "Test". The
numbers of such columns is not static but depends on a previous function.
How can I do that?
Thanks!

How to hide the "submit" button once a form is sent successfully?

How to hide the "submit" button once a form is sent successfully?

I'd like to hide the "submit" button of my form when the form is sent
successfully. I tried to add $('#submit').hide(2000); just after
$('.success').fadeIn(1000); but without success. Thanks
HTML:
<div class="block-right"> <h1>Formulaire de contact</h1>
<!-- CONTACT FORM-->
<div class="contact-form">
<form id="contactfrm" method="post" class="clearfix">
<div class="clearfix">
<input id="name" name="name" placeholder="Name"
type="text" value="">
<input id="email" name="email" placeholder="Email"
type="email" value="">
</div>
<textarea id="message" name="message"
placeholder="Message"></textarea>
<input type="submit" value="Envoyer" name="submit">
<p class="success" style="display:none">Your message has been sent
successfully.</p>
<p class="error" style="display:none">E-mail must be valid and message
must be longer than 100 characters.</p>
</form>
</div><!-- /.contact-form -->
</div> <!-- End DIV block-right -->
JS:
// Contact Form
$(document).ready(function(){
$("#contactfrm").submit(function(e){
e.preventDefault();
var name = $("#name").val();
var email = $("#email").val();
var message = $("#message").val();
var dataString = 'name=' + name + '&email=' + email + '&message=' +
message;
function isValidEmail(emailAddress) {
var pattern = new
RegExp(/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i);
return pattern.test(emailAddress);
};
if (isValidEmail(email) && (message.length > 10) && (name.length > 1)){
$.ajax({
type: "POST",
url: "sendmessage.php",
data: dataString,
success: function(){
$('.success').fadeIn(1000);
}
});
} else{
$('.error').fadeIn(1000);
}
return false;
});
});

I am unable to see my website on Facebook Fanpage - URGENT

I am unable to see my website on Facebook Fanpage - URGENT

I have searched a lot over the internet but no success. So the problem I
have is I have added the website to facebook fanpage Tab but when I go to
facebook fanpage and click on the tab the page shown is blank. Here is the
facebook fanpage website tab link -
https://www.facebook.com/drdulitskymethod/app_640172482681632 (this is
blank). So can anyone please help me in resolving this issue. I need to
get this done as soon as possible.
Thanks

Friday, 27 September 2013

Joining tables in SQL. Linking by column in the from clause

Joining tables in SQL. Linking by column in the from clause

Linking multiple tables,
Is there a chance I will output a different result if I call the column
names to be linked in a different order in the FROM clause?
For example:
SELECT *
FROM tbl1
JOIN tbl2 on tbl1.colX = tbl2.colX
JOIN tbl3 on tbl2.colY = tbl3.colY
To be clear, in the next block I call tbl2.colX whereas above I called
tbl1.colX
SELECT *
FROM tbl1
JOIN tbl2 on tbl2.colX = tbl1.colX
JOIN tbl3 on tbl2.colY = tbl3.colY

Simple JS function using text inputs and parseInt, returns NaN

Simple JS function using text inputs and parseInt, returns NaN

Can anyone help me figure out why I keep getting a NaN result?
function showShares() {
var tot = document.getElementById('total').innerHTML;
var pri = document.getElementById('price').innerHTML;
var per = document.getElementById('percent').innerHTML;
var shar = parseInt(tot, 10) * parseInt(per, 10) / parseInt(pri, 10);
document.getElementById("shares").innerHTML=Math.round(shar);
}



<td><text id="price"><%= StockQuote::Stock.quote(current_user.fund1).last
%></text></td>
<td><text id="shares"></text></td>
<td><text id="percent">.50</text></td>



<p class="alignright1"><input type="text" id="total" size="8"></input>
<br><a href onclick="showShares()">here</a>



The stock quote is returning an integer in the cell ie. 25.38. it returns
the same NaN if I remove the embedded ruby and place a simple integer ie.
50. The same is true if I replace the input with a number.
Thank You

Integrating existing C code to Go. Convert unsigned char poiner result to []byte

Integrating existing C code to Go. Convert unsigned char poiner result to
[]byte

Here is a simple example:
package main
//#include <stdio.h>
//#include <strings.h>
//#include <stdlib.h>
/*
typedef struct {
unsigned char *data;
unsigned int data_len;
} Result;
Result *foo() {
Result *r = malloc(sizeof(Result));
r->data = (unsigned char *)malloc(10);
r->data_len = 10;
memset(r->data, 0, 10);
r->data = (unsigned char *)strdup("xxx123");
r->data_len = 6;
return r;
}
*/
import "C"
import (
"fmt"
// "unsafe"
)
func main() {
result := C.foo()
fmt.Printf("%v, %v, %v\n", result.data, string(*(result.data)),
result.data_len)
}
As a result i've got something like this
0x203970, x, 6
pointer to data, first character of data and the size. But how can i get
the actual data value, preferably as a []byte type to use it in go code?
In other words - how to convert unsigned char * to []byte?

Rotating a Linked List C

Rotating a Linked List C

I am currently solving sum problems of list and function and i came across
this question i.e rotate a linked list by k anti clockwise. Here is the
code for same
void rotate_k(struct list *node,int k)
{
int count=0;
struct list *knode,*ptr=node;
while(ptr!=NULL && count < k)
{
ptr=ptr->next;
count++;
}
knode=ptr;
while(ptr->next!=NULL)
{
ptr=ptr->next;
}
ptr->next =node;
node=knode->next;
knode->next=NULL;
}
Lets say if input is 1->2->3->4->5->6 and k=4.
The output should be 5->6->1->2->3->4 but the code gives the output
1->2->3->4->5 . Help needed :)

Switch handle multidimensional array. Unexpected result

Switch handle multidimensional array. Unexpected result

so I have a javascript function that pushes a multidimensional array value
to a parameter like so:
function mouseHandle(x,y){
for(var i=0; i<buttonPos.length; i++){
if(x>buttonPos[i][0] && x<buttonPos[i][2]){
if(y>buttonPos[i][1] && y<buttonPos[i][3]){
eventButton(buttonPos[i][4]);
};
};
};
};
This pushed buttonPos[i][4] to the eventButton function which is:
function eventButton(d){
switch(d){
case 0: // STARTBUTTON
alert("Button");
break;
default:
alert("NoButton");
};
};
The array is set in the drawButton function as so:
function drawButton(x,y,width,height,string,event){
xCenterButton=x+(width/2);
yCenterButton=y+(height/2);
ctx.fillStyle="rgba(242,255,195,1)";
ctx.fillRect(x,y,width,height);
ctx.rect(x,y,width,height);
ctx.fillStyle="rgba(0,0,0,1)";
ctx.stroke();
ctx.font="25px Arial";
fontSize = getFontSize();
centerNum = fontSize/4;
ctx.fillStyle="rgba(0,0,0,1)";
ctx.textAlign="center";
ctx.fillText(string,xCenterButton,yCenterButton+centerNum);
buttonPos.push([[x],[y],[x+width],[y+height],[event]]);
};
I then call that function in the menuStart function as so:
function menuStart(){
drawButton(getCenterX(100),getCenterY(50),100,50,"Start",0);
};
So the mouseHandle function DOES give the eventButton function a parameter
of 0 as expected (I alerted the 'd' parameter within the default case).
However it's as if the switch statement doesn't recognise the 0 as it uses
the default case and alerts 'NoButton'.
Any idea why this is not working?

strange phenomenon when use QFile with character ~

strange phenomenon when use QFile with character ~

i want to create a file in /home/username/ so i write some codes like this
#define CONFIG_FILE_PATH "~/.config/xmlfile
QFile file(CONFIG_FILE_PATH);
if (!file.open(QFile:ReadOnly | QFile::Text))
{
if (!file.open(QFile::WriteOnly | QFile::Text))
{
//print error message
}
else
{
//dosomething
file.close();
}
}
but when i run the program, i cannot find "xmlfile" i tried
sudo find / -name *xmlfile*
but found nothing and the program do not show any error messages.
is there some rules with the character ~ when using QFile?
Thanks in advance.

Thursday, 26 September 2013

test that a superclass method gets called from a subclass in ruby with Test::Unit and shoulda

test that a superclass method gets called from a subclass in ruby with
Test::Unit and shoulda

So, I've got a superclass (We'll call SuperClass) and two sub-classes from
it (say SubClassA and SubClassB)
Now SuperClass has a method called my_method which SubClassA has an
override for. But SubClassB does not.
I've tested that the version on the superclass works, and that the
overrideden version on SubClassA works... but I'd also like to add a unit
test that checks that SubClassB calls the version on the superclass.
I could just copy/paste the test from the superclass... or I could write a
test-module that's called from both... but if it's working tin the
superclass - all I really need to do is check that the superclass
my_method gets successfully called when I call it on the subclas...
but how do I test that?
This is what I tried:
should "call superclass version of my_method from the sub_class" do
@sub_class = SubClassB.new({})
rval = :whatever
SuperClass.any_instance.expects(:my_method).returns(rval)
assert_equal rval, @sub_class.my_method(:anything)
end
what that gives me is this error:
unexpected invocation: #<AnyInstance:SubClassA>.nat_record(:anything)
unsatisfied expectations:
- expected exactly once, not yet invoked:
#<AnyInstance:SuperClass>.my_method(any_parameters)
test: call superclass version of my_method from the sub_class.
(SubClassATest)
It looks like it has decided that the my_method has been called on an
instance of SubClassA (which it has) and that it therefore has not been
called on the SuperClass instance.
Is there a better way to check it calls the superclass method?

Thursday, 19 September 2013

Javascript Calculator with variables

Javascript Calculator with variables

I am looking for a javacript calculator whereby you can input your annual
spending on various departments (i.e. Restaurants, Movies, Toys &
Electronics), multiply all those totals by a percentage to reveal the
total for each line item and then total all the line items to show your
annual savings (assuming 0.5% is considered the savings percentage).
I have researched left, right, up, down, in and out - unable to find a JS
script that has these capabilities.
Any help would be greatly appreciated!

Updating with Postgresql

Updating with Postgresql

For the life of me, i've been working with this for so long, i've done
many updates that have worked, but for some reason, it won't work with
this bit of code:
If anyone can see anything wrong with it, please help me out. I'm a little
stuck:
if (isset($_POST['membership'])){
$accTypeID = getAccTypeID($db, $_POST['membership']);
$res = pg_query("SELECT * FROM accounts where username='"
.$_SESSION['username']. "'");
$rec = pg_fetch_row($res);
if($res > 0){
pg_query("UPDATE accounts SET paymentdate ='" .date("Y-m-d"). "',
accounttype_id=$accTypeID
WHERE username='" .$_SESSION['username']. "'");
$p->addContent('Purchasing has succeeded.');
}
}
I run this with my website and it says it works, but when i check my
database, nothing has been updated and my console produces this error:
pg_query(): Query failed: ERROR: syntax error at or near "WHERE"\nLINE 3:
WHERE username='anuj'

TFS 2010 - Building out Nuget using TFS results in TFS error: Package restore is disabled by default. To give consent, open the

TFS 2010 - Building out Nuget using TFS results in TFS error: Package
restore is disabled by default. To give consent, open the

I downloaded a standard copy of the Nuget web app and plan to use it in
our corporate environment. We use TFS 2010 to facilitate the builds from
our local machine. When I queue a new build on TFS for Nuget, the build
fails with the error:
Package restore is disabled by default. To give consent, open the Visual
Studio Options dialog, click on Package Manager node and check 'Allow
NuGet to download missing packages during build.' You can also give
consent by setting the environment variable 'EnableNuGetPackageRestore' to
'true'.
QUESTION: do I need to do what it says above on the TFS build server, or
on my local machine in Visual Studio? How can I resolve this issue? If
this is in fact an issue on the TFS build server, and the build server
doesn't allow to download missing packages, do I need to just download
those packages and check them into Source Control?
Here's the log file that resulted from the build, which also contains the
errors:
Build started 9/19/2013 12:19:08 PM. 1>Project
"F:\Builds\2\Nuget\NuGetGallery\Sources\NuGetGallery.sln" on node 1
(default targets). 1>ValidateSolutionConfiguration: Building solution
configuration "Release|Any CPU". 1>Project
"F:\Builds\2\Nuget\NuGetGallery\Sources\NuGetGallery.sln" (1) is building
"F:\Builds\2\Nuget\NuGetGallery\Sources\Website\Website.csproj" (2) on
node 1 (default targets). 2>RestorePackages:
"F:\Builds\2\Nuget\NuGetGallery\Sources.nuget\nuget.exe" install
"F:\Builds\2\Nuget\NuGetGallery\Sources\Website\packages.config" -o
"F:\Builds\2\Nuget\NuGetGallery\Sources\packages" 1>Project
"F:\Builds\2\Nuget\NuGetGallery\Sources\NuGetGallery.sln" (1) is building
"F:\Builds\2\Nuget\NuGetGallery\Sources\Facts\Facts.csproj" (3) on node 2
(default targets). 3>RestorePackages:
"F:\Builds\2\Nuget\NuGetGallery\Sources.nuget\nuget.exe" install
"F:\Builds\2\Nuget\NuGetGallery\Sources\Facts\packages.config" -o
"F:\Builds\2\Nuget\NuGetGallery\Sources\packages"
2>F:\Builds\2\Nuget\NuGetGallery\Sources.nuget\NuGet.targets(6,9): error :
Package restore is disabled by default. To give consent, open the Visual
Studio Options dialog, click on Package Manager node and check 'Allow
NuGet to download missing packages during build.' You can also give
consent by setting the environment variable 'EnableNuGetPackageRestore' to
'true'. [F:\Builds\2\Nuget\NuGetGallery\Sources\Website\Website.csproj]
2>F:\Builds\2\Nuget\NuGetGallery\Sources.nuget\NuGet.targets(6,9): error
MSB3073: The command
""F:\Builds\2\Nuget\NuGetGallery\Sources.nuget\nuget.exe" install
"F:\Builds\2\Nuget\NuGetGallery\Sources\Website\packages.config" -o
"F:\Builds\2\Nuget\NuGetGallery\Sources\packages"" exited with code 1.
[F:\Builds\2\Nuget\NuGetGallery\Sources\Website\Website.csproj] 2>Done
Building Project
"F:\Builds\2\Nuget\NuGetGallery\Sources\Website\Website.csproj" (default
targets) -- FAILED.
3>F:\Builds\2\Nuget\NuGetGallery\Sources.nuget\NuGet.targets(6,9): error :
Package restore is disabled by default. To give consent, open the Visual
Studio Options dialog, click on Package Manager node and check 'Allow
NuGet to download missing packages during build.' You can also give
consent by setting the environment variable 'EnableNuGetPackageRestore' to
'true'. [F:\Builds\2\Nuget\NuGetGallery\Sources\Facts\Facts.csproj]
3>F:\Builds\2\Nuget\NuGetGallery\Sources.nuget\NuGet.targets(6,9): error
MSB3073: The command
""F:\Builds\2\Nuget\NuGetGallery\Sources.nuget\nuget.exe" install
"F:\Builds\2\Nuget\NuGetGallery\Sources\Facts\packages.config" -o
"F:\Builds\2\Nuget\NuGetGallery\Sources\packages"" exited with code 1.
[F:\Builds\2\Nuget\NuGetGallery\Sources\Facts\Facts.csproj] 3>Done
Building Project
"F:\Builds\2\Nuget\NuGetGallery\Sources\Facts\Facts.csproj" (default
targets) -- FAILED. 1>Done Building Project
"F:\Builds\2\Nuget\NuGetGallery\Sources\NuGetGallery.sln" (default
targets) -- FAILED.
Build FAILED.
"F:\Builds\2\Nuget\NuGetGallery\Sources\NuGetGallery.sln" (default
target) (1) ->
"F:\Builds\2\Nuget\NuGetGallery\Sources\Website\Website.csproj"
(default target) (2) ->
(RestorePackages target) ->
F:\Builds\2\Nuget\NuGetGallery\Sources\.nuget\NuGet.targets(6,9):
error : Package restore is disabled by default. To give consent, open the
Visual Studio Options dialog, click on Package Manager node and check
'Allow NuGet to download missing packages during build.' You can also give
consent by setting the environment variable 'EnableNuGetPackageRestore' to
'true'. [F:\Builds\2\Nuget\NuGetGallery\Sources\Website\Website.csproj]
F:\Builds\2\Nuget\NuGetGallery\Sources.nuget\NuGet.targets(6,9): error
MSB3073: The command
""F:\Builds\2\Nuget\NuGetGallery\Sources.nuget\nuget.exe" install
"F:\Builds\2\Nuget\NuGetGallery\Sources\Website\packages.config" -o
"F:\Builds\2\Nuget\NuGetGallery\Sources\packages"" exited with code 1.
[F:\Builds\2\Nuget\NuGetGallery\Sources\Website\Website.csproj]
"F:\Builds\2\Nuget\NuGetGallery\Sources\NuGetGallery.sln" (default
target) (1) ->
"F:\Builds\2\Nuget\NuGetGallery\Sources\Facts\Facts.csproj" (default
target) (3) ->
F:\Builds\2\Nuget\NuGetGallery\Sources\.nuget\NuGet.targets(6,9):
error : Package restore is disabled by default. To give consent, open the
Visual Studio Options dialog, click on Package Manager node and check
'Allow NuGet to download missing packages during build.' You can also give
consent by setting the environment variable 'EnableNuGetPackageRestore' to
'true'. [F:\Builds\2\Nuget\NuGetGallery\Sources\Facts\Facts.csproj]
F:\Builds\2\Nuget\NuGetGallery\Sources.nuget\NuGet.targets(6,9): error
MSB3073: The command
""F:\Builds\2\Nuget\NuGetGallery\Sources.nuget\nuget.exe" install
"F:\Builds\2\Nuget\NuGetGallery\Sources\Facts\packages.config" -o
"F:\Builds\2\Nuget\NuGetGallery\Sources\packages"" exited with code 1.
[F:\Builds\2\Nuget\NuGetGallery\Sources\Facts\Facts.csproj]
0 Warning(s)
4 Error(s)
Time Elapsed 00:00:00.82

Strange behaviour, assigning undefined variable by refrence

Strange behaviour, assigning undefined variable by refrence

I am just exploring how Symbol Tables and Variable Containers work
together with references. And I found out that
<?php
$a = & $b;
?>
doesn't throw a Notice saying "Undefined variable: b in...", while
<?php
$a = $b;
?>
does.
Why?

Can you scrape data from a website with R

Can you scrape data from a website with R

Can you scrape data from:
http://www.ngx.com/?page_id=561
and
http://ets.aeso.ca/ets_web/docroot/Market/Reports/HistoricalReportsStart.html
with R?
I have tried to see if I could use RCurl/XML libraries in R but have not
had any success.

Accessing nested object in LinkedHashMap

Accessing nested object in LinkedHashMap

I'm trying to access an object in a LinkedHashMap, but get an
InvocationTargetException when I try to do it. The LinkedHashMap is the
result of a conversion from Json to a series of Java objects. The object
'List' contains every other element:
public class List{
private Clouds clouds;
private Number dt;
private String dt_txt;
private Main main;
private Rain rain;
private Sys sys;
private List weather;
private Wind wind;
}
The class also contains getters and setter. When I do the following:
for(LinkedHashMap l : ArrayList<LinkedHashMap> result.getList()) {
Number dt = (Number) l.get("dt");
}
I can access the variable dt, and it actually returns a value. However
when I try to access any other property like the 'Main' property like
this:
Main main = (Main) l.get("main");
I'll get an InvocationTargetException. Any thoughts, tips or tricks?
Edit:
Stacktrace:
09-19 14:37:59.448: E/AndroidRuntime(11192): FATAL EXCEPTION: main
09-19 14:37:59.448: E/AndroidRuntime(11192):
java.lang.ClassCastException:
com.google.gson.internal.LinkedHashTreeMap cannot be cast to
com.censored.weather.Main
09-19 14:37:59.448: E/AndroidRuntime(11192): at
com.censored.censored.VenloAppDelegate$GetWeatherTask.onPostExecute(VenloAppDelegate.java:305)
09-19 14:37:59.448: E/AndroidRuntime(11192): at
com.censored.censored.VenloAppDelegate$GetWeatherTask.onPostExecute(VenloAppDelegate.java:1)
09-19 14:37:59.448: E/AndroidRuntime(11192): at
android.os.AsyncTask.finish(AsyncTask.java:631)
09-19 14:37:59.448: E/AndroidRuntime(11192): at
android.os.AsyncTask.access$600(AsyncTask.java:177)
09-19 14:37:59.448: E/AndroidRuntime(11192): at
android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
09-19 14:37:59.448: E/AndroidRuntime(11192): at
android.os.Handler.dispatchMessage(Handler.java:99)
09-19 14:37:59.448: E/AndroidRuntime(11192): at
android.os.Looper.loop(Looper.java:153)
09-19 14:37:59.448: E/AndroidRuntime(11192): at
android.app.ActivityThread.main(ActivityThread.java:5297)
09-19 14:37:59.448: E/AndroidRuntime(11192): at
java.lang.reflect.Method.invokeNative(Native Method)
09-19 14:37:59.448: E/AndroidRuntime(11192): at
java.lang.reflect.Method.invoke(Method.java:511)
09-19 14:37:59.448: E/AndroidRuntime(11192): at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
09-19 14:37:59.448: E/AndroidRuntime(11192): at
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)

Install Node.js

Install Node.js

I'm completely new to node.js. By reading the documentation and tutorials,
I managed to download and install node.js on my windows.
How do I test it and make it work?
The file test.js is saved in the same directory as node.exe and contains:
console.log('Hello World');
Openning the command-line I typed:
$ node test.js
But nothing hapenns, just:
...

How can I compare objects using instanceof but Interface types (not passing exact class name.)

How can I compare objects using instanceof but Interface types (not
passing exact class name.)

public interface Component{}
public class AppMnger {
public void doWork(){
SomeComponent comp = new SomeComponent ();
AddComponentToList(comp);
}
public void AddComponentToList(Component compo){
componentList.add(compo);
}
/* Give me the component I want. */
public Component getComponent(Component comp){
for (Component component : getComponentList()) {
if (component instanceof comp) {
return component;
}
}
}
private ArrayList<Component> componentList = new ArrayList<Component>();
}
public class SomeComponent implements component {
public void MyMethod() {
appMnger.getComponent(this);
}
public void setAppMnger(AppMnger appm){
this.AppMnger = appm;
}
private AppMnger appm ;
}
In Above code AppMnger is having a list of components. Components are
communicating each other. So if one component want to know another
component instance it call the AppMnger getComponent(comp) method. But I
get an error when I use instanceof operator. I don't want each component
to want compare the list but I want to delegate that task to AppMnger
because he is the one who knows about components it created. Amy thought?

Wednesday, 18 September 2013

How do I install SOIL (Simple OpenGL Image Loader)?

How do I install SOIL (Simple OpenGL Image Loader)?

The SOIL website doesn't have any installation instructions. The file I
downloaded has no readme. I failed to find anything with Google.
I doubt g++ is going to check every directory on my computer to see if it
can find it. Is there a specific folder I'm supposed to put it in? Is
there a script I'm supposed to run?
I'm using Ubuntu.

What is the purpose of function scale_rt_power?

What is the purpose of function scale_rt_power?

Does anyone has a document about the kernel power saving scheduling and
what is the function of scale_rt_power?
Thank you,

C#, Print contents of a Panel

C#, Print contents of a Panel

In C#, I have a panel on a form, the contents of which I want to print.
Currently I can't view in print preview or print the contents, but the
border does.
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
panel1.CreateGraphics().DrawLines(new Pen(Color.Black),
new Point[]{new Point(10,10),new Point(50,50)});
}
private void PrintPanel(Panel pnl)
{
PrintDialog myPrintDialog = new PrintDialog();
PrinterSettings values;
values = myPrintDialog.PrinterSettings;
myPrintDialog.Document = printDocument1;
printDocument1.PrintController = new StandardPrintController();
printDocument1.PrintPage += new
System.Drawing.Printing.PrintPageEventHandler(printDocument1_PrintPage);
printPreviewDialog1.Document = printDocument1;
printPreviewDialog1.ShowDialog();
//printDocument1.Print();
printDocument1.Dispose();
}
void printDocument1_PrintPage(object sender, PrintPageEventArgs e)
{
Bitmap bmp = new Bitmap(panel1.Width, panel1.Height);
panel1.DrawToBitmap(bmp, new Rectangle(0, 0, panel1.Width, panel1.Height));
e.Graphics.DrawImage(bmp, panel1.Width, panel1.Height);
}

Java : use String[] or char[] ? [on hold]

Java : use String[] or char[] ? [on hold]

What are common scenarios when you would use a char[] and not a String[]
object? I know the textbook difference, I'm more interested in practical
use cases.

How do I use $rootScope in Angular to store variables?

How do I use $rootScope in Angular to store variables?

How do I use $rootScope to store variables in a controller I want to later
access in another controller? For example:
angular.module('myApp').controller('myCtrl', function($scope) {
var a = //something in the scope
//put it in the root scope
});
angular.module('myApp').controller('myCtrl2', function($scope) {
var b = //get var a from root scope somehow
//use var b
});
How would I do this?

HTML elements positon changes on browser resize

HTML elements positon changes on browser resize

when i resize my browser window all HTML elements positioning is changing.
I tried a lot for finding solution for it but i cann't.
Is their any trick in CSS to show same alignment for the elements when
browser is resized?

Getting Selection Start Index and Length from WPF RichTextBox

Getting Selection Start Index and Length from WPF RichTextBox

I've looked around and can find plenty of articles for how to set the
selection on RichTextBoxes but nothing on how to get the start index and
length of the selection. I see the TextSelection class has Start and End
properties but I have no idea how to just get the clear text index from
these.

how can I detect whether the android phone in Silent mode using air

how can I detect whether the android phone in Silent mode using air

I have seen this post how can I detect whether the android phone in Silent
mode programatically can any one please tell me whether there is any ane
to access the device ringing state whether the device is in
silent/vibration mode. I want to access the device seilent/vibration mode
in air mobile app.

Android WebDriver. XMLHttpRequest cannot load 'URL'. Origin 'URL' is not allowed by Access- Control-Allow-Origin. at null:1

Android WebDriver. XMLHttpRequest cannot load 'URL'. Origin 'URL' is not
allowed by Access- Control-Allow-Origin. at null:1

I am running my automated tests on Nexus 10 (Adndroid 4.2) using Selenium
WebDriver and Java. The error I face with is:
XMLHttpRequest cannot load 'URL'. Origin 'URL' is not allowed by Access-
Control-Allow-Origin. at null:1
This error doesn't occur for FireFox, Chrome, IE 10. But it always occur
for WebDriver on Android. Due to it Log in to the system is unavailable.
WebDriver is able to click, sendKeys and etc.
So the question is: Is any workaround exists to avoid this issue? May be
some settings which I should change for WebDriver? May be some one faced
with something like this before. I appreciate any suggestions.
I've tried apk 2.21.0 and 2.32.0.

jQuery mobile: Slider Widget

jQuery mobile: Slider Widget

I made a slider calculator with Jquery UI and then noticed it doesnt work
on touch devices, so I start over with Jquery Mobile.
For some reason I can update the value of the slider with the buttons, but
the slider itself won't move.
$("#plus1").on("mousedown", function () {
$('#slider-vertical').val(Number($('#slider-vertical').val())+25)
});
Please check: http://jsfiddle.net/MJ5WT/

Tuesday, 17 September 2013

touchstart event never be triggered on Android Chrome at the first time of page loading

touchstart event never be triggered on Android Chrome at the first time of
page loading

On Android Chrome, when you create a new tab and access to a page with the
content below, your touches to #touch div have never triggered touchstart
events. Once you reload the page, you can trigger the event. Why? and How
can I avoid this situation?
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>touch start on Android</title>
<style type="text/css">
#touch, #click {
position: relative;
left: 100px;
top: 100px;
width: 200px;
height: 200px;
border: solid 1px black;
}
</style>
</head>
<body>
<div id="touch">Touch</div>
<div id="click">Click</div>
<script type="text/javascript">
document.getElementById('touch').addEventListener('touchstart', function
() {
alert('touch');
}, false);
document.getElementById('click').addEventListener('click', function () {
alert('click');
}, false);
</script>
</body>
</html>
My environment is,
Nexus 7 (2013)
Android 4.30 build number JSS15Q
Chrome 29.0.1547.72 (WebKit version 537.36(@156722), JavaScript version V8
3.19.18.21)

How to group bash command into one function?

How to group bash command into one function?

Here is what I am trying to achieve. I want to run a sequence of commands
on that file, so for example
ls * | xargs (cat - | calculateforfile)
I want to run (cat | calculateforthisfile) on each of the file separately.
So basically, how to group a list of commands as if it is one single
function?

mismatch in member variables in C# class

mismatch in member variables in C# class

I am new to C#, and writing a piece of code to do some exercises. What
surprises me is that I can use undefined member variables in a C# class as
if they had been defined. Below is my code. In class Person, I only
defined "myName" and "myAge," but I can use the member variables "Name"
and "Age" without any issue. The code can be compiled and the executable
can be run. Can someone tell me why I can use "Name" and "Age" without
defining them? Many thanks,
C# code
====================================== using System;
namespace prj01
{
class Person
{
private string myName = "N/A";
private int myAge = 0;
public string Name
{
get
{
return myName;
}
set
{
myName = value;
}
}
public int Age
{
get
{
return myAge;
}
set
{
myAge = value;
}
}
public override string ToString()
{
return "Name = " + Name + ", Age = " + Age;
}
}
class Program
{
static void Main(string[] args)
{
// property
Console.WriteLine("Simple Properties");
Person person01 = new Person();
Console.WriteLine("Person details - {0}", person01);
person01.Name = "Joe"; // Why can I use "Name"?
person01.Age = 99; // Why is "Age" accessible and usable?
Console.WriteLine("Person details - {0}", person01);
Console.ReadLine();
}
}
}
======================================

How to escape HTML entities inside array in Ruby on Rails?

How to escape HTML entities inside array in Ruby on Rails?

I am trying to populate a select box with options from an array and escape
those options so currency symbols lile € get displayed rather than &euro;.
How can this be done in Ruby on Rails?
This is my function:
def options
array = []
array << ["&dollar;", "some value"]
array << ["&euro;", "some value"]
end
And this is the form:
<%= f.select(:format, f.object.options) %>
I tried things like array.html_safe but unfortunately it's not working.
Thanks for any help.

confused about android example code

confused about android example code

I'm looking over some code on the android developer's site and have a
quick question about the example show here -
http://developer.android.com/guide/components/fragments.html
In particular, I'm looking at this piece of code -
public static class DetailsActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getResources().getConfiguration().orientation
== Configuration.ORIENTATION_LANDSCAPE) {
// If the screen is now in landscape mode, we can show the
// dialog in-line with the list so we don't need this activity.
finish();
return;
}
if (savedInstanceState == null) {
// During initial setup, plug in the details fragment.
DetailsFragment details = new DetailsFragment();
details.setArguments(getIntent().getExtras());
getFragmentManager().beginTransaction().add(android.R.id.content,
details).commit();
}
}
What is the point of the second if statement -
if (savedInstanceState == null) {
I can't find any situation where this if statement wouldn't be true. I've
tested this code by adding an else statement and setting a breakpoint in
it. I could not get to that breakpoint no matter I tried. So why even
bother with an if statement? Why not leave it out all together?

IsMobileDevice returns False for Android (On some servers)

IsMobileDevice returns False for Android (On some servers)

I am developing a website using MVC 4 that has both Desktop and Mobile
views. I have created a DisplayModeProvider entry in my Global.asax that
allows iPhone's or Android mobiles.
I would like the user to be able to switch between Mobile and Desktop at
the click of a button. So I created a view that changes between Desktop
and Mobile as follows...
@If (ViewContext.HttpContext.GetOverriddenBrowser().IsMobileDevice) Then
@Html.ActionLink("Desktop View", "SwitchView", "Navigation", New With
{.Mobile = False, .ReturnUrl = Request.Url.PathAndQuery}, New With
{.rel = "external", .data_role = "button", .data_inline = "true"})
Else
@<a href="@Url.Action("SwitchView", "Navigation", New With {.Mobile =
True, .ReturnUrl = Request.Url.PathAndQuery})">Mobile View</a>
End If
... and this is the action...
Public Function SwitchView(Mobile As Boolean, ReturnUrl As String) As
RedirectResult
If Request.Browser.IsMobileDevice = Mobile Then
HttpContext.ClearOverriddenBrowser()
Else
HttpContext.SetOverriddenBrowser(If(Mobile,
BrowserOverride.Mobile, BrowserOverride.Desktop))
End If
Return Redirect(ReturnUrl)
End Function
This works perfectly on iPhone's.
But now I am testing with an Samsung Galaxy S3 (Android). On a Windows 7
IIS this works perfectly. However, when I run the same website on a 2003
Server IIS it does not work.
I think this is because the browser files
C:\WINDOWS\Microsoft.NET\Framework\v4.0.30319\Config\Browsers are
outdated, therefore IsMobileDevice returns False for Androids.
Questions:-
Is it possible to modify the code above to make Android's work? I am not
sure what I would change in the Action to allow this to work.
Alternatively, is it possible at project level to modify the browser files
so that Android's would return True for IsMobileDevice on a 2003 Server? I
don't want to update the browser definition files on the machine itself
because we distribute our website to dozens of different customers and a
project level solution would be preferred.

Sunday, 15 September 2013

Delete the uploded image file using ajax code

Delete the uploded image file using ajax code

I want to delete the images that are uploded one by one in php.
I used the following code for displaying the images.On clicking the delete
button the image gets deleted from the upload folder.
Code
ImageLap.tpl.php
foreach($mainfile as $files)
{
echo '<img src="'.$files.'" width="100" height="65">';
echo '<input type="hidden" value="'.$files.'"
name="delete_file" />';
echo '<input type="submit" value="Delete image" />';
}
ImageLap.php
if (array_key_exists('delete_file', $_POST))
{
$filename = $_POST['delete_file'];
if (file_exists($filename))
{
unlink($filename);
echo 'File '.$filename.' has been deleted';
}
}
This code is working well.But the page has to be refreshed on each file
deletion. I need a help to delete the files without refreshing the page.I
heard that ajax is used for this.But I don't have knowledge in ajax
Please do help me to implement ajax in this code.

non static variable cannot be referenced from static context?

non static variable cannot be referenced from static context?

I'm new to java and I have been exploring the different variable types.
Right now I am trying to determine is printed when I add 1 to a byte
variable of value 127 (the maximum value for a byte var). This is what my
code looks like:
public class vars {
byte b = 127;
byte c = 1;
public static void main(String[] args) {
System.out.println(b + c);
}
}
and on my System.out.println line I get the error message that my
non-static variables, b and c, cannot be referenced from a static context.
How should I fix this? Is there a better way to do this project in
general?
Thanks

Why do I see NSAutoresizingMaskLayoutConstraint when all UI Elements are set to setTranslatesAutoresizingMaskIntoConstraints = NO

Why do I see NSAutoresizingMaskLayoutConstraint when all UI Elements are
set to setTranslatesAutoresizingMaskIntoConstraints = NO

I am trying to debug a UI Layout and all the elements I have added in the
code are labelled with [self.element
setTranslatesAutoresizingMaskIntoConstraints:NO]; The only thing that is
set in XIB file is the background color of the view (one of many views in
a tabbed viewController.
When I look at the NSLog I am seeing the following:
*<UIWindow:0xc352370> - AMBIGUOUS LAYOUT
| *<UILayoutContainerView:0xc3651b0>
| | *<UINavigationTransitionView:0xc355b40>
| | | *<UIViewControllerWrapperView:0xbd3e250>
| | | | *<UILayoutContainerView:0xbd3da60>
| | | | | *<UITransitionView:0xbd46ed0>
| | | | | | *<UIViewControllerWrapperView:0xc09a450>
| | | | | | | *<UIView:0xbd51f40>
| | | | | | | | *<_UILayoutGuide:0xbd51fa0> - AMBIGUOUS
LAYOUT
| | | | | | | | *<_UILayoutGuide:0xbd50a10> - AMBIGUOUS
LAYOUT
| | | | | | | | *<UIButton:0xc064170> - AMBIGUOUS LAYOUT
| | | | | | | | | *<UIButtonLabel:0xc09d640>
| | | | | | | | *<UILabel:0xc073990> - AMBIGUOUS LAYOUT
| | | | | | | | *<UIButton:0xc0576a0> - AMBIGUOUS LAYOUT
| | | | | | | | | *<UIButtonLabel:0xc095290>
| | | | | | | | *<UIButton:0xc096640> - AMBIGUOUS LAYOUT
| | | | | | | | | <UIButtonLabel:0xc096820>
| | | | | | | | *<UIButton:0xc098b70> - AMBIGUOUS LAYOUT
| | | | | | | | | <UIButtonLabel:0xc098cb0>
| | | | | | | | *<UIButton:0xc09a4c0> - AMBIGUOUS LAYOUT
| | | | | | | | | <UIButtonLabel:0xc09a6d0>
| | | | | | | | *<UILabel:0xc09c9d0> - AMBIGUOUS LAYOUT
| | | | | | | | *<UILabel:0xc09cc60> - AMBIGUOUS LAYOUT
| | | | | | | | *<UIButton:0xc09ce00> - AMBIGUOUS LAYOUT
| | | | | | | | | <UIButtonLabel:0xc09d010>
| | | | | | | | *<UILabel:0xc0a25f0> - AMBIGUOUS LAYOUT
| | | | | | | | *<UIButton:0xc0a2800> - AMBIGUOUS LAYOUT
| | | | | | | | | <UIButtonLabel:0xc0a2a10>
| | | | | | | | *<UILabel:0xc0a5720> - AMBIGUOUS LAYOUT
| | | | | <UITabBar:0xc356c00>
| | | | | | <_UITabBarBackgroundView:0xbe28cc0>
| | | | | | | <_UIBackdropView:0xbe29100>
| | | | | | | | <_UIBackdropEffectView:0xbe296e0>
| | | | | | | | <UIView:0xbe29780>
| | | | | | <UITabBarButton:0xbd42000>
| | | | | | | <UITabBarSwappableImageView:0xbd41050>
| | | | | | | <UITabBarButtonLabel:0xbd43320>
| | | | | | <UITabBarButton:0xbd462e0>
| | | | | | | <UITabBarSwappableImageView:0xbd45d60>
| | | | | | | <UITabBarButtonLabel:0xbd45c70>
| | | | | | <UITabBarButton:0xbd47770>
| | | | | | | <UITabBarSwappableImageView:0xbd48a90>
| | | | | | | <UITabBarButtonLabel:0xbd486c0>
| | | | | | <UITabBarButton:0xbd4c0c0>
| | | | | | | <UITabBarSwappableImageView:0xbd4c220>
| | | | | | | <UITabBarButtonLabel:0xbd4aea0>
| | | | | | <UIImageView:0xbe29ed0>
| | <UINavigationBar:0xc06c4a0>
| | | <_UINavigationBarBackground:0xc05e720>
| | | | <_UIBackdropView:0xc357d70>
| | | | | <_UIBackdropEffectView:0xc3639a0>
| | | | | <UIView:0xc355470>
| | | | <UIImageView:0xc071980>
| | | <UINavigationItemView:0xc074c80>
| | | | <UILabel:0xc083730>
| | | <_UINavigationBarBackIndicatorView:0xc36edb0>
po [
(lldb) po [0xbd51fa0 constraintsAffectingLayoutForAxis:0]
<__NSArrayM 0xbd39190>(
)
(lldb) po [0xbd50a10 constraintsAffectingLayoutForAxis:0]
<__NSArrayM 0x1121f8f0>(
)
(lldb) po [0xc064170 constraintsAffectingLayoutForAxis:0]
<__NSArrayM 0xc0a14e0>(
<NSLayoutConstraint:0xc093aa0 H:|-(NSSpace(20))-[UIButton:0xc064170]
(Names: '|':UIView:0xbd51f40 )>,
<NSLayoutConstraint:0xc093b30 UIButton:0xc064170.width ==
UIButton:0xc0576a0.width>,
<NSLayoutConstraint:0xc093be0
H:[UIButton:0xc064170]-(20)-[UILabel:0xc073990]>,
<NSLayoutConstraint:0xc093c10 UILabel:0xc073990.width ==
UIButton:0xc0576a0.width>,
<NSLayoutConstraint:0xc096530
H:[UILabel:0xc073990]-(20)-[UIButton:0xc0576a0]>,
<NSLayoutConstraint:0xc096590 H:[UIButton:0xc0576a0]-(NSSpace(20))-|
(Names: '|':UIView:0xbd51f40 )>,
<NSAutoresizingMaskLayoutConstraint:0xc0af130 h=--& v=--&
H:[UIView:0xbd51f40(768)]>
)
(lldb) po [0xc09a4c0 constraintsAffectingLayoutForAxis:0]
<__NSArrayM 0xc36a0a0>(
<NSLayoutConstraint:0xc09c9a0 H:|-(<=0)-[UIButton:0xc09a4c0] (Names:
'|':UIView:0xbd51f40 )>,
<NSContentSizeLayoutConstraint:0xc0ad530 H:[UIButton:0xc09a4c0(110)]
Hug:250 CompressionResistance:750>
As you can see from po commands, I am getting
NSAutoresizingMasktLayoutContraints. I thought this shouldn't happen?
How can I ensure that I don't get this?

GridView with ListActivity instead of ListView

GridView with ListActivity instead of ListView

I have an app that pulls data from a database and puts it into a listview
via a ListActivity as well as a Cursor Loader.
The code is below:
public class PersonRecord extends ListActivity implements
LoaderManager.LoaderCallbacks<Cursor> {
private Uri addUri;
private TextView nameOfPerson, creditOfPerson;
private SimpleCursorAdapter adapter;
private String nameOfThePersonString;
// Used for menu deleting of a record
private static final int DELETE_ID = Menu.FIRST + 1;
// List for Listview
private ListView lv;
private static final String AUTHORITY =
"com.fthatnoise.borrow.me.contentprovider";
// ---------------------------------------------------
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.person_record);
this.getListView().setDividerHeight(2);
init(); // Initialize parameters and GUI
// Gets the name of the person that was sent from the Borrower List
// class
Bundle extras = getIntent().getExtras();
// Toast.makeText(this, nameOfThePersonString, Toast.LENGTH_SHORT)
// .show();
if (extras != null) {
addUri = extras
.getParcelable(BorrowMeContentProvider.CONTENT_ITEM_TYPE);
// Try-catch when the records are finished, this prevents the program
// from crashing (Pulling 0 from database)
try{
fillData(addUri);
} catch (Exception e)
{
Toast.makeText(this, "There are no more records for this
person", Toast.LENGTH_SHORT)
.show();
}
}
// Registers a content menu to the ListView
registerForContextMenu(getListView());
}
// ---------------------------------------------------
// Adding content menu to allow for the deletion of stored entries under
peoples names
@Override public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId()) {
case (DELETE_ID):
// Gets the content for the assigned content menu - in this case the
listview
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item
.getMenuInfo();
// Find the entry for the item currently clicked on
Uri uri = Uri.parse(BorrowMeContentProvider.CONTENT_URI +
"/" + info.id);
getContentResolver().delete(uri, null, null);
// Reload the list with new data based on the name sent over
// from the person credit screen
/*
* Removed filldata for now, seems to work without it even
though it crashes
* When removed it works fine but fails to refresh person record
* causes an error if all records are removed and person still
shows up in
* the record screen.
*/
try {
} catch (Exception e){
Toast.makeText(this, "There are no more records for this
person", Toast.LENGTH_SHORT)
.show();
}
return true;
}
return super.onContextItemSelected(item);
}
// ---------------------------------------------------
// Create Content Menu
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
// TODO Auto-generated method stub
super.onCreateContextMenu(menu, v, menuInfo);
//showDialog(DIALOG_SAB_PRIORITY_ID);
menu.add(0, DELETE_ID, 0, "Delete Record");
}
// ---------------------------------------------------
private void init() {
nameOfPerson = (TextView) findViewById(R.id.person_name);
creditOfPerson = (TextView) findViewById(R.id.person_credit);
}
// ---------------------------------------------------
// Loads record that was sent based on the ID
private void fillData(Uri uri) {
// Loads up the name of the person
String[] projection = { BorrowMeTable.COLUMN_NAME }; // Pulls only the
// name so far
Cursor databaseCursor = getContentResolver().query(uri, projection,
null, null, null);
if (databaseCursor != null) {
databaseCursor.moveToFirst();
nameOfThePersonString = databaseCursor.getString(databaseCursor
.getColumnIndexOrThrow(BorrowMeTable.COLUMN_NAME));
nameOfPerson.setText(nameOfThePersonString);
}
// Makes a raw query to the database in order to pull credit score for
// person being looked at.
ContentProviderClient client = getContentResolver()
.acquireContentProviderClient(AUTHORITY);
SQLiteDatabase dbHandle = ((BorrowMeContentProvider) client
.getLocalContentProvider()).getDbHandle();
Cursor cursor = dbHandle.rawQuery("SELECT sum("
+ BorrowMeTable.COLUMN_CREDIT_SCORE
+ ") AS creditcardtotal FROM " + BorrowMeTable.DATABASE_TABLE
+ " WHERE " + BorrowMeTable.COLUMN_NAME + "= \""
+ nameOfThePersonString + "\"", null);
cursor.moveToFirst();
int total = cursor.getInt(0);
cursor.close();
cursor.deactivate();
client.release(); // End of Credit Pull
// This is the formula to calc credit score.
// Everyone starts with 7, then it adds based on borrowed and returned
items.
int defaultScore = 7;
int cnt = 0;
cnt = defaultScore + total;
// This is the start of the credit evaluation system.
// Based on what the final numbers are, this will assign them a credit
score.
if (cnt >= 5 && cnt <= 6){
creditOfPerson.setText(cnt + " - Average");
creditOfPerson.setTypeface(null, Typeface.NORMAL);
}else if (cnt >= 7 && cnt <= 8){
creditOfPerson.setText(cnt + " - Good");
creditOfPerson.setTextColor(Color.MAGENTA);
creditOfPerson.setTypeface(null, Typeface.NORMAL);
}else if (cnt >= 2 && cnt <= 4){
creditOfPerson.setText(cnt + " - Bad");
creditOfPerson.setTextColor(Color.RED);
creditOfPerson.setTypeface(null, Typeface.NORMAL);
}else if (cnt >= 9){
creditOfPerson.setText(cnt + " - Fantastic");
creditOfPerson.setTextColor(Color.GREEN);
creditOfPerson.setTypeface(null, Typeface.NORMAL);
}else if (cnt <1){
// Stops showing the score if it drops below 1
creditOfPerson.setText("1 - Terrible");
creditOfPerson.setTextColor(Color.RED);
creditOfPerson.setTypeface(null, Typeface.BOLD);
}else if (cnt >= 10){
// Stops showing the score if it raises above 10
creditOfPerson.setText("10 - Wicked Awesome");
creditOfPerson.setTextColor(Color.GREEN);
creditOfPerson.setTypeface(null, Typeface.BOLD);
}
// End of credit score pull
// Loads the data for the rows of all items this person has borrowed
String[] from = new String[] { BorrowMeTable.COLUMN_ITEM,
BorrowMeTable.COLUMN_DATE, BorrowMeTable.COLUMN_BORROW_FLAG,
BorrowMeTable.COLUMN_RETURN_DATE,
BorrowMeTable.COLUMN_RETURN_FLAG, BorrowMeTable.COLUMN_IMAGE};
int[] to = new int[] { R.id.items_for_the_person_record,
R.id.borrowed_on_the_date, R.id.returned_on_the_date,
R.id.returned_on_the_day, R.id.returned_cond,
R.id.pic_of_item};
//getLoaderManager().initLoader(0, null, this); // This is where it
was originally
adapter = new SimpleCursorAdapter(this, R.layout.rows_people_records,
null, from, to, 0);
// The viewbinder that allows the adapter to display BLOB images
adapter.setViewBinder(new MyViewBinder());
setListAdapter(adapter);
// Here is where I attempt to load the custom view binder to load the
blob data
getLoaderManager().initLoader(0, null, this); // I have commented out
above and placed it here
}
// ---------------------------------------------------
@Override
public Loader<Cursor> onCreateLoader(int arg0, Bundle arg1) {
String mSelection = BorrowMeTable.COLUMN_NAME + "=?"; // SQL request
String[] selectionArgs = { nameOfThePersonString }; // The actual
// argument
String[] projection = { BorrowMeTable.COLUMN_ID,
BorrowMeTable.COLUMN_ITEM, BorrowMeTable.COLUMN_DATE,
BorrowMeTable.COLUMN_BORROW_FLAG,
BorrowMeTable.COLUMN_RETURN_DATE,
BorrowMeTable.COLUMN_RETURN_FLAG, BorrowMeTable.COLUMN_IMAGE};
CursorLoader cursorLoader = new CursorLoader(this,
BorrowMeContentProvider.CONTENT_URI, projection, mSelection,
selectionArgs, null);
return cursorLoader;
}
// ---------------------------------------------------
@Override
public void onLoadFinished(Loader<Cursor> arg0, Cursor arg1) {
adapter.swapCursor(arg1);
}
// ---------------------------------------------------
@Override
public void onLoaderReset(Loader<Cursor> arg0) {
adapter.swapCursor(null);
}
}
I would like to know if this can be done easily reusing the same code of
if i'll have to redo a bunch. I've looked at tutorials but i've seen
nothing that answers my question fully.
Thanks!

Why do I need a TestDriver when using Java?

Why do I need a TestDriver when using Java?

Today, I had my first Java lecture at the university and I heard a lot
about HelloWorld and a TestDriver. I somehow get the concept that the
TestDriver is the class that starts you program. But what is the advantage
of having a TestDriver? Why can't I just write a main method in my
HelloWorld class and start it from there?

Do something in jquery if element has exact property & value

Do something in jquery if element has exact property & value

I want to do something in jquery if my element has a given property & value.
This is what I'm trying that doesn't work:
if ($('.myElement').css('opacity','1')){
console.log('test');
}
What is the correct syntax for this?

Debug an specific Symfony2 bundle method

Debug an specific Symfony2 bundle method

I need to know if a specific bundle in Symfony 2.3 is been called when a
form is persisted, or better yet, see all the methods called before an
error message.
I'm using the Debug Component of Symfony2:
http://symfony.com/doc/current/components/debug.html, but I'm not seeing
the bundle listed, so I guess is not been executed, but I need to be sure
about it 'cause the bundle configuration is fine. All the unit tests of
that bundle pass ok, so the bundle is not the problem.
The bundle in question is VichUploaderBundle.
Thanks in advance.

Saturday, 14 September 2013

For loop iteration issue

For loop iteration issue

Hey so i have tried many variations of this code including using a scanf
function and every time it increments by 2 points instead of one. Here is
the code.
#include <stdio.h>
int main(void)
{
double nc;
for(nc = 0; getchar() != EOF; ++nc)
printf("%.0f\n", nc);
}
This is the output i get. the input i used was qwerty, and the outputs are
numbers 0-11 instead of 0-5 as expected.
q 0 1 w 2 3 e 4 5 r 6 7 t 8 9 y 10 11
one thought i has was that when i press enter, it is counted as a value
for getchar along with the character i enter and this causes the loop to
run through 2 iterations? can further explain this concept or provide
links to more information about it for me, thanks.

Ruby on Rails: form_for is not showing content inside

Ruby on Rails: form_for is not showing content inside

I'm trying to create a form so I can update user's content information,
but my form is not showing up.
My form in views/admin/dashboard/index.html.erb:
<% form_for @admin do |f| %>
... form content...
<% end %>
this is my controller in controllers/admin/dashboard_controller.rb
class Admin::DashboardController < ApplicationController
def index
@users = User.all
@admin = User.new
end
end
this is my model: models/admin.rb
class Admin < ActiveRecord::Base
belongs_to :user
end
Then in my users model: models/user.rb
class User < ActiveRecord::Base
has_many :admins
end