Thursday, 3 October 2013

C++ Template Restriction on having a method

C++ Template Restriction on having a method

I want to learn whether there is a way to restrict templates such that
instances have a specific method. For example, think of a generic isLess
function which needs operator< or operator>. Is there a way to control
that?
template <Class T>
bool isLess(T first,T second){ return first < second; }
When we use this with a class not having operator< it will give an error.
How can I deal with it?

Wednesday, 2 October 2013

C++ and returning a reference

C++ and returning a reference

Can any one explain to me the difference between these two functions:
int& test(int a)
{
return a;
}
and
int test(int a)
{
return a;
}
and tell me what the purpose when we use '&' operator after return type of
a function? When should we use it because I've rarely seen it before.

Get value from string array index

Get value from string array index

I have following string [,] called School. It has values like:
[0,0] = Class1
[0,1] = Class1
[0,2] = Class1
[0,3] = Class1
[0,4] = Class2
[0,5] = Class2
[0,6] = Class3
All the Classes are in order. Like Class2 will come after Class1 and so
on. I need to know index of Class3. In above scenario it will be 6. First
part will always be 0. So i need only the second array value which is 6.
Is there easier way in C# to get that value?

Form processing in PHP

Form processing in PHP

I have three questions about some code. Heres the code and questions.
Questions:
1.How does isset($_POST['submit']) know when the submit button has been
clicked. I dont get the the mechanics behind this? 2. Why is each input
element using a name with a value of "artist[]" with the square brackets
like that? Are we defining and array inside HTML? 3. I was told that the
value of name given to an input element has to match the name given to the
$_POST variable. But in this case $_POST is using "artist" with without
the square brackets. Whats going on here?
<html>
<head></head>
<body>
<?php
// check for submit
if (!isset($_POST['submit'])) {
// and display form
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
<input type="checkbox" name="artist[]" value="Bon Jovi">Bon Jovi
<input type="checkbox" name="artist[]" value="N'Sync">N'Sync
<input type="checkbox" name="artist" value="Boyzone">Boyzone
<input type="checkbox" name="artist" value="Britney Spears">Britney Spears
<input type="checkbox" name="artist" value="Jethro Tull">Jethro Tull
<input type="checkbox" name="artist" value="Crosby, Stills & Nash">Crosby,
Stills & Nash
<input type="submit" name="submit" value="Select">
</form>
<?php
}
else {
// or display the selected artists
// use a foreach loop to read and display array elements
if (is_array($_POST['artist'])) {
echo 'You selected: <br />';
foreach ($_POST['artist'] as $a) {
echo "<i>$a</i><br />";
}
}
else {
echo 'Nothing selected';
}
}
?>
</body>
</html>

How to disable "snap to grid" from jQuery UI draggable?

How to disable "snap to grid" from jQuery UI draggable?

Anyone know how we can disable "Snap to Grid" from jQuery UI Draggable
base on checkbox.
I m using below code to enable snap to grid dynamically.
$(".WidgetCl").draggable({containment: '#editorWindow',scroll: true, snap:
".gridCol", snapMode: "both", stop :function()
{$(this).trigger("stopdrag");}})
$(".WidgetCl").draggable("option", "grid", [ gridSize,
gridSize ]);
Thanks, Sonal

Tuesday, 1 October 2013

SDWebImage check if UIImage get from the cache

SDWebImage check if UIImage get from the cache

I am using SDWebImage to download and cache image in the device. I would
like to show some animation after the download process but the cache
image.
Here is my code:
__weak typeof(self) weakSelf = self;
//SDWebImage Method
[self.imageView setImageWithURL:imageUrl
placeholderImage:[UIImage
imageNamed:@"imageview_placeholder.png"]
completed:^(UIImage *image, NSError *error,
SDImageCacheType cacheType) {
if (!error && image)
{
if (weakSelf.spinner) [weakSelf.spinner
removeFromSuperview];
// if downloaded from server, add animation
if (isDownloadedFromServer])
{
[weakSelf.imageView setAlpha:0.0];
[weakSelf.imageView setImage:image];
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:0.5];
[weakSelf.imageView setAlpha:1.0];
[UIView commitAnimations];
}
else
{
[weakSelf.imageView setImage:image];
}
}
}];
Is there any way to distinguish between cache or download?
Thanks!

Forcing ASP.NET WebAPI client to send a client certificate even when no CA match

Forcing ASP.NET WebAPI client to send a client certificate even when no CA
match

I have a specific application that requires the use of client certificates
for mutual authentication of HTTPS requests. The server has a flexible
certificate validation policy that allows it to accept self-signed client
certificates that are not present in the server's certificate store. This
is known to work just fine using curl as a client.
What I've determined via testing and packet sniffing is that Microsoft's
ASP.NET HttpClient tries to be overly smart during the SSL handshake. This
particular client will only use a client certificate (from the
WebRequestHandler.ClientCertificates collection) if it has chain of trust
to one of the server's trusted roots. What I've observed is that if there
are no certificates with chain of trust then the client simply won't send
a certificate at all during the handshake.
This is understandable default behavior but is overly restrictive and
there appears to be no way to turn it off. I have experimented with
various other WebRequestHandler properties, including AuthenticationLevel
and ClientCertificateOptions but to no avail.
Is there a way to force HttpClient to send a client certificate when it is
available in the ClientCertificates collection, even though it appears
that it will not validate on the server side? I'm open to both
straightforward and dirty (reflection hacks) solutions as I really need
this client to work.

Tunnel HTTP traffic from an EC2 instance to an Heroku Application

Tunnel HTTP traffic from an EC2 instance to an Heroku Application

We have a web application that runs perfectly on Heroku. However, that
application is not available from within a given subnetwork due to
firewall restriction on the Heroku IPs.
So built a simple EC2 instance with an elastic IP that works within the
firewall restriction. But rather than setting up a new application to run
on that instance I was thinking that we could setup some sort of HTTP
tunnel on port 80 (and maybe HTTPS as well) to direct the traffic directly
to the Heroku application that way we don't need to maintain a second
application.
Is there any way to achieve this ?

Ubuntu 12.10 hangs on "Ubuntu" logo screen after running Ubuntu Tweak's "Janitor" tool

Ubuntu 12.10 hangs on "Ubuntu" logo screen after running Ubuntu Tweak's
"Janitor" tool

I dual-boot Ubuntu 12.10 and Windows 7 64-bit. Previously I had no issues.
Tonight I ran Ubuntu-Tweak's "Janitor", which cleaned old packages and
such from my Ubuntu partition. When I rebooted, Ubuntu would not boot past
the "Ubuntu" splash screen (the dots would fill up, and then the system
would hang there). I can boot into Windows 7 just fine. I can also get to
the recovery mode command line. I'm afraid that Ubuntu-Tweak "Janitor"
uninstalled something crucial to booting.
What to do? Thanks in advance for your help.

Monday, 30 September 2013

Does the term "dark matter" apply to nonluminescent bodies which still interact electromagnetically=?iso-8859-1?Q?=3F_=96_physics.stackexchange.com?=

Does the term "dark matter" apply to nonluminescent bodies which still
interact electromagnetically? – physics.stackexchange.com

On the new Astronomy.SE site, I was having a short discussion on one of my
answers. The basic discrepancy was; can MACHOs like black holes/brown
dwarfs/neutron stars be termed "dark matter"? My ...

How to show that a lattice is isomorphic to an other lattice?

How to show that a lattice is isomorphic to an other lattice?

pBy definition, a homomorphism of two lattices say g:L-S is called an
isomorphism if it is one-to-one and onto. I think we can prove this by
drawing Hasse diagrams for both lattice but what if the set is too big?
Any analytical method ?/p

How to select the 10% of highest and lowest values from a vector in R?

How to select the 10% of highest and lowest values from a vector in R?

As introduce in the title, I would like to select the 10% highest and the
10% lowest values from a vector. How can I manage to do that?
Anyone can help me ? Thanks a lot

My jquery image gallery doesn't work in firefox (23.0.1)

My jquery image gallery doesn't work in firefox (23.0.1)

I made this jquery image gallery and it works perfect in my chrome
browser. The gallery works with 3 thumbnails which you can click on to
show it in the "current_image" div.
But If I try to use it in firefox I can't click on a thumbnail to show it.
Does anyone know how I can improve this piece of code so it works in
Firefox too?
This is my jquery code:
// Image gallery
$("#small_images .small_image").first().addClass('active');
$(".small_image").click(function () {
event.preventDefault();
var image = $(this).prop("rel");
$('#under').prop('src', image);
$('#above').fadeOut(600, function () {
$('#above').prop('src', $('#under').prop('src')).show();
});
$(".small_image.active").removeClass('active');
$(this).addClass('active');
});
This it the HTML:
<div id="image_gallery">
<div id="current_image">
<img id="above" width="100%" src="<?php
the_field('image_1'); ?>" />
<img id="under" width="100%" src="<?php
the_field('image_2'); ?>" />
</div><!--End current_image-->
<div id="small_images">
<?php foreach($pictures as $picture) : ?>
<a class="small_image" rel="<?php the_field($picture);
?>"><img width="100%" src="<?php the_field($picture); ?>"
/></a>
<?php endforeach; ?>
</div><!--End small_images-->
<div class="clear"></div>
</div><!--End image_gallery-->

