Monday, May 14, 2012

How can I create an MSI setup?

I've created setups for all my Delphi tools with Inno Setup for years. Now some users rather want an MSI installation package, so they can deploy the setups from a central server to all workstations.



How do I create one? Do I have to buy Visual Studio or some other product?





What is the fastest way to XOR two integers in C#?

I need to XOR one integer a against array of integers q (max of 100,000). i.e. if i am looping, I will a XOR q[0]..... a XOR q[100000] (100,000 times)



I will have a series of such a to be XORed.



I am writing a console application which will be pass the required input.



I am using the built-in C# ^ operator to do the XOR operation. Is there any other way?



Would converting the integer to a byte array and then XORing each bit and figuring out the end result be a good idea?





How do I draw an half Circle in opengl

I use this method which works perfectly to draw a full circle(might be typos in code text I wrote from memory):



drawCircle(GLAutodrawble drawble){
GL gl = drawble.getGL();
gl.glTranslatef(0.0f,0.0f,-7.0f);
gl.glBeginf(GL_LINE_LOOP);
gl.glColorf(0.0f,0.0f,0.0);
final dobule PI = 3.141592654;
double angle = 0.0;
int points = 100;
for(int i =0; i < points;i++){
angle = 2 * PI * i / points;
gl.glVertexf((float)Math.cos(angle),(float)Math.sin(angle));
}
gl.glScalef(1.0f,1.0f,0.0f);
gl.glEnd();
}


I want to use the same priciples to make method to make a half circle, I don't get my head around what I should do with the cos sin stuff. Can anyone take a look and help me.



Thanks goes to all that thakes a look at the problem!





check if string contains url anywhere in string using javascript

I want to check if string contains a url using javascript i got this code from google



        if(new RegExp("[a-zA-Z\d]+://(\w+:\w+@)?([a-zA-Z\d.-]+\.[A-Za-z]{2,4})(:\d+)?(/.*)?").test(status_text)) {
alert("url inside");
}


But this one works only for the url like "http://www.google.com" and "http://google.com" but it doesnt work for "www.google.com" .Also i want to extract that url from string so i can process that url.





ajax post no update in django template

I want to post some text in django with ajax,and save the input data,show the data in same page and no refresh,like twitter.



my js:



$('#SumbitButton').click(function(){
var data_1 = $('#data_1').val()
var data_2 = $('#data_2').val()
var data_3 = $('#data_3').val()
var data_4 = $('#data_4').val()
var user = $('#AuthorName').text()
var authorprotrait = $('#UserProprait').html()
if(data_1.length>0){
$.ajax({
type: 'POST',
url: '/post/',
data:{'data_1':data_1,'data_2':data_2,'data_3':data_3,'data_4':data_4},
async: false,
error: function(msg){alert('Fail')},
success: function(msg){
$('#TopicWrap').prepend("<div class='topic-all even'><div class='topic-left'><div class='topic-author'><div class='topic-author-protrait'>"+authorprotrait+"</div><div class='topic-author-nickname'>"+authorname+"</div></div></div><div class='topic-right'><div class='topic-meta'><span class='topic-datetime'></span></div><div class='topic-content-wrap'><div class='topic-content'>"+msg+"</div></div></div><div class='clearfix'></div></div>");
$('#data_1').val('');
$('#data_2').val('');
$('#data_3').val('');
$('#data_4').val('');
}
});
} else {
alert('The data_1's length error ?'+data_1.length);
}
});


and the html:



<div id="TopicTextarea">
<div>
data1:<input tabindex="4" id="data_1" type="text" name="data1" value="" maxlength="6" placeholder=""/></br>
data2:<input tabindex="4" id="data_2" type="text" name="data2" value="" maxlength="8" placeholder=""/></br>
data3:<input tabindex="4" id="data_3" type="text" name="data3" value="" maxlength="10" placeholder=""/></br>
data4:<input tabindex="4" id="data_4" type="text" name="data4" value="" maxlength="10" placeholder=""/>
<div id="TopicFormControl">
<button type="button" id="SumbitButton" class="button orange">sumbit</button>
</div>
</div>
?? <div class="clearfix"></div>
</div>
<div id="TopicWrap">
{% include 'topics.html'%}
</div>


and the views:



@login_required
def post(request):

assert(request.method=='POST' and request.is_ajax()==True)
data_1 = smart_unicode(request.POST['data_1'])
data_2 = smart_unicode(request.POST['data_2'])
data_3 = smart_unicode(request.POST['data_3'])
data_4 = smart_unicode(request.POST['data_4'])

data_obj = DataPool(user=request.user,data_1=data_1,data_2=data_2,data_3=data_3, data_4=data_4)
data_obj.save()

content = '"+data_3+" ?"+data_4+"?"+data_1+"("+data_2+")'

response = HttpResponse(cgi.escape(content))

return response


when I input the data and click the sumbit button,it can save the data ,but it can't show the data.what's wrong in my code?



thanks.





Is it possible to set the cookie content with CURL?

I have been searching for a way, to specify the cookie data for CURL. I have found some solutions on how to save the cookies from a visited page, but that's not what I need. What I want is, to write the data for the cookie myself, so CURL uses it.





Source code for java.lang.Object

Is there any web site that I could see the source code for the Java standard library? Most so the two classes java.lang.* and java.net.* ??





For loop in SCSS with a combination of variables

I've got a bunch of elements:
(#cp1, #cp2, #cp3, #cp4)



that I want to add a background colour to using SCSS.



My code is:



$colour1: rgb(255,255,255); // white
$colour2: rgb(255,0,0); // red
$colour3: rgb(135,206,250); // sky blue
$colour4: rgb(255,255,0); // yellow

@for $i from 1 through 4 {
#cp#{i} {
background-color: rgba($(colour#{i}), 0.6);

&:hover {
background-color: rgba($(colour#{i}), 1);
cursor: pointer;
}
}
}




Partitioning a sequence into sets of unique pairs

I'm in need a of function which can split a sequence into pairs, and then combine them such that all elements in a combination is unique. I have tried a number of approaches using python's itertools, but have not found a solution.



To illustrate i would like a function which would take this sequence:
[1, 2, 3, 4]



and split it into the following 3 combinations:



[[1, 2], [3, 4]]
[[1, 3], [2, 4]]
[[1, 4], [2, 3]]


it should also work for longer sequences, but does not have to handle sequences of odd length. eg.



[1,2,3,4,5,6]


splits into the following 15 combinations:



[[1, 2], [3, 4], [5, 6]]
[[1, 2], [3, 5], [4, 6]]
[[1, 2], [3, 6], [4, 5]]
[[1, 3], [2, 4], [5, 6]]
[[1, 3], [2, 5], [4, 6]]
[[1, 3], [2, 6], [4, 5]]
[[1, 4], [2, 3], [5, 6]]
[[1, 4], [2, 5], [3, 6]]
[[1, 4], [2, 6], [3, 5]]
[[1, 5], [2, 3], [4, 6]]
[[1, 5], [2, 4], [3, 6]]
[[1, 5], [2, 6], [3, 4]]
[[1, 6], [2, 3], [4, 5]]
[[1, 6], [2, 4], [3, 5]]
[[1, 6], [2, 5], [3, 4]]


... and so on.



The CAS called Maple has this function implemented under the name setpartition.



Edit: fixed a critical late night typing error pointed out by wks, and clarified the outputs.





Python pexpect - TIMEOUT falls into traceback and exists,

I'm new to python-pexpect. In Tcl/expect when I hit a timeout - I would respond with message and exit the function. I have tried to experiment with similar response using sample code posted
http://pexpect.svn.sourceforge.net/viewvc/pexpect/trunk/pexpect/examples/sshls.py?revision=489&view=markup



I based on this code above - if I give a bogus password, I would expect this to just timeout, print "ERROR!", and exit program. But when I run it - goes into a 'Traceback output (see below), can someone help me to get the program to print "ERROR" and exit program gracefully.



test@ubuntu:~/scripts$ ./tmout.py 
Hostname: 192.168.26.84
User: root
Password:
Timeout exceeded in read_nonblocking().
<pexpect.spawn object at 0xb77309cc>
version: 2.3 ($Revision: 399 $)
command: /usr/bin/ssh
args: ['/usr/bin/ssh', '-l', 'root', '192.168.26.84', '/bin/ls', '-l']
searcher: searcher_re:
0: EOF
buffer (last 100 chars):
Permission denied, please try again.
root@192.168.26.84's password:
before (last 100 chars):
Permission denied, please try again.
root@192.168.26.84's password:
after: <class 'pexpect.TIMEOUT'>
match: None
match_index: None
exitstatus: None
flag_eof: False
pid: 14997
child_fd: 3
closed: False
timeout: 30
delimiter: <class 'pexpect.EOF'>
logfile: None
logfile_read: None
logfile_send: None
maxread: 2000
ignorecase: False
searchwindowsize: None
delaybeforesend: 0.05
delayafterclose: 0.1
delayafterterminate: 0.1
Traceback (most recent call last):
File "./tmout.py", line 54, in <module>
traceback.print_exc()
NameError: name 'traceback' is not defined
test@ubuntu:~/scripts$


Source Code:



#!/usr/bin/env python

"""This runs 'ls -l' on a remote host using SSH. At the prompts enter hostname,
user, and password.

$Id$
"""

import pexpect
import getpass, os

def ssh_command (user, host, password, command):

"""This runs a command on the remote host. This could also be done with the
pxssh class, but this demonstrates what that class does at a simpler level.
This returns a pexpect.spawn object. This handles the case when you try to
connect to a new host and ssh asks you if you want to accept the public key
fingerprint and continue connecting. """

ssh_newkey = 'Are you sure you want to continue connecting'
child = pexpect.spawn('ssh -l %s %s %s'%(user, host, command))
i = child.expect([pexpect.TIMEOUT, ssh_newkey, 'password: '])
if i == 0: # Timeout
print 'ERROR!'
print 'SSH could not login. Here is what SSH said:'
print child.before, child.after
return None
if i == 1: # SSH does not have the public key. Just accept it.
child.sendline ('yes')
child.expect ('password: ')
i = child.expect([pexpect.TIMEOUT, 'password: '])
if i == 0: # Timeout
print 'ERROR!'
print 'SSH could not login. Here is what SSH said:'
print child.before, child.after
return None
child.sendline(password)
return child

def main ():

host = raw_input('Hostname: ')
user = raw_input('User: ')
password = getpass.getpass('Password: ')
child = ssh_command (user, host, password, '/bin/ls -l')
child.expect(pexpect.EOF)
print child.before

if __name__ == '__main__':
try:
main()
except Exception, e:
print str(e)
traceback.print_exc()
os._exit(1)




Access object created in one class into another

I have a primary class as below:



public class classB{

public classC getObject(String getstring){
return new classC(getstring);
}
}


The classC has a contructor:



public class classC{

String string;

public classC(String s){
this.string = s;
}

public methodC(int i){
<using the `string` variable here>
}
}


Now I've a classA which will be using the object created in classB(which is of course, an instance of classC).



public classA{
int a = 0.5;

<Get the object that was created in classB>.methodC(a);

}


This is needed as a variable is created on some actions from the user and stored in classB and this would be further used in classC's methods. Creating a new object will render my variable in classB set to null which isn't intended.



How can I achieve this?



Please help!





$facebook -> getUser() returns wrong value?

The question is the same as title. I'm using the latest php-sdk (v3.1.1) to operate server-side authentication flow.



I have 2 tabs in Chrome, one is my Facebook page and the other is php test page. These 2 problems happen many times:




  • $facebook->getUser() still returns 0 even when I logged in.

  • $facebook->getUser() still returns an ID even when I logged out.



I have to do a work-around of this: try initiating a graph API request with provided access_token, and check if $response->error->type == "OAuthException" to ensure there's an active session or not.



Is there any way to use $facebook->getUser() "stably"? I've searched a lot through SO but not found best answer for php-sdk 3.1.1 yet.



Highly appreciate any helps. Thanks.





playframework use find with IN and a list of models

i've got a problem with the following code, written in play (1.2.4):



List<MSprache> sprachen = MSprache.find("active = ?", true).fetch();
List<MFieldDscr> textey = MFieldDscr.find("sprache IN", sprachen).fetch();


And if i execute a test, wich test this part of code, the following Error displays:



A java.lang.IllegalArgumentException has been caught, org.hibernate.hql.ast.QuerySyntaxException: unexpected token: null near line 1, column 48 [from models.Sprache.MFieldDscr where sprache IN]


I don't understand where the misstake is... Can anybody help me?
Greetz
V





Uneven tree of processes using fork()

I have to construct a tree of processes using fork() in C. I get a sequence of numbers from standard input (for example: 1 5 0 3) and those numbers tell me how many children each node has. If we take the example then the root process creates 1 child, then this one child creates 5 children of its own, then from those 5 children the first one doesn't create any children, the second one creates 3 of them and then we're done. After this is complete the root process calls pstree that draws out the tree.



Here is a picture of the example:





My question is how can I make new children from a specific node? One needs to create 0 new processes and the next one needs to create 3 of them. I don't know how to distinguish so that only that specific child makes new children and not all of them. Also I'm not sure how to use pstree, because the tree is normally already gone when pstree gets called. I know I can wait() for children to execute first but last ones do not have any children to wait for so they end too fast.





search in multidimensional array php

I have a multidimensional array with various sites links, here is output:



Array
(
[0] => Array
(
[0] => http://www.msn.com/etc
[1] => http://www.yahoo.com/etc
[2] => http://www.google.com
)

[1] => Array
(
[0] => http://www.abc.com/etc
[1] => http://www.hotmail.com/etc
[2] => http://www.hotmail.com/page/2
)

[2] => Array
(
[0] => http://www.live.com/etc
[1] => http://www.google.com/etc
[2] => http://www.stock.com
)

)


I wants to match multiple URL's, here my example code:



$sites = array("msn.com","hotmail.com","live.com");
$links = array(
array("http://www.msn.com/1","http://www.yahoo.com/etc","http://www.google.com"),
array("http://www.msn.com/2","http://www.hotmail.com/","http://www.hotmail.com/page/2"),
array("http://www.live.com/etc","http://www.google.com/etc","http://www.stock.com")
);


I need whatever sites are in $sites,first it will find msn.com site from $links array, so if it found msn.com in first array($links[0]) it will not search msn.com in other $links array but keep searching for other (hotmail.com and live.com), and if it find 2 links of same host in one array, it will join them, means if it finds a host in one array element it will not search that host in other elements of $links array, so final output from above will be this:



Array
(
[msn] => Array
(
[0] => http://www.msn.com/1
)

[hotmail] => Array
(
[0] => http://www.hotmail.com/
[1] => http://www.hotmail.com/page/2
)

[live] => Array
(
[0] => http://www.live.com/etc
)

)


I am not sure how to perform this task, I would be grateful for any input. Thanks





Problem using MySQLdb: Symbol not found: _mysql_affected_rows

A colleague got this error message when trying to use MySQLdb from Django:



[...]
ImproperlyConfigured("Error loading MySQLdb module: %s" % e) django.core.exceptions.ImproperlyConfigured:
Error loading MySQLdb module: dlopen(/Users/roy/.python-eggs/MySQL_python-1.2.3c1-py2.5-macosx-10.5-i386.egg-tmp/_mysql.so, 2):
Symbol not found: _mysql_affected_rows
Referenced from: /Users/roy/.python-eggs/MySQL_python-1.2.3c1-py2.5-macosx-10.5-i386.egg-tmp/_mysql.so Expected in: dynamic lookup



He's using OS X 10.5, Python 2.5 (arriving with OS X), MySQL 5.1 & MySQLdb 1.2.3c1.



Any idea how to attack this?





Rails logs me out when I run a query

I have a site built using the railstutorial as a template. I have added a search controller to allow me to perform site searches and redirect the user to a search view. When I go to the path '/search' it is as expected (no results) but if I actually use the search input box I get logged out and have to log back in. What would be causing this?



My form:



<form action="/search" method="POST" class="navbar-search pull-right">
<input name="query" type="text" class="search-query" placeholder="Search">
</form>


My search controller:



class SearchController < ApplicationController
def index
unless params[:query].nil?
@results = ThinkingSphinx.search params[:query]
else
@results = []
end
end
end


My view:



<% unless @results.empty? %>
<table class="table">
<% @results.each do |result| %>
<tr>
<% if result.class.name == "Event" %>
<td><%= link_to result.name, organisation_event_path(result.organisation, result.slug) %></td>
<td><%= result.summary %></td>
<% end %>
</tr>
<% end %>
</table>
<% else %>
<p>No results found.</p>
<% end %>


My route:



match '/search', to: 'search#index'




Convert Java String in ISO timestamp format to SimpleDateFormat

I am trying to convert a String in ISO timestamp format to a SimpleDateFormat like so:



public static void convertDate () {
String timestamp = DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT.format(new Date());
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZZ");
Date date = (Date)formatter.parse(timestamp);
}


The above code throws the following exception:



java.text.ParseException: Unparseable date:




ld lookup to find library

I'm cross compiling to an arm embedded system and receiving an error that I have questions about. Here is the error:



[ 19%] Built target cxjpeg-6b
Linking CXX shared library /home/botbear/JAUS++-2.110519- src/libraries/jaus++/2.0/lib/libcxutils.so
/home/botbear/openwrt/trunk/staging_dir/toolchain-arm_v6k_gcc-linaro_uClibc- 0.9.32_eabi/lib/gcc/arm-openwrt-linux-uclibcgnueabi/4.5.4/../../../../arm-openwrt-linux- uclibcgnueabi/bin/ld: cannot find -lpng
collect2: ld returned 1 exit status
make[2]: *** [/home/botbear/JAUS++-2.110519-src/libraries/jaus++/2.0/lib/libcxutils.so] Error 1
make[1]: *** [libcxutils/CxUtils/libcxutils/CMakeFiles/cxutils.dir/all] Error 2
make: *** [all] Error 2


As you can see the linker is looking for a static library named 'libpng'. In addition to the libpng lib., the command in the sub-make file using the -l switch to link to the following libraries: -lpng -lz -lX11 -lXtst -lpthread -Wl. All of the libraries (libpng,libz,libX11, etc) are in my host /usr/lib/ directory but my target toolchain does not have the the libraries. My question is if I manually recompile the libraries with my target compiler will that solved my problem? Or I'm going to have find and install packages for each of the libraries for my target platform.



Thanks in advance.





Adding hyphenation to Core Text?

I am trying to add hyphenation to a string to draw with Core Text. So far I've found this category extension on NSString that attempts to add hyphens, but it is outdated, and doesn't work when the string has apostrophes, as well as many other issues. And then this other guy uses that code to do this, but this is dependent on the first source code, which is no good.



But now in iOS 5 there is apparently a built in method for hyphenation, though tutorials and examples are extremely scarce: CFStringGetHyphenationLocationBeforeIndex. Can anyone more experienced with Core Text and CF cook up a quick example of how I could potentially use this function?





Why isn't it the same with canvas, and webgl renderer? (three.js)

I try to render a sphere with three.js, but if I render it with canvasRenderer, then there are grey lines on the sphere



code: http://jsfiddle.net/jzpSJ/



screenshot: http://desmond.imageshack.us/Himg209/scaled.php?server=209&filename=canvase.png&res=landing



But if I render it with webGL renderer in opera next, then it looks awful



code: http://jsfiddle.net/jzpSJ/1/



screenshot: http://desmond.imageshack.us/Himg51/scaled.php?server=51&filename=webglopera.png&res=landing



In google chrome it looks as it should be.



Thanks in advance,





Javascript sort alphabetically matching the beginning of string then alphabetically for contained text

I need help sorting through some data.
Say I type "piz" in a searchfield. I get in return and array with all the entries that contain "piz".



I now want to display them in the following order:



pizza 
pizzeria
apizzetto
berpizzo


First the items that start with what I typed in alphabetical order then the ones that contain what I typed in alphabetical order.



Instead if I sort them alphabetically I get the following



apizzetto
berpizzo
pizza
pizzeria


Does anyone know how to do this?
Thanks for your help.





Android, the alarm icon on the right side of notification area?

When I set an alarm with the build-in alarm clock application, there will be an icon on the right side of notification area. But it won't be there if I set an alarm with AlarmManager. Is there a way I can make that icon show?





Storing multiple values for a single field in a database

Suppose i have a table with 3 fields



Person_id, Name and address. Now the problem is that a person can have multiple addresses. and the principle of atomic values says that data should be atomic.



So then how am i suppose to store multiple addresses for a single person ?





Custom .NET Membership

I use .net membership but everything what i work i want to be custom.



What i want to do is:




  1. Create custom data table [Users] with custom fields

  2. Import current data into new table

  3. Create custom classes and functions about everything what i need for [Users]



I`m not sure how .net membership works, but maybe it send encrypted cookie then when i use



var user = Membership.GetUser();


.Net decrypt user cookie and know which user is.



Here is a screenshot how .net create user AUTH cookie http://prntscr.com/97043



But everytime user logout-login, this value is different.



So what i want to know is:




  1. Lets say i want to make 100% custom website, how i can make custom login?

  2. Can you tell me all security issues about going for custom membership?





trying to read a text file data into an array to be manipulated then spit back out

My aim is to take the data from the file, split it up and place them into an array for future modification.



The is what the data looks like:



course1-Maths|course1-3215|number-3|professor-Mark

sam|scott|12|H|3.4|1/11/1991|3/15/2012

john|rummer|12|A|3|1/11/1982|7/15/2004

sammy|brown|12|C|2.4|1/11/1991|4/12/2006

end_Roster1|


I want to take maths, 3215, 3 and Mark and put into an array,
then sam scott 12 H 3.4 1/11/1991 3/15/2012.



This is what I have so far:



infile.open("file.txt", fstream::in | fstream::out | fstream::app);
while(!infile.eof())
{
while ( getline(infile, line, '-') )
{
if ( getline(infile, line, '|') )
{
r = new data;
r->setRcourse_name(line);
r->setRcourse_code(3);//error not a string
r->setRcredit(3);//error not a string pre filled
r->setRinstructor(line);

cout << line << endl;
}
}
}


Then I tried to view it nothing is stored.





Icon of JTree for top level element looks cut when using SynthLookAndFeel

I have a strange behavior when "plus" image of top level element of JTree is cut in the middle. (This image for all other levels look good)



For example: if I use the following method images look correct:



UIManager.put("Tree.collapsedIcon", IconFactory.getImage("Images/nodeClosed.png"));


and it look like this:
enter image description here



If i use "SynthLookAndFeel" it look cut in the middle:



SynthLookAndFeel laf = new SynthLookAndFeel();
InputStream is = EmsApplet.class.getResourceAsStream("lNf_test.xml");
laf.load(is , EmsApplet.class);
UIManager.setLookAndFeel(laf);


it look like this:enter image description here



And here is part of XML file:



<style id="TreeStyle">
<imageIcon id="treeCollapsedIcon" path="nodeClosed.png"/>
</style>


note: red color is just to mark specific region. please ignore it.





how to give some access to students acording to their levels

i have designed a student learning website through php.. here i uses levels of students that is level 1,level 2 and level 3 stored in database (mysql).



Now my ques is that, if student login and if he is in level 1 so he cant access level 3 or level 2... an appropriate message would be shown if he click on 2 or 3 level...





MODX: where are new_folder_permissions and new_file_permissions?

Those are asked during the installation, but are not anywhere in config files\tables to change afterwards





Add retina support for iPhone OpenGL ES app

I have a working opengl app written on 3.2 SDK. What must be done to make it look better on Retina display?



I have followed these instructions with no luck.