Monday, April 23, 2012

Display Tweets In Readable Format In Tweepy

How can I make tweepy return actual tweets, I mean it should display tweets in human readable format?



I don't want it to return tweets like this:



   <tweepy.models.Status object at 0x95F1ABPo>


Codes



  def tweetstream(request):
consumer_key=""
consumer_secret=""
access_token=""
access_token_secret=""
auth=tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api=tweepy.API(auth)
statuses=Cursor(api.list_timeline, owner='', slug='').pages()
for status in statuses:
print status
return render_to_response('dash.html',{'statuses': statuses},context_instance=RequestContext(request))




Java StackOverflowError after putting ArrayList to HashMap

Hello, can somebody explain to me why this block of code doesn't work?



ArrayList<Object> list = new ArrayList<Object>();
list.add(list);

HashMap<Object, Integer> map = new HashMap<Object, Integer>();
map.put(list, 1);


After I put list to map, it throws StackOverFlowError.



I know this code doesn't make any sense, I just want to know why it's not working.



Thanks!



Edit:



stacktrace:



Exception in thread "main" java.lang.StackOverflowError
at java.util.ArrayList.get(Unknown Source)
at java.util.AbstractList$Itr.next(Unknown Source)
at java.util.AbstractList.hashCode(Unknown Source)
at java.util.AbstractList.hashCode(Unknown Source)
...




Multi-level navigation controller on left-hand side of UISplitView with a small twist

I'm trying make something similar to (but not exactly like) the email app found on the iPad.



Specifically, I'd like to create a tab-based app, but each tab would present the user with a different UISplitView.



Each UISplitView contains a Master and a Detail view (obviously).



In each UISplitView I would like the Master to be a multi-level navigational controller where new UIViewControllers are pushed onto (or popped off of) the stack. This type of navigation within the UISplitView is where the application is similar to the native email app.



To the best of my knowledge, the only place that has described a decent "splitviewcontroller inside of a uitabbarcontroller" is here: http://stackoverflow.com/questions/2475139/uisplitviewcontroller-in-a-tabbar-uitabbarcontroller and I've tried to follow the accepted answer.



The accepted solution seems to work for me (i.e., I get a tab-bar controller that allows me to switch between different UISplitViews).



The problem is that I don't know how to make the left-hand side of the UISplitView to be a multi-level navigation controller.



Here is the code I used within my app delegate to create the initial "split view 'inside' of a tab bar controller" (it's pretty much as suggested in the aforementioned link).



- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {    

NSMutableArray *tabArray = [NSMutableArray array];

NSMutableArray *array = [NSMutableArray array];
UISplitViewController *splitViewController = [[UISplitViewController alloc] init];
MainViewController *viewCont = [[MainViewController alloc] initWithNibName:@"MainViewController" bundle:nil];
[array addObject:viewCont];
[viewCont release];
viewCont = [[DetailViewController alloc] initWithNibName:@"DetailViewController" bundle:nil];
[array addObject:viewCont];
[viewCont release];
[splitViewController setViewControllers:array];
[tabArray addObject:splitViewController];
[splitViewController release];



array = [NSMutableArray array];
splitViewController = [[UISplitViewController alloc] init];
viewCont = [[Master2 alloc] initWithNibName:@"Master2" bundle:nil];
[array addObject:viewCont];
[viewCont release];
viewCont = [[Slave2 alloc] initWithNibName:@"Slave2" bundle:nil];
[array addObject:viewCont];
[viewCont release];
[splitViewController setViewControllers:array];
[tabArray addObject:splitViewController];
[splitViewController release];

// Add the tab bar controller's current view as a subview of the window
[tabBarController setViewControllers:tabArray];

[window addSubview:tabBarController.view];
[window makeKeyAndVisible];

return YES;
}


the class MainViewController is a UIViewController that contains the following method:



- (IBAction)push_me:(id)sender {
M2 *m2 = [[[M2 alloc] initWithNibName:@"M2" bundle:nil] autorelease];
[self.navigationController pushViewController:m2 animated:YES];
}


this method is attached (via interface builder) to a UIButton found within MainViewController.xib
Obviously, the method above (push_me) is supposed to create a second UIViewController (called m2) and push m2 into view on the left-side of the split-view when the UIButton is pressed.
And yet it does nothing when the button is pressed (even though I can tell that the method is called).



Thoughts on where I'm going wrong?



TIA!





Facebook like button gets URL correct but not the meta information

I'm implementing a like button but for some reason the info in the meta tags is not being transferred properly.



If I place the URL into the <fb:like></fb:like> tags then the correct URL is loaded into the wall post on FB. But the image and all the other items described in the meta tags doesn't post with it. If I leave the href out of the <fb:like></fb:like> tags then the link defaults to the page the like button is on. Unfortunately, I need to add some parameters to the link so when the user clicks through to the site from the FB post, it shows correctly.



I've run my link through the link linter and it still shows the same image and the basic site information in the wall post, not the image or the description in the meta tags that shows up in the linter.



Basically, it looks like some of my meta information is being ignored. What am I doing wrong? Is this a cache issue?



EDIT I just tested this in IE and I get an error where the like button should be that says the page can not be found...



The head of the document:



<?xml version="1.0"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:og="http://ogp.me/ns#"
xmlns:fb="http://www.facebook.com/2008/fbml">
<head>
<meta property="og:title" content="Product Title" />
<meta property="og:type" content="product" />
<meta property="og:url" content="http://www.mysite.com/folder/folder/gateway.cfm?ifcn=1&amp;fbx=true&amp;type=product&amp;product=771&amp;page=gateway" />
<meta property="og:image" content="http://www.mysite.com/folder/folder/images/theImage.jpg" />
<meta property="og:site_name" content="My Site" />
<meta property="fb:admins" content="ADMIN_ID123" />


Just inside the body tag:



</head>
<body>
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({status: true, cookie: true,
xfbml: true});
};
(function() {
var e = document.createElement('script'); e.async = true;
e.src = document.location.protocol +
'//connect.facebook.net/en_US/all.js';
document.getElementById('fb-root').appendChild(e);
}());
</script>