Sunday, 29 September 2013

How to display legend in bottom right corner instead of top right?

How to display legend in bottom right corner instead of top right?

Normally the legend appears in the top-right corner when using the command
legend('aa', 'bb', 'cc', 'dd')
But that blocks my curves.
How to place it in the bottom-right corner instead?

DATABASE ERROR android.sqlite.SQLiteException: near "Wall"

DATABASE ERROR android.sqlite.SQLiteException: near "Wall"

the code snippent in which i am getting error is
String table = "WONDERS";
String column = "iamge";
String name = "name";
String query = "UPDATE " + table
+ " SET " + column + "=" + sle
+ " WHERE " + name + link_global;
Cursor cu = sqlHandler.selectQuery(query);
cu.moveToFirst();
cu.close();
showList();
please help .

Large font-size in a text-input breaks out of container

Large font-size in a text-input breaks out of container

I have a text input wrapped inside a inline element which adds some
padding and border. But when I increase the font-size the input grows
beyond the containing element.
display:flex-inline seems to fix it, but I don't think that has good IE
support?
http://jsfiddle.net/3hyjd/1/
How can I make the height of the container automatically adjust?
Preferably with IE<9 support.

Live preview inside iFrame and saving draft every 30 seconds

Live preview inside iFrame and saving draft every 30 seconds

I am making a website where you type in CSS and there is a preview
(preview.php) - which is shown inside an iFrame - which has set text. I
would like preview.php to update live to when you type CSS into the css
file (relative to preview.php: designname/css/style.css), and to save the
edited CSS file every 30 seconds.

Saturday, 28 September 2013

vertical autoscroll on mouseover - like deviantart.com "Project giveaway" has

vertical autoscroll on mouseover - like deviantart.com "Project giveaway" has

http://www.deviantart.com/ is vertically scrolling the content of one of
their container upwards when you move your cursor over it. and on
mouseleave, it scrolling back down.
You can see it in action on their main page - right now at least - in a
container with the text "Project Giveaway: 100 point giveaway #4". I'm
wondring how they do this?
Found this line of code trough firebug:
onmouseout="if (window.LitBox) LitBox.out(this)" onmouseover="if
(window.LitBox) LitBox.hover(this, true)".
So I tried to google for "LitBox" - but didn't get any luck. All I found
was lightbox and listbox...
The exact effect is what I'm looking for.
Anyone know how?

Finding the (guaranteed unique) path between two nodes in a tree

Finding the (guaranteed unique) path between two nodes in a tree

I have a (likely) simple graph traversal question. I'm a graph newbie
using networkx as my graph data structures. My graphs always look like
this:
0
1 8
2 3 9 10
4 5 6 7 11 12 13 14
I need to return the path from the root node to a given node (eg., path(0,
11) should return [0, 8, 9, 11]).
I have a solution that works by passing along a list which grows and
shrinks to keep track of what the path looks like as you traverse the
tree, ultimately getting returned when the target node is found:
def VisitNode(self, node, target, path):
path.append(node)
# Base case. If we found the target, then notify the stack that we're
done.
if node == target:
return True
else:
# If we're at a leaf and it isn't the target, then pop the leaf off
# our path (backtrack) and notify the stack that we're still looking
if len(self.neighbors(node)) == 0:
path.pop()
return False
else:
# Sniff down the next available neighboring node
for i in self.neighbors_iter(node):
# If this next node is the target, then return the path
# we've constructed so far
if self.VisitNode(i, target, path):
return path
# If we've gotten this far without finding the target,
# then this whole branch is a dud. Backtrack
path.pop()
I feel in my bones that there is no need for passing around this "path"
list... I should be able to keep track of that information using the call
stack, but I can't figure out how... Could someone enlighten me on how you
would solve this problem recursively using the stack to keep track of the
path?

adjust element position with css

adjust element position with css

I have a ul wrapped in a .box. I have set the bottom border for the .box.
The ul items also have bottom border, I want the li border to place over
the .box border so that the .box border is no more visible. I'm trying to
do that by setting margin-bottom: -1px but doesn't work.
Please see attached image:

Here's what I'm trying:
HTML:
<div class="box">
<ul>
<li>Hello</li>
<li>World</li>
</ul>
</div>
CSS:
.box{
border-bottom: 1px solid blue;
overflow: hidden;
}
ul{
list-style: none;
margin: 0;
padding: 0;
}
ul li{
float: left;
background: green;
border: 1px solid red;
}
Demo: http://jsfiddle.net/b9H2j/

Android: Push bot sending a notification to certain group of registered devices

Android: Push bot sending a notification to certain group of registered
devices

I have a question regarding pushbot! How can I send a push notification to
a certain group of registered device's of those people who I'd like to
receive the notification I pushed? Please help me! Thank you!

Friday, 27 September 2013

Populate HTML5 dropdown values with JSON data

Populate HTML5 dropdown values with JSON data

