Can I do batch password change of all email in a cPanel account?
Does anyone know of a way to reset the password of one or more email
addresses in a cPanel account from the command line?
Thanks
Monday, 30 September 2013
How to define a command using \lowercase in \csname tex.stackexchange.com
How to define a command using \lowercase in \csname – tex.stackexchange.com
I was being lazy and had a lot of commands of the form \def\foo{...Foo...}
So I was thinking about taking an approach like ...
I was being lazy and had a lot of commands of the form \def\foo{...Foo...}
So I was thinking about taking an approach like ...
NameError: global name 'NAME' is not defined
NameError: global name 'NAME' is not defined
I met a problem following below,I can't understand why it happend and how
to solve it by myself
Models.py:
class Regions(models.Model):
id =models.AutoField(primary_key=True)
name = models.CharField(max_length=30)
english_name = models.CharField(max_length=20)
parentid = models.ForeignKey('self', blank=True,null=True)
slug_name = models.SlugField(max_length=40,blank=True)
regions_level = models.PositiveIntegerField()
comment = models.CharField(max_length=50,blank=True,null=True)
class Radio(models.Model):
station_name = models.CharField(max_length=30)
description = models.TextField()
regions = models.ForeignKey(Regions,blank=True,null=True)
custom_url = models.SlugField(max_length=100,blank=True)
stream = models.ForeignKey(Stream,related_name='radio_stream')
attributes = models.OneToOneField(Attributes,blank=True,null=True)
type = models.ForeignKey(Type,related_name='radio_type')
tags = models.ManyToManyField(Tag, blank=True)
comment =
models.ForeignKey(Comment,related_name='radio_comment',blank=True,null=True)
publish_time = models.DateTimeField(auto_now_add=True)
update_time = models.DateTimeField(auto_now_add=True)
Views.py
def location_show(request, id):
try:
radio_single = Regions.objects.get(id = id)
if radio_single.regions_level == 0:
ars = Regions.objects.filter(parentid_id=id)
ListFirst = [f.id for f in ars]
arrs = Regions.objects.filter(parentid_id in ListFirst)
ListSencond = [s.id for s in arrs]
arrss = Regions.objects.filter(parentid in ListSecond)
ListThird = [t.id for t in arrss]
listFirst.extend(ListSecond)
ListFirst.extend(listThird)
ListFirst.append(id)
radios = Radio.objects.filter(regions in ListFirst)
return
render_to_response("radio_location_show.html",{"ars":ars,"radios":radios})
elif radio_single.regions_level == 1:
ars = Regions.objects.filter(parentid_id=id)
listFirst = [p.id for p in ars]
arss = Regions.objects.filter(parentid in ListFirst)
ListsSecond = [s.id for s in arss]
ListFirst.extend(ListSecond)
ListFirst.append(id)
radios = Radio.objects.filter(regions in ListFirst)
return
render_to_response("radio_location_show.html",{"ars":ars,"radios":radios})
elif radio_single.regions_level == 2:
ars = Regions.objects.filter(parentid_id=id)
ListFirst= [p.id for p in ars]
ListFirst.append(id)
radios = Radio.objects.filter(regions in ListFirst)
return
render_to_response("radio_location_show.html",{"ars":ars,"radios":radios})
else:
ars = Regions.objects.filter(parentid_id = id)
ListFirst = [f.id for f in ars]
radios = Radio.objects.filter(regions in ListFirst)
return
render_to_response("radio_location_show.html",{"ars":ars,"radios":radios})
except Radio.DoesNotExist:
raise Http404
I am getting the following Error Message :
Traceback (most recent call last):
File "D:\Python27\lib\site-packages\django\core\handlers\base.py", line
115, i
n get_response
response = callback(request, *callback_args, **callback_kwargs)
File "D:\Project\myproject\radio\views.py", line 33, in location_show
arrs = Regions.objects.filter(parentid_id in ListFirst)
NameError: global name 'parentid_id' is not defined
would really appreciate a little help if anyone knows where i am going
wrong and can explain
I met a problem following below,I can't understand why it happend and how
to solve it by myself
Models.py:
class Regions(models.Model):
id =models.AutoField(primary_key=True)
name = models.CharField(max_length=30)
english_name = models.CharField(max_length=20)
parentid = models.ForeignKey('self', blank=True,null=True)
slug_name = models.SlugField(max_length=40,blank=True)
regions_level = models.PositiveIntegerField()
comment = models.CharField(max_length=50,blank=True,null=True)
class Radio(models.Model):
station_name = models.CharField(max_length=30)
description = models.TextField()
regions = models.ForeignKey(Regions,blank=True,null=True)
custom_url = models.SlugField(max_length=100,blank=True)
stream = models.ForeignKey(Stream,related_name='radio_stream')
attributes = models.OneToOneField(Attributes,blank=True,null=True)
type = models.ForeignKey(Type,related_name='radio_type')
tags = models.ManyToManyField(Tag, blank=True)
comment =
models.ForeignKey(Comment,related_name='radio_comment',blank=True,null=True)
publish_time = models.DateTimeField(auto_now_add=True)
update_time = models.DateTimeField(auto_now_add=True)
Views.py
def location_show(request, id):
try:
radio_single = Regions.objects.get(id = id)
if radio_single.regions_level == 0:
ars = Regions.objects.filter(parentid_id=id)
ListFirst = [f.id for f in ars]
arrs = Regions.objects.filter(parentid_id in ListFirst)
ListSencond = [s.id for s in arrs]
arrss = Regions.objects.filter(parentid in ListSecond)
ListThird = [t.id for t in arrss]
listFirst.extend(ListSecond)
ListFirst.extend(listThird)
ListFirst.append(id)
radios = Radio.objects.filter(regions in ListFirst)
return
render_to_response("radio_location_show.html",{"ars":ars,"radios":radios})
elif radio_single.regions_level == 1:
ars = Regions.objects.filter(parentid_id=id)
listFirst = [p.id for p in ars]
arss = Regions.objects.filter(parentid in ListFirst)
ListsSecond = [s.id for s in arss]
ListFirst.extend(ListSecond)
ListFirst.append(id)
radios = Radio.objects.filter(regions in ListFirst)
return
render_to_response("radio_location_show.html",{"ars":ars,"radios":radios})
elif radio_single.regions_level == 2:
ars = Regions.objects.filter(parentid_id=id)
ListFirst= [p.id for p in ars]
ListFirst.append(id)
radios = Radio.objects.filter(regions in ListFirst)
return
render_to_response("radio_location_show.html",{"ars":ars,"radios":radios})
else:
ars = Regions.objects.filter(parentid_id = id)
ListFirst = [f.id for f in ars]
radios = Radio.objects.filter(regions in ListFirst)
return
render_to_response("radio_location_show.html",{"ars":ars,"radios":radios})
except Radio.DoesNotExist:
raise Http404
I am getting the following Error Message :
Traceback (most recent call last):
File "D:\Python27\lib\site-packages\django\core\handlers\base.py", line
115, i
n get_response
response = callback(request, *callback_args, **callback_kwargs)
File "D:\Project\myproject\radio\views.py", line 33, in location_show
arrs = Regions.objects.filter(parentid_id in ListFirst)
NameError: global name 'parentid_id' is not defined
would really appreciate a little help if anyone knows where i am going
wrong and can explain
Text Steganography - Encrypt/Hide text using JavaScript and Decrypt/Unhide using PHP
Text Steganography - Encrypt/Hide text using JavaScript and Decrypt/Unhide
using PHP
I've googled a lot about steganography for text and found this:
http://www.fourmilab.ch/javascrypt/javascrypt.html &
http://www.fourmilab.ch/javascrypt/stego.html
The basic fundamental of these url is to convert any text into encrypted
code & then using second url convert that encrypted code into NON SENSE
english words with punctuation.
This is done using javascript and it works perfect. My half work is done
here.
Now I'll be sending this NON SENSE english words, with punctuations, to my
server using form. I don't know how to decrypt the data at server end
using PHP because it is converted via JavaScript.
I don't want the data which is transferred via network to be read by
anyone. I want only english words to be transferred via network, nothing
else.
Do you know anything similar to this? Steganograph the form (only to
English Words with punctuations) before sending using JS/JQuery and decode
using PHP.
Or can anybody suggest how to make the server side part working from the
above links.??
Any help is welcomed.
Thanks
using PHP
I've googled a lot about steganography for text and found this:
http://www.fourmilab.ch/javascrypt/javascrypt.html &
http://www.fourmilab.ch/javascrypt/stego.html
The basic fundamental of these url is to convert any text into encrypted
code & then using second url convert that encrypted code into NON SENSE
english words with punctuation.
This is done using javascript and it works perfect. My half work is done
here.
Now I'll be sending this NON SENSE english words, with punctuations, to my
server using form. I don't know how to decrypt the data at server end
using PHP because it is converted via JavaScript.
I don't want the data which is transferred via network to be read by
anyone. I want only english words to be transferred via network, nothing
else.
Do you know anything similar to this? Steganograph the form (only to
English Words with punctuations) before sending using JS/JQuery and decode
using PHP.
Or can anybody suggest how to make the server side part working from the
above links.??
Any help is welcomed.
Thanks
Sunday, 29 September 2013
Andorid Development: How do I predict expected battery life based on current battery level?
Andorid Development: How do I predict expected battery life based on
current battery level?
I have a requirement of predicting the battery duration from within my
android app. I have the cpu data, memory information and current battery
level. I have also plotted graphs of these values over the past few
minutes using the AndroidPlot library. Using these data (or anything
else), what is the best way of predicting the time before the battery runs
out on the device?
current battery level?
I have a requirement of predicting the battery duration from within my
android app. I have the cpu data, memory information and current battery
level. I have also plotted graphs of these values over the past few
minutes using the AndroidPlot library. Using these data (or anything
else), what is the best way of predicting the time before the battery runs
out on the device?
What is the most secure way for storing user's passwords inside database using PHP?
What is the most secure way for storing user's passwords inside database
using PHP?
Which is the most secure and most efficient way for storing passwords
inside the database tables using PHP?
So far I have used the md5() and the sha256 algorithm for storing
passwords where both of them can be easily hacked using rainbow tables if
finally someone gain access on the database.
using PHP?
Which is the most secure and most efficient way for storing passwords
inside the database tables using PHP?
So far I have used the md5() and the sha256 algorithm for storing
passwords where both of them can be easily hacked using rainbow tables if
finally someone gain access on the database.
Keeping SKSpriteNode in bounds of screen
Keeping SKSpriteNode in bounds of screen
I am trying to check whether my SKSpriteNode will remain in bounds of the
screen during a drag gesture. I've gotten to the point where I am pretty
sure my logic toward approaching the problem is right, but my
implementation is wrong. Basically, before the player moves from the
translation, the program checks to see whether its in bounds. Here is my
code:
-(CGPoint)checkBounds:(CGPoint)newLocation{
CGSize screenSize = self.size;
CGPoint returnValue = newLocation;
if (newLocation.x <= self.player.position.x){
returnValue.x = MIN(returnValue.x,0);
} else {
returnValue.x = MAX(returnValue.x, screenSize.width);
}
if (newLocation.y <= self.player.position.x){
returnValue.y = MIN(-returnValue.y, 0);
} else {
returnValue.y = MAX(returnValue.y, screenSize.height);
}
NSLog(@"%@", NSStringFromCGPoint(returnValue));
return returnValue;
}
-(void)dragPlayer: (UIPanGestureRecognizer *)gesture {
CGPoint translation = [gesture translationInView:self.view];
CGPoint newLocation = CGPointMake(self.player.position.x +
translation.x, self.player.position.y - translation.y);
self.player.position = [self checkBounds:newLocation];
}
For some reason, my player is going off screen. I think my use of the MIN
& MAX macros may be wrong, but I am not sure.
I am trying to check whether my SKSpriteNode will remain in bounds of the
screen during a drag gesture. I've gotten to the point where I am pretty
sure my logic toward approaching the problem is right, but my
implementation is wrong. Basically, before the player moves from the
translation, the program checks to see whether its in bounds. Here is my
code:
-(CGPoint)checkBounds:(CGPoint)newLocation{
CGSize screenSize = self.size;
CGPoint returnValue = newLocation;
if (newLocation.x <= self.player.position.x){
returnValue.x = MIN(returnValue.x,0);
} else {
returnValue.x = MAX(returnValue.x, screenSize.width);
}
if (newLocation.y <= self.player.position.x){
returnValue.y = MIN(-returnValue.y, 0);
} else {
returnValue.y = MAX(returnValue.y, screenSize.height);
}
NSLog(@"%@", NSStringFromCGPoint(returnValue));
return returnValue;
}
-(void)dragPlayer: (UIPanGestureRecognizer *)gesture {
CGPoint translation = [gesture translationInView:self.view];
CGPoint newLocation = CGPointMake(self.player.position.x +
translation.x, self.player.position.y - translation.y);
self.player.position = [self checkBounds:newLocation];
}
For some reason, my player is going off screen. I think my use of the MIN
& MAX macros may be wrong, but I am not sure.
Saturday, 28 September 2013
django: user is never authenticated even when username and password is correct
django: user is never authenticated even when username and password is
correct
Okay, so my auth_view is this (the view where I authenticate the login /
check if the username matches the password).
def auth_view(request):
username = request.POST['username']
password = request.POST['password']
if username is not None and password is not None: #making sure
username and password is not empty
user = authenticate(username=username, password=password)
else:
return redirect('/loggedin_invalid_view/')
if user is not None:
auth.login(request, user)
return redirect('/loggedin_view/')
else:
return redirect('/loggedin_invalid_view/')
and my login form in the template is this:
<form method="post" action="/auth_view/">{% csrf_token %}
<label for="username">Username:</label>
<input type="text" name="username" value="" id="username">
<label for="password">Password:</label>
<input type="password" name="password" value="" id="password">
<input type="submit" value="Login">
</form>
Now, my model where I have the username and password saved in is called
Users and I created a form from it called UsersForm. In the form, it has a
SlugField called 'username' 'password'. The template in which the Users
form is:
<form method="post" action="">{% csrf_token %}
{{ form.first_name }} <br>
{{ form.username }} {{ form.password }} <br>
<input type="submit" value="Register"/>
</form>
So I registered (the UsersForm is basically the registration form) with
the username as 'user1' and the password as 'password1' and then when I
try signing in, it redirects to /loggedin_inavlid_view rather than to
loggedin_view, how come? Do I have to edit my view to manually go into the
Users model and check if there is a user with the username called user1
and then check if user1's password is password1?
correct
Okay, so my auth_view is this (the view where I authenticate the login /
check if the username matches the password).
def auth_view(request):
username = request.POST['username']
password = request.POST['password']
if username is not None and password is not None: #making sure
username and password is not empty
user = authenticate(username=username, password=password)
else:
return redirect('/loggedin_invalid_view/')
if user is not None:
auth.login(request, user)
return redirect('/loggedin_view/')
else:
return redirect('/loggedin_invalid_view/')
and my login form in the template is this:
<form method="post" action="/auth_view/">{% csrf_token %}
<label for="username">Username:</label>
<input type="text" name="username" value="" id="username">
<label for="password">Password:</label>
<input type="password" name="password" value="" id="password">
<input type="submit" value="Login">
</form>
Now, my model where I have the username and password saved in is called
Users and I created a form from it called UsersForm. In the form, it has a
SlugField called 'username' 'password'. The template in which the Users
form is:
<form method="post" action="">{% csrf_token %}
{{ form.first_name }} <br>
{{ form.username }} {{ form.password }} <br>
<input type="submit" value="Register"/>
</form>
So I registered (the UsersForm is basically the registration form) with
the username as 'user1' and the password as 'password1' and then when I
try signing in, it redirects to /loggedin_inavlid_view rather than to
loggedin_view, how come? Do I have to edit my view to manually go into the
Users model and check if there is a user with the username called user1
and then check if user1's password is password1?
Makefile won't check if updated, and just compiles anyway
Makefile won't check if updated, and just compiles anyway
My makefile will not check if there has been any updates and just compiles
if it has more than a single source file added in. It works fine with just
a single source file.
It seems that it's any source file that's not listed as the first one will
always be recompiled and linked.
SOURCES=myclass.cpp mylock.cpp
EXECUTABLE=locktest
LIBRARIES=-pthread
CFLAGS=-Wall
CXX=g++
DIR=host/
EXE=$(EXECUTABLE)
OBJECTS=$(SOURCES:%.cpp=$(DIR)%.o)
$(EXE): $(OBJECTS)
$(CXX) -o $@ $(OBJECTS) $(LIBRARIES)
$(DIR)%.o: %.cpp $(DIR)
$(CXX) $(CFLAGS) -c $< -o $@
$(DIR):
@mkdir $(DIR)
clean:
@rm $(OBJECTS) $(EXE)
@rmdir $(DIR)
Output shows problem:
stud@pc:~/Desktop/Locktest$ make
g++ -Wall -c myclass.cpp -o host/myclass.o
g++ -Wall -c mylock.cpp -o host/mylock.o
g++ -o locktest host/myclass.o host/mylock.o -pthread
stud@pc:~/Desktop/Locktest$ make
g++ -Wall -c myclass.cpp -o host/myclass.o
g++ -o locktest host/myclass.o host/mylock.o -pthread
My makefile will not check if there has been any updates and just compiles
if it has more than a single source file added in. It works fine with just
a single source file.
It seems that it's any source file that's not listed as the first one will
always be recompiled and linked.
SOURCES=myclass.cpp mylock.cpp
EXECUTABLE=locktest
LIBRARIES=-pthread
CFLAGS=-Wall
CXX=g++
DIR=host/
EXE=$(EXECUTABLE)
OBJECTS=$(SOURCES:%.cpp=$(DIR)%.o)
$(EXE): $(OBJECTS)
$(CXX) -o $@ $(OBJECTS) $(LIBRARIES)
$(DIR)%.o: %.cpp $(DIR)
$(CXX) $(CFLAGS) -c $< -o $@
$(DIR):
@mkdir $(DIR)
clean:
@rm $(OBJECTS) $(EXE)
@rmdir $(DIR)
Output shows problem:
stud@pc:~/Desktop/Locktest$ make
g++ -Wall -c myclass.cpp -o host/myclass.o
g++ -Wall -c mylock.cpp -o host/mylock.o
g++ -o locktest host/myclass.o host/mylock.o -pthread
stud@pc:~/Desktop/Locktest$ make
g++ -Wall -c myclass.cpp -o host/myclass.o
g++ -o locktest host/myclass.o host/mylock.o -pthread
Error in calculating theta of angle
Error in calculating theta of angle
This question / bug is directly related to this Angle Measurer in C#. The
problem seems to be that the theta is wrong in angles greater than 180
(I'm working in degrees, not radians).
Here's a helpful screen shot. This picture represents an overhead view of
three dinosaurs. The body of the dinosaurs are in gray. The heads are a
white dot. The 'angle of vision' for each dinosaur (not the same for all
species) are the blue lines.
As you can see the facing of each dinosaur is correct. The theta for the
angle between John and Julie looks correct. However, the angles from Julie
to John and Muffie to John are quite wrong. Each should be > 180 degrees.
Here's the code snippet:
double DinoAFacing = FindAngle(Dinosaurs[DinoA].Head.X,
Dinosaurs[DinoA].Head.Y,
Dinosaurs[DinoA].Location[Dinosaurs[DinoA].Location.Count - 1].X,
Dinosaurs[DinoA].Location[Dinosaurs[DinoA].Location.Count - 1].Y);
int Specie = ReturnDinosaurSpecie(DinoA);
double x = 50 * Math.Cos((DinoAFacing - 90) * (Math.PI / 180.0));
double y = 50 * Math.Sin((DinoAFacing - 90) * (Math.PI / 180.0));
x += Dinosaurs[DinoA].Head.X;
y += Dinosaurs[DinoA].Head.Y;
System.Windows.Point A = new System.Windows.Point();
A.X = x - Dinosaurs[DinoA].Head.X;
A.Y = y - Dinosaurs[DinoA].Head.Y;
System.Windows.Point B = new System.Windows.Point();
B.X = Dinosaurs[DinoB].Head.X - Dinosaurs[DinoA].Head.X;
B.Y = Dinosaurs[DinoB].Head.Y - Dinosaurs[DinoA].Head.Y;
double ALen = Math.Sqrt(Math.Pow(A.X, 2) + Math.Pow(A.Y, 2));
double BLen = Math.Sqrt(Math.Pow(B.X, 2) + Math.Pow(B.Y, 2));
double dotProduct = A.X * B.X + A.Y * B.Y;
double Angle = Math.Abs(((180 / Math.PI) * Math.Acos(dotProduct / (ALen *
BLen))));
slug = Dinosaurs[DinoA].PersonalName + " is facing: " +
string.Format("{0:f2}", string.Format("{0:f2}", DinoAFacing)) +
"\nThe angle between " + Dinosaurs[DinoA].PersonalName
+ " and " + Dinosaurs[DinoB].PersonalName + " is " +
string.Format("{0:f2}", Angle) +
"\n" + Dinosaurs[DinoA].PersonalName + " CAN see " +
Dinosaurs[DinoB].PersonalName;
System.Windows.MessageBox.Show(slug, "Dino vision",
System.Windows.MessageBoxButton.OK);
Can any of you math boffins see the error of my ways?
Thanks!
This question / bug is directly related to this Angle Measurer in C#. The
problem seems to be that the theta is wrong in angles greater than 180
(I'm working in degrees, not radians).
Here's a helpful screen shot. This picture represents an overhead view of
three dinosaurs. The body of the dinosaurs are in gray. The heads are a
white dot. The 'angle of vision' for each dinosaur (not the same for all
species) are the blue lines.
As you can see the facing of each dinosaur is correct. The theta for the
angle between John and Julie looks correct. However, the angles from Julie
to John and Muffie to John are quite wrong. Each should be > 180 degrees.
Here's the code snippet:
double DinoAFacing = FindAngle(Dinosaurs[DinoA].Head.X,
Dinosaurs[DinoA].Head.Y,
Dinosaurs[DinoA].Location[Dinosaurs[DinoA].Location.Count - 1].X,
Dinosaurs[DinoA].Location[Dinosaurs[DinoA].Location.Count - 1].Y);
int Specie = ReturnDinosaurSpecie(DinoA);
double x = 50 * Math.Cos((DinoAFacing - 90) * (Math.PI / 180.0));
double y = 50 * Math.Sin((DinoAFacing - 90) * (Math.PI / 180.0));
x += Dinosaurs[DinoA].Head.X;
y += Dinosaurs[DinoA].Head.Y;
System.Windows.Point A = new System.Windows.Point();
A.X = x - Dinosaurs[DinoA].Head.X;
A.Y = y - Dinosaurs[DinoA].Head.Y;
System.Windows.Point B = new System.Windows.Point();
B.X = Dinosaurs[DinoB].Head.X - Dinosaurs[DinoA].Head.X;
B.Y = Dinosaurs[DinoB].Head.Y - Dinosaurs[DinoA].Head.Y;
double ALen = Math.Sqrt(Math.Pow(A.X, 2) + Math.Pow(A.Y, 2));
double BLen = Math.Sqrt(Math.Pow(B.X, 2) + Math.Pow(B.Y, 2));
double dotProduct = A.X * B.X + A.Y * B.Y;
double Angle = Math.Abs(((180 / Math.PI) * Math.Acos(dotProduct / (ALen *
BLen))));
slug = Dinosaurs[DinoA].PersonalName + " is facing: " +
string.Format("{0:f2}", string.Format("{0:f2}", DinoAFacing)) +
"\nThe angle between " + Dinosaurs[DinoA].PersonalName
+ " and " + Dinosaurs[DinoB].PersonalName + " is " +
string.Format("{0:f2}", Angle) +
"\n" + Dinosaurs[DinoA].PersonalName + " CAN see " +
Dinosaurs[DinoB].PersonalName;
System.Windows.MessageBox.Show(slug, "Dino vision",
System.Windows.MessageBoxButton.OK);
Can any of you math boffins see the error of my ways?
Thanks!
Multipeer Connectivity stops working when user turns off and on bluetooth
Multipeer Connectivity stops working when user turns off and on bluetooth
I am using multipeer connectivity in ios7 in my app. The file sending and
receiving works absolutely fine, but in the moment that a user accesses
from within my app the control center (or even settings) and switches off
either bluetooth or wifi, the file exchange stops working. When the user
witches both of them back on, still it doesn't work. In order for them to
work again, the user must close and re-open the app.
The files are sent in this way:
MCSession *session = [[MCSession alloc]
initWithPeer:key];
NSCalendar *gregorian = [[NSCalendar alloc]
initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *dateComponents = [[NSDateComponents
alloc] init];
dateComponents.year = 2100;
dateComponents.month = 1;
dateComponents.day = 1;
dateComponents.hour = 0;
dateComponents.minute = 0;
dateComponents.second = 0;
NSDate *referenceDate = [gregorian dateFromComponents:
dateComponents];
NSDate *now = [NSDate date];
NSTimeInterval interval = [now
timeIntervalSinceDate:referenceDate];
NSData *Recording = [NSData
dataWithContentsOfFile:myFilePath];
NSString* str = [NSString stringWithFormat:@"%@.ext",
button.titleLabel.text];
NSMutableDictionary *dict = [[NSMutableDictionary
alloc] init];
[dict setObject:str forKey:@"fileName"];
[dict setObject:@"Recording" forKey:@"fileType"];
[dict setObject:Recording forKey:@"FileData"];
NSData *myData = [NSKeyedArchiver
archivedDataWithRootObject:dict];
[browser invitePeer:key
toSession:session
withContext:myData
timeout:interval];
The user can reload the devices at any time using:
[browser startBrowsingForPeers];
I think that the problem is the timeout, but I am not sure.
I am using multipeer connectivity in ios7 in my app. The file sending and
receiving works absolutely fine, but in the moment that a user accesses
from within my app the control center (or even settings) and switches off
either bluetooth or wifi, the file exchange stops working. When the user
witches both of them back on, still it doesn't work. In order for them to
work again, the user must close and re-open the app.
The files are sent in this way:
MCSession *session = [[MCSession alloc]
initWithPeer:key];
NSCalendar *gregorian = [[NSCalendar alloc]
initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *dateComponents = [[NSDateComponents
alloc] init];
dateComponents.year = 2100;
dateComponents.month = 1;
dateComponents.day = 1;
dateComponents.hour = 0;
dateComponents.minute = 0;
dateComponents.second = 0;
NSDate *referenceDate = [gregorian dateFromComponents:
dateComponents];
NSDate *now = [NSDate date];
NSTimeInterval interval = [now
timeIntervalSinceDate:referenceDate];
NSData *Recording = [NSData
dataWithContentsOfFile:myFilePath];
NSString* str = [NSString stringWithFormat:@"%@.ext",
button.titleLabel.text];
NSMutableDictionary *dict = [[NSMutableDictionary
alloc] init];
[dict setObject:str forKey:@"fileName"];
[dict setObject:@"Recording" forKey:@"fileType"];
[dict setObject:Recording forKey:@"FileData"];
NSData *myData = [NSKeyedArchiver
archivedDataWithRootObject:dict];
[browser invitePeer:key
toSession:session
withContext:myData
timeout:interval];
The user can reload the devices at any time using:
[browser startBrowsingForPeers];
I think that the problem is the timeout, but I am not sure.
Friday, 27 September 2013
How to add new line of row in devexpress gridcontrol?
How to add new line of row in devexpress gridcontrol?
I want to add a new line of row when pressing a button. In datagridview it
would be: datagridview1.Rows.Add()
What is the equivalent code for that in gridcontrol? Please help me.
I want to add a new line of row when pressing a button. In datagridview it
would be: datagridview1.Rows.Add()
What is the equivalent code for that in gridcontrol? Please help me.
REMOVE ALL CLASSES OF ALL APGE
REMOVE ALL CLASSES OF ALL APGE
It took days and days trying to fix something but do not know how. In my
index.html page I have many divs with a class called "input". I need to
remove this class of all divs when the browser window is less than 960
pixels. Here is my code:
$(window).resize(function() {
if ($(window).width() > 960) {
$("div").removeClass("input");
}
});
In advance thank you very much for your help. And excuse me for asking a
question as a beginner, but can not find a solution.
Sorry for my English.
It took days and days trying to fix something but do not know how. In my
index.html page I have many divs with a class called "input". I need to
remove this class of all divs when the browser window is less than 960
pixels. Here is my code:
$(window).resize(function() {
if ($(window).width() > 960) {
$("div").removeClass("input");
}
});
In advance thank you very much for your help. And excuse me for asking a
question as a beginner, but can not find a solution.
Sorry for my English.
Flash v11.8.800.168 function call fails in Internet Explorer
Flash v11.8.800.168 function call fails in Internet Explorer
Company recently upgraded to Flash v11.8.800.168 and a flash movie which
is loaded using SWFObject (1.1) is not working correctly in Internet
Explorer (Firefox works fine). The movie is loaded dynamically using a
jquery document.ready method using the "new SWFObject(...);
so.write("ID")" method (again SWFObject 1.1).\
The movie on load calls a JavaScript function (which is built dynamically
using server scripting). The function is being called correctly as checked
by a debugger. The JavaScript function calls a method in the flash movie
passing it some XML (which is used to render some user and navigation
items).
Something like this:
function calledFromFlash() {
document.getElementById("FlashMovie").renderUsingXml('<?xml version
1.0"?><lotsofxml></lotsofxml>');
}
Like I said, this all works still in Firefox with the new Flash version.
When I step through the function above, using step into with the IE
Debugger, I get the following steps:
function anonymous() {
return eval(this.CallFunction("<invoke name=\"renderUsingXml\"
returntype=\"javascript\">" + __flash__argumentsToXML(arguments, 0) +
"</invoke>"));
}
At this point, I checked the arguments variable and it contains the XML as
one would expect. After the next step into, I get this:
try { __flash__toXML(calledFromFlash(undefined)); } catch (e) {
"<undefined/>"; }
At this point the debugger is already on the catch, yet one more step into
take the code into the "<undefined/>" section and I can see that e is
Object Expected
What I've tried:
Static implementation without SWFObject. This works. But then Firefox
doesn't process the XML properly (and it seems to be the same issue as IE)
Upgrading to SWFObject 2.2. Using dynamic implementation it fails still.
Using static implementation it works in IE but not Firefox
This is NOT my flash movie, the source is... well, I don't know. The guy
that wrote it has left the company. That said, this seems like such a
crazy issue.
My proposed fix is simply to use SWFObject for Firefox and use a static
implementation for IE, but I really want to know what is wrong.
Company recently upgraded to Flash v11.8.800.168 and a flash movie which
is loaded using SWFObject (1.1) is not working correctly in Internet
Explorer (Firefox works fine). The movie is loaded dynamically using a
jquery document.ready method using the "new SWFObject(...);
so.write("ID")" method (again SWFObject 1.1).\
The movie on load calls a JavaScript function (which is built dynamically
using server scripting). The function is being called correctly as checked
by a debugger. The JavaScript function calls a method in the flash movie
passing it some XML (which is used to render some user and navigation
items).
Something like this:
function calledFromFlash() {
document.getElementById("FlashMovie").renderUsingXml('<?xml version
1.0"?><lotsofxml></lotsofxml>');
}
Like I said, this all works still in Firefox with the new Flash version.
When I step through the function above, using step into with the IE
Debugger, I get the following steps:
function anonymous() {
return eval(this.CallFunction("<invoke name=\"renderUsingXml\"
returntype=\"javascript\">" + __flash__argumentsToXML(arguments, 0) +
"</invoke>"));
}
At this point, I checked the arguments variable and it contains the XML as
one would expect. After the next step into, I get this:
try { __flash__toXML(calledFromFlash(undefined)); } catch (e) {
"<undefined/>"; }
At this point the debugger is already on the catch, yet one more step into
take the code into the "<undefined/>" section and I can see that e is
Object Expected
What I've tried:
Static implementation without SWFObject. This works. But then Firefox
doesn't process the XML properly (and it seems to be the same issue as IE)
Upgrading to SWFObject 2.2. Using dynamic implementation it fails still.
Using static implementation it works in IE but not Firefox
This is NOT my flash movie, the source is... well, I don't know. The guy
that wrote it has left the company. That said, this seems like such a
crazy issue.
My proposed fix is simply to use SWFObject for Firefox and use a static
implementation for IE, but I really want to know what is wrong.
Logcat shows messages of system and other applications but not my application?
Logcat shows messages of system and other applications but not my
application?
I have a LG Optimus 4x HD and I'm trying to run my android application on
it. the problem is that the logcat doesn't show any of my log messages
although it shows messages of other apps as well as the system messages. I
selected my device from the DDMS Perspective, enabled debugging mode on my
device, don't have any filters in my logcat, tried verbose, error, ...
application?
I have a LG Optimus 4x HD and I'm trying to run my android application on
it. the problem is that the logcat doesn't show any of my log messages
although it shows messages of other apps as well as the system messages. I
selected my device from the DDMS Perspective, enabled debugging mode on my
device, don't have any filters in my logcat, tried verbose, error, ...
Not all styles in a class apply
Not all styles in a class apply
Any one have any idea why styles in title_services class apply all and in
the title_services2 class there apply only line-height, font-weight;
letter-spacing? When I use Tool for Developers in Chrome and select
h4.title_services it lists all styles, but when I select
h4.title_services2 it shows only those three styles. Below is the CSS (h4
and h4.title_services work correctly, h4.title_services2 not)
h4 {
font-size:28px;
line-height:2em;
color:#fff;
font-weight:normal;
letter-spacing:-1px;
}
h4.title_services {
font-size:28px;
margin-top:15px;
margin-bottom:15px;
text-align:center;
line-height:1em;
color:#fff;
font-weight:normal;
letter-spacing:-1px;
}
h4.title_services2 {
font-size:28px;
margin-top:25px;
margin-bottom:15px;
text-align:center;
line-height:1em;
color:blue;/*#fff;*/
font-weight:normal;
letter-spacing:-1px;
}
HTML is as follows:
<article class="grid_3">
<div class="indent-left">
<img style="display: block; margin: 0 auto;"
src="../images/services_kid.png" />
<h4 class="title_services">First headline</h4>
<div id="button2"><a class="button2" href="#">BUTTON</a></div>
</div>
</article>
<article class="grid_3">
<div class="indent-left">
<img style="display: block; margin: 0 auto;"
src="../images/services_kid2.png" />
<h4 class="title_services2">Second headline</h4>
<div id="button2"><a class="button2" href="#">CENÍK</a></div>
</div>
</article>
Any one have any idea why styles in title_services class apply all and in
the title_services2 class there apply only line-height, font-weight;
letter-spacing? When I use Tool for Developers in Chrome and select
h4.title_services it lists all styles, but when I select
h4.title_services2 it shows only those three styles. Below is the CSS (h4
and h4.title_services work correctly, h4.title_services2 not)
h4 {
font-size:28px;
line-height:2em;
color:#fff;
font-weight:normal;
letter-spacing:-1px;
}
h4.title_services {
font-size:28px;
margin-top:15px;
margin-bottom:15px;
text-align:center;
line-height:1em;
color:#fff;
font-weight:normal;
letter-spacing:-1px;
}
h4.title_services2 {
font-size:28px;
margin-top:25px;
margin-bottom:15px;
text-align:center;
line-height:1em;
color:blue;/*#fff;*/
font-weight:normal;
letter-spacing:-1px;
}
HTML is as follows:
<article class="grid_3">
<div class="indent-left">
<img style="display: block; margin: 0 auto;"
src="../images/services_kid.png" />
<h4 class="title_services">First headline</h4>
<div id="button2"><a class="button2" href="#">BUTTON</a></div>
</div>
</article>
<article class="grid_3">
<div class="indent-left">
<img style="display: block; margin: 0 auto;"
src="../images/services_kid2.png" />
<h4 class="title_services2">Second headline</h4>
<div id="button2"><a class="button2" href="#">CENÍK</a></div>
</div>
</article>
Thursday, 26 September 2013
how to list data according to date using jquery or jquery mobile mobile
how to list data according to date using jquery or jquery mobile mobile
I'm developing a library mobile application using jquery mobile and
asp.net I'm new to jquery mobile and I'm facing an issue and I don't have
the slightest idea about the solution I need to display books arrival
according to the date in my page the date will be the title and below the
thumbnails of books will display like displayed below
I don't except the code for this solution I just need little ideas for
solving this problem
I'm developing a library mobile application using jquery mobile and
asp.net I'm new to jquery mobile and I'm facing an issue and I don't have
the slightest idea about the solution I need to display books arrival
according to the date in my page the date will be the title and below the
thumbnails of books will display like displayed below
I don't except the code for this solution I just need little ideas for
solving this problem
Wednesday, 25 September 2013
how can we use mercurial instead of git to host a website in heroku?
how can we use mercurial instead of git to host a website in heroku?
i want to host a website on heroku.I Have developed it using ruby on
rails.i have used postgres database and mercurial repository. where ever i
check, i can find only ways to host using git.can someone help me out
here.
i want to host a website on heroku.I Have developed it using ruby on
rails.i have used postgres database and mercurial repository. where ever i
check, i can find only ways to host using git.can someone help me out
here.
Thursday, 19 September 2013
Is there a SFINAE test to check if an enum is unsigned?
Is there a SFINAE test to check if an enum is unsigned?
Actually, I'm not sure if using the operator< or any other comparison
operator other than operator== is even valid, but I've not seen anything
to suggest otherwise. So assuming that is valid, is there a way of
determining if an enum is valid using SFINAE?
Actually, I'm not sure if using the operator< or any other comparison
operator other than operator== is even valid, but I've not seen anything
to suggest otherwise. So assuming that is valid, is there a way of
determining if an enum is valid using SFINAE?
Capybara server can't access data created in a spec
Capybara server can't access data created in a spec
I am running Sinatra, Capybara and RSpec. I am testing javascript
interactions with webkit headless browser. I am using factory girl to
create data that I need to be present for my test. I then use capybara to
perform interactions with my application. During these interactions the
data that I created at the start of the test is no longer available. It's
created with no issue however when debugging in the controller the
database is empty. Why is my database empty in the controller but not in
the spec that interacts with the contorller?
I am running Sinatra, Capybara and RSpec. I am testing javascript
interactions with webkit headless browser. I am using factory girl to
create data that I need to be present for my test. I then use capybara to
perform interactions with my application. During these interactions the
data that I created at the start of the test is no longer available. It's
created with no issue however when debugging in the controller the
database is empty. Why is my database empty in the controller but not in
the spec that interacts with the contorller?
Fill columns of list with People information
Fill columns of list with People information
If a user adds there name to a column is there a way to fill the next
columns with their department and reports information? Calculated columns
are not allowed on People columns
If a user adds there name to a column is there a way to fill the next
columns with their department and reports information? Calculated columns
are not allowed on People columns
Image gallery with permalinks
Image gallery with permalinks
I'm looking for a way to create a page that displays all of the images in
a folder that I already have uploaded to my server. I would prefer to use
PHP, but I can deal with JavaScript as well. I also need each image, when
clicked, to take the user to a permalink page where just that image is
displayed.
This doesn't need to be very fancy, just functional.
Thank you!
I'm looking for a way to create a page that displays all of the images in
a folder that I already have uploaded to my server. I would prefer to use
PHP, but I can deal with JavaScript as well. I also need each image, when
clicked, to take the user to a permalink page where just that image is
displayed.
This doesn't need to be very fancy, just functional.
Thank you!
code dont work for placeholder?
code dont work for placeholder?
<textarea id="a">text are text?</textarea>
I am tryingt to make something similar like placeholder, everything should
work, but it doesnt, any suguestions?
var standard_message = $('#a').val();
$('#a').focus(
function() {
if ($(this).val() == standard_message)
$(this).val("");
}
);
$('#a').blur(
function() {
if ($(this).val() == "")
$(this).val(standard_message);
}
);
<textarea id="a">text are text?</textarea>
I am tryingt to make something similar like placeholder, everything should
work, but it doesnt, any suguestions?
var standard_message = $('#a').val();
$('#a').focus(
function() {
if ($(this).val() == standard_message)
$(this).val("");
}
);
$('#a').blur(
function() {
if ($(this).val() == "")
$(this).val(standard_message);
}
);
what is wrong in my program? although it runs all right
what is wrong in my program? although it runs all right
i want to make a following program: Given a natural number n (1 <= n <=
500000), that outputs the summation of all its proper divisors. e.g.
number 20 has 5 proper divisors: 1, 2, 4, 5, 10, and the divisor summation
is: 1 + 2 + 4 + 5 + 10 = 22.
Input An integer stating the number of test cases (equal to about 200000),
and that many lines follow, each containing one integer between 1 and
500000 inclusive.
Output One integer each line: the divisor summation of the integer given
respectively.
Example
Sample Input:
3
2
10
20
Sample Output:
1
8
22
i have made following code:
#include <stdio.h>
#include <math.h>
int main()
{
long int R,i,q,a,b,k,sum[200000],a1,a2,s,ar[200000];
//printf("enter range");
scanf("%ld",&R);
//sum[0]=1;
for(i=0;i<R;i++)
{
// printf("enter number");
scanf("%ld",&ar[i]);
}
for(q=0;q<R;q++)
{
sum[q]=1;
s=sqrt(ar[q]);
if(ar[q]==1)
{
sum[i]=0;
}
for(b=2;b<=s;b++)
{
if(ar[q]%b==0)
{
a1=b; //factor
a2=ar[q]/b; //it will also be a factor
sum[q]=sum[q]+a1+a2;
if(a1==a2) sum[q]=sum[q]-a2;
if(a1>=a2) break;
}
}
}
if(q==R)
{ for(k=0;k<R;k++)
printf("%ld\n",sum[k]);
}
return 0;
}
i think i have made the code right and its also working fine, but when i
submit the code here (at submit button on top) i get a response as :
"wrong answer", please help anybody, i can't figure it out, why is my
answer wrong?
i want to make a following program: Given a natural number n (1 <= n <=
500000), that outputs the summation of all its proper divisors. e.g.
number 20 has 5 proper divisors: 1, 2, 4, 5, 10, and the divisor summation
is: 1 + 2 + 4 + 5 + 10 = 22.
Input An integer stating the number of test cases (equal to about 200000),
and that many lines follow, each containing one integer between 1 and
500000 inclusive.
Output One integer each line: the divisor summation of the integer given
respectively.
Example
Sample Input:
3
2
10
20
Sample Output:
1
8
22
i have made following code:
#include <stdio.h>
#include <math.h>
int main()
{
long int R,i,q,a,b,k,sum[200000],a1,a2,s,ar[200000];
//printf("enter range");
scanf("%ld",&R);
//sum[0]=1;
for(i=0;i<R;i++)
{
// printf("enter number");
scanf("%ld",&ar[i]);
}
for(q=0;q<R;q++)
{
sum[q]=1;
s=sqrt(ar[q]);
if(ar[q]==1)
{
sum[i]=0;
}
for(b=2;b<=s;b++)
{
if(ar[q]%b==0)
{
a1=b; //factor
a2=ar[q]/b; //it will also be a factor
sum[q]=sum[q]+a1+a2;
if(a1==a2) sum[q]=sum[q]-a2;
if(a1>=a2) break;
}
}
}
if(q==R)
{ for(k=0;k<R;k++)
printf("%ld\n",sum[k]);
}
return 0;
}
i think i have made the code right and its also working fine, but when i
submit the code here (at submit button on top) i get a response as :
"wrong answer", please help anybody, i can't figure it out, why is my
answer wrong?
Open a file without getOpenFileName?
Open a file without getOpenFileName?
is there a way to open files without using QFileDialog.getOpenFileName
parameter? The thing is, I have a some buttons that upon clicking them, a
notepad will pop up in which you can type anything into the notepad. Then,
you can save whatever you wrote in that notepad as a file. What I want to
do is, if I click the button again, I will reopen the file that I had
previously edited via the notepad and can continue typing where I left
off. However, I don't want to use getOpenFileName. Would it be possible to
open a file without using this functionality? Below is my attempt but my
if statement keeps evaluating to be false. If anyone could help that would
be great. Thanks!
#Testing if the file already exists
if(os.path.exists("~/Desktop/" +self.fileName + ".txt")):
f = open(self.fileName + ".txt", 'r')
filedata = f.read()
self.text.setText(filedata)
f.close()
#Opens a new notepad if there wasn't a previous fileconstructed
else:
self.textBox = textBoxWindow(self.fileName)
self.textBox.show()
is there a way to open files without using QFileDialog.getOpenFileName
parameter? The thing is, I have a some buttons that upon clicking them, a
notepad will pop up in which you can type anything into the notepad. Then,
you can save whatever you wrote in that notepad as a file. What I want to
do is, if I click the button again, I will reopen the file that I had
previously edited via the notepad and can continue typing where I left
off. However, I don't want to use getOpenFileName. Would it be possible to
open a file without using this functionality? Below is my attempt but my
if statement keeps evaluating to be false. If anyone could help that would
be great. Thanks!
#Testing if the file already exists
if(os.path.exists("~/Desktop/" +self.fileName + ".txt")):
f = open(self.fileName + ".txt", 'r')
filedata = f.read()
self.text.setText(filedata)
f.close()
#Opens a new notepad if there wasn't a previous fileconstructed
else:
self.textBox = textBoxWindow(self.fileName)
self.textBox.show()
Wednesday, 18 September 2013
How to make an import command in python shell work in Jgrasp for python?
How to make an import command in python shell work in Jgrasp for python?
I am wondering if the Jgrasp IDE for python has any major differences from
the basic shell. I am having some issues with importing a module to Jgrasp
using a sequence that worked fine in shell:
import random
random.random()
(random number came here)
This is not working in Jgrasp, and I am wondering how i can modify it to
make it functional.
I am wondering if the Jgrasp IDE for python has any major differences from
the basic shell. I am having some issues with importing a module to Jgrasp
using a sequence that worked fine in shell:
import random
random.random()
(random number came here)
This is not working in Jgrasp, and I am wondering how i can modify it to
make it functional.
getInputStream() is not returning readable information
getInputStream() is not returning readable information
My homework assignment is to call a .jar from within a java program but I
can't get the input stream to return the results into something readable.
Here is what I did first:
InputStream in = proc.getInputStream();
System.out.println(in);
But that didn't work, and I found some different variation:
BufferedReader input = new BufferedReader(new
InputStreamReader(p.getInputStream()));
System.out.println(input);
But that didn't work either, both scenarios it returned something like
this: java.io.BufferedReader@2ce908. How can I get it to return a readable
output?
My homework assignment is to call a .jar from within a java program but I
can't get the input stream to return the results into something readable.
Here is what I did first:
InputStream in = proc.getInputStream();
System.out.println(in);
But that didn't work, and I found some different variation:
BufferedReader input = new BufferedReader(new
InputStreamReader(p.getInputStream()));
System.out.println(input);
But that didn't work either, both scenarios it returned something like
this: java.io.BufferedReader@2ce908. How can I get it to return a readable
output?
SQLiteNet Index and Lambda expressions
SQLiteNet Index and Lambda expressions
We are using Xamarin with SQLiteNet as ORM.
In our data layer class we have the method below.
filter = ri => ri.ItemVersioniId == itemVersionId;
The method is getting the records matching the Id. If the lambda
expression is hardcoded, instead of using the "filter" parameter it is
much faster... even though it is the same logic.
We would to be able to pass the filter as a parameter but still get a good
performance. Any advise?
public virtual List<ResourceItem> GetResourceItems (string itemVersionId,
Func<ResourceItem,bool> filter ){
//var t = db.Table<ResourceItem> ().Where (ri => ri.ItemVersionId
== itemVersionId); --* this line is 10 times faster
var t = db.Table<ResourceItem> ().Where (filter); --* this line is
10 times slower
return new List<ResourceItem> (t);
}
We are using Xamarin with SQLiteNet as ORM.
In our data layer class we have the method below.
filter = ri => ri.ItemVersioniId == itemVersionId;
The method is getting the records matching the Id. If the lambda
expression is hardcoded, instead of using the "filter" parameter it is
much faster... even though it is the same logic.
We would to be able to pass the filter as a parameter but still get a good
performance. Any advise?
public virtual List<ResourceItem> GetResourceItems (string itemVersionId,
Func<ResourceItem,bool> filter ){
//var t = db.Table<ResourceItem> ().Where (ri => ri.ItemVersionId
== itemVersionId); --* this line is 10 times faster
var t = db.Table<ResourceItem> ().Where (filter); --* this line is
10 times slower
return new List<ResourceItem> (t);
}
Make "if" dynamic in JSViews
Make "if" dynamic in JSViews
I am trying to use JSViews to make a dynamic ui. I want to have radio
buttons that hide/show different parts of the ui, and have the radio
button be bound to my data.
Creating and binding the radio buttons works ok, but I am stuck on the
next part. I tried using an {{if}} to show different parts of the ui based
on the same value that is driving the radio buttons. It shows the correct
ui based on the initial value, but when I change the radio button, the if
doesn't evaluate with the new value.
Here is a jsfiddle that shows what I have so far.
The part that doesn't work the way I want is
template += '{{if dynamic}}';
template += 'dynamic';
template += '{{else}}';
template += 'static';
template += '{{/if}}';
template += "</div>";
Is it even possible to do what I want with jsviews? I am trying to get rid
of a bunch of code that was handling all the clicks and hiding and showing
manually.
I am trying to use JSViews to make a dynamic ui. I want to have radio
buttons that hide/show different parts of the ui, and have the radio
button be bound to my data.
Creating and binding the radio buttons works ok, but I am stuck on the
next part. I tried using an {{if}} to show different parts of the ui based
on the same value that is driving the radio buttons. It shows the correct
ui based on the initial value, but when I change the radio button, the if
doesn't evaluate with the new value.
Here is a jsfiddle that shows what I have so far.
The part that doesn't work the way I want is
template += '{{if dynamic}}';
template += 'dynamic';
template += '{{else}}';
template += 'static';
template += '{{/if}}';
template += "</div>";
Is it even possible to do what I want with jsviews? I am trying to get rid
of a bunch of code that was handling all the clicks and hiding and showing
manually.
handling two inputs under one onClick event
handling two inputs under one onClick event
I am completely new to android development, my problem is that i had two
editText boxes in my layout and self created number button 0-9,enterButton
and Clr button. now my problem is to get two inputs from user via these
number button in two diffrent editText boxes. Help me out!!! Here is the
code`@Override public void onClick(View view) { // button clicked if
(view.getId() == R.id.buttonEnter) { // enter button
}
} else if (view.getId() == R.id.buttonClr) {
// clear button
} else {
// number button
response.setVisibility(View.INVISIBLE);
// here i want to take two inputs by clicking two buttons and display
them
int entered1 = Integer.parseInt(view.getTag().toString());
editTxt1.setText(String.valueOf(entered1));
int entered2 = Integer.parseInt(view.getTag().toString());
editTxt2.setText(String.valueOf(entered2));
}
}`
I am completely new to android development, my problem is that i had two
editText boxes in my layout and self created number button 0-9,enterButton
and Clr button. now my problem is to get two inputs from user via these
number button in two diffrent editText boxes. Help me out!!! Here is the
code`@Override public void onClick(View view) { // button clicked if
(view.getId() == R.id.buttonEnter) { // enter button
}
} else if (view.getId() == R.id.buttonClr) {
// clear button
} else {
// number button
response.setVisibility(View.INVISIBLE);
// here i want to take two inputs by clicking two buttons and display
them
int entered1 = Integer.parseInt(view.getTag().toString());
editTxt1.setText(String.valueOf(entered1));
int entered2 = Integer.parseInt(view.getTag().toString());
editTxt2.setText(String.valueOf(entered2));
}
}`
Ajax post returning error
Ajax post returning error
Im having the following ajax cal in my JS file in Durundal ,
var dataJSON ={ID : "jo"};
self.js = $.ajax({
type: "POST",
dataType: String,
url: "http://localhost:53081/api/File",
data: JSON.stringify(dataJSON),
error: function (xhr, status, error) {
alert(status);
},
success: function (json) {
alert("Data Returned: " + JSON.stringify(json));
}
});
and my REST api is
[HttpPost]
public string upload(string ID)
{
string givenId = ID;
return givenId;
}
but when i call thsi methos im simply getting error alert . what went wrong
Im having the following ajax cal in my JS file in Durundal ,
var dataJSON ={ID : "jo"};
self.js = $.ajax({
type: "POST",
dataType: String,
url: "http://localhost:53081/api/File",
data: JSON.stringify(dataJSON),
error: function (xhr, status, error) {
alert(status);
},
success: function (json) {
alert("Data Returned: " + JSON.stringify(json));
}
});
and my REST api is
[HttpPost]
public string upload(string ID)
{
string givenId = ID;
return givenId;
}
but when i call thsi methos im simply getting error alert . what went wrong
how to define the process of retrieving data from sqlite programmatically?
how to define the process of retrieving data from sqlite programmatically?
Im new to these sqlite accessing programming.i have 9 edittext and coded
to store values in sqlite db...next time if i insert the same value in
first edittext the remaining value should display without entering..code
below is what i have tried but couldnt get back the values
//this is my dbhandler class method
> public Data findProduct(String phone) { String query = "Select *
> FROM " + TABLE_FEEDBACK + " WHERE " + COLUMN_PHONENO + " = \"" +
> phone + "\"";
> SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(query, null);
Data data = new Data();
if (cursor.moveToFirst()) { cursor.moveToFirst();
data.setPHONE(cursor.getString(0));
data.setName(cursor.getString(1));
data.setFood(cursor.getString(2));
data.setService(cursor.getString(3));
data.setCleanliness(cursor.getString(4));
data.setExperience(cursor.getString(5));
data.setAddress(cursor.getString(6));
data.setEmail(cursor.getString(7));
data.setBirthday(cursor.getString(8));
data.setAnniversary(cursor.getString(9));
data.setFavrestaurant(cursor.getString(10));
data.setFavstaff(cursor.getString(11));
data.setFavdish(cursor.getString(12));
data.setSuggestion(cursor.getString(13));
data.setReturn(cursor.getString(14)); cursor.close();
} else {
data = null; }
db.close(); return data; }
/*public void openDataBase(SQLiteDatabase db) throws SQLException {
//Open the database
String myPath = DB_PATH + DATABASE_NAME;
db = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READONLY);
} */
//this is my mainactivity method
public void lookupProduct (View view) { DBHandler dbHandler = new
DBHandler(MainActivity.this);
Data data =
dbHandler.findProduct(phonenumber.getText().toString());
if (data != null) {
name.setText(String.valueOf(data.getName()));
address.setText(String.valueOf(data.getAddress()));
} else {
name.setText("No Match Found");
} }
Im new to these sqlite accessing programming.i have 9 edittext and coded
to store values in sqlite db...next time if i insert the same value in
first edittext the remaining value should display without entering..code
below is what i have tried but couldnt get back the values
//this is my dbhandler class method
> public Data findProduct(String phone) { String query = "Select *
> FROM " + TABLE_FEEDBACK + " WHERE " + COLUMN_PHONENO + " = \"" +
> phone + "\"";
> SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(query, null);
Data data = new Data();
if (cursor.moveToFirst()) { cursor.moveToFirst();
data.setPHONE(cursor.getString(0));
data.setName(cursor.getString(1));
data.setFood(cursor.getString(2));
data.setService(cursor.getString(3));
data.setCleanliness(cursor.getString(4));
data.setExperience(cursor.getString(5));
data.setAddress(cursor.getString(6));
data.setEmail(cursor.getString(7));
data.setBirthday(cursor.getString(8));
data.setAnniversary(cursor.getString(9));
data.setFavrestaurant(cursor.getString(10));
data.setFavstaff(cursor.getString(11));
data.setFavdish(cursor.getString(12));
data.setSuggestion(cursor.getString(13));
data.setReturn(cursor.getString(14)); cursor.close();
} else {
data = null; }
db.close(); return data; }
/*public void openDataBase(SQLiteDatabase db) throws SQLException {
//Open the database
String myPath = DB_PATH + DATABASE_NAME;
db = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READONLY);
} */
//this is my mainactivity method
public void lookupProduct (View view) { DBHandler dbHandler = new
DBHandler(MainActivity.this);
Data data =
dbHandler.findProduct(phonenumber.getText().toString());
if (data != null) {
name.setText(String.valueOf(data.getName()));
address.setText(String.valueOf(data.getAddress()));
} else {
name.setText("No Match Found");
} }
lua load() output not working as expected
lua load() output not working as expected
So I'm trying to load some lua code from a file, but keep doing something
wrong.
The code does not print(). Is the output going to some stream saved in a
variable? Or what I dunno...
New to lua.
Also same question with binary code instead of text...
> i= io.input("lua1.lua")
> ii = i:read("*a")
> print(ii)
print("hawhaw!")
> env={}
> e=load(ii,nil,"bt",env)
> pcall(e)
> print(pcall(e))
false [string "print("hawhaw!")..."]:1: attempt to call global 'print'
(a nil value)
> local print = print
> e=load(ii,nil,"bt",env)
> print(pcall(e))
true
> pcall(e)
> e()
> print(e())
So I'm trying to load some lua code from a file, but keep doing something
wrong.
The code does not print(). Is the output going to some stream saved in a
variable? Or what I dunno...
New to lua.
Also same question with binary code instead of text...
> i= io.input("lua1.lua")
> ii = i:read("*a")
> print(ii)
print("hawhaw!")
> env={}
> e=load(ii,nil,"bt",env)
> pcall(e)
> print(pcall(e))
false [string "print("hawhaw!")..."]:1: attempt to call global 'print'
(a nil value)
> local print = print
> e=load(ii,nil,"bt",env)
> print(pcall(e))
true
> pcall(e)
> e()
> print(e())
Tuesday, 17 September 2013
accessing method like get in didInsertElement of view
accessing method like get in didInsertElement of view
im trying to using jquery drag and drop and i want to using some tools of
ember in my view but i cant .
App.myView = Ember.View.extend({
tagName:'li',
didInsertElement:function(){
this.$().draggable({
start:function(event,ui){
console.log(this.get('tagName'));
}
});
}
});
but i get an error :
Uncaught TypeError: Object #<HTMLLIElement> has no method 'get'
can i use methods like get/set or other in didInsertElement in jquery
section ?
im trying to using jquery drag and drop and i want to using some tools of
ember in my view but i cant .
App.myView = Ember.View.extend({
tagName:'li',
didInsertElement:function(){
this.$().draggable({
start:function(event,ui){
console.log(this.get('tagName'));
}
});
}
});
but i get an error :
Uncaught TypeError: Object #<HTMLLIElement> has no method 'get'
can i use methods like get/set or other in didInsertElement in jquery
section ?
how to store input from echo in arrays on C
how to store input from echo in arrays on C
if I were to type in echo "1001" | ./test in the terminal.
and test takes "1001" and stores it into a array how would I do that
in test.c
#include <stdio.h>
main() {
int c, i, j;
int a[4];
while(c = (getchar() != EOF)) {
a[i++] = c;
}
for(j = 0; j < 5; j++ {
printf("%d", a[j]);
}
}
but it's not working.
if I were to type in echo "1001" | ./test in the terminal.
and test takes "1001" and stores it into a array how would I do that
in test.c
#include <stdio.h>
main() {
int c, i, j;
int a[4];
while(c = (getchar() != EOF)) {
a[i++] = c;
}
for(j = 0; j < 5; j++ {
printf("%d", a[j]);
}
}
but it's not working.
jquery .ajax always returns error - data being added to database
jquery .ajax always returns error - data being added to database
I am trying to add users to a database using jquery ajax calls. The users
get added just fine to the database, but the ajax always returns with
error. I'm not sure how to retrieve the specific error either. Below is my
code, form, php, and jquery.
Here is the jquery
$(document).ready(function() {
//ajax call for all forms.
$('.button').click(function() {
var form = $(this).closest('form');
$.ajax({
type: "POST",
url: form.attr('data'),
dataType: 'json',
data: form.serialize(),
success: function (response) {
alert('something');
},
error: function() {
alert('fail');
}
});
});
});
Here is the PHP
<?php
include 'class_lib.php';
if(isset($_POST['username'])) {
$user = new Users;
$user->cleanInput($_POST['username'], $_POST['password']);
if($user->insertUser()) {
echo json_encode('true');
} else {
echo json_encode('false');
}
}
Here is the HTML
<div id='newUser' class='tool'>
<h3>New User</h3>
<form method='post' name='newUser' data='../php/newUser.php'>
<span>Username</span><input type='text' name='username'><br>
<span>Password</span><input type='password' name='password'>
<input type='submit' name='submit' class='button'
style='visibility: hidden'>
</form>
<span class='result'> </span>
</div>
I am trying to add users to a database using jquery ajax calls. The users
get added just fine to the database, but the ajax always returns with
error. I'm not sure how to retrieve the specific error either. Below is my
code, form, php, and jquery.
Here is the jquery
$(document).ready(function() {
//ajax call for all forms.
$('.button').click(function() {
var form = $(this).closest('form');
$.ajax({
type: "POST",
url: form.attr('data'),
dataType: 'json',
data: form.serialize(),
success: function (response) {
alert('something');
},
error: function() {
alert('fail');
}
});
});
});
Here is the PHP
<?php
include 'class_lib.php';
if(isset($_POST['username'])) {
$user = new Users;
$user->cleanInput($_POST['username'], $_POST['password']);
if($user->insertUser()) {
echo json_encode('true');
} else {
echo json_encode('false');
}
}
Here is the HTML
<div id='newUser' class='tool'>
<h3>New User</h3>
<form method='post' name='newUser' data='../php/newUser.php'>
<span>Username</span><input type='text' name='username'><br>
<span>Password</span><input type='password' name='password'>
<input type='submit' name='submit' class='button'
style='visibility: hidden'>
</form>
<span class='result'> </span>
</div>
Is it faster to read raw json files or jsonified C# classes?
Is it faster to read raw json files or jsonified C# classes?
It is easier for me to create the data my site uses in a .cshtml file that
instantiates N objects of a class (as opposed to creating a .json file). I
only recently changed to this method, after previously creating raw json
files.
The code to read the data, whether .json or .cshtml, is the same:
$.getJSON('Content/nba.json', function (data) {
$.each(data, function (i, dataPoint) {
. . .
$.getJSON('getHugos.cshtml', function (data) {
$.each(data, function (i, dataPoint) {
. . .
Presumably, reading raw json, like such:
. . .
{
"category":"Outdoor Literature",
"title":"Almost Somewhere: Twenty-Eight Days on the John Muir Trail",
"author":"Suzanne Roberts",
"kindle":"B008SAOT4C",
"hardbound":"--",
"paperback":"0803240120",
"imghref":"http://rads.stackoverflow.com/amzn/click/B008SAOT4C"
target=\"_blank\" ><img height=\"180\" width=\"120\"
src=\"http://images.amazon.com/images/P/B008SAOT4C.01.MZZZZZZZ.jpg\"
alt=\"Suzanne Roberts Book Cover\" /></a>"
},
. . .
...would be more performant than this sort of thing:
new Book {category='Best Novel', ... };
// jsonify and return the data above
...which has to go through the additional step via ASP.NET of being
converted to this:
[...,{"Year":2013,"YearDisplay":"2013","Category":"Best
Novel","Title":"Redshirts","Author":"John
Scalzi","KindleASIN":"B0079XPUOW","HardboundASIN":"0765316994","PaperbackASIN":"0765334798","ImgSrc":"http://images.amazon.com/images/P/B0079XPUOW.01.MZZZZZZZ"},...]
...but as we all know, presuming things sometimes gets us into trouble.
I know what you're thinking - just test it and find out; but I haven't
created enough of the cshtml records yet to be able to compare the two
approaches, but wonder if anybody knows whether the speed of loading raw
json files would be noticeably speedier than converting the C# classes
into json data? If so, I might have to revert to my previous
methodology...
It is easier for me to create the data my site uses in a .cshtml file that
instantiates N objects of a class (as opposed to creating a .json file). I
only recently changed to this method, after previously creating raw json
files.
The code to read the data, whether .json or .cshtml, is the same:
$.getJSON('Content/nba.json', function (data) {
$.each(data, function (i, dataPoint) {
. . .
$.getJSON('getHugos.cshtml', function (data) {
$.each(data, function (i, dataPoint) {
. . .
Presumably, reading raw json, like such:
. . .
{
"category":"Outdoor Literature",
"title":"Almost Somewhere: Twenty-Eight Days on the John Muir Trail",
"author":"Suzanne Roberts",
"kindle":"B008SAOT4C",
"hardbound":"--",
"paperback":"0803240120",
"imghref":"http://rads.stackoverflow.com/amzn/click/B008SAOT4C"
target=\"_blank\" ><img height=\"180\" width=\"120\"
src=\"http://images.amazon.com/images/P/B008SAOT4C.01.MZZZZZZZ.jpg\"
alt=\"Suzanne Roberts Book Cover\" /></a>"
},
. . .
...would be more performant than this sort of thing:
new Book {category='Best Novel', ... };
// jsonify and return the data above
...which has to go through the additional step via ASP.NET of being
converted to this:
[...,{"Year":2013,"YearDisplay":"2013","Category":"Best
Novel","Title":"Redshirts","Author":"John
Scalzi","KindleASIN":"B0079XPUOW","HardboundASIN":"0765316994","PaperbackASIN":"0765334798","ImgSrc":"http://images.amazon.com/images/P/B0079XPUOW.01.MZZZZZZZ"},...]
...but as we all know, presuming things sometimes gets us into trouble.
I know what you're thinking - just test it and find out; but I haven't
created enough of the cshtml records yet to be able to compare the two
approaches, but wonder if anybody knows whether the speed of loading raw
json files would be noticeably speedier than converting the C# classes
into json data? If so, I might have to revert to my previous
methodology...
SWT Table with date chooser fields
SWT Table with date chooser fields
This is an obvious question but for some reason I haven't found a solution
that works. I have a table with 3 columns, the first two are dates, the
third one I'm using a Spinner because I want the user to only enter
numbers. I need all fields to be editable, but
the field should be editable only when it's in focus, when it's clicked on
the other fields in the same row should not be editable
when the field loses focus, it should go back to "default" mode
These are all normal things that one would expect in an editable table.
For some reason I couldn't make this work in SWT. Right now what I have
is:
I add a new row, all fields are "default"
I click on the row, all fields turn into editable (the date fields become
combo boxes etc.)
after the row losing focus, it remains editable
This is the code that I have right now, it's based on some other code I
found on the internet:
// this will happen when you click on the table
table.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Clean up any previous editor control
final TableEditor editor1 = new TableEditor(table);
// The editor must have the same size as the cell and must
// not be any smaller than 50 pixels.
editor1.horizontalAlignment = SWT.LEFT;
editor1.grabHorizontal = true;
editor1.minimumWidth = 50;
Control oldEditor = editor1.getEditor();
if (oldEditor != null)
oldEditor.dispose();
// Identify the selected row
TableItem item = (TableItem)e.item;
if (item == null) return;
// this is the editor for the first column
DateTime startDateTxt = new DateTime(table, SWT.BORDER |
SWT.DROP_DOWN | SWT.LONG);
startDateTxt.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
DateTime text = (DateTime)editor1.getEditor();
editor1.getItem().setText(0, new LocalDate(text.getYear(),
text.getMonth(), text.getDay()).toString());
}
});
editor1.setEditor(startDateTxt, item, 0);
// and now comes the editor for the 2nd column
//~~~~
// Clean up any previous editor control
final TableEditor editor2 = new TableEditor(table);
// The editor must have the same size as the cell and must
// not be any smaller than 50 pixels.
editor2.horizontalAlignment = SWT.LEFT;
editor2.grabHorizontal = true;
editor2.minimumWidth = 50;
oldEditor = editor2.getEditor();
if (oldEditor != null)
oldEditor.dispose();
// this is the editor for the second column
DateTime endDateTxt = new DateTime(table, SWT.BORDER |
SWT.DROP_DOWN | SWT.LONG);
endDateTxt.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
DateTime text = (DateTime)editor2.getEditor();
editor2.getItem().setText(1, new LocalDate(text.getYear(),
text.getMonth(), text.getDay()).toString());
}
});
editor2.setEditor(endDateTxt, item, 1);
//~~~~
// Clean up any previous editor control
final TableEditor editor3 = new TableEditor(table);
// The editor must have the same size as the cell and must
// not be any smaller than 50 pixels.
editor3.horizontalAlignment = SWT.LEFT;
editor3.grabHorizontal = true;
editor3.minimumWidth = 50;
oldEditor = editor3.getEditor();
if (oldEditor != null)
oldEditor.dispose();
// this is the editor for the third column
Spinner percentTxt = createNewSpinner(table, SWT.NONE);
percentTxt.addModifyListener(new ModifyListener() {
public void modifyText(ModifyEvent me) {
Spinner text = (Spinner)editor3.getEditor();
editor3.getItem().setText(2, text.getText());
}
});
editor3.setEditor(percentTxt, item, 2);
//~~~~
}
});
As you can see, when the user clicks on the table, I get the current row,
and add 3 editors to the row. What I would like to do is get the selected
column. I haven't found how to do this. If I get the selected column, then
I would be able to create an editor just for the selected cell, and not
the whole row.
I also haven't figured out how to dispose the editor after it loses focus.
If the user clicks outside the table, then it has clearly happened. But
what if the user just clicks on another cell? Then I would have to dispose
the old editor and create a new one.
This is an obvious question but for some reason I haven't found a solution
that works. I have a table with 3 columns, the first two are dates, the
third one I'm using a Spinner because I want the user to only enter
numbers. I need all fields to be editable, but
the field should be editable only when it's in focus, when it's clicked on
the other fields in the same row should not be editable
when the field loses focus, it should go back to "default" mode
These are all normal things that one would expect in an editable table.
For some reason I couldn't make this work in SWT. Right now what I have
is:
I add a new row, all fields are "default"
I click on the row, all fields turn into editable (the date fields become
combo boxes etc.)
after the row losing focus, it remains editable
This is the code that I have right now, it's based on some other code I
found on the internet:
// this will happen when you click on the table
table.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Clean up any previous editor control
final TableEditor editor1 = new TableEditor(table);
// The editor must have the same size as the cell and must
// not be any smaller than 50 pixels.
editor1.horizontalAlignment = SWT.LEFT;
editor1.grabHorizontal = true;
editor1.minimumWidth = 50;
Control oldEditor = editor1.getEditor();
if (oldEditor != null)
oldEditor.dispose();
// Identify the selected row
TableItem item = (TableItem)e.item;
if (item == null) return;
// this is the editor for the first column
DateTime startDateTxt = new DateTime(table, SWT.BORDER |
SWT.DROP_DOWN | SWT.LONG);
startDateTxt.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
DateTime text = (DateTime)editor1.getEditor();
editor1.getItem().setText(0, new LocalDate(text.getYear(),
text.getMonth(), text.getDay()).toString());
}
});
editor1.setEditor(startDateTxt, item, 0);
// and now comes the editor for the 2nd column
//~~~~
// Clean up any previous editor control
final TableEditor editor2 = new TableEditor(table);
// The editor must have the same size as the cell and must
// not be any smaller than 50 pixels.
editor2.horizontalAlignment = SWT.LEFT;
editor2.grabHorizontal = true;
editor2.minimumWidth = 50;
oldEditor = editor2.getEditor();
if (oldEditor != null)
oldEditor.dispose();
// this is the editor for the second column
DateTime endDateTxt = new DateTime(table, SWT.BORDER |
SWT.DROP_DOWN | SWT.LONG);
endDateTxt.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
DateTime text = (DateTime)editor2.getEditor();
editor2.getItem().setText(1, new LocalDate(text.getYear(),
text.getMonth(), text.getDay()).toString());
}
});
editor2.setEditor(endDateTxt, item, 1);
//~~~~
// Clean up any previous editor control
final TableEditor editor3 = new TableEditor(table);
// The editor must have the same size as the cell and must
// not be any smaller than 50 pixels.
editor3.horizontalAlignment = SWT.LEFT;
editor3.grabHorizontal = true;
editor3.minimumWidth = 50;
oldEditor = editor3.getEditor();
if (oldEditor != null)
oldEditor.dispose();
// this is the editor for the third column
Spinner percentTxt = createNewSpinner(table, SWT.NONE);
percentTxt.addModifyListener(new ModifyListener() {
public void modifyText(ModifyEvent me) {
Spinner text = (Spinner)editor3.getEditor();
editor3.getItem().setText(2, text.getText());
}
});
editor3.setEditor(percentTxt, item, 2);
//~~~~
}
});
As you can see, when the user clicks on the table, I get the current row,
and add 3 editors to the row. What I would like to do is get the selected
column. I haven't found how to do this. If I get the selected column, then
I would be able to create an editor just for the selected cell, and not
the whole row.
I also haven't figured out how to dispose the editor after it loses focus.
If the user clicks outside the table, then it has clearly happened. But
what if the user just clicks on another cell? Then I would have to dispose
the old editor and create a new one.
IOS 7 - css - html height - 100% = 692px
IOS 7 - css - html height - 100% = 692px
I have a weird bug on iPad iOS7 landscape mode.
What i was able to investigate is that in iOS7 window.outerHeight is 692px
and window.innerHeight 672px; while in previous versions both values are
672px.
Even though my <html> and <body> tags have height 100% there seems to be
space for scrolling, and the weird thing is that this problem only shows
up on landscpae
You can see what i am talking about by visiting t.cincodias.com, for
example, in a iOS 7 iPad the footer bar (or the header sometimes) will be
cut. But on previous iOS versions the content displays fine at fullscreen.
Even when i set the height of both tags to height: 672px !importante and
position:absolute; bottom: 0;, you can still scroll the content vertically
by touching an iframe (the ads are iframes).
I'm running the release candidate version of iOS7
thanks for any help.
I have a weird bug on iPad iOS7 landscape mode.
What i was able to investigate is that in iOS7 window.outerHeight is 692px
and window.innerHeight 672px; while in previous versions both values are
672px.
Even though my <html> and <body> tags have height 100% there seems to be
space for scrolling, and the weird thing is that this problem only shows
up on landscpae
You can see what i am talking about by visiting t.cincodias.com, for
example, in a iOS 7 iPad the footer bar (or the header sometimes) will be
cut. But on previous iOS versions the content displays fine at fullscreen.
Even when i set the height of both tags to height: 672px !importante and
position:absolute; bottom: 0;, you can still scroll the content vertically
by touching an iframe (the ads are iframes).
I'm running the release candidate version of iOS7
thanks for any help.
Sunday, 15 September 2013
Use Openquery in local WHERE Clause
Use Openquery in local WHERE Clause
I work on SQL Server 2008 R2.
I have a REFERENCE Database on Server_1 that contains a scalar-valued
function MyFunc that takes two params and returns an INT.
I need to build a query on a table MyTable on server_2 based on the result
of MyFunc, like:
SELECT *
FROM MyTable
WHERE MyFunc(MyTable.param1, MyTable.param2) <> 0
I tried using Openquery, but it did not work
SELECT *
FROM MyTable
WHERE OPENQUERY(Server_1,'SELECT REFERENCE.ref.MyFunc(param1, param2)') <> 0
What would be the best way to handle this type of query ? Thanks
I work on SQL Server 2008 R2.
I have a REFERENCE Database on Server_1 that contains a scalar-valued
function MyFunc that takes two params and returns an INT.
I need to build a query on a table MyTable on server_2 based on the result
of MyFunc, like:
SELECT *
FROM MyTable
WHERE MyFunc(MyTable.param1, MyTable.param2) <> 0
I tried using Openquery, but it did not work
SELECT *
FROM MyTable
WHERE OPENQUERY(Server_1,'SELECT REFERENCE.ref.MyFunc(param1, param2)') <> 0
What would be the best way to handle this type of query ? Thanks
Struct and Pointers
Struct and Pointers
So in my code I have two structures. The first is a node which contains an
int value and a pointer to another node. The second structure is used to
create an array of 10 pointers each point to a another node. And it also
contains link2 which will be used to traverse the array and all the nodes
that it points to. I'm trying to add 3 nodes each holds the value 3 into
the third index of the array. The pointer in the third index should point
to the first 3 then that should point to the second three and so on. When
I put add(a,3) three times and then print it it only prints out two nodes
rather than three. I tried tracing the code but that still didn't make any
sense to me because I always end up with three nodes. Can someone point me
in some direction? Thanks!:)/>
#include <stdio.h>
#include<stdlib.h>
#include<string.h>
struct node{
int x;
struct node *link;
};
struct listofnodes{
struct node *alist[10];
struct node *link2;
};
addFirst(struct listofnodes *a,int num)
{
struct node *nodeone = (struct node *)malloc(sizeof(struct node));
nodeone->x=num;
a->alist[num]=nodeone;
//printf("IT WENT THROUGH\n");
}
add(struct listofnodes *a,int num)
{
struct node *current;
current=a->alist[3];
struct node *nodeone = (struct node *)malloc(sizeof(struct node));
nodeone->x=num;
current->x=5;
{
while(a->alist[3]!=NULL)
{
if(a->alist[3]->link==NULL)
{
a->alist[3]->link=nodeone;
printf("IT WENT THROUGH\n");
break;
}
a->alist[3]=a->alist[3]->link;
}
}
}
main(void)
{
struct listofnodes *a=(struct listofnodes *)malloc(sizeof(struct
listofnodes));
//a->alist[3]=NULL;
addFirst(a,3);
add(a,3);
add(a,3);
add(a,5);
}
So in my code I have two structures. The first is a node which contains an
int value and a pointer to another node. The second structure is used to
create an array of 10 pointers each point to a another node. And it also
contains link2 which will be used to traverse the array and all the nodes
that it points to. I'm trying to add 3 nodes each holds the value 3 into
the third index of the array. The pointer in the third index should point
to the first 3 then that should point to the second three and so on. When
I put add(a,3) three times and then print it it only prints out two nodes
rather than three. I tried tracing the code but that still didn't make any
sense to me because I always end up with three nodes. Can someone point me
in some direction? Thanks!:)/>
#include <stdio.h>
#include<stdlib.h>
#include<string.h>
struct node{
int x;
struct node *link;
};
struct listofnodes{
struct node *alist[10];
struct node *link2;
};
addFirst(struct listofnodes *a,int num)
{
struct node *nodeone = (struct node *)malloc(sizeof(struct node));
nodeone->x=num;
a->alist[num]=nodeone;
//printf("IT WENT THROUGH\n");
}
add(struct listofnodes *a,int num)
{
struct node *current;
current=a->alist[3];
struct node *nodeone = (struct node *)malloc(sizeof(struct node));
nodeone->x=num;
current->x=5;
{
while(a->alist[3]!=NULL)
{
if(a->alist[3]->link==NULL)
{
a->alist[3]->link=nodeone;
printf("IT WENT THROUGH\n");
break;
}
a->alist[3]=a->alist[3]->link;
}
}
}
main(void)
{
struct listofnodes *a=(struct listofnodes *)malloc(sizeof(struct
listofnodes));
//a->alist[3]=NULL;
addFirst(a,3);
add(a,3);
add(a,3);
add(a,5);
}
How to verify whether a text is the same as the string in position of the array mentioned and do a corresponding job?
How to verify whether a text is the same as the string in position of the
array mentioned and do a corresponding job?
Okay, I want that if the text 'A' is same as the text as in the string in
an array at the position 0 / 1, send an SMS 'A is correct' to 5666 when I
click on the button 'b0'? and that if the text 'B' is same as the text as
in the string in an array at the position 0 / 1, send an SMS 'B is
correct' to 5666 when I click on the button 'b1'????
Code :
@Override
public void onClick(View arg0) {
switch(arg0.getId()) {
case R.id.b0:
if ("A".equals(names[0]))
sendSMS("5666", "A");
else if ("B".equals(names[0]))
sendSMS("5666", "B");
case R.id.b0:
if ("A".equals(names[1]))
sendSMS("5666", "A");
else if ("B".equals(names[1]))
sendSMS("5666", "B");
}
}
Now, suppose names[0]=A and names[1]=B , it does the work of sending "A"
to 5666 when I click button b0 but it doesn't send "B" to 5666 when I
click button b1!
array mentioned and do a corresponding job?
Okay, I want that if the text 'A' is same as the text as in the string in
an array at the position 0 / 1, send an SMS 'A is correct' to 5666 when I
click on the button 'b0'? and that if the text 'B' is same as the text as
in the string in an array at the position 0 / 1, send an SMS 'B is
correct' to 5666 when I click on the button 'b1'????
Code :
@Override
public void onClick(View arg0) {
switch(arg0.getId()) {
case R.id.b0:
if ("A".equals(names[0]))
sendSMS("5666", "A");
else if ("B".equals(names[0]))
sendSMS("5666", "B");
case R.id.b0:
if ("A".equals(names[1]))
sendSMS("5666", "A");
else if ("B".equals(names[1]))
sendSMS("5666", "B");
}
}
Now, suppose names[0]=A and names[1]=B , it does the work of sending "A"
to 5666 when I click button b0 but it doesn't send "B" to 5666 when I
click button b1!
valueChangeListener on h:inputHidden not working
valueChangeListener on h:inputHidden not working
My XHTML:
<h:inputHidden id="json" value="#{indexManaged.json}"
valueChangeListener="#{indexManaged.goTo('datatable')}" />
My ManagedBean:
@ManagedBean
@ViewScoped
public class IndexManaged implements Serializable {
public String goTo(String page) {
Flash flash =
FacesContext.getCurrentInstance().getExternalContext().getFlash();
flash.put("json", json);
return page + "?faces-redirect=true";
}
}
Why isn't #{indexManaged.goTo('datatable')} getting fired?
My XHTML:
<h:inputHidden id="json" value="#{indexManaged.json}"
valueChangeListener="#{indexManaged.goTo('datatable')}" />
My ManagedBean:
@ManagedBean
@ViewScoped
public class IndexManaged implements Serializable {
public String goTo(String page) {
Flash flash =
FacesContext.getCurrentInstance().getExternalContext().getFlash();
flash.put("json", json);
return page + "?faces-redirect=true";
}
}
Why isn't #{indexManaged.goTo('datatable')} getting fired?
alternative of scrollLeft()
alternative of scrollLeft()
G'day!
I have a page which has Horizontally Scroll feature going on there.
I have a side bar and a content box
In side bar I have 5 links, say LINK1 - LINK2
In the content box, I have 3500px of width which contains 5 sections of
divs of 700px.
So the page initially loads in the first 700px div. So if I click on Link
3, it will smoothly scrolling to 3rd div section.
However, I would like to load the page in the 2nd div.
I was able to do this using scrollLeft()
<script>$("div.content1").scrollLeft(700);</script>
But the horizontal scrolling will be messed up. The second div will act as
first div, which means when I click LINK1, it won't be scrolled back.
Help?
*I think this code is needed
<script>
function goto(id, t){
//animate to the div id
$(".contentbox-wrapper").stop().animate({"left":
-($(id).position().left)}, 1200);
}
</script>
G'day!
I have a page which has Horizontally Scroll feature going on there.
I have a side bar and a content box
In side bar I have 5 links, say LINK1 - LINK2
In the content box, I have 3500px of width which contains 5 sections of
divs of 700px.
So the page initially loads in the first 700px div. So if I click on Link
3, it will smoothly scrolling to 3rd div section.
However, I would like to load the page in the 2nd div.
I was able to do this using scrollLeft()
<script>$("div.content1").scrollLeft(700);</script>
But the horizontal scrolling will be messed up. The second div will act as
first div, which means when I click LINK1, it won't be scrolled back.
Help?
*I think this code is needed
<script>
function goto(id, t){
//animate to the div id
$(".contentbox-wrapper").stop().animate({"left":
-($(id).position().left)}, 1200);
}
</script>
C++/CLI Generic Static Class
C++/CLI Generic Static Class
I've been trying to convert some C# code to C++/CLI code (for some
performance reasons, as well as avoiding a bunch of interop issues),
however I've hit a wall. Admittedly, my C++/CLI knowledge is lacking (at
the absolute best).
Trying to convert a generic static class, that we used for size caching,
is proving to be a major headache.
The C# class is as follows;
public static class SizeCache<T>
{
public static int Size = Marshal.SizeOf(typeof(T));
}
And the C++/CLI wrapper (as far as I've gotten) is the following;
generic <typename T>
public ref class SizeCache abstract sealed
{
private:
static SizeCache()
{
Size = Marshal::SizeOf(T::typeid);
}
public:
static int Size;
};
Everything seems to compile fine, however, when I access it via;
int size = SizeCache<T>::Size;
I get compiler errors.
error C2039: 'Size' : is not a member of '`global namespace''
error C2065: 'Size' : undeclared identifier
Unfortunately, I can't see what I'm doing wrong in this case.
The reason for the class in the first place, is to avoid some issues with
the Marshaler (specifically when dealing with generic structure types),
and avoid the performance hit incurred by constantly calling SizeOf on the
same basic types.
What am I doing wrong here?
I've been trying to convert some C# code to C++/CLI code (for some
performance reasons, as well as avoiding a bunch of interop issues),
however I've hit a wall. Admittedly, my C++/CLI knowledge is lacking (at
the absolute best).
Trying to convert a generic static class, that we used for size caching,
is proving to be a major headache.
The C# class is as follows;
public static class SizeCache<T>
{
public static int Size = Marshal.SizeOf(typeof(T));
}
And the C++/CLI wrapper (as far as I've gotten) is the following;
generic <typename T>
public ref class SizeCache abstract sealed
{
private:
static SizeCache()
{
Size = Marshal::SizeOf(T::typeid);
}
public:
static int Size;
};
Everything seems to compile fine, however, when I access it via;
int size = SizeCache<T>::Size;
I get compiler errors.
error C2039: 'Size' : is not a member of '`global namespace''
error C2065: 'Size' : undeclared identifier
Unfortunately, I can't see what I'm doing wrong in this case.
The reason for the class in the first place, is to avoid some issues with
the Marshaler (specifically when dealing with generic structure types),
and avoid the performance hit incurred by constantly calling SizeOf on the
same basic types.
What am I doing wrong here?
ASP physical and virtual path
ASP physical and virtual path
This is the first time I make an asp site. This line of code is working
fine on my pc but obviously to make it working on the production server I
need to change the reference.
DirectoryInfo dir = new DirectoryInfo(@"C:\Users\Pink\Documents\Visual
Studio
2012\Projects\ManagDoc_Framework\Test1_managDoc\Test1_managDoc\Allegati\"
+ recordIDcreateDir);
I have tried many sort of path combination but I am not getting it right.
I would like to find a solution that makes the code working on both pc,
during development, and hosting server without having to change the code.
How should i write the path? Some help will be appreciated.
This is the first time I make an asp site. This line of code is working
fine on my pc but obviously to make it working on the production server I
need to change the reference.
DirectoryInfo dir = new DirectoryInfo(@"C:\Users\Pink\Documents\Visual
Studio
2012\Projects\ManagDoc_Framework\Test1_managDoc\Test1_managDoc\Allegati\"
+ recordIDcreateDir);
I have tried many sort of path combination but I am not getting it right.
I would like to find a solution that makes the code working on both pc,
during development, and hosting server without having to change the code.
How should i write the path? Some help will be appreciated.
Saturday, 14 September 2013
Use instance of one class in another class method
Use instance of one class in another class method
I defined two classes class A and class B. They are completely
independent. Now I create c as instance of class B and d as instance of
class A. This c is called in method of A. I want to perform operations on
c using methods in B.
Sample code:
class A
{public:
functionOfA();
.....;
}
class B
{public:
functionOfB();
}
A::functionOFA()
{
c.functionOfB();
}
B::functionOfB()
{
.....
}
main()
{
A d;
B c;
d.functionOfA();
}
Compiler error: c is not declared in this scope. I tried to make it
general and short.( My original code is ~100 lines.)
I defined two classes class A and class B. They are completely
independent. Now I create c as instance of class B and d as instance of
class A. This c is called in method of A. I want to perform operations on
c using methods in B.
Sample code:
class A
{public:
functionOfA();
.....;
}
class B
{public:
functionOfB();
}
A::functionOFA()
{
c.functionOfB();
}
B::functionOfB()
{
.....
}
main()
{
A d;
B c;
d.functionOfA();
}
Compiler error: c is not declared in this scope. I tried to make it
general and short.( My original code is ~100 lines.)
Why would I use a # in my links? SEO with AJAX
Why would I use a # in my links? SEO with AJAX
I have a full ajax website and in order to have a good ranking on google
and make some SEO, I went on this page:
https://developers.google.com/webmasters/ajax-crawling/docs/getting-started.
Now this made me realise I should maybe start using links for my ajax
request, but first I want to know why? Beside being better for the SEO,
what is the # for in links? Is it used to pass some informations? Does it
replace a query string? I don't really get it.
Normally, I just use buttons and assign a click event on them, but I think
this is not going to work for SEO. Can you explain why?
I have a full ajax website and in order to have a good ranking on google
and make some SEO, I went on this page:
https://developers.google.com/webmasters/ajax-crawling/docs/getting-started.
Now this made me realise I should maybe start using links for my ajax
request, but first I want to know why? Beside being better for the SEO,
what is the # for in links? Is it used to pass some informations? Does it
replace a query string? I don't really get it.
Normally, I just use buttons and assign a click event on them, but I think
this is not going to work for SEO. Can you explain why?
Idiomatic usage of EitherT and errors
Idiomatic usage of EitherT and errors
I have written the following code to replace the error message I get from
readFile:
module Main where
import Control.Error
import qualified Data.ByteString.Lazy as BSL
replaceLeftT :: Monad m => String -> EitherT String m a -> EitherT String m a
replaceLeftT message e = EitherT $ do
unwrapped <- runEitherT e
let x = case unwrapped of
Left _ -> Left message
y -> y
return x
main :: IO ()
main = runScript $ do
contents <- replaceLeftT "Could not read file" $
scriptIO $ BSL.readFile "somefile"
scriptIO $ putStrLn "Won't get here"
It feels clunky to me, like I'm missing a fundamental concept. Probably
because I derived this function mostly by trial and error...
Any suggestions for a way to do this using existing Control.Error
primitives, or monad primitives in general?
I have written the following code to replace the error message I get from
readFile:
module Main where
import Control.Error
import qualified Data.ByteString.Lazy as BSL
replaceLeftT :: Monad m => String -> EitherT String m a -> EitherT String m a
replaceLeftT message e = EitherT $ do
unwrapped <- runEitherT e
let x = case unwrapped of
Left _ -> Left message
y -> y
return x
main :: IO ()
main = runScript $ do
contents <- replaceLeftT "Could not read file" $
scriptIO $ BSL.readFile "somefile"
scriptIO $ putStrLn "Won't get here"
It feels clunky to me, like I'm missing a fundamental concept. Probably
because I derived this function mostly by trial and error...
Any suggestions for a way to do this using existing Control.Error
primitives, or monad primitives in general?
Python script using regex (re) to remove extra newlines
Python script using regex (re) to remove extra newlines
guys!
I have a tab-delimited text file that may have some values containing
newlines, like this:
col1 col2 col3
row1 val1 "Some text
containing newlines. Yup, possibly
more than one... val3
row2 val4 val5 val6
Note:
Number of rows or columns may be different.
Any value may be text or may be a number, may contain newlines and may not
I am trying to write a small Python script using re in order to:
get rid of extra newlines (but preserve the original ones, i.e. at the end
of each row)
enclose every single value in double quotes
It would be great to have in a form like that:
def normalize_format(data, delimiter = '\t'):
data = re.sub(_DESIRED_REGEX_, r'"\1"', data)
return data
where data is the whole file contents as a single string and
_DESIRED_REGEX_ is the one I would like to have figured out
Usage of re is not mandatory, but short and elegant solution is
appreciated :)
guys!
I have a tab-delimited text file that may have some values containing
newlines, like this:
col1 col2 col3
row1 val1 "Some text
containing newlines. Yup, possibly
more than one... val3
row2 val4 val5 val6
Note:
Number of rows or columns may be different.
Any value may be text or may be a number, may contain newlines and may not
I am trying to write a small Python script using re in order to:
get rid of extra newlines (but preserve the original ones, i.e. at the end
of each row)
enclose every single value in double quotes
It would be great to have in a form like that:
def normalize_format(data, delimiter = '\t'):
data = re.sub(_DESIRED_REGEX_, r'"\1"', data)
return data
where data is the whole file contents as a single string and
_DESIRED_REGEX_ is the one I would like to have figured out
Usage of re is not mandatory, but short and elegant solution is
appreciated :)
Find all intervals [s,e] where s,e in N_0 and s < e that overlap with another given interval
Find all intervals [s,e] where s,e in N_0 and s < e that overlap with
another given interval
I have an algorithmic problem where I would like to see if it can be
solved in better than O(n):
I have given a table T of n elements where each element is a tuple (s_i,
e_i) with s_i, e_i in N and s_i < e_i, i.e. each tuple is some kind of an
interval. I have to find all intervals that overlap with a given interval
[t0, t1] with t0, t1 in N and t0 < t1. Further, I have available two
sorted lists S and E, containing the s values, or e values respectively,
together with the index i pointing to the respective entry in T. The lists
are sorted by s values, or e values respectively. (Let's assume both, s
and e values, are unique.)
Problem:
We have to find each interval/tuple (s_i, e_i) in T where s_i <= t1 and
e_i >= t0.
My thoughts so far:
We can exclude some elements by either applying one of the interval
boundaries, i.e. searching t1 in S or t0 in E. This gives us a list L of
remaining elements:
L <- {e in E | e >= t0} or L <- {s in S | s <= t1}
However, there is no guarantee on the number of elements in L, no matter
which search we perform. Further, we have to check every element in L if s
<= t1, or e >= t0 respectively depending on which search we performed
before.
The complexity for this solution is O(n).
However, let's say that k is the maximum number of elements overlapping
with interval [t0, t1]. If we assume k << n, then the complexity is O(n/2)
since we can exclude at least n/2 elements by choosing the appropriate
search for L. Still O(n/2) is in O(n).
Can you think of a better approach to solve this problem?
(Please feel free to improve this question. Maybe it's not very clear.
Thanks)
another given interval
I have an algorithmic problem where I would like to see if it can be
solved in better than O(n):
I have given a table T of n elements where each element is a tuple (s_i,
e_i) with s_i, e_i in N and s_i < e_i, i.e. each tuple is some kind of an
interval. I have to find all intervals that overlap with a given interval
[t0, t1] with t0, t1 in N and t0 < t1. Further, I have available two
sorted lists S and E, containing the s values, or e values respectively,
together with the index i pointing to the respective entry in T. The lists
are sorted by s values, or e values respectively. (Let's assume both, s
and e values, are unique.)
Problem:
We have to find each interval/tuple (s_i, e_i) in T where s_i <= t1 and
e_i >= t0.
My thoughts so far:
We can exclude some elements by either applying one of the interval
boundaries, i.e. searching t1 in S or t0 in E. This gives us a list L of
remaining elements:
L <- {e in E | e >= t0} or L <- {s in S | s <= t1}
However, there is no guarantee on the number of elements in L, no matter
which search we perform. Further, we have to check every element in L if s
<= t1, or e >= t0 respectively depending on which search we performed
before.
The complexity for this solution is O(n).
However, let's say that k is the maximum number of elements overlapping
with interval [t0, t1]. If we assume k << n, then the complexity is O(n/2)
since we can exclude at least n/2 elements by choosing the appropriate
search for L. Still O(n/2) is in O(n).
Can you think of a better approach to solve this problem?
(Please feel free to improve this question. Maybe it's not very clear.
Thanks)
How to maintain session in android using an HttpClient
This summary is not available. Please
click here to view the post.
chorme extension context menu, not working
chorme extension context menu, not working
so i'm trying to build a simple extension that adds an option to the menu
when you right click a link, i wrote the "code" that reEdit the link but
for some reason i dont even see the option when i right click a link. i
have tried everything(i have to admit i dont have a any experience with
javaScript or chrome extensions)
here is my manifest code:
{
"name": "EditURL",
"description": "editing URL in SERET website",
"version": "0.7",
"permissions": ["contextMenus"],
"background": {
"persistent": true,
"scripts": ["sample.js"]
},
"manifest_version": 2
}
and js code:
function killAdd(info)
{
var domain = info.selectionText;
var index = domain.lastIndexOf(":");
domain = domain.substring(index - 4);
chrome.tabs.create({url: domain})
}
chrome.contextMenus.create({title: "Addkill", contexts: ["link"], onclick:
function KillAdd(onClickData)});
any ideas???
so i'm trying to build a simple extension that adds an option to the menu
when you right click a link, i wrote the "code" that reEdit the link but
for some reason i dont even see the option when i right click a link. i
have tried everything(i have to admit i dont have a any experience with
javaScript or chrome extensions)
here is my manifest code:
{
"name": "EditURL",
"description": "editing URL in SERET website",
"version": "0.7",
"permissions": ["contextMenus"],
"background": {
"persistent": true,
"scripts": ["sample.js"]
},
"manifest_version": 2
}
and js code:
function killAdd(info)
{
var domain = info.selectionText;
var index = domain.lastIndexOf(":");
domain = domain.substring(index - 4);
chrome.tabs.create({url: domain})
}
chrome.contextMenus.create({title: "Addkill", contexts: ["link"], onclick:
function KillAdd(onClickData)});
any ideas???
Friday, 13 September 2013
Restore failed for server (Microsoft.SqlServer.SmoExtended)
Restore failed for server (Microsoft.SqlServer.SmoExtended)
Hi I am using SQLServer2008. While i am restoring database from backup
file i got the error.
Restore failed for Server 'WIN-TUT3YRM1MMN\SQLEXPRESS'.
(Microsoft.SqlServer.SmoExtended)
System.Data.SqlClient.SqlError: RESTORE detected an error on page
(44262:41495) in database "KBCLDBNEW" as read from the backup set.
(Microsoft.SqlServer.Smo)
I have tried restoring in new database but still gives the error. I am
cannot find the what is the problem. Thanks for helping me.
Hi I am using SQLServer2008. While i am restoring database from backup
file i got the error.
Restore failed for Server 'WIN-TUT3YRM1MMN\SQLEXPRESS'.
(Microsoft.SqlServer.SmoExtended)
System.Data.SqlClient.SqlError: RESTORE detected an error on page
(44262:41495) in database "KBCLDBNEW" as read from the backup set.
(Microsoft.SqlServer.Smo)
I have tried restoring in new database but still gives the error. I am
cannot find the what is the problem. Thanks for helping me.
Python 'text analyzer'
Python 'text analyzer'
I'm just getting into Python and I'm building a program that analyzes a
group of words and returns how many times each letter appears in the text.
i.e 'A:10, B:3, C:5...etc'. So far it's working perfectly except that i am
looking for a way to condense the code so i'm not writing out each part of
the program 26 times. Here's what I mean..
print("Enter text to be analyzed: ")
message = input()
A = 0
b = 0
c = 0
...etc
for letter in message:
if letter == "a":
a += 1
if letter == "b":
b += 1
if letter == "c":
c += 1
...etc
print("A:", a, "B:", b, "C:", c...etc)
I'm just getting into Python and I'm building a program that analyzes a
group of words and returns how many times each letter appears in the text.
i.e 'A:10, B:3, C:5...etc'. So far it's working perfectly except that i am
looking for a way to condense the code so i'm not writing out each part of
the program 26 times. Here's what I mean..
print("Enter text to be analyzed: ")
message = input()
A = 0
b = 0
c = 0
...etc
for letter in message:
if letter == "a":
a += 1
if letter == "b":
b += 1
if letter == "c":
c += 1
...etc
print("A:", a, "B:", b, "C:", c...etc)
broken pipe while using SCP command
broken pipe while using SCP command
I have 2 machines, I work on a mac and I wish to transfer a file to my
linux machine.
When I tried to transfer a file from my mac to linux the following appeared
Write failed: Broken pipe lost connection
However I can transfer files from my linux to my mac (opposite direction)
It seems its something to do with how long the connection is open but if
one direction works, shouldn't the other direction too?
Thank you
I have 2 machines, I work on a mac and I wish to transfer a file to my
linux machine.
When I tried to transfer a file from my mac to linux the following appeared
Write failed: Broken pipe lost connection
However I can transfer files from my linux to my mac (opposite direction)
It seems its something to do with how long the connection is open but if
one direction works, shouldn't the other direction too?
Thank you
Getting date and time from mysql to output into html table
Getting date and time from mysql to output into html table
I have been working on this thing for awhile now and cannot figure it out.
What I'm wanting to do is run a function that will call all my records for
a specific date and output them in an html table. I can do it by running
the query inside the loop but I'm wanting to learn how to use arrays to
accomplish this.
function getAll(){
include('inc/connect.php');
$a = $data->query("SELECT * FROM bookings WHERE active = 'true'");
$args = array();
while($b = $a->fetch_array()){
$t1 = strtotime($b["endtime"]);
$t2 = strtotime($b["starttime"]);
$diff = $t1 - $t2;
$hours = $diff / ( 60 * 60 );
$args[] = array(
'start' => $b["starttime"],
'end' => $b["endtime"],
'span' => $hours
);
}
return $args;
}
Above is the function that I run to get all and return the arrays but I'm
very new to arrays and have no idea how to run them against the below.
$interval = 1800; // Interval in seconds
$date_first = "02-09-2013 00:00:00";
$date_second = "03-09-2013 00:00:00";
$time_first = strtotime($date_first);
$time_second = strtotime($date_second);
$go = getAll();
for ($i = $time_first; $i <= $time_second; $i += $interval){
$timeOut = date('d-m-Y H:i', strtotime("+30 minutes", $i));
//////I WOULD LIKE TO RUN THE ARRAY CALLED BY $go HERE TO SEE IF start ==
$timeOut/////
}
I'm try to get the following results onto the html table. Thanks in
advance for the help.
http://i.stack.imgur.com/vMFH7.jpg
I have been working on this thing for awhile now and cannot figure it out.
What I'm wanting to do is run a function that will call all my records for
a specific date and output them in an html table. I can do it by running
the query inside the loop but I'm wanting to learn how to use arrays to
accomplish this.
function getAll(){
include('inc/connect.php');
$a = $data->query("SELECT * FROM bookings WHERE active = 'true'");
$args = array();
while($b = $a->fetch_array()){
$t1 = strtotime($b["endtime"]);
$t2 = strtotime($b["starttime"]);
$diff = $t1 - $t2;
$hours = $diff / ( 60 * 60 );
$args[] = array(
'start' => $b["starttime"],
'end' => $b["endtime"],
'span' => $hours
);
}
return $args;
}
Above is the function that I run to get all and return the arrays but I'm
very new to arrays and have no idea how to run them against the below.
$interval = 1800; // Interval in seconds
$date_first = "02-09-2013 00:00:00";
$date_second = "03-09-2013 00:00:00";
$time_first = strtotime($date_first);
$time_second = strtotime($date_second);
$go = getAll();
for ($i = $time_first; $i <= $time_second; $i += $interval){
$timeOut = date('d-m-Y H:i', strtotime("+30 minutes", $i));
//////I WOULD LIKE TO RUN THE ARRAY CALLED BY $go HERE TO SEE IF start ==
$timeOut/////
}
I'm try to get the following results onto the html table. Thanks in
advance for the help.
http://i.stack.imgur.com/vMFH7.jpg
a ClassNotFoundException error when trying to excute a Cordova push notification plugin
a ClassNotFoundException error when trying to excute a Cordova push
notification plugin
i get a ClassNotFoundException error when i was trying to execute this
example of a push notification plugin:
java.lang.RuntimeException: Unable to instantiate activity
ComponentInfo{com.cordova2.gcm/com.cordova2.gcm.MainActivity}:
java.lang.ClassNotFoundException: Didn't find class
"com.cordova2.gcm.MainActivity" on path: /data/app/com.cordova2.gcm-1.apk
this is my AndroidManifest.xml :
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.cordova2.gcm"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="15" />
<supports-screens
android:largeScreens="true"
android:normalScreens="true"
android:smallScreens="true"
android:resizeable="true"
android:anyDensity="true" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission
android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission
android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission
android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.RECEIVE_SMS" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission
android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.WRITE_CONTACTS" />
<uses-permission
android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission
android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.BROADCAST_STICKY" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission
android:name="com.google.android.c2dm.permission.RECEIVE" />
<permission android:name="com.cordova2.gcm.permission.C2D_MESSAGE"
android:protectionLevel="signature" />
<uses-permission
android:name="com.cordova2.gcm.permission.C2D_MESSAGE" />
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.cordova2.gcm.MainActivity"
android:label="@string/title_activity_main"
android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale"
>
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver
android:name="com.google.android.gcm.GCMBroadcastReceiver"
android:permission="com.google.android.c2dm.permission.SEND" >
<intent-filter>
<action
android:name="com.google.android.c2dm.intent.RECEIVE" />
<action
android:name="com.google.android.c2dm.intent.REGISTRATION"
/>
<category android:name="com.cordova2.gcm" />
</intent-filter>
</receiver>
<service android:name=".GCMIntentService" />
</application>
</manifest>
notification plugin
i get a ClassNotFoundException error when i was trying to execute this
example of a push notification plugin:
java.lang.RuntimeException: Unable to instantiate activity
ComponentInfo{com.cordova2.gcm/com.cordova2.gcm.MainActivity}:
java.lang.ClassNotFoundException: Didn't find class
"com.cordova2.gcm.MainActivity" on path: /data/app/com.cordova2.gcm-1.apk
this is my AndroidManifest.xml :
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.cordova2.gcm"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="15" />
<supports-screens
android:largeScreens="true"
android:normalScreens="true"
android:smallScreens="true"
android:resizeable="true"
android:anyDensity="true" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission
android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission
android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission
android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.RECEIVE_SMS" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission
android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.WRITE_CONTACTS" />
<uses-permission
android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission
android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.BROADCAST_STICKY" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission
android:name="com.google.android.c2dm.permission.RECEIVE" />
<permission android:name="com.cordova2.gcm.permission.C2D_MESSAGE"
android:protectionLevel="signature" />
<uses-permission
android:name="com.cordova2.gcm.permission.C2D_MESSAGE" />
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.cordova2.gcm.MainActivity"
android:label="@string/title_activity_main"
android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale"
>
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver
android:name="com.google.android.gcm.GCMBroadcastReceiver"
android:permission="com.google.android.c2dm.permission.SEND" >
<intent-filter>
<action
android:name="com.google.android.c2dm.intent.RECEIVE" />
<action
android:name="com.google.android.c2dm.intent.REGISTRATION"
/>
<category android:name="com.cordova2.gcm" />
</intent-filter>
</receiver>
<service android:name=".GCMIntentService" />
</application>
</manifest>
I need to get Facebook photo stream into my application using their Facebook id javascript
I need to get Facebook photo stream into my application using their
Facebook id javascript
I am developing a web page default in an mvc application .I need to get
Facebook photo stream into my application using their Facebook id. I am
unable to get suitable solution.Please help me the complete solution for
the same .i am using c#
Facebook id javascript
I am developing a web page default in an mvc application .I need to get
Facebook photo stream into my application using their Facebook id. I am
unable to get suitable solution.Please help me the complete solution for
the same .i am using c#
Thursday, 12 September 2013
MySQL - Returning X number of each GROUP BY
MySQL - Returning X number of each GROUP BY
In this query I specify which models of cars I want to return
(hard-coded). So the SQL below returns one record for each model:
SELECT
*
FROM
main
WHERE
(
(marka_name = 'SUBARU' AND model_name = 'IMPREZA' AND (kuzov =
'GC8' OR kuzov = 'GF8')) OR
(marka_name = 'MAZDA' AND model_name = 'RX-7' AND kuzov =
'FD3S') OR
(marka_name = 'MITSUBISHI' AND model_name = 'LANCER' AND
(kuzov = 'CN9A' OR kuzov = 'CP9A')) OR
(marka_name = 'NISSAN' AND model_name = 'SKYLINE' AND (kuzov =
'ER34' OR kuzov = 'BCNR33')) OR
(marka_name = 'NISSAN' AND model_name = 'SILVIA' AND kuzov =
'S14') OR
(marka_name = 'TOYOTA' AND model_name = 'CELICA' AND kuzov =
'ST205') OR
(marka_name = 'TOYOTA' AND model_name = 'ARISTO' AND kuzov =
'JZS161') OR
(marka_name = 'MITSUBISHI' AND model_name = 'DELICA' AND
(kuzov = 'PE8W' OR kuzov = 'PD8W' OR kuzov = 'PF8W'))
)
AND
(rate != 'RA' AND rate != 'RR' AND rate != 'A1' AND rate != 'A'
AND rate != 'R' AND rate >= '3')
AND
(mileage >= 0 AND mileage <= 150000)
AND
(year >= 1990 AND year <= 1998)
GROUP BY
model_name
ORDER BY
mileage ASC,
rate DESC
Now is it possible, without unions, to have this SQL return more than one
model specified by some field. Example:
GROUP BY
model_name
HAVING COUNT(model_name) = 2
ORDER BY
mileage ASC,
rate DESC
I know that HAVING COUNT doesn't make sense, but I need a way to specify
how many cars per model to return.
http://sqlfiddle.com/#!2/421e4/1/0
In this query I specify which models of cars I want to return
(hard-coded). So the SQL below returns one record for each model:
SELECT
*
FROM
main
WHERE
(
(marka_name = 'SUBARU' AND model_name = 'IMPREZA' AND (kuzov =
'GC8' OR kuzov = 'GF8')) OR
(marka_name = 'MAZDA' AND model_name = 'RX-7' AND kuzov =
'FD3S') OR
(marka_name = 'MITSUBISHI' AND model_name = 'LANCER' AND
(kuzov = 'CN9A' OR kuzov = 'CP9A')) OR
(marka_name = 'NISSAN' AND model_name = 'SKYLINE' AND (kuzov =
'ER34' OR kuzov = 'BCNR33')) OR
(marka_name = 'NISSAN' AND model_name = 'SILVIA' AND kuzov =
'S14') OR
(marka_name = 'TOYOTA' AND model_name = 'CELICA' AND kuzov =
'ST205') OR
(marka_name = 'TOYOTA' AND model_name = 'ARISTO' AND kuzov =
'JZS161') OR
(marka_name = 'MITSUBISHI' AND model_name = 'DELICA' AND
(kuzov = 'PE8W' OR kuzov = 'PD8W' OR kuzov = 'PF8W'))
)
AND
(rate != 'RA' AND rate != 'RR' AND rate != 'A1' AND rate != 'A'
AND rate != 'R' AND rate >= '3')
AND
(mileage >= 0 AND mileage <= 150000)
AND
(year >= 1990 AND year <= 1998)
GROUP BY
model_name
ORDER BY
mileage ASC,
rate DESC
Now is it possible, without unions, to have this SQL return more than one
model specified by some field. Example:
GROUP BY
model_name
HAVING COUNT(model_name) = 2
ORDER BY
mileage ASC,
rate DESC
I know that HAVING COUNT doesn't make sense, but I need a way to specify
how many cars per model to return.
http://sqlfiddle.com/#!2/421e4/1/0
fortran assigns a NaN (sometimes)
fortran assigns a NaN (sometimes)
I have this piece of super old fortran code:
do 1823 i=1,n
g(i) = 0d0
1823 continue
The code works most of the time, but sometimes when n = 2, I get g(2)=-NaN
(0xfffffffffffff). n is an integer, i is an integer, g is allocatable
real(dp) with dimension of 2, in this case.
I have this piece of super old fortran code:
do 1823 i=1,n
g(i) = 0d0
1823 continue
The code works most of the time, but sometimes when n = 2, I get g(2)=-NaN
(0xfffffffffffff). n is an integer, i is an integer, g is allocatable
real(dp) with dimension of 2, in this case.
Another string to datevalue conversion for Excel
Another string to datevalue conversion for Excel
This is another question on date string to datevalue conversion. Input
format is "March 17, 2013 7:04:28 PM GMT-07:00". (Output of SAP tool)
=DATEVALUE(B26) fails.
Any chances?
Thanks, Gert
This is another question on date string to datevalue conversion. Input
format is "March 17, 2013 7:04:28 PM GMT-07:00". (Output of SAP tool)
=DATEVALUE(B26) fails.
Any chances?
Thanks, Gert
Differences in using array in main program or in functions sub-routines
Differences in using array in main program or in functions sub-routines
I'v got some question about using array pointers in program. When I use
some array name (which is a const pointer to first array element)
char charTab[] = "ABCDEFGHIJKLMNOPRSTUWXYZ"; /* Basic data buffer */
char *charPtr = charTab; /* Assign */
charPtr += 3; /* It's ok, now we point
4th element */
charTab += 3; /* No, the lvalue required
for '+' operand */
But when I create let's say the following function:
void CharTabMove(char *tabToMove, int noToMove);
With definition
void CharTabMove(char *tabToMove, int noToMove)
{
printf("-------IN FUNCTION---------\n");
printf("It's pointing to %c\n", *tabToMove);
tabToMove += noToMove;
printf("Now it's pointing to %c\n", *tabToMove);
printf("-------LEAVING FUNCTION---------\n");
fflush(stdout);
}
The function is allow to move this pointer along the array with no
problem. Sure, after leaving the function the pointer will be still
pointing to first element of charTab, but why the function is allowed to
move the constant pointer? Thanks in advice for response, I'm trying to
explain that to my 11 yo nephew :)
I'v got some question about using array pointers in program. When I use
some array name (which is a const pointer to first array element)
char charTab[] = "ABCDEFGHIJKLMNOPRSTUWXYZ"; /* Basic data buffer */
char *charPtr = charTab; /* Assign */
charPtr += 3; /* It's ok, now we point
4th element */
charTab += 3; /* No, the lvalue required
for '+' operand */
But when I create let's say the following function:
void CharTabMove(char *tabToMove, int noToMove);
With definition
void CharTabMove(char *tabToMove, int noToMove)
{
printf("-------IN FUNCTION---------\n");
printf("It's pointing to %c\n", *tabToMove);
tabToMove += noToMove;
printf("Now it's pointing to %c\n", *tabToMove);
printf("-------LEAVING FUNCTION---------\n");
fflush(stdout);
}
The function is allow to move this pointer along the array with no
problem. Sure, after leaving the function the pointer will be still
pointing to first element of charTab, but why the function is allowed to
move the constant pointer? Thanks in advice for response, I'm trying to
explain that to my 11 yo nephew :)
Sending email alerts to multiple to addresses
Sending email alerts to multiple to addresses
While sending email alerts i have multiple email groups
email group for english speaking users, email group for spanish speaking
users, email group for portuguese speaking users
A template (using velocity templates) is defined to each mail user group.
Now email alerts have to be sent to all 3 user groups with different
contents defined in the template. How do i set up the outbound email
endpoint and send emails.
While sending email alerts i have multiple email groups
email group for english speaking users, email group for spanish speaking
users, email group for portuguese speaking users
A template (using velocity templates) is defined to each mail user group.
Now email alerts have to be sent to all 3 user groups with different
contents defined in the template. How do i set up the outbound email
endpoint and send emails.
Query section symbol (§) i SQL Server 2012 full text index
Query section symbol (§) i SQL Server 2012 full text index
We are using the SQL Server 2012 for doing full text indexing of
legislative documents. However, it appears that in 2012 it is not possible
to create queries containing characters like the section symbol (§).
I can't seem to find the documentation on MSDN that states which
characters are "un-queryable". In our use case, it seems rather annoying
that section symbols (§) are filtered out from the query (as confirmed
when parsing query using sys.dm_fts_parser).
Would this be possible to do using SQL server 2012 and full text search,
by implementing some configuration or workaround?
We are using the SQL Server 2012 for doing full text indexing of
legislative documents. However, it appears that in 2012 it is not possible
to create queries containing characters like the section symbol (§).
I can't seem to find the documentation on MSDN that states which
characters are "un-queryable". In our use case, it seems rather annoying
that section symbols (§) are filtered out from the query (as confirmed
when parsing query using sys.dm_fts_parser).
Would this be possible to do using SQL server 2012 and full text search,
by implementing some configuration or workaround?
How to make a bash script to read from stdin
How to make a bash script to read from stdin
I have some scripts that work with parameters, they work just fine but i
would like them to be able to read from stdin, from a pipe for example, an
example, suppose this is called read:
#!/bin/bash
function read()
{
echo $*
}
read $*
Now this works with read "foo" "bar" I would like to use it as:
echo "foo" | read
How do i accomplish this?
I have some scripts that work with parameters, they work just fine but i
would like them to be able to read from stdin, from a pipe for example, an
example, suppose this is called read:
#!/bin/bash
function read()
{
echo $*
}
read $*
Now this works with read "foo" "bar" I would like to use it as:
echo "foo" | read
How do i accomplish this?
Strange behaviour with C# SQL
Strange behaviour with C# SQL
string sql = "SELECT column1 FROM table1 INNER JOIN table2 ON
table1.table2ID = table2.table2ID where column1 = \"testData\"";
using (var command = new SqlCommand(sql, connection))
{
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
Console.WriteLine(reader["column1"].ToString());
}
Console.ReadLine();
}
}
The above SQL query works fine when there is without the where clause and
I able to writeline "testData". But when I restrict the condition, then
its giving me sqlException saying that "testData" is an invalid column?
string sql = "SELECT column1 FROM table1 INNER JOIN table2 ON
table1.table2ID = table2.table2ID where column1 = \"testData\"";
using (var command = new SqlCommand(sql, connection))
{
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
Console.WriteLine(reader["column1"].ToString());
}
Console.ReadLine();
}
}
The above SQL query works fine when there is without the where clause and
I able to writeline "testData". But when I restrict the condition, then
its giving me sqlException saying that "testData" is an invalid column?
Wednesday, 11 September 2013
Passing custom values to a karma plugin
Passing custom values to a karma plugin
I'm developing a karma reporter plugin and i'm attempting to pass a value
from a custom matcher and/or dsl to the specComplete function. There is no
immediately obvious way to accomplish this. any ideas?
I'm developing a karma reporter plugin and i'm attempting to pass a value
from a custom matcher and/or dsl to the specComplete function. There is no
immediately obvious way to accomplish this. any ideas?
Android build environment
Android build environment
I have been working with standard android for some time. Recently I have
been building android sdk for windows and find some interesting things in
Android build env. There is a command called lunch which can be used to
list all available targets to build. However, it does not list sdk and its
variants,even though they are valid options. Does anyone know why is that
the case?
Also can I build any specific module in Android sdk without building the
whole sdk. (It could be a great help as I dont wanna build the whole sdk,
if I gonna do a small change in one component.)
Thanks
I have been working with standard android for some time. Recently I have
been building android sdk for windows and find some interesting things in
Android build env. There is a command called lunch which can be used to
list all available targets to build. However, it does not list sdk and its
variants,even though they are valid options. Does anyone know why is that
the case?
Also can I build any specific module in Android sdk without building the
whole sdk. (It could be a great help as I dont wanna build the whole sdk,
if I gonna do a small change in one component.)
Thanks
Making HTML onClick events conditional
Making HTML onClick events conditional
I've asked this question before, and got it to be functional in ie7. Since
then, we upgraded to IE 8 and I can not find a way to make it work. I have
a form that is manually filled out by the user, and when they click copy,
the form is concatenated into a single text box with formatting applied. I
need the formatting to be conditional, so if certain parts of the form are
not entered or left blank, they do not leave an empty line break in the
formatting. Example Form:
<body>
<form name="data_entry" id="frm1"
<tr>
<td>Name of Person:</td>
<td><textarea name="name" rows="2" cols="30" id="name"></textarea></td>
</tr><br>
<tr>
<td>Type of Service:</td>
<td><select name="drop1" id="txt_drop1">
<option value="">None</option>
<option value="Type of Service: Minimal">Minimal</option>
<option value="Type of Service: Normal">Normal</option>
<option value="Type of Service: Full">Full</option>
<option value="Type of Service: Premium">Premium</option>
</select></td>
</tr><br>
<tr>
<td>Dollar Amount:</td>
<td><textarea name="amount" rows="1" cols="30"
id="txt_info2"></textarea></td>
</tr><br>
<tr>
<td><textarea name="bigtextbox" rows="5" cols="30"
id="txt_info2"></textarea></td>
</tr>
</form>
</body>
<input type="button" style="font-weight:bold;" name="clipboard_copy"
value="Copy" onClick="document.data_entry.bigtextbox.value = 'Name: '
+ document.data_entry.name.value + '\n' + document.data_entry.drop1.value
+ '\n' + 'Amount: $' + document.data_entry.amount.value">
</body>
The result Im looking to acheive is to have it look like so if the "type
of service" value is empty:
Name: John Smith
Amount:$123
Rather than:
Name: John Smith
Amount:$123
It would also need to work for cases where they leave any other field blank.
Thanks in advance, and sorry for the repeat question!
I've asked this question before, and got it to be functional in ie7. Since
then, we upgraded to IE 8 and I can not find a way to make it work. I have
a form that is manually filled out by the user, and when they click copy,
the form is concatenated into a single text box with formatting applied. I
need the formatting to be conditional, so if certain parts of the form are
not entered or left blank, they do not leave an empty line break in the
formatting. Example Form:
<body>
<form name="data_entry" id="frm1"
<tr>
<td>Name of Person:</td>
<td><textarea name="name" rows="2" cols="30" id="name"></textarea></td>
</tr><br>
<tr>
<td>Type of Service:</td>
<td><select name="drop1" id="txt_drop1">
<option value="">None</option>
<option value="Type of Service: Minimal">Minimal</option>
<option value="Type of Service: Normal">Normal</option>
<option value="Type of Service: Full">Full</option>
<option value="Type of Service: Premium">Premium</option>
</select></td>
</tr><br>
<tr>
<td>Dollar Amount:</td>
<td><textarea name="amount" rows="1" cols="30"
id="txt_info2"></textarea></td>
</tr><br>
<tr>
<td><textarea name="bigtextbox" rows="5" cols="30"
id="txt_info2"></textarea></td>
</tr>
</form>
</body>
<input type="button" style="font-weight:bold;" name="clipboard_copy"
value="Copy" onClick="document.data_entry.bigtextbox.value = 'Name: '
+ document.data_entry.name.value + '\n' + document.data_entry.drop1.value
+ '\n' + 'Amount: $' + document.data_entry.amount.value">
</body>
The result Im looking to acheive is to have it look like so if the "type
of service" value is empty:
Name: John Smith
Amount:$123
Rather than:
Name: John Smith
Amount:$123
It would also need to work for cases where they leave any other field blank.
Thanks in advance, and sorry for the repeat question!
Accented characters using JavaFX on Linux
Accented characters using JavaFX on Linux
I'm developing an application and just noticed that not a single accented
character, for example, the Brazilian Portuguese "é", neither "ã" are
displayed when I'm running the JavaFX application on Linux.
BUT, if I copy/paste those characters they appear normally, so I don't
think it's an encoding problem.
On the other hand, the exactly same code works on Windows and those
characters are displayed normally.
Is this a known bug?
Thanks in advance.
I'm developing an application and just noticed that not a single accented
character, for example, the Brazilian Portuguese "é", neither "ã" are
displayed when I'm running the JavaFX application on Linux.
BUT, if I copy/paste those characters they appear normally, so I don't
think it's an encoding problem.
On the other hand, the exactly same code works on Windows and those
characters are displayed normally.
Is this a known bug?
Thanks in advance.
Alert user before session expires
Alert user before session expires
In my application session expire time is set as 30 mins. Application will
alert user "your session is about to expire" if the user is inactive for
some times.
I have modified the code to display the alert "your session is about to
expire" at 25th min. Alert will have two buttons "Ok" to continue wit the
session and "Cancel" to logout. If suppose the user noticed the alert
after 30 mins, even if they click on "Ok" it should not allow them. It
should display "your session expired" alert. How to handle this? Also If
the user noticed the alert before session expires(before 30 mins), need
the user to continue wit same session. How to do?
Thanks
In my application session expire time is set as 30 mins. Application will
alert user "your session is about to expire" if the user is inactive for
some times.
I have modified the code to display the alert "your session is about to
expire" at 25th min. Alert will have two buttons "Ok" to continue wit the
session and "Cancel" to logout. If suppose the user noticed the alert
after 30 mins, even if they click on "Ok" it should not allow them. It
should display "your session expired" alert. How to handle this? Also If
the user noticed the alert before session expires(before 30 mins), need
the user to continue wit same session. How to do?
Thanks
Re: How can I safeguard my Php Form?
Re: How can I safeguard my Php Form?
Below I have a Php Registration form that is working well, but am a bit
concerned as the form is wide open for an Sql injection attack, I am aware
about it but have very limited coding knowledge to prevent it, but still
learning.
Have managed to add a Captcha to prevent bots from auto-filling the form
and submitting, but unfortunately the same can't be said of being able to
validate the First name and Last name,am just wondering how can I
safeguard myself against such an attack.
The Relevant code is shown below, Thank You!
Check.php
$FirstName = strip_tags($_POST['FirstName']); $LastName =
strip_tags($_POST['LastName']); $Msisdn = $_POST['Msisdn']; $month =
$_POST['month']; $day = $_POST['day']; $year = $_POST['year']; $date =
$year . "-" . $month . "-" . $day; $dob = date('y-m-d', strtotime($date));
$Gender = $_POST['Gender']; $Faith = $_POST['Faith']; $City =
$_POST['City']; $MarritalStatus = $_POST['MarritalStatus']; $Profession
=$_POST['Profession']; $Country = $_POST['Country']; $query="insert into
users set FirstName='".$FirstName."',LastName='".$LastName
."',Msisdn='".$Msisdn."',dob='".$dob."',Gender='".$Gender."',Faith='".$Faith."',City='".$City."',MarritalStatus='".$MarritalStatus."',Profession='".$Profession."',Country='".$Country."'";
mysql_query($query)or die("".mysql_error());
echo "Successful Registration!";
}
?>
Registration.php
</tr>
Sign Up It's free and anyone can join
<form method="post" action="check.php" enctype="multipart/form-data">
<table width="900" align="center" cellpadding = "15">
<tr>
<td>FirstName:</td>
<td><input type="text" name="FirstName" maxlength="10" required=""
></td>
</tr>
<tr>
<td>LastName:</td>
<td><input type="text" name="LastName" maxlength="10"
required=""></td>
Below I have a Php Registration form that is working well, but am a bit
concerned as the form is wide open for an Sql injection attack, I am aware
about it but have very limited coding knowledge to prevent it, but still
learning.
Have managed to add a Captcha to prevent bots from auto-filling the form
and submitting, but unfortunately the same can't be said of being able to
validate the First name and Last name,am just wondering how can I
safeguard myself against such an attack.
The Relevant code is shown below, Thank You!
Check.php
$FirstName = strip_tags($_POST['FirstName']); $LastName =
strip_tags($_POST['LastName']); $Msisdn = $_POST['Msisdn']; $month =
$_POST['month']; $day = $_POST['day']; $year = $_POST['year']; $date =
$year . "-" . $month . "-" . $day; $dob = date('y-m-d', strtotime($date));
$Gender = $_POST['Gender']; $Faith = $_POST['Faith']; $City =
$_POST['City']; $MarritalStatus = $_POST['MarritalStatus']; $Profession
=$_POST['Profession']; $Country = $_POST['Country']; $query="insert into
users set FirstName='".$FirstName."',LastName='".$LastName
."',Msisdn='".$Msisdn."',dob='".$dob."',Gender='".$Gender."',Faith='".$Faith."',City='".$City."',MarritalStatus='".$MarritalStatus."',Profession='".$Profession."',Country='".$Country."'";
mysql_query($query)or die("".mysql_error());
echo "Successful Registration!";
}
?>
Registration.php
</tr>
Sign Up It's free and anyone can join
<form method="post" action="check.php" enctype="multipart/form-data">
<table width="900" align="center" cellpadding = "15">
<tr>
<td>FirstName:</td>
<td><input type="text" name="FirstName" maxlength="10" required=""
></td>
</tr>
<tr>
<td>LastName:</td>
<td><input type="text" name="LastName" maxlength="10"
required=""></td>
Change the shape of a set of points
Change the shape of a set of points
How to change the form of a shape by stretching it out in different
directions, without the perimeter changing? take a piece of string with
both ends connected as an example, it would form a shape resembling a
circle, if one side is pushed in or out, only the shape will change, but
the perimeter and area will stay the same. Im trying to accomplish
something almost if not identical to this.
I am not sure if I am being very clear with my question, please let me
know if it needs to be given more detail. Any help would be appreciated.
Even though this is needed for an application written in objective-c, code
in C, C++, or C# will also be of help.
How to change the form of a shape by stretching it out in different
directions, without the perimeter changing? take a piece of string with
both ends connected as an example, it would form a shape resembling a
circle, if one side is pushed in or out, only the shape will change, but
the perimeter and area will stay the same. Im trying to accomplish
something almost if not identical to this.
I am not sure if I am being very clear with my question, please let me
know if it needs to be given more detail. Any help would be appreciated.
Even though this is needed for an application written in objective-c, code
in C, C++, or C# will also be of help.
How to cluster with weighted values
How to cluster with weighted values
I try to create cluster based on object containing weighted values.
Values are about songs and objects are users. For example:
If user1 likes 3 pop songs, 1 rap song and no hip-hop song he will be
reprensent as:
u1 = {3,1,0}
So if i have 3 users with random values I could have a matrix like this:
3 1 0 0 4 5 1 2 3
u1 = {3,1,0} u2 = {0,4,5} u3 = {1,2,3}
My question is, it is possible to create cluster on that kind of data? And
what kind of algorithm is the best one.
First I tried to calculate using binary data but I will lost some
information if I do something like this.
In a second way, I try to calculate similarity between each values. I sum
all similarity and I do it again between each object values.
As an example:
I take u1 and u2 and I get:
u1 = {3,1,0} u2 = {0,4,5}
|3 - 0| = 3 |4 - 1| = 3 |0 - 5| = 5
(3 + 3 + 5) / 3 = 11/3
u1 = {3,1,0} u3 = {1,2,3}
|3 - 1| = 2 |1 - 2| = 1 |0 - 3| = 3
(2 + 1 +3) / 3 = 6/3 = 2
11/3 > 2 so u1 and u3 are more similar.
But I am not sure this approach is good too.
The goal of this is to compare clusters with other clusters to match some
search results.
Thanks in advance
I try to create cluster based on object containing weighted values.
Values are about songs and objects are users. For example:
If user1 likes 3 pop songs, 1 rap song and no hip-hop song he will be
reprensent as:
u1 = {3,1,0}
So if i have 3 users with random values I could have a matrix like this:
3 1 0 0 4 5 1 2 3
u1 = {3,1,0} u2 = {0,4,5} u3 = {1,2,3}
My question is, it is possible to create cluster on that kind of data? And
what kind of algorithm is the best one.
First I tried to calculate using binary data but I will lost some
information if I do something like this.
In a second way, I try to calculate similarity between each values. I sum
all similarity and I do it again between each object values.
As an example:
I take u1 and u2 and I get:
u1 = {3,1,0} u2 = {0,4,5}
|3 - 0| = 3 |4 - 1| = 3 |0 - 5| = 5
(3 + 3 + 5) / 3 = 11/3
u1 = {3,1,0} u3 = {1,2,3}
|3 - 1| = 2 |1 - 2| = 1 |0 - 3| = 3
(2 + 1 +3) / 3 = 6/3 = 2
11/3 > 2 so u1 and u3 are more similar.
But I am not sure this approach is good too.
The goal of this is to compare clusters with other clusters to match some
search results.
Thanks in advance
Tuesday, 10 September 2013
Javascript indexOf or Contains
Javascript indexOf or Contains
I would like to validate a field with the following condition: Password
should not contain any words in the email.
e.g. email: tryemail@yahoo.com
So password must not contain tryemail word.
With this code, I achieve it:
var emailSubstring = email.substr(0, email.indexOf("@"));
if (password.indexOf(emailSubstring) != -1)
{
// do something here //
}
My problem is this: When I enter the word try on the password field, it is
not validating it. Unless I make it tryemail.
Is there any possible way to do it? Thanks in advance!
Note: This is not a password requirements policy issue. I appreciate your
opinion about why should I validate password. My answer would be business
requirements. Thanks!
I would like to validate a field with the following condition: Password
should not contain any words in the email.
e.g. email: tryemail@yahoo.com
So password must not contain tryemail word.
With this code, I achieve it:
var emailSubstring = email.substr(0, email.indexOf("@"));
if (password.indexOf(emailSubstring) != -1)
{
// do something here //
}
My problem is this: When I enter the word try on the password field, it is
not validating it. Unless I make it tryemail.
Is there any possible way to do it? Thanks in advance!
Note: This is not a password requirements policy issue. I appreciate your
opinion about why should I validate password. My answer would be business
requirements. Thanks!
Template-based wrapper function for boost::bimap lookup not correctly working
Template-based wrapper function for boost::bimap lookup not correctly working
I have a pair of functions which, simply put, retrieve the left/right
values of a bimap and print a message (or, depending on a bool arg of the
function, cause a fatal error in the program):
#ifdef __cplusplus
template<typename Lt, typename Rt>
Rt Q_bimapleft( boost::bimap<Lt, Rt> themap, Lt L, bool throwError = false )
{
try
{
Rt returnVal = themap.left.at(L);
return returnVal;
}
catch( ... )
{
if( throwError )
{
Com_Error(ERR_FATAL, "Q_bimapright failure on lookup of %s\n",
boost::lexical_cast<char *, Lt>(L));
}
else
{
Com_Printf(S_COLOR_YELLOW "WARNING: Q_bimapright failure on
lookup of %s\n", boost::lexical_cast<char *, Lt>(L));
}
}
return (Rt)-1;
}
template<typename Lt, typename Rt>
Lt Q_bimapright( boost::bimap<Lt, Rt> themap, Rt R, bool throwError = false )
{
try
{
Lt returnVal = themap.right.at(R);
return returnVal;
}
catch( ... )
{
if( throwError )
{
Com_Error(ERR_FATAL, "Q_bimapleft failure on lookup of %s\n",
boost::lexical_cast<char *, Rt>(R));
}
else
{
Com_Printf(S_COLOR_YELLOW "WARNING: Q_bimapleft failure on
lookup of %s\n", boost::lexical_cast<char *, Rt>(R));
}
}
return (Lt)-1;
}
I have a pair of functions which, simply put, retrieve the left/right
values of a bimap and print a message (or, depending on a bool arg of the
function, cause a fatal error in the program):
#ifdef __cplusplus
template<typename Lt, typename Rt>
Rt Q_bimapleft( boost::bimap<Lt, Rt> themap, Lt L, bool throwError = false )
{
try
{
Rt returnVal = themap.left.at(L);
return returnVal;
}
catch( ... )
{
if( throwError )
{
Com_Error(ERR_FATAL, "Q_bimapright failure on lookup of %s\n",
boost::lexical_cast<char *, Lt>(L));
}
else
{
Com_Printf(S_COLOR_YELLOW "WARNING: Q_bimapright failure on
lookup of %s\n", boost::lexical_cast<char *, Lt>(L));
}
}
return (Rt)-1;
}
template<typename Lt, typename Rt>
Lt Q_bimapright( boost::bimap<Lt, Rt> themap, Rt R, bool throwError = false )
{
try
{
Lt returnVal = themap.right.at(R);
return returnVal;
}
catch( ... )
{
if( throwError )
{
Com_Error(ERR_FATAL, "Q_bimapleft failure on lookup of %s\n",
boost::lexical_cast<char *, Rt>(R));
}
else
{
Com_Printf(S_COLOR_YELLOW "WARNING: Q_bimapleft failure on
lookup of %s\n", boost::lexical_cast<char *, Rt>(R));
}
}
return (Lt)-1;
}
Regex list files, when windows cannot create that file that already exists
Regex list files, when windows cannot create that file that already exists
Basically, I want to list only those files that windows will not create.
How do I list 4.txt and 4a.txt instead ... s == s being true?
myList = '''
4.txt
4a.txt
spam
'''
myregex = 'a'
s = re.sub(myregex,'',myList)
if s == s:
print "got it!" # prints 'got it'
print s == s # prints 'true'
Basically, I want to list only those files that windows will not create.
How do I list 4.txt and 4a.txt instead ... s == s being true?
myList = '''
4.txt
4a.txt
spam
'''
myregex = 'a'
s = re.sub(myregex,'',myList)
if s == s:
print "got it!" # prints 'got it'
print s == s # prints 'true'
Quering two tables in grails
Quering two tables in grails
pI have two domain classes in my grails project. the first one is user and
second one is contact. the user has one to many relationship with the
contact class, i.e one user has many contacts. the user class is like
this/p precodepackage contacts class User { String name String email
String password static constraints = { name(nullable: false)
email(nullable: false,email: true,blank: false ) password(nullable:
false,size: 6..8,blank: false,password:true) } static hasMany = [contacts:
Contact] String toString(){ return name } } /code/pre pand the contact
class is like this/p precodepackage contacts class Contact { String
firstName String lastName String email String phone String address Date
dateCreated static constraints = { firstName(nullable: false)
lastName(nullable: true) email(nullable: false) phone(nullable: true)
address(nullable: true) dateCreated() } static belongsTo = [user: User] }
/code/pre pwhen I compile this, it creates two tables named user and
contact, the contact table has user_id as foriegn key from user table
which is called id in user table. Now I want retrieve all the contacts of
some specific user. I am wondering how to do this. I have tried different
approuches of dynamic quering but failed. can anybody help me to solve
this.. Thanks in advance/p
pI have two domain classes in my grails project. the first one is user and
second one is contact. the user has one to many relationship with the
contact class, i.e one user has many contacts. the user class is like
this/p precodepackage contacts class User { String name String email
String password static constraints = { name(nullable: false)
email(nullable: false,email: true,blank: false ) password(nullable:
false,size: 6..8,blank: false,password:true) } static hasMany = [contacts:
Contact] String toString(){ return name } } /code/pre pand the contact
class is like this/p precodepackage contacts class Contact { String
firstName String lastName String email String phone String address Date
dateCreated static constraints = { firstName(nullable: false)
lastName(nullable: true) email(nullable: false) phone(nullable: true)
address(nullable: true) dateCreated() } static belongsTo = [user: User] }
/code/pre pwhen I compile this, it creates two tables named user and
contact, the contact table has user_id as foriegn key from user table
which is called id in user table. Now I want retrieve all the contacts of
some specific user. I am wondering how to do this. I have tried different
approuches of dynamic quering but failed. can anybody help me to solve
this.. Thanks in advance/p
Activity.class - Class File Editor: The JAR file c:\sdk\platforms\android-17\android.jar has no source attachment
Activity.class - Class File Editor: The JAR file
c:\sdk\platforms\android-17\android.jar has no source attachment
For some reason a new tab opens in my debugger titled: Activity.class with
a header stating: Class File Editor and the error stating: The JAR file
c:\sdk\platforms\android-17\android.jar has no source attachment. You can
attach a source by clicking attach source below.
c:\sdk\platforms\android-17\android.jar has no source attachment
For some reason a new tab opens in my debugger titled: Activity.class with
a header stating: Class File Editor and the error stating: The JAR file
c:\sdk\platforms\android-17\android.jar has no source attachment. You can
attach a source by clicking attach source below.
iScroll refresh now working when displaying a ul
iScroll refresh now working when displaying a ul
Building an App for a publication. For the table of contents I have a
simple dropdown, that initially hides the unordered list with the
sections, and on 'tap' the corresponding ul will display. Im using iScroll
and when an ul is shown the scrolling is broke and has the bounce effect,
which doesn't allow you to scroll down or up. I'm using jqt.bars.js also,
which pulls in iScroll and init it. I understand iScroll has the refresh
method which gets the new height of the container, allowing you to scroll
correctly. I can't get it to work right. Please any suggestions or fixes,
thank you. Let me know if you need anymore details. Here is my jQuery/JS
var myScroll;
function createIScroll(){
myScroll = new iScroll('div#chapters div.sections-contents');
console.log('createIScroll');
}
function iScrollRefresh(){
setTimeout(function(){
myScroll.refresh();
}, 300);
console.log('refresh iScroll');
}
//CHAPTERS DROPDOWN
$(function() {
var chapter = $('ul#nav a.chapter-title');
var sections = $('ul#nav li ul');
sections.hide();
chapter.addClass('chapter-active');
$(chapter).on('tap', function() {
sections.slideUp();
chapter.removeClass('chapter-highlighted').addClass('chapter-active');
if( !$(this).next().is(":visible") ){
$(this).removeClass('chapter-active').addClass('chapter-highlighted');
$(this).next().slideDown(200);
console.log("slidedown");
iScrollRefresh();
}
});
Building an App for a publication. For the table of contents I have a
simple dropdown, that initially hides the unordered list with the
sections, and on 'tap' the corresponding ul will display. Im using iScroll
and when an ul is shown the scrolling is broke and has the bounce effect,
which doesn't allow you to scroll down or up. I'm using jqt.bars.js also,
which pulls in iScroll and init it. I understand iScroll has the refresh
method which gets the new height of the container, allowing you to scroll
correctly. I can't get it to work right. Please any suggestions or fixes,
thank you. Let me know if you need anymore details. Here is my jQuery/JS
var myScroll;
function createIScroll(){
myScroll = new iScroll('div#chapters div.sections-contents');
console.log('createIScroll');
}
function iScrollRefresh(){
setTimeout(function(){
myScroll.refresh();
}, 300);
console.log('refresh iScroll');
}
//CHAPTERS DROPDOWN
$(function() {
var chapter = $('ul#nav a.chapter-title');
var sections = $('ul#nav li ul');
sections.hide();
chapter.addClass('chapter-active');
$(chapter).on('tap', function() {
sections.slideUp();
chapter.removeClass('chapter-highlighted').addClass('chapter-active');
if( !$(this).next().is(":visible") ){
$(this).removeClass('chapter-active').addClass('chapter-highlighted');
$(this).next().slideDown(200);
console.log("slidedown");
iScrollRefresh();
}
});
got stuck with this set of code in jquery validate
got stuck with this set of code in jquery validate
var formRules = $(this).data('rules');
var formValues = $(this).data('values');
if(formRules || formValues){
var rulesArray = formRules.split(',');
var valuesArray = formValues.split(',');
for(var i=0; i < rulesArray.length; i++){
//alert(rulesArray[i]);
$.validationEngine.defaults.rulesArray[i] = valuesArray[i];
}
}
else{
return false;
}
This throws an error like following
Error: TypeError: $.validationEngine.defaults.rulesArray is undefined
Source File: http://localhost:8380/javascript/jquery.validationEngine.js
Line: 2092
I cannot find the problem with this code.Any help is welcome
EDIT:
I am trying to set the global options eg:scroll using the for loop. The
formRules string will have these options comma seperated and the
corresponding values in the formValues string.
So i am expecting it to come like $.validationEngine.defaults.scroll = true;
var formRules = $(this).data('rules');
var formValues = $(this).data('values');
if(formRules || formValues){
var rulesArray = formRules.split(',');
var valuesArray = formValues.split(',');
for(var i=0; i < rulesArray.length; i++){
//alert(rulesArray[i]);
$.validationEngine.defaults.rulesArray[i] = valuesArray[i];
}
}
else{
return false;
}
This throws an error like following
Error: TypeError: $.validationEngine.defaults.rulesArray is undefined
Source File: http://localhost:8380/javascript/jquery.validationEngine.js
Line: 2092
I cannot find the problem with this code.Any help is welcome
EDIT:
I am trying to set the global options eg:scroll using the for loop. The
formRules string will have these options comma seperated and the
corresponding values in the formValues string.
So i am expecting it to come like $.validationEngine.defaults.scroll = true;
iAds display issue, for ios
iAds display issue, for ios
Ads never show when I open the app. It always take a long time/ a lot of
clicks before they appear. Often they never appear. Now also when I tap on
the iAd ads, nothing happens
Ads never show when I open the app. It always take a long time/ a lot of
clicks before they appear. Often they never appear. Now also when I tap on
the iAd ads, nothing happens
Add 3 Hours to an NSDate's Hour
Add 3 Hours to an NSDate's Hour
I want to add 3 hours to my current date. I am using the following code to
add hours but it adds 6 hours to the current date.
NSDate *n = [NSDate date];
int daysToAdd = 3; // or 60 :-)
// set up date components
NSDateComponents *components1 = [[[NSDateComponents alloc] init]
autorelease];
[components1 setHour:daysToAdd];
// create a calendar
NSCalendar *gregorian12 = [NSCalendar currentCalendar];
NSDate *newDate2 = [gregorian12 dateByAddingComponents:components toDate:n
options:0];
NSLog(@"Clean: %@", newDate2);
Result is :-
2013-09-10 12:25:24.752 project[1554:c07] Clean: 2013-09-10 06:55:15 +0000
I want to add 3 hours to my current date. I am using the following code to
add hours but it adds 6 hours to the current date.
NSDate *n = [NSDate date];
int daysToAdd = 3; // or 60 :-)
// set up date components
NSDateComponents *components1 = [[[NSDateComponents alloc] init]
autorelease];
[components1 setHour:daysToAdd];
// create a calendar
NSCalendar *gregorian12 = [NSCalendar currentCalendar];
NSDate *newDate2 = [gregorian12 dateByAddingComponents:components toDate:n
options:0];
NSLog(@"Clean: %@", newDate2);
Result is :-
2013-09-10 12:25:24.752 project[1554:c07] Clean: 2013-09-10 06:55:15 +0000
Monday, 9 September 2013
fancybox next and previous buttons not working in mobile
fancybox next and previous buttons not working in mobile
I'm working on my portfolio website and I've used Fancybox 2 to showcase
some portfolio items. Everything works beautifully on the desktop in
Firefox, Safari and Chrome, but for some reason on mobile (iPhone) the
next and previous buttons don't work and the images go all small and jump
to the right slightly. The close button works just fine.
This is my javascript:
<script type="text/javascript">
$(document).ready(function() {
$("a.fancybox").fancybox({
'transitionIn': 'fade',
'transitionOut': 'fade',
'speedIn': 600,
'speedOut': 200,
'overlayShow': true,
margin: [60, 60, 50, 60] // top, right, bottom, left
});
});</script>
I haven't changed any of the default css that came with the fancybox
download, but I did customize the close and nav buttons. I don't think
that would have anything to do with it though, would it?
If there's anyone who might know how to fix this, I would very much
appreciate the help!
Thanks!
I'm working on my portfolio website and I've used Fancybox 2 to showcase
some portfolio items. Everything works beautifully on the desktop in
Firefox, Safari and Chrome, but for some reason on mobile (iPhone) the
next and previous buttons don't work and the images go all small and jump
to the right slightly. The close button works just fine.
This is my javascript:
<script type="text/javascript">
$(document).ready(function() {
$("a.fancybox").fancybox({
'transitionIn': 'fade',
'transitionOut': 'fade',
'speedIn': 600,
'speedOut': 200,
'overlayShow': true,
margin: [60, 60, 50, 60] // top, right, bottom, left
});
});</script>
I haven't changed any of the default css that came with the fancybox
download, but I did customize the close and nav buttons. I don't think
that would have anything to do with it though, would it?
If there's anyone who might know how to fix this, I would very much
appreciate the help!
Thanks!
Subscribe to:
Comments (Atom)