My Like button:



<fb:like href="http://www.mysite.com/folder/folder/product.cfm?pid=562&ifcn=1&fbx=true&type=product&product=562&page=gateway " show_faces="false" width="450" font=""></fb:like>




Get gateway ip address in android

How to get gateway IP details , There is option using wifimanager but. If there is no wify how to find gateway,dns and other details in android device when connected using usb tethering.





Unexpected whitespace in python generated strings

I am using Python to generate an ASCII file composed of very long lines. This is one example line (let's say line 100 in the file, '[...]' are added by me to shorten the line):



{6 1,14 1,[...],264 1,270 2,274 2,[...],478 1,479 8,485 1,[...]}


If I open the ASCII file that I generated with ipython:



f = open('myfile','r')
print repr(f.readlines()[99])


I do obtain the expected line printed correctly ('[...]' are added by me to shorten the line):



'{6 1,14 1,[...],264 1,270 2,274 2,[...],478 1,479 8,485 1,[...]}\n'


On the contrary, if I open this file with the program that is suppose to read it, it will generate an exception, complaining about an unexpected pair after 478 1.
So I tried to open the file with vim. Still vim shows no problem, but if I copy the line as printed by vim and paste it in another text editor (in my case TextMate), this is the line that I obtain ('[...]' are added by me to shorten the line):



{6 1,14 1,[...],264 1,270      2,274 2,[...],478 1,4     79 8,485 1,[...]}


This line indeed has a problem after the pair 478 1.
I tried to generate my lines in different ways (concatenating, with cStringIO, ...), but I always obtain this result. When using the cStringIO, for example, the lines are generated as in the following (even though I tried to change this, as well, with no luck):



def _construct_arff(self,attributes,header,data_rows):
"""Create the string representation of a Weka ARFF file.
*attributes* is a dictionary with attribute_name:attribute_type
(e.g., 'num_of_days':'NUMERIC')
*header* is a list of the attributes sorted
(e.g., ['age','name','num_of_days'])
*data_rows* is a list of lists with the values, sorted as in the header
(e.g., [ [88,'John',465],[77,'Bob',223]]"""

arff_str = cStringIO.StringIO()
arff_str.write('@relation %s\n' % self.relation_name)

for idx,att_name in enumerate(header):
try:
name = att_name.replace("\\","\\\\").replace("'","\\'")
arff_str.write("@attribute '%s' %s\n" % (name,attributes[att_name]))
except UnicodeEncodeError:
arff_str.write('@attribute unicode_err_%s %s\n'
% (idx,attributes[att_name]))

arff_str.write('@data\n')
for data_row in data_rows:
row = []
for att_idx,att_name in enumerate(header):
att_type = attributes[att_name]
value = data_row[att_idx]
# numeric attributes can be sparse: None and zeros are not written
if ((not att_type == constants.ARRF_NUMERIC)
or not ((value == None) or value == 0)):
row.append('%s %s' % (att_idx,value))
arff_str.write('{' + (','.join(row)) + '}\n')
return arff_str.getvalue()


UPDATE: As you can see from the code above, the function transforms a given set of data to a special arff file format. I noticed that one of the attributes I was creating contained numbers as strings (e.g., '1', instead of 1). By forcing these numbers into integers:



features[name] = int(value)


I recreated the arff file successfully. However I don't see how this, which is a value, can have an impact on the formatting of *att_idx*, which is always an integer, as also pointed out by @JohnMachin and @gnibbler (thanks for your answers, btw). So, even if my code runs now, I still don't see why this happens. How can the value, if not properly transformed into int, influence the formatting of something else?





Integrate Cocos2d with Qualcomm's Augmented Reality SDK

I would like to integrate Qualcomm's Augmented Reality SDK with Cocos2d or 3d to create an app. I would like to do something similar to the multi markers example they have provided where I want it to recognize an object and have 2d images appear on the screen that is all apart of a game. I'm just not sure how to integrate the two together?





Paginatin not work after I add search bar for

I am facing an issue, I am using the parse framework, I need to add a search bar for my PFQueryTableViewController, I need to rewrite the below methods "number of sections", "number of rows in section" as well as "cell for row at index path".



After rewrite the above methods , I found that even through I enabled the pagination function, Seems the Load more label will not appear, Only the first 10(I set 10 per page) records can be displayed. I think you should have some logic to fetch the total record count if it is bigger than 10, then the load more will appears. So which method should I rewrite so that the pagination can work.





PHP Arrays: A good way to check if an array is associative or sequential?

PHP treats all arrays as associative, so there aren't any built in functions. Can anyone recommend a fairly efficient way to check if an array contains only numeric keys?



Basically, I want to be able to differentiate between this:



$sequentialArray = array('apple', 'orange', 'tomato', 'carrot');


and this:



$assocArray = array('fruit1' => 'apple', 
'fruit2' => 'orange',
'veg1' => 'tomato',
'veg2' => 'carrot');




Drupal 7 views - multiple contextual filters with spaces

I have a view with a contextual filter, which works fine - except that filter terms with spaces in don't work if I select 'Allow multiple values'. If I don't select this then the term with the spaces works fine. But I really need multiple values! Is there any way to work around this?





Silent exporting of globals using %GOF in Caché

I would like to know if it's possible to use "^%GOF" without user interaction. I'm using Caché 2008. ^%GO isn't an option as it's to slow. I'm using input from a temporary file for automatically answer the questions, but it can fail (rarely happens).



I couldn't find the routine of this utility in %SYS. Where is it located?



Thanks,



Answer: Using "%SYS.GlobalQuery:NameSpaceList" to get list of globals (system globals excluding).



Set Rset = ##class(%ResultSet).%New("%SYS.GlobalQuery:NameSpaceList")
d Rset.Execute(namespace, "*", 0)
s globals=""

while (Rset.Next()){
s globalName=Rset.Data("Name")_".gbl"
if (globals=""){
s globals = globalName
}else{
s globals = globals_","_globalName
}

d ##class(%Library.Global).Export(namespace, globals, "/tmp/export.gof", 7)


The only drawback is that if you have a namespace with concatination of globals exceeding the maximum allowed for a global entry, the program crashes. You should then split the globals list.





Generating all combinations using brute force

if we have a nxm array...for e.g...if n=3 and m=5



then our array will be of size 3x5 then there will be 15 different positions....we have to place m (5) tasks in different combinations....how much such different combinations can we make..?



i repeat....we have 15 positions according to above mentioned problem in the 2d array....we have to place 5 words in it...how many differnt combinations can we make and how?



plz help me to make a generic approach for a c++ program?



thanks in advance..





GWT data grid isn't presented

I'm trying to switch from CellTable to DataGrid. The actual change was very easy (APIs are the quite the same) - but I cannot get the grid to be visible without setting explicitly its width and height. In the CellTable it was enough to set width and height to 100% - and that is the behavior I want.



In my view I have two sections in HotrizontalPanel: one shows some tabs (buttons) and the other shows the grid. Each time a tab is clicked, the grid area is cleared and a new grid is created.



The view looks like this:



<ui:style>
.expanded {
width: 100%;
height: 100%;
}

.simpleContainer {
border-top: 5px solid #484848;
border-bottom: 5px solid #484848;
}
</ui:style>

<c:SimpleContainer addStyleNames="{style.simpleContainer} SimpleContainer">
<g:HorizontalPanel>
<g:HorizontalPanel ui:field="headersContainer"/>
<g:FlowPanel ui:field="tablePanel" styleName="{style.expanded}"/>
</g:HorizontalPanel>
</c:SimpleContainer>


And this is the snap of HTML from the running application:



<div class="GKQJTVMDCNC-com-mycode-management-client-ui-panels-PropertiesPaneView_PropertiesPaneUiBinderImpl_GenCss_style-simpleContainer SimpleContainer" id="x-widget-21" style="width: 1730px; height: 126px; ">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td align="left" style="vertical-align: top; ">....</td>
<td align="left" style="vertical-align: top; ">
<div class="GKQJTVMDBNC-com-mycode-management-client-ui-panels-PropertiesPaneView_PropertiesPaneUiBinderImpl_GenCss_style-expanded">
<div style="position: relative; overflow-x: hidden; overflow-y: hidden; " __gwtcellbasedwidgetimpldispatchingfocus="true" __gwtcellbasedwidgetimpldispatchingblur="true">
....
</div>
</div>
</td>
</tr>
</tbody>
</table>




The upper div has the right width and height, but somehow the DataGrid div has 1px height and 0px width (at list according to the chrome developer tool)



<div class="GKQJTVMDBNC-com-mycode-management-client-ui-panels-PropertiesPaneView_PropertiesPaneUiBinderImpl_GenCss_style-expanded">


Any idea?





IOS: nsstring leave some spaces

I have a particular problem:



in a NSSTring I have this value " abcdef ghil"
I want to check if first character is a space and delete it (with stringbyreplacing...?)
and in other space (from "f" to "g") I want insert a "-"



can you help me?



if it may be helpful; I take this string from a textfield...





Hql "in" statement doesn't work with an @ElementCollection



I have a class collection property with @ElementCollection and @Enumerated(EnumType.ORDINAL)

I am trying to perform an in statement on that collection however in the generated sql i get this -> {non-qualified-property-ref} in (?)



I might be doing something wrong while creating the hql itself. Could it be because the elements are actually enum values ?



Thanks,
Peter





xcode objective c - when I call 2 methods - only the last called method runs and first one is skipped

-(void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
{

[self NextHeading]; // this plays an mp3 file

[self NextHeadingMeaning]; // this plays an Mp3 file

}


Only [self NextHeadingMeaning] method is called and NextHeading method is missed each time



-(IBAction) NextHeading{ 
[audio stop];

NSString *Filename = [[NSString alloc]initWithFormat:@"CH%@S%@",Heading,Meaning];
Filepath = [[NSBundle mainBundle]pathForResource:Filename ofType:@"mp3"];

audio = [[AVAudioPlayer alloc]initWithContentsOfURL:[NSURL fileURLWithPath:Filepath] error:NULL];

audio.delegate = self;
[audio play];
[Filename autorelease];
}

-(IBAction) NextHeadingMeaning {
[audio stop];

NSString *Filename = [[NSString alloc] initWithFormat:@"CH%@S%@",bold**Chapter**bold, Meaning];
Filepath = [[NSBundle mainBundle]pathForResource:Filename ofType:@"mp3"];

audio = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:Filepath] error:NULL];

audio.delegate = self;
[audio play];
[Filename autorelease];
}


Why is this happening and how can I resolve it ?



Please advice, thanks in advance.





"Illegal seek" error when working with socket streams with non-empty read buffers

I'm currently writing a server application on Linux x86_64 using <sys/socket.h>.
After accepting a connection via accept(), I use fdopen() to wrap the retrieved socket into a FILE* stream.



Writing to, and reading from, that FILE* stream usually works quite well, but the socket becomes unsusable as soon as I write to it while it has a non-empty read buffer.



For demonstration purposes, I've written some code that listens for a connection, then reads the input, line by line, into a read buffer using fgetc(). If the line is too long to fit into the buffer, it's not completely read, but instead read during the next iteration.



#include <unistd.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>

FILE* listen_on_port(unsigned short port) {
int sock = socket(AF_INET, SOCK_STREAM, 0);
struct sockaddr_in name;
name.sin_family = AF_INET;
name.sin_port = htons(port);
name.sin_addr.s_addr = htonl(INADDR_ANY);
if(bind(sock, (struct sockaddr*) &name, sizeof(name)) < 0)
perror("bind failed");
listen(sock, 5);
int newsock = accept(sock, 0, 0);
return fdopen(newsock, "r+");
}

int main(int argc, char** argv) {
int bufsize = 8;
char buf[9];
buf[8] = 0; //ensure null termination

int data;
int size;

//listen on the port specified in argv[1]
FILE* sock = listen_on_port(atoi(argv[1]));
puts("New connection incoming");

while(1) {
//read a single line
for(size = 0; size < bufsize; size++) {
data = fgetc(sock);
if(data == EOF)
break;
if(data == '\n') {
buf[size] = 0;
break;
}
buf[size] = (char) data;
}

//check if the read failed due to an EOF
if(data == EOF) {
perror("EOF: Connection reset by peer");
break;
} else {
printf("Input line: '%s'\n", buf);
}

//try to write ack
if(fputs("ack\n", sock) == EOF)
perror("sending 'ack' failed");

//try to flush
if(fflush(sock) == EOF)
perror("fflush failed");
}

puts("Connection closed");
}


The code should compile in gcc without any special parameters. Run it with the port number as argument and use netcat to connect to it locally.



Now, if you try sending strings that are shorter than 8 characters, this will run flawlessly.
But if you send a string containing more than 10 characters, the program will fail.
This sample input:



ab
cd
abcdefghij


Will create this output:



New connection incoming
Input line: 'ab'
Input line: 'cd'
Input line: 'abcdefgh'
fflush failed: Illegal seek
EOF: Connection reset by peer: Illegal seek
Connection closed


As you see, (rightly) only the first 8 characters of abcdefgh are read, but when the program tries to send the 'ack' string (which the client never receves), and then flush the output buffer, we receive an Illegal seek error, and the next call to fgetc() returns EOF.



If the fflush() part is commented out, the same error still occurs, but the



fflush failed: Illegal seek


line is missing from the server output.



If the fputs(ack) part is commented out, everything seems to work as intended, but a perror() manually called from gdb still reports an 'Illegal seek' error.



If both fputs(ack) and fflush() are commented out, everything does work as intended.



Unfortunately, I've not been able to find any good documentation, nor any Internet discussions on this problem, so your help would be greatly appreciated.



edit



The solution i finally settled for is to not use fdopen() and FILE*, since there seems to be no clean way of converting a socket fd into a FILE* that can reliably used in r+ mode.
Instead, I directly worked on the socket fd, writing my own replacement code for fputs and fprintf.



If anyone needs it, here is the code.





Optional properties when deserializing a DataContract/Serializable mish-mash

I have an existing codebase that persists a couple of simple classes to disk via NetDataContractSerializer, but the classes are unfortunately not adorned with [DataContract], but rather with [Serializable]. This works fine, but now I want to add a few new properties to the persisted classes, while still be able to read the files generated by the old version.



Let's say this is the class:



[Serializable]
public class Persisted
{
public int OldProperty {get;set;}
public int NewProperty {get;set;}
}


Now, when I deserialize the old files, I get an exception because they don't contain NewProperty. This makes sense. So I wanted to have NewProperty ignored, but while there's a [OptionalField] attribute to have the serializer ignore the missing field, it can't be applied to properties - only fields.



So I figured I'll use [DataContract] and [DataMember], which also has an IsRequired property, but this changes the layout of the serialized file, and it can't read the old data files. Moreover, you can't mix [Serializable] and [DataMember] - if the serializer sees the [Serializable] attribute, it ignores the [DataMember] directives.



So, barring the option to do a one-time conversion of the old files (possible, but not my first choice), is there a way to get the NetDataContractSerializer to ignore a field in an existing XML serialized object?





AWK - command system () and function ()

I have a file:



AA
BB


This command prints:



$ awk '{ORS=""; printf "%s ", $0 } END {print "\n"}' file

AA BB


I want to use these commands, but the function:



The first function:



awk 'function my() { system("echo | awk '{ ORS=""; printf "%s ", $0 } END {print "\n"}' file") } BEGIN { my() }'


The second function:



awk 'function my() { system("cat file") } BEGIN { my() }'


I want to print the result:



AA BB


Thank you for your help.



EDIT:



I want to use system(command) in my() function.



awk  'function my() { system(Here I want to insert proper command) } BEGIN { my() }' -> to print the result:

AA BB


It is possible to print the result by nesting awk command?



Thanks for any proposed solution.





setting call back url for facebook login in django app

i have created a django app, which has a facebook login option also. For doing it i was following this link django-facebook connect with ajax. I did everything as said by the link, and i am getting the user signed in with facebook connect. But after the user logs in from 'registrationForm'(FB log in button given) page, the outh page pop ups to enter username and password. when giving it the user is signed in but the same registrationForm comes again without redirecting the page. Can somebody help me to set a callback url after the FB logs in is success. for FB connect i am using the same code as given in the above site.



facebookconnect.py



class FacebookScriptNode(template.Node):
def render(self, context):
return """
<script src="http://static.ak.connect.facebook.com/js/api_lib/v0.4/FeatureLoader.js.php" type="text/javascript"></script>

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>

<script type="text/javascript"> FB.init("%s", "%s");
function facebook_onlogin() {
var uid = FB.Facebook.apiClient.get_session().uid;
var session_key = FB.Facebook.apiClient.get_session().session_key;
var expires = FB.Facebook.apiClient.get_session().expires;
var secret = FB.Facebook.apiClient.get_session().secret;
var sig = FB.Facebook.apiClient.get_session().sig;

fb_connect_ajax(expires, session_key, secret, uid, sig);

}

function fb_connect_ajax(expires, session_key, ss, user, sig) {

var post_string = 'expires=' + expires;
post_string = post_string + '&session_key=' + session_key;
post_string = post_string + '&ss=' + ss;
post_string = post_string + '&user=' + user;
post_string = post_string + '&sig=' + sig;

$.ajax({
type: "POST",
url: "%s",
data: post_string,
success: function(msg) {
window.location = '%s'; //.reload()
}
});
}
</script>
""" % (settings.FACEBOOK_API_KEY, reverse('xd_receiver'), reverse('facebook_connect_ajax'), settings.LOGIN_REDIRECT_URL)


def facebook_connect_script(parser, token): return FacebookScriptNode()

register.tag(facebook_connect_script)

class FacebookLoginNode(template.Node):
def render(self, context):
return "<fb:login-button onlogin='facebook_onlogin();'></fb:login-button>"

def facebook_connect_login_button(parser, token): return FacebookLoginNode()

register.tag(facebook_connect_login_button)


views.py



def login_facebook_connect(request):
status = 'unknown failure'
try:
expires = request.POST['expires']
ss = request.POST['ss']
session_key = request.POST['session_key']
user = request.POST['user']
sig = request.POST['sig']

pre_hash_string = "expires=%ssession_key=%sss=%suser=%s%s" % (
expires,
session_key,
ss,
user,
settings.FACEBOOK_APPLICATION_SECRET,
)
post_hash_string = hashlib.new('md5')
post_hash_string.update(pre_hash_string)
if post_hash_string.hexdigest() == sig:
try:
fb = FacebookUser.objects.get(facebook_id=user)
status = "logged in existing user"
except FacebookUser.DoesNotExist:
contrib_user = User()
contrib_user.save()
contrib_user.username = u"fbuser_%s" % contrib_user.id

fb = FacebookUser()
fb.facebook_id = user
fb.contrib_user = contrib_user

temp = hashlib.new('sha1')
temp.update(str(datetime.datetime.now()))
password = temp.hexdigest()

contrib_user.set_password(password)
fb.contrib_password = password
fb.save()
contrib_user.save()
status = "created new user"

authenticated_user = auth.authenticate(
username=fb.contrib_user.username,
password=fb.contrib_password)
auth.login(request, authenticated_user)
else:
status = 'wrong hash sig'

logging.debug("FBConnect: user %s with exit status %s" % (user, status))

except Exception, e:
logging.debug("Exception thrown in the FBConnect ajax call: %s" % e)

return HttpResponse("%s" % status)

def xd_receiver(request):
return render_to_response('xd_receiver.html')


in settings.py



LOGIN_REDIRECT_URL = '/forgotPassword/'


html login part [registrationForm]



<p>Login via facebook!</p>

{% load facebookconnect %}
{% facebook_connect_login_button %}

{% facebook_connect_script %}




How to serialize a delegate

Lets look at an example of grid filling.



We have Column class. It has a delegate FormatCell, which take some Data and convert it to a string. FormatCell delegate is unknown at design time - it might be set by a plugin.



public class ColumnFormatter
{
public Func<Data, string> FormatCell {get; set;}
//...
}


Here is an example of how such Columns are used.



public class Table
{
public List<Column> Columns;

public List<List<string>> BuildTable(List<Data> dataRows)
{
var table = new List<List<string>>();

foreach (var data in dataRows)
{
var line = new List<string>();
foreach (var column in Columns)
{
line.Add(column.FormatCell(data));
}

table.Add(line);
}

return table;
}
}


Now each column should save its state. And the question is how to serialize this FormatCell delegate?



P.S. I'm aware of this question but my question is much more case specific. And maybe one has a specific reliable run-in solution for the such case?





rake db:migrate (mysql)

Why i get this error?? What's means?



i have installed mysql2 gem, "sudo gem install mysql2"



Gemfile:



gem 'mysql2'


~: rake db:migrate --trace



rake aborted!
dlopen(/Library/Ruby/Gems/1.8/gems/mysql2-0.3.11/lib/mysql2/mysql2.bundle, 9): Library not loaded: libmysqlclient.18.dylib
Referenced from: /Library/Ruby/Gems/1.8/gems/mysql2-0.3.11/lib/mysql2/mysql2.bundle
Reason: image not found - /Library/Ruby/Gems/1.8/gems/mysql2-0.3.11/lib/mysql2/mysql2.bundle
/Library/Ruby/Gems/1.8/gems/mysql2-0.3.11/lib/mysql2/mysql2.bundle
/Library/Ruby/Gems/1.8/gems/mysql2-0.3.11/lib/mysql2.rb:9
/Library/Ruby/Gems/1.8/gems/bundler-1.0.21/lib/bundler/runtime.rb:68:in `require'
/Library/Ruby/Gems/1.8/gems/bundler-1.0.21/lib/bundler/runtime.rb:68:in `require'
/Library/Ruby/Gems/1.8/gems/bundler-1.0.21/lib/bundler/runtime.rb:66:in `each'
/Library/Ruby/Gems/1.8/gems/bundler-1.0.21/lib/bundler/runtime.rb:66:in `require'
/Library/Ruby/Gems/1.8/gems/bundler-1.0.21/lib/bundler/runtime.rb:55:in `each'
/Library/Ruby/Gems/1.8/gems/bundler-1.0.21/lib/bundler/runtime.rb:55:in `require'
/Library/Ruby/Gems/1.8/gems/bundler-1.0.21/lib/bundler.rb:122:in `require'
/Users/leonardo/dev/myproject/config/application.rb:7
/Library/Ruby/Site/1.8/rubygems/custom_require.rb:36:in `gem_original_require'
/Library/Ruby/Site/1.8/rubygems/custom_require.rb:36:in `require'
/Users/leonardo/dev/myproject/Rakefile:5
/Library/Ruby/Gems/1.8/gems/rake-0.9.2.2/lib/rake/rake_module.rb:25:in `load'
/Library/Ruby/Gems/1.8/gems/rake-0.9.2.2/lib/rake/rake_module.rb:25:in `load_rakefile'
/Library/Ruby/Gems/1.8/gems/rake-0.9.2.2/lib/rake/application.rb:501:in `raw_load_rakefile'
/Library/Ruby/Gems/1.8/gems/rake-0.9.2.2/lib/rake/application.rb:82:in `load_rakefile'
/Library/Ruby/Gems/1.8/gems/rake-0.9.2.2/lib/rake/application.rb:133:in `standard_exception_handling'
/Library/Ruby/Gems/1.8/gems/rake-0.9.2.2/lib/rake/application.rb:81:in `load_rakefile'
/Library/Ruby/Gems/1.8/gems/rake-0.9.2.2/lib/rake/application.rb:65:in `run'
/Library/Ruby/Gems/1.8/gems/rake-0.9.2.2/lib/rake/application.rb:133:in `standard_exception_handling'
/Library/Ruby/Gems/1.8/gems/rake-0.9.2.2/lib/rake/application.rb:63:in `run'
/Library/Ruby/Gems/1.8/gems/rake-0.9.2.2/bin/rake:33
/usr/bin/rake:19:in `load'
/usr/bin/rake:19




Play 2.0 - auxiliary constructors in templates

Is it possible to have auxiliary constructors in Play 2.0 templates?





Display a sessionStorage item

I want to display the field player but i can't:



<body>

<header>
<h1>My memory Game</h1>
</header>

<div id="timer">
Player Name:
<span id="player-name">

<script type='text/javascript'>

sessionStorage.getItem('player');

//alert("Your name is: " + sessionStorage.getItem('player'));

</script>
</span>
</div>


When i test it by using javascript alert everything work : the player name is desplayed without a problem
Any idea please





GetElementsByTagName in Htmlagilitypack

How do I select an element for e.g. textbox if I don't know its id?



If I know its id then I can simply write:



HtmlAgilityPack.HtmlNode node = doc.GetElementbyId(id);


But I don't know textbox's ID and I can't find GetElementsByTagName method in HtmlagilityPack which is available in webbrowser control.
In web browser control I could have simply written:



HtmlElementCollection elements = browser[i].Document.GetElementsByTagName("form");
foreach (HtmlElement currentElement in elements)
{

}


EDIT



Here is the HTML form I am talking about



<form id="searchform" method="get" action="/test.php">
<input name="sometext" type="text">
</form>


Please note I don't know the ID of form. And there can be several forms on same page. The only thing I know is "sometext" and I want to get this element using just this name. So I guess I will have to parse all forms one by one and then find this name "sometext" but how do I do that?





Get ConfigObj to quote strings

If I run the following script:



from configobj import ConfigObj
config = ConfigObj()
config.filename = 'test.cfg'
config['keyword1'] = "the value"
config['keyword2'] = "'{0:s}'".format("the value")
config['keyword3'] = '"{0:s}"'.format("the value")
config.write()


the output is:



keyword1 = the value
keyword2 = "'the value'"
keyword3 = '"the value"'


Is there any way to produce the following output?



keyword1 = 'the value'




Does anyone know how to register for Google Backup API key now?

The URL to register for Google Backup API key no longer works.



(http://code.google.com/android/backup/signup.html) - I am redirected to my developer console.



Does anyone know how to register an app for a new API key now?





Changing the buttons in the Applicationbar?

I want to change the icons and what they do in code in my WP7 application. I've tried in the MainPage constructor and in the MainPage_Loaded but it says ApplicationBar (x:Name) is null all the time.



How can I change it since I use same page and different states?





objective-c count

So, after I load the animations sprite frames into the cache in the game I'm making, I count how many frames each animation has. I do this because in the game config there's a value for the duration of each animation, and when I create the CCAnimation, the delay attr is AnimationDuration/FramesAmount.



To count the amount of frames per animation, I open the animations.plist and iterate the entries getting every key, removing the file name, and storing every frame (as key) in a NSMutableDictionary with the amount as an NSNumber that I update through the iteration. The thing is that I don't like how I need to get the NSNumber intValue, do +1, and then alloc another NSNumber and re set the value for the key. Is there any better way of doing this?? Thanks all! (like.. in php OR JS would be dictonary[frame]++)



Here is the code:
NSString *finalPath = [path stringByAppendingPathComponent:@"animations.plist"];
NSDictionary *plistData = [[NSDictionary dictionaryWithContentsOfFile:finalPath] retain];



NSMutableDictionary *conf = [NSMutableDictionary dictionary];
NSDictionary *frames = [plistData valueForKey:@"frames"];

NSNumber *amount;
for( int i=0; i < [frames count]; i++ ) {
NSString *frame = [[frames allKeys] objectAtIndex:i];

NSRange range = [frame rangeOfString:@"/" options:NSBackwardsSearch];
frame = [frame substringToIndex:range.location];

if( [conf objectForKey:frame] == nil )
amount = [[NSNumber alloc] initWithInt:1];
else
amount = [[NSNumber alloc] initWithInt:[[conf objectForKey:frame] intValue]+1];//amount++...

[conf setObject:amount forKey:frame];
}




coding with Vectors algebra using the Accelerate framework

I'm playing around with the Accelerate framework for the first time. I've never tried to do anything close to linear algebra in XCode. Having some experience with MATLAB, I wonder if using Accelerate is indeed that much more of a pain. Suppose I'd want to calculate the following:



b = 4*(sin(a/2))^2 where a and b are vectors.



MATLAB code:



a = 1:4;
b = 4*(sin(a/2)).^2;


However, as I see it after some spitting through the documentation, things are quite different using Accelerate.



My C implementation:



float a[4]  = {1,2,3,4};                        //define a
int len = 4;
float div = 2; //define 2
float a2[len]; //define intermediate result 1
vDSP_vsdiv(a, 1, &div, a2, 1, len); //divide
float sinResult[len]; //define intermediate result 2
vvsinf(sinResult, a2, &len); //take sine
float sqResult[len]; //square the result
vDSP_vsq(sinResult, 1, sqResult, 1, len); //take square
float factor = 4; //multiply all this by four
float b[len]; //define answer vector
vDSP_vsmul(sqResult, 1, &factor, b, 1, len); //multiply

//unset all variables I didn't actually need


Honestly, I don't know what's worst here: keeping track of all intermediate steps, trying to memorize how the arguments are passed in vDSP with respect to VecLib (quite different), or that it takes so much time doing something quite trivial.



I really hope I am missing something here and that most steps can be merged or shortened. Any recommendations on coding resources, good coding habits (learned the hard way or from a book), etc. would be very welcome! How do you all deal with multiple lines of vector calculations?