I have US states JSON data as below
{"States":["Alaska","Alabama","Arkansas","American
Samoa","Arizona","California","Colorado","Connecticut","District of
Columbia","Delaware","Florida","Federated States of
Micronesia","Georgia","Guam","Hawaii","Iowa","Idaho","Illinois","Indiana","Kansas","Kentucky","Louisiana","Massachusetts","Maryland","Maine","Marshall
Islands","Michigan","Minnesota","Missouri","Northern
Marianas","Mississippi","Montana","North Carolina","North
Dakota","Nebraska","New Hampshire","New Jersey","New Mexico","Nevada","New
York","Ohio","Oklahoma","Oregon","Pennsylvania","Puerto
Rico","Palau","Rhode Island","South Carolina","South
Dakota","Tennessee","Texas","Utah","Virginia","Virgin
Islands","Vermont","Washington","Wisconsin","West
Virginia","Wyoming","Armed Forces Europe, the Middle East, and
Canada","Armed Forces Pacific","Armed Forces Americas"]}
Now in my web app I deserialize JSON and bind to HTML5 dropdown to get
following

What I am trying to get to is that; How can I modify JSON data so that
when I bind to dropdown, Value is state code and text is full state name
so some thing like this
<option value="IL">Illinois</option>

Call web service from PHP

Call web service from PHP

I have generated the proxy classes using wsdl2php generator. Not sure how
to use them from php client to call the service. Any small example would
be a great help.

Using Rack gem in Rails

Using Rack gem in Rails

I'm trying to use a stupid little Rack gem I just wrote in my Rails
project, but I keep on getting an uninitialized constant error whenever I
call it. This is driving me insane because I've already written Rack gems
before, and those work in my Rails projects just fine.
In my Gemfile:
gem 'hide_heroku', :git => 'https://github.com/ykessler/hide-heroku'
In my application.rb:
module Tester
class Application < Rails::Application
config.middleware.use Rack::HideHeroku
But starting my local server, I get:
uninitialized constant Rack::HideHeroku (NameError)
The gem:
module Rack
class HideHeroku
def initialize(app)
@app=app
end
def call(env)
@status, @headers, @response = @app.call(env)
@request = Rack::Request.new(env)
[@status, _apply_headers, @response]
end
private
def _apply_headers
if /\.herokuapp\.com\/?.*/ =~ @request.url
@headers['X-Robots-Tag'] = 'noindex, nofollow'
end
@headers
end
end
end
See it here: https://github.com/appgrinders/rack-conditional-response-headers

Twitter Bootstrap Responsive Background-Image inside Div

Twitter Bootstrap Responsive Background-Image inside Div

i have an problem, i can't find solution..
i have a standart page:
<div class="container">
<div class="row">
<div class="col-md-2"></div>
<div class="col-md-8 col-sm-6 col-xs-12 well" id="bg">
</div>
<div class="col-md-2"></div>
</div>
</div>
css:
@import url('bootstrap.min.css');
body{
background: url('../img/bg.jpg') no-repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
margin-top: 12%;
}
#bg{
background:url('../img/con_bg4.png') no-repeat center center;
height: 500px;
}
How i can modify #bg image so it would be Responsive ? resizable and
proportional in all browser.
Thanks

Why isn't my if then statement working in ERB?

Why isn't my if then statement working in ERB?

All I want if to output "test" if all_day is set to "true"
Here's my code:
<%= event.all_day == "true" ? 'test' : '' %>
If I just have <%= event.all_day %> it does work and it does output either
true or false. So, I'm not sure what I'm doing wrong here.

Strange string.Format behavior

Strange string.Format behavior

I've a double variable called totalCost and it's value is 1025. The result
of calling a simple string.Format is the following:
?string.Format("{0}",totalCost)
"1,025"
Since my thousand separator is the coma while the decimal separator is the
dot.
The weird part is the following:
?string.Format("{0:0.0}",totalCost)
"1,0"
Doesn't it should be 1025.0 (or 1,025.0)?
It seems that it converts the double in a string (giving "1.025") and then
re-parse it without using my separator settings (interpreting it as
1-and-25-thousandths) and finally it formats the converted value.

Thursday, 26 September 2013

I want dynamic way to get the package name from any class in java

I want dynamic way to get the package name from any class in java

I have code like below sample. in that I am telling the class_name to get
package name. instead of this method, i need another logic to get the
package name withoud telling the class_name directly.
package smk.jsf.bean;
public class test {
public static void main(String[] args) {
System.out.println(test.class.getPackage().getName());
//Is there any option like "this.class.getPackage().getName();" bz. i
don't want use class_name direclty
}
}
Output : smk.jsf.bean

Thursday, 19 September 2013

Can't select a value from list

Can't select a value from list

I have this code:
import os
import pprint
print("Hello")
ModList = os.listdir("C:/Users/Dat/AppData/Roaming/.minecraft/mods")
print ("The current mods you have installed are:\n")
pprint.pprint(ModList)
DisableNumber = input("To disable a mod, type it's number in the list.\n")
int (DisableNumber)
FileToDisable = ModList[DisableNumber]
print (FileToDisable)
It's supposed to list the files in a directory, print the list, ask the
user to input a number, and it renames the filename with that index in the
list. However, when I run this, I get an error:
Traceback (most recent call last):
File "C:\Users\Dat\Desktop\Python\ModDisabler.py", line 9, in <module>
FileToDisable = ModList[DisableNumber]
TypeError: list indices must be integers, not str
What is the cause of this error? I think it's because the
int(DisableNumber) is not working, but I can't seem to find out why for
the life of me. Am I missing something?

Python - having multiple "if" statements

Python - having multiple "if" statements

Basically, I'm trying to make a basic login program, that asks the user
for a username and password, and records any right or wrong text in a
logfile. The problems I'm having are that when I try to have more than 1
username and password combination I get syntax errors. Sorry if I've not
explained this well enough, hopefully you know what I'm on about because
of my code. I'm aware this code is terrible and messy and basic, but I'm
about 1 week into Python.
#login program
output = open("logfile.txt", 'a')
login = input("please enter the correct username and password\n")
a = "username password"
b = "username1 password1"
if a in login:
print("successfully logged in")
import time
localtime = time.asctime(time.localtime(time.time()))
output.write("Somebody successfully logged in at ")
output.write(localtime)
output.write("\n")
output.close()
if b in login:
print("successfully logged in")
import time
localtime = time.asctime(time.localtime(time.time()))
output.write("Somebody successfully logged in at ")
output.write(localtime)
output.write("\n")
output.close()
else:
print("access denied.")
import time
output = open("logfile.txt", "a")
localtime = time.asctime(time.localtime(time.time())
output.write("Somebody unsuccessfully logged at ")
output.write(localtime)
output.write("\n")
output.close()

Surface Area of a Hypar

Surface Area of a Hypar

Segway from this question: Speeding up a closest point one a surface
algorithm
Given four points (p0,p1,p2,p3) to define a hyperbolic paraboloid, what is
the best (fastest) way to compute its surface area using python's numpy
module?

How to set a timeout using perl (to kill hung child program)

How to set a timeout using perl (to kill hung child program)

I am on Windows running a Perl script that calls an .exe program. I want
to kill the .exe program if it takes longer than 10 minutes and then
resume the perl script from the point after the call. Is there an easy way
to do this? Thanks!

Can I use dirname(__FILE__) as a part of a string?

Can I use dirname(__FILE__) as a part of a string?

I use dirname(__FILE__) in includes in php scripts but the other day I
included it as part of a string and it caused an error. Any ideas?
THe line was
private $errorfile = dirname(__FILE__).'/../../../error_logs/error.log';
or
private $errorfile = '/../../../error_logs/error.log';
error_log($message,3, dirname(__FILE__).$this->errorfile);
and it caused an error such as
PHP Parse error: syntax error, unexpected '(', expecting ',' or ';' in
/home2/futsalti/public_html/_futsal-time-v4.9/public/scripts/php/databaseClass.php
PHP Parse error: syntax error, unexpected ';' in
/home2/futsalti/public_html/_futsal-time-v4.9/public/scripts/php/databaseClass.php
EDIT:
Ok, just came to me... Maybe the question should be can I use
dirname(__FILE__) inside a class?

WIndows Phone: POST request doesn't work

WIndows Phone: POST request doesn't work

i'm tryng to send the notification link and deviceID to a script on the
web via a POST request. the problem is that the script receive only empty
params. i followed another example and my code looks like this:
WebClient wc = new WebClient();
System.Diagnostics.Debug.WriteLine("sending rquest");
var URI = new
Uri("http://www.jack-prove.comuv.com/update_link.php");
wc.UploadStringCompleted += new
UploadStringCompletedEventHandler(wc_UploadStringCompleted);
byte[] myDeviceID =
(byte[])Microsoft.Phone.Info.DeviceExtendedProperties.GetValue("DeviceUniqueId");
string ID = Convert.ToBase64String(myDeviceID);
String par = "?link=" + e.ChannelUri.ToString() + "&ID=" + ID;
MessageBox.Show(par);
wc.UploadStringAsync(URI, "POST", par);
NOTE: the ID string contains a '=' charater could this be the problem?
i've tried to call the script from the web and it works even with the '='
any idea?

Comparing two strings in python

Comparing two strings in python

I need to compare two strings that are almost the same. Then find the
point at which they differ using python. Any help?
for example two strings a and b
A = 'oooooSooooooooooooooooooRoMooooooAooooooooooooooo'
B = 'oooooSooooooooooooooooooooMooooooAooooooooooooooo'
Thanks

Wednesday, 18 September 2013

my iframe video playing wrong video

my iframe video playing wrong video

iam used this code for my little project using local host xampp:
<iframe title="YouTube video player" class="youtube-player" type="text/html"
width="580" height="300" src="http://www.youtube.com/embed/2KkRwefwns0"
frameborder="0" allowFullScreen></iframe>
for video in this link
http://youtu.be/2KkRwefwns0
but in my local host the iframe going to this link
http://youtu.be/ZnuwB35GYMY
why?

Need Method to Return only matching numbers in Java

Need Method to Return only matching numbers in Java

/** * This method should compare two Sets of Integers and return a new *
Set of Integers that represent all of the matching numbers. * * For
example, if the lotteryNumbers are (4, 6, 23, 34, 44, 45) and * the
userNumbers are (4, 18, 22, 24, 35, 45) then the returned Set * of
Integers should be (4, 45) * * @param lotteryNumbers the lottery numbers
that were randomly generated. * @param userNumbers the user picked numbers
that were picked in the console. * @return Set of matched numbers */.
public Set<Integer> playLottery (Set<Integer> lotteryNumbers,
Set<Integer> userNumbers) {
Set<Integer> listOfRandom = new HashSet<Integer>(lotteryNumbers);
listOfRandom.equals(lotteryNumbers);
listOfRandom.addAll(lotteryNumbers);
Set<Integer> s = new HashSet<Integer>(userNumbers);
s.equals(userNumbers);
s.addAll(userNumbers);
Set<Integer> e = new HashSet<Integer>();
for (Integer integer : userNumbers) {
if (userNumbers.equals(lotteryNumbers));
userNumbers.remove(lotteryNumbers);
}
return userNumbers;
}
}
As of now it only returns all the userNumbers. I assumed the remove()
method would remove any duplicate values returned.I need this to pass my
unit Test.

Catching program making keystrokes

Catching program making keystrokes

It seems I have a program on my computer sending key combinations without
any action from me. I am wondering if there's any way I could catch key
combinations, and most importantly, any program that initiates them so
that I can find out what the offending program is and remove it. I'd like
to write a program to manage this since I think it would be a kind of
entertaining exercise, but if there is software that does this already I
would be interested to know about it as well. Also, I'm having the problem
on Windows 7 64-bit. I'm most familiar with C/C++ and python but would be
more than happy to try another language if there is one more suited for
this. Thanks for the help!

C# Getting Return Value from Stored Procedure Is Not Working

C# Getting Return Value from Stored Procedure Is Not Working

I am trying to run a stored procedure returning a single integer value and
I can't figure out where its going wrong. From what I've read the
following should work but is not and I can't see where I'm going wrong.
Here is my stored procedure:
ALTER PROCEDURE [dbo].[getDDNTempID]
AS
BEGIN
declare @tempID int
select top 1 @tempID = tempID from tblDDNHdr order by tempID asc
if @tempID is null
return 0
else
return @tempID
END
Here is the code where I try to get the return value:
using (SqlConnection conn = new
SqlConnection(ConfigurationManager.ConnectionStrings["test"].ConnectionString))
{
SqlCommand cmd = new SqlCommand("getDDNTempID", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection.Open();
Int32 tempID = (Int32)cmd.ExecuteScalar();
if (tempID == 0) { tempID = -1; }
return tempID;
}
When this procedure is called I get a NullReferenceException and the line
giving the error is:
Int32 tempID = (Int32)cmd.ExecuteScalar();
I would appreciate any guidance you guys could give.
Thanks

Slow motion animations with Xcode 5 iOS simulator

Slow motion animations with Xcode 5 iOS simulator

Before Xcode 5, it was possible to turn on slow-motion animations by
hitting the "Shift" key three times. I'm trying to do the same in Xcode 5
and nothing is happening. Did Apple remove this feature from Xcode 5? Has
anyone figured out how to do this in Xcode 5?

Looping through all items in legend bar in highcharts

Looping through all items in legend bar in highcharts

We have a requirement to autoscroll the legend bar to the first
highlighted item. This was achieved using "load" event
Now I want to loop through all available items in legend bar to check for
highlighted item and then scroll the legend bar to that page. Please
provide your suggestions on how this can be achieved
We need the implementation to be something like this load:function(event){
for(each page in the legend bar) { for(each item available in the above
page) { if(item is visible) { this.legend.scroll(page); break; } } }
Thanks in advance!

Change behavior of mouse buttons - do I have to write a driver? (Sharkoon Drakonia)

Change behavior of mouse buttons - do I have to write a driver? (Sharkoon
Drakonia)

I just bought a Sharkoon Drakonia (just for information). It has 11
buttons, but only two of them (except left, right and middle button of
course) can be used as 4th and 5th mouse button (eg. in games), the other
ones can only be modified to behave like a double click etc. via the
configurator software shipped with the mouse. So I wondered if there is a
way to completely change or remap (some of) the mouse buttons to be
recognized in games as for example "Mouse 6" and "Mouse 7". I think I have
to write a driver for it, am I right? Is there another way to achieve my
aim?
Thank you in advance!

How to use subquery to populate column in Access query

How to use subquery to populate column in Access query

I am working on an Access database which is used for forecasting purchases
and I am trying to create a query in which would give me list of records
with valid prices and row sums.
I am running into problems when I try to combine prices to quantities. I
have following tables
Table that contains forecasting data (columns not relevant for this query
omitted)
need_rows
ID product_id qty use_date
----------------------------
1 1 100 1.1.2014
2 1 50 15.1.2014
...
And table for prices
prices
ID product_id price valid_from
----------------------------------
1 1 1 1.12.2013
2 1 2 24.12.2013
3 1 5 10.1.2014
...
Query resulst should be something like below:
result of query
product_id use_date qty price sum
---------------------------------------
1 1.1.2014 100 2 200
1 15.1.2014 50 5 250
...
Meaning that I need to fetch valid price to each of the rows based on the
use_date from need_rows and valid_from date from prices. Valid prices is
the one that has valid_from date equal or most recent to use_date.
Below is one of the approaches I have tried with no luck.
SELECT prices.price
FROM prices
WHERE (((prices.product_id)=[product_id]) AND ((prices.valid_from)=
(SELECT Max(prices.valid_from) AS valid
FROM prices
WHERE (((prices.product_id)=[product_id]) AND
((prices.valid_from)<=[use_date]));).));
Any help is appreciated!

How to improve the perfomance to read the file in tar.gz folder?

How to improve the perfomance to read the file in tar.gz folder?

I have successfully read pdf file in tar.gz format folder . But I faced
performance issue - taking more time to open tar.gz folder containing more
than 1000 small pdf files each file size 10 - 25 MB .Total size of the
folder is 2GB
How to improve the performance of unzip file reading ?
FileInputStream fin = new FileInputStream(tarName);
BufferedInputStream in = new BufferedInputStream(fin);
GzipCompressorInputStream gzIn = new
GzipCompressorInputStream(in);
TarArchiveInputStream tarIn = new
TarArchiveInputStream(gzIn);
TarArchiveInputStream tarIn1 = new
TarArchiveInputStream(tarIn);
TarArchiveEntry entry = null;
byte[] buffer = new byte[5024];
int nrBytesRead;
while ((entry = (TarArchiveEntry)
tarIn1.getNextEntry()) != null) {
System.out.println("it finds a file "
+ entry.getName().toString());
if (entry.getName().toString().equals(fileName)) {
while ((nrBytesRead =
tarIn1.read(buffer)) > 0) {
out.write(buffer, 0, nrBytesRead);
}
break;
}

Tuesday, 17 September 2013

This pice of code from w3schools is not working properly?

This pice of code from w3schools is not working properly?

Tt seems to be working here but when i just copy paste the code into
notepad and try to run in browser.i get an extra `">" character before
name like this.
php 4.3.0

<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
// define variables and set to empty values
$nameErr = $emailErr = $genderErr = $websiteErr = "";
$name = $email = $gender = $comment = $website = "";
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
if (empty($_POST["name"]))
{$nameErr = "Name is required";}
else
{
$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name))
{
$nameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["email"]))
{$emailErr = "Email is required";}
else
{
$email = test_input($_POST["email"]);
// check if e-mail address syntax is valid
if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/",$email))
{
$emailErr = "Invalid email format";
}
}
if (empty($_POST["website"]))
{$website = "";}
else
{
$website = test_input($_POST["website"]);
// check if URL address syntax is valid (this regular expression also
allows dashes in the URL)
if
(!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$website))
{
$websiteErr = "Invalid URL";
}
}
if (empty($_POST["comment"]))
{$comment = "";}
else
{$comment = test_input($_POST["comment"]);}
if (empty($_POST["gender"]))
{$genderErr = "Gender is required";}
else
{$gender = test_input($_POST["gender"]);}
}
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<h2>PHP Form Validation Example</h2>
<p><span class="error">* required field.</span></p>
<form method="post" action="<?php $_SERVER["PHP_SELF"];?>">
<label>Name:</label> <input type="text" name="name"> <span
class="error">* <?php echo $nameErr;?></span>
<br><br>
<label>E-mail:</label> <input type="text" name="email"> <span
class="error">* <?php echo $emailErr;?></span>
<br><br>
<label>Website:</label> <input type="text" name="website"> <span
class="error"><?php echo $websiteErr;?></span>
<br><br>
<label>Comment:</label> <input type="text" name="comment">
<br><br>
<label>Gender:</label>
<input type="radio" name="gender" value="female">Female
<input type="radio" name="gender" value="male">Male
<span class="error">* <?php echo $genderErr;?></span>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
<?php
echo "<h2>Your Input:</h2>";
echo $name;
echo "<br>";
echo $email;
echo "<br>";
echo $website;
echo "<br>";
echo $comment;
echo "<br>";
echo $gender;
?>

Twig: filter vs funciton?

Twig: filter vs funciton?

When should some functionality be created as a filter instead of a
function and vice versa?
user | function
vs
function(user)
Thanks.

Android creating internal gps points

Android creating internal gps points

I would like to be able to label specific internal points on a gps from a
specific building. For example: Using a blueprint from your house, we
label each room in the home with a specific gps point, like: "my room",
"living room", "bathroom", etc. I'm not sure exactly how to approach this
issue.

Get the first two distinct successors of a string from List

Get the first two distinct successors of a string from List

Consider the following example
List<string> subList1 = new List<string>();
subList1.Add("start");
List<string> subList2 = new List<string>();
subList2.Add("start");
subList2.Add("string1");
subList2.Add("string2");
List<string> subList3 = new List<string>();
subList3.Add("start");
subList3.Add("string3");
subList3.Add("string4");
subList3.Add("string5");
List<string> subList4 = new List<string>();
subList4.Add("start");
subList4.Add("string3");
subList4.Add("string6");
List<List<string>> mainList = new List<List<string>>();
mainList.Add(subList1);
mainList.Add(subList2);
mainList.Add(subList3);
mainList.Add(subList4);
So now if my
search string ="start" , output = {"string1" , "string3"}
search string ="string3" , output = {"string4" , "string6"}
Any suggestions?

gnuplot option 'set fit quiet' not recognised on Gnuplot Version 4.4, patchlevel 3

gnuplot option 'set fit quiet' not recognised on Gnuplot Version 4.4,
patchlevel 3

I have Gnuplot Version 4.4, patchlevel 3 installed. According to synaptic,
this is the latest version. However when I try to use the option 'set fit
quiet', gnuplot does not recognise it, and says 'unknown --- expected
'logfile' or [no]errorvariables'. I would like to use this option as, if
it works, all of the text produced to the screen when gnuplot fits some
data would no longer go to the screen, and this should speed up the rate
at which gnuplot makes the fit. Does anyone else have this issue? Perhaps
it is related to the patchlevel 3 I have installed??? How would I update
the patchlevel if this is the case? Thanks for any help you can offer me,
Cheers, Rory.

Sunday, 15 September 2013

Using a constructor inside of main [on hold]

Using a constructor inside of main [on hold]

I am in need of some help for my homework
In the same bluej project, create a new class named TestPickle with a main
method. Do the following in that main method.
Create a new Pickle object named p1 using the no-parameter constructor.
Create a new Pickle object named p2 using the parameter constructor. Pass
the values 10 and "Gherkin" as arguments in the constructor.
Set p1's type to "Sweet" using the appropriate mutator.
Set p2's weight to 6 using the appropriate mutator
I have already finished the first part of this assignment and I am now
stuck on this part. I need help with how to make the constructor within
the main method. Any input would be greatly appreciated.
Here is the code I have so far,
public class TestPickle {
public ex(int p1, int p2)
{
this.p1 = p1
this.p2 = p2
}
public static void main(String[] args)
{
System.out.printf("\t%-12s%-12s\n", "Type", "Weight");
System.out.printf("\t%-12s%-12s\n", p1.getType(), p1.getWeight());
System.out.printf("\t%-12s%-12s\m", p2.getType(), p2.getWeight());
}
}
The printf functions are there as described in the assignment

html to json on fly library using nodejs

html to json on fly library using nodejs

can someone suggest me a library where can parse on fly html to JSON using
NodeJS.
Thanksin advice!
Something similar to
yahoo console link

PHP CMS, When I upload the image it corrupts for some reason

PHP CMS, When I upload the image it corrupts for some reason

The image is being corrupted when uploaded to the database so i tried to
do the base64_encode but it didn't work any suggestions as to what i can
do ? its a school project and its due 2 more days hope you can help :/ thx
and appreciate the help.
<?php
session_start();
include_once('../includes/connection.php');
if(isset($_SESSION['logged_in'])){
if(isset($_POST['title'], $_POST['content'], $_POST['image'] )){
$title = $_POST['title'];
$image = $_POST['image'];
$image = base64_encode($image);
$content = nl2br($_POST['content']);
if(empty($title) or empty($content) or empty($content)){
$error = 'All fields are required';
} else{
$query = $pdo->prepare('INSERT INTO articles (article_title,
article_content, picture_upload) VALUES (?, ?, ?)');
$query->bindValue(1, $title);
$query->bindValue(2, $content);
$query->bindValue(3, $image);
$query->execute();
header('Location: index.php');
}
}
?>
<html>
<head>
<title>CMS</title>
<link rel="stylesheet" href="../assets/style.css"
</head>
<body>
<div class="container">
<a href="index.php" id="logo">CMS</a>
<br />
<h4>Add Article</h4>
<?php if(isset($error)){ ?>
<small style="color:#aa0000;"><?php echo $error;?> </small>
<?php } ?>
<br /><br />
<form action="add.php" method="post" autocomplete="off">
<input type="text" name="title" placeholder="Title" />
<br /><br /> <input type="file" name="image" id="file"><br><br />
<textarea rows="15" cols="50" placeholder="Content"
name="content"></textarea>
<input type="submit" value="Submit Article" />
</form>
</div>
</body>
<?php
} else{
header('Location index.php');
}
?>

Petclinic hibernate.dialect for HSQL

Petclinic hibernate.dialect for HSQL

I am trying to understand Spring Petclinic Application . By default it
seems that HSQL database and JPA is used . But I am unableto find where
the Hibernate.Dialect for HSQL is mentioned in the application . I
understand that it is a mandatory property for Hibernate . Kindly suggest

rails - single table inheritance and has_and_belongs_to_many (both inheriting tables with many to many relations with another model)

rails - single table inheritance and has_and_belongs_to_many (both
inheriting tables with many to many relations with another model)

class User ..
class UserA < User
class UserB < User
class Biscuit < Active...
Now, lets say, UserA has many biscuits and a biscuit has many UserA's.
Then we can do like:
class UserA < User
has_and_belongs_to_many :biscuits
end
class Biscuit < User
has_and_belongs_to_many :useras
end
Migration:
create_table :biscuits_users do |t|
#notice name: _users and not _useras. Biscuit instance expecting user
table name after underscore so may be if we can make biscuit expect
separately like biscuit_useras and biscuit_userbs. But not sure how to do.
t.belongs_to :usera
t.belongs_to :biscuit
end
Requirement:
What if both UserA and UserB has many to many relation with Biscuit?
Since, UserA and UserB has a common table, User, the migration table will
be biscuits_users whether we want it to be UserA or UserB.
Not just Biscuit that is having many to many with them. Many such models
have many to many relation with both UserA and UserB. So, how ?
Please let me know for more info.
Thanks.

HTTP Status 500 - Error applying layout [Grails]

HTTP Status 500 - Error applying layout [Grails]

Sometime when is run my app i get the following error. What causes this
error and how can I fix it?

Here is the stacktrace:
2013-09-15 07:34:14,903 [http-nio-80-exec-9] ERROR StackTrace - Full
Stack Trace:
org.codehaus.groovy.grails.web.pages.exceptions.GroovyPagesException:
Error applying layout : welcome2
at
org.codehaus.groovy.grails.web.sitemesh.SpringMVCViewDecorator.render(SpringMVCViewDecorator.java:74)
at
org.codehaus.groovy.grails.web.sitemesh.SpringMVCViewDecorator.render(SpringMVCViewDecorator.java:52)
at
org.codehaus.groovy.grails.web.sitemesh.GrailsPageFilter.doFilter(GrailsPageFilter.java:161)
at
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:369)
at
org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:109)
at
org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:83)
at
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:381)
at
org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:97)
at
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:381)
at
org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:78)
at
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:381)
at
org.springframework.security.web.authentication.rememberme.RememberMeAuthenticationFilter.doFilter(RememberMeAuthenticationFilter.java:112)
at
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:381)
at
org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:54)
at
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:381)
at
org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:187)
at
org.codehaus.groovy.grails.plugins.springsecurity.RequestHolderAuthenticationFilter.doFilter(RequestHolderAuthenticationFilter.java:40)
at
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:381)
at
org.codehaus.groovy.grails.plugins.springsecurity.MutableLogoutFilter.doFilter(MutableLogoutFilter.java:79)
at
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:381)
at
org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:79)
at
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:381)
at
org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:168)
at
org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:346)
at
org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:259)
at
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at
org.codehaus.groovy.grails.web.servlet.mvc.GrailsWebRequestFilter.doFilterInternal(GrailsWebRequestFilter.java:69)
at
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76)
at
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at
org.codehaus.groovy.grails.web.filters.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:66)
at
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76)
at
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at
org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88)
at
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76)
at
org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:346)
at
org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:259)
at
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at
org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at
org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at
org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
at
org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
at
org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at
org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1023)
at
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
at
org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1686)
at
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:724)

python 3.3 search for match in webpage results

python 3.3 search for match in webpage results

Good day, I have the following code, I am wondering how to search the
results for a match? I will be trying to match two to three words. I have
tried html2text, beautifulsoup, re.search, and several others. Wether ive
not implemented the things ive tried correctly, or they just dont work.
import requests
s = requests.session()
url = 'http://company.name.com/donor/index.php'
values = {'username': '1234567',
'password': '7654321'}
r = s.post(url, data=values)
# page which requires being logged in to view
url = "http://company.name.com/donor/donor.php"
# sending cookies as well
result = s.get(url)
Ive tried many different ways, just cant get it. I am wondering which
module I will need to be working with? And will i need to change the form
of data that "result" is in? One thing I havent tried is writing "result"
to a text file. I guess I could do that, and then search for my matches in
that file... Im just thinking there is a very simple way to do this.
thanks for any help or direction

Saturday, 14 September 2013

How to set foreign key in EntityTypeConfiguration Class

How to set foreign key in EntityTypeConfiguration Class

I just started to make EntityTypeConfiguration class and did following
public class Xyz
{
public int PlaceId { get; set; }
public string Name { get; set; }
public DbGeography Location { get; set; }
public int HumanTypeId { get; set; }
public int AddressId { get; set; }
}
and in EntityTypeConfiguration class
public sealed class XyzConfiguration:EntityTypeConfiguration<Xyz>
{
public XyzConfiguration()
{
ToTable("Place", "dbo");
HasKey(p => p.PlaceId);
Property(p => p.PlaceId)
.HasColumnName("PlaceId")
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
Property(p => p.Name);
Property(p => p.Location). ;
Property(p => p.HumanTypeId);
Property(p => p.AddressId);
}
}
Now how to set DbGeography and foreign key columns HumanTypeId , AddressId ?
Thanks in advance

Selecting macports python as default in non-admin account

Selecting macports python as default in non-admin account

I have two accounts on my system, an admin account and a user account.
I use the admin account to install macport and have set the default python
using
sudo port select --set python python27
On the user account I can run all the python I need using
/opt/local/bin/python
but how do I select that to be default?
port select --list python
reports
python27 (active)
but
which python returns
/usr/bin/python

drupal 7 file_save_upload returning false

drupal 7 file_save_upload returning false

I have a custom form, with a field for the user to upload an image file
(their logo). In the form validate hook, I've implemented
file_save_upload, which is continually returning false. I can see that the
file is in fact being saved in the correct location on upload, so why
isn't file_save_upload working?
The form field:
$form['company_logo'] = array(
'#type' => 'managed_file',
'#title' => t('Company Logo'),
'#description' => t('Allowed extensions: gif png jpg jpeg'),
'#upload_location' => 'public://uploads/',
'#upload_validators' => array(
'file_validate_extensions' => array('gif png jpg jpeg'),
// Pass the maximum file size in bytes
//'file_validate_size' => array(MAX_FILE_SIZE*1024*1024),
),
);
The validation hook:
$file = file_save_upload( 'company_logo' , array(),
'public://uploads/', FILE_EXISTS_RENAME);
if (!$file) {
form_set_error('company_logo', t('Unable to access file or file is
missing.'));
}

Drag & Drop on Div Elements

Drag & Drop on Div Elements

I have a image gallery of 12 images sitting in 12 div containers. All 12
are hard coded, if there is no image, there will be an Empty-Image. Cant
change much on that code, too hard implementet.
Now i wanna have a Drag & Drop-System in which I can sort these 12 Images
& Div-Containers for the order who will it be displayed the next request.
How to do?

Android Calendar styling

Android Calendar styling

I have tried this answer to change my calendarview's style: Change
CalendarView style but it has given me errors onthe items that the are
undefined

Apache TeeOutputStream usage on an InputStream (tee an InputStream)

Apache TeeOutputStream usage on an InputStream (tee an InputStream)

I've adapted the Apache IOUtil sample to work with the WeatherTelnet
sample a little differently. While the comments for WeatherTelnet state
that:
The TelnetClient class used by itself is mostly intended for automating
access to telnet resources rather than interactive use.
I would like to split the output using Apache TeeOutputStream, but the API
branches OutputStream whereas TelnetClient "output" is in the form of an
InputStream, so that, of course, it can be read. Conveniently, the Apache
copyStream utility method will copy an InputStream to an OutputStream.
1.) How do I copy the InputStream to an OutputStream in printKindaWorks or
printToFile? 2.) How do I either write the OutputStream to a file, or tee
it?
the trick is to do these operations live, while the user interacts with
the weather server.
I did my best to look at the source code for copyStream and used that for
reference, but it just plain doesn't work. I haven't yet looked at the
internals for the Apache implementation of tee.
The utility class:
package apache;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.commons.net.io.Util;
public final class IOUtil {
private static final Logger log =
Logger.getLogger(IOUtil.class.getName());
private static void readFromConsole(final OutputStream outputStream) {
Thread read = new Thread() {
@Override
public void run() {
int ch;
try {
while ((ch = System.in.read()) != -1) {
outputStream.write(ch);
outputStream.flush();
}
} catch (IOException ioe) {
log.warning(ioe.toString());
}
}
};
read.start();
}
private static void writeToConsole(final InputStream inputStream) {
Thread write = new Thread() {
@Override
public void run() {
try {
Util.copyStream(inputStream, System.out);
} catch (IOException ioe) {
log.warning(ioe.toString());
}
}
};
write.start();
}
private static void printKindaWorks(final InputStream inputStream) {
Thread write = new Thread() {
@Override
public void run() {
PrintStream printStream = null;
try {
File file = new File("weather.log");
FileOutputStream fos = new FileOutputStream(file, true);
printStream = new PrintStream(fos);
Util.copyStream(inputStream, printStream);
} catch (IOException ioe) {
log.warning(ioe.toString());
}
}
};
write.start();
}
// TeeOutputStream tee = new TeeOutputStream(inputStream,
bis);
private static void writeToFile(final InputStream inputStream) throws
FileNotFoundException, IOException {
final String fname = "whether.log";
File f = new File(fname);
f.createNewFile();
Thread fileWriter = new Thread() {
@Override
public void run() {
char c = 0;
int r = 0;
try {
while ((r = inputStream.read()) != -1) {
c = (char) r;
PrintWriter out = new PrintWriter(new
BufferedWriter(new FileWriter(fname, true)));
out.print(c);
out.close();
}
} catch (IOException ex) {
Logger.getLogger(IOUtil.class.getName()).log(Level.SEVERE,
null, ex);
}
}
};
fileWriter.start();
}
public static void readWriteLog(final InputStream inputStream, final
OutputStream outputStream) throws FileNotFoundException, IOException {
readFromConsole(outputStream);
writeToConsole(inputStream);
writeToFile(inputStream); //doesn't write much
// printKindaWorks(inputStream); //blocks writeToConsole ?
}
}
and the driver:
package weather;
import apache.IOUtil;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import org.apache.commons.net.telnet.TelnetClient;
public class Weather {
public Weather() {
}
public static void main(String[] args) throws UnknownHostException,
IOException {
int port = 3000;
InetAddress host =
InetAddress.getByName("rainmaker.wunderground.com");
TelnetClient telnetClient = new TelnetClient();
telnetClient.connect(host, port);
IOUtil.readWriteLog(telnetClient.getInputStream(),
telnetClient.getOutputStream());
}
}
Please consider the code under the ASL.

Returning Multiple Values From Map

Returning Multiple Values From Map

Is there a way to do:
a = b.map{ |e| #return multiple elements to be added to a }
Where rather than returning a single object for each iteration to be added
to a, multiple objects can be returned.
I'm currently achieving this with:
a = []
b.map{ |e| a.concat([x,y,z]) }
Is there a way to this in a single line without having to declare a = []
up front?

Friday, 13 September 2013

Maping json in into ember model

Maping json in into ember model

i have custom url for getting and saving json from server so i created an
object for getting json :
App.Cubes = Ember.Object.extend();
App.Cubes.reopenClass({
findAll: function() {
var c = Ember.A();
var xhr = $.ajax({
type: 'POST',
dataType: 'json',
contentType: 'application/json',
url: 'http://localhost:9095/service.asmx/getCubes',
data: '{}',
success: function(response) {
var data = JSON.parse(response.d);
$.each(data, function(i, v) {
c.pushObject(App.Cubes.create(v));
});
}
});
return c;
}
});
but i need to map these json to model like :
OlapApp.Cube = DS.Model.extend({
name: DS.attr('string'),
uniqueName: DS.attr('string')
});
and then using Cube model not using Cubes Object? but i dont know how to
map these json or Cubes object to Cube model.

Delete SQL Query

Delete SQL Query

I want to delete rows of a column on the basis of condition of another
column. For example:
DELETE FROM table_name column_name WHERE another_column_name='some value';

Reset all javscript-applied styles

Reset all javscript-applied styles

Let's say we have this
var e = document.getElementById("someElement");
e.style.borderColor = "gold";
e.style.background = "yellow";
e.style.padding = "5px";
// more style modifications via javascript
There may have been other styles set inline or in an external CSS file.
Is there a method to clear all Javascript-applied styles? Like e.style.* =
inherit or e.removeJavaScriptAppliedStyles().

How to Create a Simple To Do Script on Windows

How to Create a Simple To Do Script on Windows

I built simple todo script that adds a text file to desktop for every todo
item. I need help to simplify the process of launching this script:
Step 1) Create todo.bat file on Desktop, with the following command
echo.>%1.txt
Step 2) Right-click on Desktop > Open Command Window here
Step 3) Type:
todo remember-the-milk
Step 4) Exit Command Line
Step 5) Notice that Desktop now contains
remember-the-milk.txt
I am running Windows 8.1, and I used a batch file to make this script
work, but I'm open to suggestions.
Thanks in advance.
P.S. Zach Holman from GitHub was able to accomplish this script using
UNIX. See: http://zachholman.com/posts/inbox-zero-everything-zero/

How does rails compiles the application.scss to public/aplication.css?

How does rails compiles the application.scss to public/aplication.css?

I am using rails 4 with sass rails
gem "sass-rails", "~> 4.0.0"
I upgrade a hello rails application from 3.2 to rails 4.0. I have an
application.css.scss file and running rake assets:precompile I don't get
any errors, there is a file public/application.css from a previous
precompile command I guess and from my broswer I can see that is the one
rails loads. The problem is that is not been updated. How can I compile
the application.css.scss over a previous one.

Place element inside other element using absolute. Elements are siblings

Place element inside other element using absolute. Elements are siblings

I am trying to place an element, "inner", flush against the upper right
hand corner of another div, "outer", using absolute positioning. The
"inner" element is not a child of "outer". I therefore need to look up the
positioning of "outer" using js and use that.
However, it's not coming out quite right:
http://jsfiddle.net/BZBSF/1/
#wrapper{background:red
;
width:100px;
height:100px;}
#inner{
position:absolute;
background:green;
width:50px;
height:100px;
margin:0;padding:0;
}
#body{position:relative;}
<div id = "body">
<div id = "wrapper"></div>
<div id = "inner"></div>
</div>
var rect = document.getElementById("wrapper").getBoundingClientRect();
$("#inner").css({ 'top': String($(window).scrollTop()+rect.top)+"px" });
width_inner = $("#inner").width();
$("#inner").css({ 'left':
String($(window).scrollLeft()+rect.right-width_inner)+"px" });

AngularJS: Communication between directives

AngularJS: Communication between directives

I'm writing a directive which creates an mp3/audio player. The issue is
that you can have many audio players in one page. What I would like to do
is when one is playing and you start an other, that the one currently
playing pauses. How can I achieve this with angular directives?
Thanks in advance!

Thursday, 12 September 2013

How to focus on a newly created input element in Meteor

How to focus on a newly created input element in Meteor

Consider this requirement.
In template, there is
a button to insert a blank record into Meteor Collection
a list of input element represented the collection which can edit value of
the record
When I pressed the button, the input element with blank record will be
displayed into html because of Meteor's reactivity. But how to set the
input to be auto-focused when created?
I know maybe setting an ID into session and judging it in rendered fuction
will be a solution. Is there any easier way to implement that?

Audio Panning using DirectX

Audio Panning using DirectX

I'm creating a video player that plays on two external screens. For the
two screens there is a button for the left and right screen. For each
screen I want to pan the audio to the left and to the right respectively.
I've added this into my btnRightPlay, however the audio still does not
play on the right channel only. Does anyone have an advice on this? Do I
need to add a buffer?
Pan.Right.Equals(10000);

MouseListener in Java

MouseListener in Java

I would like to create method that allows me to move an object along the
path created by all the clicks I execute in a JFrame panel. Can someone
please help me to do it? I am trying with MouseClicked event but still no
result, don't know how to make the first click link to the path of the
second and so one when it is not a straight horizontal or vertical line.

Center Map based on Route

Center Map based on Route

How do I center the Google Map based on the center-point of the route,
without using fitbounds? Is it possible to use map.setCenter? I have
commented out the line that I need I need help with.
google.maps.event.addListener(dr, 'directions_changed', function() {
var route = dr.getDirections().routes[0];
var path = route.overview_path;
es.getElevationAlongPath({
path: path,
samples: Math.max(50, path.length * 2)
}, function(result, status) {
if (status == google.maps.ElevationStatus.OK) {
drawElevation(result);
recalcHeight();
if (fitBounds) {
map.setZoom(route.bounds);
//map.setCenter();
fitBounds = false;
}
}
else {
$('#error').text(status).show();
}
recalcHeight();
});
});

merging changes beteen two tags onto another branch - CVS

merging changes beteen two tags onto another branch - CVS

I want to merge the changes made to all the files between two tags and
merge those changes with another branch in CVS.
I can get the files changed from cvs diff -N -c -r revison_1 -r revision_2
| grep "Index:" > diff.out
but hw to merge the changes made to these files to a different branch.
thanks

$stdout puts not working

$stdout puts not working

Hey I'm reading the Well-Grounded Rubyist and I can't seem to get the file
output to work correctly.
record = File.open("/tmp/record", "w")
old_stdout = $stdout
$stdout = record
$stderr = $stdout
puts "This is a record"
z = 10/0
I can't seem to get the output to a file when I run it from command line
or pry. Any ideas why this wouldn't work?

how can we implement compare method of compartor class

how can we implement compare method of compartor class

how can we implement compare method based on employee Id?
public int compare(Employee emp1, Employee emp2) {
throw new UnsupportedOperationException("Not supported yet.");
if(emp1.getEmpid()<emp2.getEmpid())
{
return -1;
}
else if(emp1.getEmpid()>emp2.getEmpid())
return 1;
else
return 0;
}

Wednesday, 11 September 2013

canceling oid request in NDIS driver

canceling oid request in NDIS driver

How to cancel oid request. Can anybody please tell me detailed procedure?
Suppose NDIS sends any request to miniport driver. How driver will cancel
the request and send it to the miniport driver.

How to do a search with SearchWidget

How to do a search with SearchWidget

I have already set up the search widget on the action bar as per
viperbone's answer on How to add a SearchWidget to the ActionBar?, however
I don't know what to put in the Search class to process the query.
All the items I want to search are in a simple ArrayList of Strings. I can
handle the comparator, I just don't know how to pass the ArrayList and the
query to the class to process it.
Please don't send me links, especially to the Android Developer site,
because it is VERY confusing to me. I would really appreciate it if you
could write some code for me to use specific to my situation.
Thanks in advance

What am I doing wrong while parsing this XML

What am I doing wrong while parsing this XML

I'm trying to parse an xml that has the following structure
And here's the code snippet Ive written to parse it
doc.getDocumentElement().normalize();
System.out.println ("Root element: " +
doc.getDocumentElement().getNodeName());//prints
GoodReadsResponse correctly
NodeList bk = doc.getElementsByTagName("book");// single all
encompassing element in response
Node n= bk.item(1);// since the 0th node is id the 1st must be the
title
System.out.println("Node value"+n.getLocalName());
Element e=(Element)n;
NodeList titleList= e.getElementsByTagName("title");//get the title
Element titleElem = (Element) titleList.item(1);
Node titleNode = titleElem.getChildNodes().item(0);// get the node
value
book.setTitle(titleNode.getLocalName());// this prints null
instead of printing Hamlet--why??
System.out.println("Title in
parser"+titleNode.getLocalName());//null again
Any idea why this is happening? Pointers would be appreciated!

Rails loop arrangement

Rails loop arrangement

So I have some loops going on, but im trying to organize how the
information is displayed.
Im using bootstrap for the stylesheets.
Here is the loop:
<% @users.each do |i| %>
<h3><%= i.firstname %><%= i.lastname %></h3>
Birthday: <%= i.dateofbirth %><br />
Address: <%= i.address %><br />
City: <%= i.city %><br />
Province: <%= i.province %><br />
Phone Number: <%= i.phonenumber %><br />
Service Provider: <%= i.serviceprovider %><br />
Gender: <%= i.gender %><br />
Languages: <%= i.languages %><br />
<% end %>
<% @apps.each do |f| %>
<h3>School Information</h3>
Highschool: <%= f.highschool %><br />
Address: <%= f.highschool_address %><br />
City: <%= f.highschool_city %><br />
Province: <%= f.highschool_province %><br />
Postal Code: <%= f.highschool_postalcode %><br />
<h4>Post Secondary Schools of Interest</h4>
<% f.postsecondaries.each do |ps| %>
Post Secondary Name: <%= ps.postsecondary %><br />
Address: <%= ps.postsecondary_address %><br />
City: <%= ps.postsecondary_city %><br />
Province: <%= ps.postsecondary_province %><br />
Postal Code: <%= ps.postsecondary_postalcode %><br />
Country: <%= ps.postsecondary_country %><br />
Program: <%= ps.postsecondary_program %><br />
Faculty: <%= ps.postsecondary_faculty %><br />
Status: <%= ps.postsecondary_status %><br />
<% end %>
<h3>Grades</h3>
<% f.grades.each do |grade| %>
<br />Course: <%= grade.course %><br />
Grade: <%= grade.course_grade %>
<% end %>
<h3>Extracurricular Activities</h3>
<% f.extra_activities.each do |e| %>
Activity: <%= e.activity %><br />
Position: <%= e.activity_position %><br />
Dates: <%= e.activity_dates %><br />
Times Per Week: <%= e.activity_timeperweek %><br />
Contact Name: <%= e.activity_contact %><br />
Contact Position: <%= e.activity_contact_position %><br />
Contact Phone Number: <%= e.activity_contact_phonenumber %><br />
Contact Email: <%= e.activity_contact_email %><br />
Description: <%= e.activity_description %>
<% end %>
<h3>Paragraph</h3>
Recall a time... <%= f.recall_a_time %><br />
Description: <%= f.paragraph_description %>
<br />Recall a time... <%= f.recall_a_time_two %><br />
Description: <%= f.paragraph_description_two %>
<br />Recall a time... <%= f.recall_a_time_three %><br />
Description: <%= f.paragraph_description_three %>
<% end %>
I cant get the school information to be posted in the same bootstrap well
that users information is stored.

atmega8a fuses external crystal 16MHz

atmega8a fuses external crystal 16MHz

I´am working in a project with the atmel atmega8a MCU. I´ve designed a
code that works with an external 16MHz crystal. For that reason i burn the
atmega8a´s fuses with the AVRISPmkII programer (HIGH FUSE:C9 LOW FUSE:FF)
for a external 16MHz crystal. I test the functionality of the system with
a atmega8a PU and this works perfectly. Now i´m trying to do the same in a
PCB with the atmega8a AU but the burn fuses process don´t work in the same
way. After this process the atmega8a AU MCU doesn´t work again and the
programer can´t recognize it.
It´s something different in the burn fuses process between the atmega8a PU
and the atmega8a AU? anybody knows why happens this???
I hope you can help me with this trouble. I´ll been waiting your answer.
Thanks a lot.

PostgreSQL conditional conjunction and disjunction in one query

PostgreSQL conditional conjunction and disjunction in one query

How to create a query which selects products of given features where
feature statement is formed by "and" or "or" condition depending on a
group they belong to?
Description of the situation
There is a store with products.
Products may have features or not.
A customer looks for specific features of products which means filling out
the form and sending an array of feature ids.
In the database, each feature belongs to only one group of features.
The first group (disjunction attribute is true, called "OR") allows to
display the product if one of the features matches any feature submitted
by the customer.
Example: selecting shapes: circle, square, triangle displays products
which are circles or squares or triangles.
The second group (disjunction attribute is false, called "AND") allows to
display the product only if the product has all of the features submitted
by the customer.
Example: selecting colors: red, green, blue displays products which are
red and green and blue.
Test environment
http://sqlfiddle.com/#!12/f4db7
"OR" Query
It works except for those product which have no features.
SELECT product_id
FROM product_features
WHERE product_features.feature_id IN (
SELECT feature_id FROM features
LEFT JOIN feature_groups
ON features.feature_group_id = feature_groups.feature_group_id
WHERE feature_id IN (11, 12, 13) AND feature_groups.disjunction = TRUE
)
GROUP BY product_id
"AND" Query
This query cannot be used because the number of features where disjunction
is false is not known.
SELECT product_id FROM product_features
WHERE feature_id IN (43, 53, 63)
GROUP BY product_id
HAVING COUNT(DISTINCT feature_id) = 3

Getting Text from ComboBox in WPF

Getting Text from ComboBox in WPF

I have a ComboBox in WPF and I cant access its selected item text.
I have tried
cbItem.Text;
cbItem.SelectedItem.ToString();
XAML:
<ComboBox Name="cbItem" SelectedValuePath="ITEM_ID">
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding ITEM_NAME}" />
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>

What is new in Facebook 6.4.2?

What is new in Facebook 6.4.2?

What is new in Facebook 6.4.2 ? I tried on google but could not found any
useful..

Tuesday, 10 September 2013

Masking sprites in cocos2d for android

Masking sprites in cocos2d for android

I want to develop a game like jigsaw where the player will attach pieces
of puzzle to match to a sprite.For this I've figured out to do Masking. I
even found one class in cocos2d for iphone named CCMask that does this
task pretty well. However when I try to port this to the java code for use
with cocos2d-android I get Null pointer exception at CCRenderTexture. The
class that I am trying to port is here.
Somewhere I read that if I do CCRenderTexture under the layer's onEnter
callback the code will not crash and it doesn't crash when I do it like
that. But then I don't get any masked sprite either as I have to add the
CCMask class as a child to a layer to call the onEnter method.
Can anybody help me with the proper flow of the code or by confirming that
it really works for cocos2d-android. This is the link for the library that
I am using.

how to synchronize data between DAL and classes that created the object

how to synchronize data between DAL and classes that created the object

For example, I have three classes named TriggerBLL. TriggerDAL and Scheduler.

1.TriggerBLL.LoadFrom(string xmlContent) method will create a Trigger
object from xml string such as

<trigger id="15" name="trigger1" />

2. TriggerDAL.AddTrigger(Trigger t) will save a trigger object into a
table in database which id is set to auto increase.

3. Scheduler will use trigger's id to do some operations.


Thus the question is, when the trigger table in database is empty. it's
trigger id may start from 1, but the trigger object created from
TriggerBLL may have its id set to 15, how can Scheduler get the trigger
object which owns database's id instead of TriggerBLL's ?

Add a domain to an Azure web site via code

Add a domain to an Azure web site via code

How do I programmatically add an additional domain name to an Azure Web Site?
Hopefully there .NET API for this that I missed, perhaps in the Azure SDK
or a NuGet package. Or perhaps there is a REST interface.

AS3 Calling Function containing startDrag from another function

AS3 Calling Function containing startDrag from another function

I got 2 objects and a number of hitbox "nodes", if you release on the node
it hides the object and puts up a dummy object. when you click the object
it brings back the old object and hides the dummy .
what im having trouble with is clicking the dummy object and starting drag
on the original object from the dummy object.the objects are not dragging.
// code located on dummy object
hideb.addEventListener(MouseEvent.MOUSE_DOWN, hideEventab);
function hideEventab(event:MouseEvent):void
{
this.visible = false;
// this statment finds out if its object 1 or object 2
if (currentFrame == 1 )
{
MovieClip(parent.parent).VoltageAs.redBtn1.visible = true;
MovieClip(parent.parent).VoltageAs.dragcurrentClip7 =
MovieClip(parent.parent).VoltageAs.redBtn1;
MovieClip(parent.parent).VoltageAs.item_onMouseUp3(null);
}
else if (currentFrame == 2 )
{
MovieClip(parent.parent).VoltageAs.blkbtn1.visible = true;
MovieClip(parent.parent).VoltageAs.dragcurrentClip7 =
MovieClip(parent.parent).VoltageAs.blkbtn1;
MovieClip(parent.parent).VoltageAs.item_onMouseUp3(null);
}
}
and next
// this function is supposed to be called when you click the dummy object.
function item_onMouseDown3(event:MouseEvent):void
{
dragcurrentClip7.y = mouseY;
dragcurrentClip7.x = mouseX;
startX7 = dragcurrentClip7.x;
startY7 = dragcurrentClip7.y;
dragcurrentClip7.startDrag();
trace(dragcurrentClip7.name);
stage.addEventListener(MouseEvent.MOUSE_UP, item_onMouseUp3);
if (dragcurrentClip7 == redBtn1 || dragcurrentClip7 == blkbtn1)
{
dragcurrentClip7.nextFrame();
}
}

Posting to Ruby on Rails JSON PUT

Posting to Ruby on Rails JSON PUT

I am trying to post to the following method /users.json
Here's my code in Ruby on Rails
# POST /users
# POST /users.json
def create
@user = User.new(user_params)
respond_to do |format|
if @user.save
format.html { redirect_to @user, notice: 'User was successfully
created.' }
format.json { render action: 'show', status: :created, location:
@user }
else
format.html { render action: 'new' }
format.json { render json: @user.errors, status:
:unprocessable_entity }
end
end
end
and inside my user params
def user_params
params.require(:user).permit(:name, :password, :password_confirmation,
:avatar)
end
I am using chrome Advanced REST client to post
(http://postimg.org/image/fphun12fx/)

Rails kept giving me error stating param not found :user, how do I create
the param for user?
Also, if we have the parameter :user, does it mean for jQuery ajax, I
would have to do something like the below?
data: { user: {name: xx, password: xx, password_confirmation: xx} }

Sencha Touch testing build not working

Sencha Touch testing build not working

I've finished my first app using sencha touch 2.2.1. Now I uploaded it
onto my server and tried to access it with my phone. Everything works
well. My Dashboard contains 6 buttons, but only 1 of them is working. Each
other throws the following error
TypeError: 'undefined' is not an object (evaluating 'name.substring')
The error occurs in the function parseNamespace. But I don't know what is
wrong. I build the app using Sencha Architect and in the preview
everything was fine. The testing package was created using the
build-button from architect. If anyone could help me, the app is located
here: app.ttv-rees-groin.de
Many thanks

Storing in array or in fields? Which is better?

Storing in array or in fields? Which is better?

Today I was working on my website and I asked myself a simple question.
Does storing an array with all informations is better than saving those
one in different fields?
For example if I store an ID, a password and a number in one field on the
database in this way
+-------------+----------------------------------------------------------------+
| Field | Value
|
+-------------+----------------------------------------------------------------+
| all |
["1","fa26be19de6bff93f70bc2308434e4a440bbad02","25468684888"] |
+-------------+----------------------------------------------------------------+
Is it better than saving it in this way?
+-------------+------------------------------------------+
| Field | Value |
+-------------+------------------------------------------+
| id | 1 |
| password | fa26be19de6bff93f70bc2308434e4a440bbad02 |
| number | 25468684888 |
+-------------+------------------------------------------+
I think that the first method is faster than the last one because you need
only to SELECT one field and not three or more. What do you think about
it?

Using RibbonTab for the Ribbon control in Visual Studio 2012

Using RibbonTab for the Ribbon control in Visual Studio 2012

I have problems using the ribbon control for visual studio 2012. I simply
need to create tabs, but for whatever reason they are not displayed
properly. Here is my code:
<Window x:Class="Arelion.InternalProjects.RouteVisualization.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Route Visualization" Height="350" Width="525">
<Grid>
<Ribbon Name="ribbon">
<RibbonTab Name="ribbonTab1" IsSelected="True">
Tab1
</RibbonTab>
</Ribbon>
</Grid>
</Window>
Thanks

Monday, 9 September 2013

Kendo UI grid. Not transmitted parameters - pageSize and Skip

Kendo UI grid. Not transmitted parameters - pageSize and Skip

This is my code:
var crudServiceBaseUrl = "/admin",
dataSource = new kendo.data.DataSource({
serverPaging: true,
pageSize: 2,
type: 'json',
transport: {
read: {
url: crudServiceBaseUrl + '/user'
},
update: {
url: function (item) {
return crudServiceBaseUrl + "/user/update/" + item.id
},
dataType: "json"
},
destroy: {
url: crudServiceBaseUrl + "/user/destroy",
dataType: "json"
},
create: {
url: crudServiceBaseUrl + "/user/create",
dataType: "json"
},
parameterMap: function (options, operation) {
if (operation !== "read" && options.models) {
return {models: kendo.stringify(options.models)};
}
}
},
batch: true,
schema: {
data: function (rawData) {
return rawData[0].data;
},
total: function (rawData) {
return rawData[1].total;
}
}
});
$("#users").kendoGrid({
dataSource: dataSource,
navigatable: true,
pageable: true,
selectable: "multiple",
sortable: {
mode: "single",
allowUnsort: false
},
height: 430,
toolbar: ["save", "cancel"],
columns: [
{ field: "id", title: "ID", width: 20},
{ field: "username", title: "E-mail", width: 110 },
{ field: "firstname", title: 'firstname', width: 110 },
{ field: "lastname", title: 'lastname', width: 110 },
{ field: "activated", title: 'Activated', width: 110 },
{ field: "disabled", title: 'Disabled', width: 110 },
{ command: ['edit', 'destroy'], title: " ", width: 90 }
],
editable: 'popup'
});
But when i try to click on "page two", parameters "skip" and "pageSize"
not transmitted. I getting this url "/admin/list" without parameters. What
i doing wrong?