Monday, April 30, 2012

Parallel delaunay triangulation naive algorithm

The following code(Pg.187,Computational Geom in C by Rourke) takes same time to run serially as well as in parallel(2 proc).
Please help me identify the problem.
Here's the parallel portion



int chunk;
chunk=10;
#pragma omp parallel private(i,j,k,xn,yn,zn)
{
#pragma omp for schedule(static,chunk)
for(i=0;i<n-2;i++)
{
for(j=i+1;j<n;j++)
for(k=i+1;k<n;k++)
if(j!=k)
{
xn=(y[j]-y[i])*(z[k]-z[i])-(y[k]-y[i])*(z[j]-z[i]);
yn=(x[k]-x[i])*(z[j]-z[i])-(x[j]-x[i])*(z[k]-z[i]);
zn=(x[j]-x[i])*(y[k]-y[i])-(x[k]-x[i])*(y[j]-y[i]);
if(flag=(zn<0))
for(m=0;m<n;m++)
flag=flag && ((x[m]-x[i])*xn + (y[m]-y[i])*yn + (z[m]-z[i])*zn <=0);
if (flag)
printf("%d\t%d\t%d\n",i,j,k);
}
}
}




Response.Redirect behaves different from within UpdatePanel

Everywhere in my web application i use redirects like these:



Response.Redirect("~/SearchResults.aspx", true); 


And this always takes me to the right page. http://localhost/myapp/SearchResults.aspx



But now i'm doing this in the onclick event of a button that sits in an ASP.NET UpdatePanel and it tries to bring me to the following address:
http://localhost/myapp/%2fmyapp%2fSearchResults.aspx



Does anyone have an idea how to fix this?





UITableView with Core Data ordered by time, not alphabetically

I'm working on an app that uses Core Data and a UITableView. What I've noticed is that when I add a new TableView entry, the cells seem to order alphabetically. Is there a way to make it so the cells are ordered by the time I add them (from top to bottom) rather than by the alphabet. Thanks!





MYSQL ordering columns in my query

I have been working on trying to get a bunch of data to work in a table structure displayed neatly using PHP, and I must say I am having a difficult time. I have finally been able to call the columns so that in case I add a field it will always add it in my table, and I hope for this to be very easily managed. However, when I initially set up the table, I put it in a random order. Now when I come use the DESCRIBE table it gives them to me in exact order, and I cannot find a way to organize them better. It would not make sense to say have month/year at the end of the database for my form that I have.



<?php 
require 'connect.php';
?>
<h3>Monthly Finances | <a href="new.php">Add New Month</a> </h3>
<table border="1" bordercolor ="#000000">
<tr>
<?php
$columns = "DESCRIBE `month` ";
if($query_run_columns = mysql_query($columns)){
$columnNames = array();
while($column = mysql_fetch_assoc($query_run_columns)){
echo '<th>'.$column['Field'].'</th>';
}
}else{
echo'sql error';
}

?>


<?php
$gatherdata = "SELECT `month`, `year`,`rent`,`electric`,`cable`,`cellphone`,`renters` FROM `month` ";
if($query_run = mysql_query($gatherdata)){

while($row = mysql_fetch_assoc($query_run)){
$rent = $row['rent'];
$electric = $row['electric'];
$cable = $row['cable'];
$cellphone = $row['cellphone'];
$renters = $row['renters'];
$month = $row['month'];
$year = $row['year'];

echo '<tr>';
echo '<td align="center">'.$month.'</td>';
echo '<td algin="center">'.$year.'</td>';
echo '<td align="center">'.$rent.'</td>';
echo '<td align="center">'.$electric.'</td>';
echo '<td align="center">'.$cable.'</td>';
echo '<td align="center">'.$cellphone.'</td>';
echo '<td align="center">'.$renters.'</td>';
echo '</tr>';
}
}else{
echo 'query error';
}
?>
<br>View by month
</table>
<form action="index.php" method="GET">
<select name="months" value="all">
<?php
$gathermonths = "SELECT `month`, `year` FROM `month";

if($query_month_selector = mysql_query($gathermonths)){
while($month_row = mysql_fetch_assoc($query_month_selector)){
$month = $month_row['month'];
$year = $month_row['year'];

echo '<option value="'.$month.' '.$year.'">' .$month.' '.$year.'</option>';
}
}
echo $_GET['months'];
?>
<input type="submit" value="View Selected Date"></input>
</select>
</form>


My code is very far from complete, or orderly but I have been slacking on this project and I will clean it up more when I have more time. But if you could please give me a hand on an efficient organizational method that would be appreciated.





Android: Append not shown ActionItems to Icon instead of Context Menu

I found an example how to use a context menu with actionBar. This example waits for clicks on the phones menu button. But I want to have it appended to the icon or better the activity name. thanks



  public class menu extends Activity {

@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_fragen, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
..




StringBuilder Append vs AppendFormat efficiency in C#

Which is more efficient in C#, 1 or 2?



StringBuilder sb = new StringBuilder();
sb.Append("my string " + myVar + " my string"); // 1
sb.AppendFormat("my string {0} my string", myVar); // 2


I'm guessing that the question could also be rephrased:



string y = "my string " + myVar + " my string";              // 1
string x = String.Format("my string {0} my string", myVar); // 2




Ruby is very slow

I have a PC with 2 processors of 2GHz and 4go of ram. I use RVM with ruby-1.9.3-p194-perf and rails 3.2.3. When I load my rails application, it take a few time and I think it's not normal.



This is some example :



time rails new speed_test
...
real 0m7.240s
user 0m4.484s
sys 0m0.184s

time rails g scaffold Articles title:string description:text
...
real 0m4.910s
user 0m4.052s
sys 0m0.348s

time rake db:migrate
...
real 0m4.172s
user 0m3.716s
sys 0m0.244s

time rake
...
real 0m15.981s
user 0m14.045s
sys 0m1.048s


This is some short commands but, with some hundred of tests, it's very long, even with spork.



Do you have a solution?



Thanks a lot!





Match comma separated list with Ruby Regex

Given the following string, I'd like to match the elements of the list:




foo,bar,baz




The minimum number of elements is 1, and there can be arbitrarily many. Assume no whitespace and lower case.



I've tried this, which should work, but doesn't populate all the match groups for some reason:



^([a-z]+)(?:,([a-z]+))*



That matches foo in \1 and baz (or whatever the last element is) in \2. I don't understand why I don't get a match group for bar.



Any ideas?



EDIT: Ruby 1.9.3, if that matters.



EDIT2: Rubular link: http://rubular.com/r/cDQh9SZyA2





Dividing an application with Spring and Mybatis into multiple modules

I'd like to divide my project into multiple maven modules. But I'm not sure of what structure would be preferable. The main goal is to take out the service logic in a separate module.



Right now I have four packages in my project: controller, domain, persistence, service. Say, this can be divided into two main parts: database related stuff (domain and persistence packages) and the service part (service and, oh, maybe a controller). Is this a good structure? Do service and controller packages seem to be a good separated service? I'm pretty sure it's better to put service and controller parts in a single module due to the fact they are autowired now (and also logically wired). Should each child module be a web application of a full value (obviously with a lack of packages and files)?



And I'm not sure about the placement of the web pages. Should they all be in a Spring parent module? That would make sense. But different pages could also be in different web-app modules (I guess), and that also makes sense.



I understand that this question doesn't seem to be a concrete one. It's because I don't have a formed understanding of a preferable (and also of a working) structure. An advice would be appreciated, thanks in advance.





Visual C++ Undo and Redo operations

I have a rather large application I'm trying to make in Visual-C++, and I am now trying to add undo/redo functionality.



Having a rather large amount of events (button clicks, label text changed, etc.), I would like to find a way to undo/redo without adding code to every function.
For Instance, I would like a class that can read every event done and store it automatically. Then in my undo/redo events, I can just get the latest action stored.



If that is not possible, I would not mind some other way.



Any help?





Tomcat memory consumption is more than heap + permgen space

I am observing a mismatch in Tomcat RAM consumption between what the OS says and what jVisualVM says.



From htop, the Tomcat JVM is has 993 MB of resident memory



From jVisualVM, the Tomcat JVM is using




  • Heap Max: 1,070,399,488 B

  • Heap Size: 298.438.656 B

  • Heap Used: variable, between 170MB and and 270MB

  • PermGen Max: 268,435,456 B

  • PermGen Size: 248,872,960 B

  • PermGen Used: slightly variable, around 150MB



From my understanding the OS memory consumption should be Heap Size + PermGen Size ~= 522 MB. But that's 471 MB less than what I'm observing.



Anyone got an idea what am I missing here?



PS: I know that my max heap is much higher than what is used, but I'm assuming that should have no effect if the JVM does not use it (i.e. Heap Size is lower).



Thanks!
Marc





Java Bit Operation on Long - Removing some bits

I have a long number. Now, what I want to do is the following:



long l = "001000......10001100000" (bits representation)


I need to remove the 3rd and 4th bits of it (i.e. 10) from the left and convert the remaining 62 bits to long



long newl = "0000......10001100000" (bits representation)


Can anybody help me do this efficiently in Java ?





Why is System.Random giving '1' a lot of times in a row, then not for a while, then again?

Not sure how else to explain this, so the title pretty much describes the problem.



Random is not being re-initialised every part of the loop. It's a static member of a class which I always call on from other classes.



I am not using a custom seed.



The initialisation code is:



    public static Random random = new Random();

for (int x = 0; x < 75; x++)
{
if (main.random.Next(11) == 1)
{
tiles[heightMap[x] - 1][x] = 4;
tiles[heightMap[x] - 2][x] = 4;
tiles[heightMap[x] - 3][x] = 4;
tiles[heightMap[x] - 4][x] = 4;
tiles[heightMap[x] - 5][x] = 4;
tiles[heightMap[x] - 5][x - 1] = 5;
tiles[heightMap[x] - 6][x - 1] = 5;
tiles[heightMap[x] - 6][x] = 5;
tiles[heightMap[x] - 5][x + 1] = 5;
tiles[heightMap[x] - 6][x + 1] = 5;
}
}


This (Ignore my ugly hax for making a tree, it's rudimentary and temporary) generates a tree.



However my terrain often looks like:



AIR AIR AIR AIR TREE TREE TREE AIR AIR TREE TREE AIR AIR AIR AIR TREE TREE TREE



As in it seems to get clusters of 1 at a time.



Can anyone give insight into why this is happening? Is there a better alternative than using the System.Security.Cryptography.Random class (Since that's slower and this is a game not a bank program I want it to have very fast loading speeds)



I'd expect an average of 9 gap per tree, but it's more like 7 and then 3 trees closely clustered together.



enter image description here





Assignment = operator overloading

Please help to complete this execution of an assignment overloading function.



Here is the instruction:



Assignment operator (=) which will copy the source string into the destination string. Note that size of the destination needs to be adjusted to be the same as the source.



Both addition (+) and assignment (=) operators need to be capable of cascaded operations. This means String3 = String1 + String2, or String1 = String2 = String3 should work.



Here is my .cpp file:



MyString& MyString::operator=(const MyString& rhs)
{

if(this != &rhs)
{

delete [] String;
String = new char[Size];

for(int i = 0; i < counter+1 ; i++)
{
String[i] = rhs.String[i];
}


}
return *this;

}


It is called in the main.cpp file by:



String1=String2=String3;



I feel as though I am missing something.Help!!





Bitwise shifting array of char's

I've got an array of char's that I'm trying to bitwise shift right, then "&" with another array. I think I've got the wrong idea of how to do this. I thought, even though it was an array of char's just stating "my_array >>= 1" would shift everything but I'm getting a: "error: invalid operands to binary >> (have 'char[8]' and 'int')"

The bitwise comparision I'm trying to do is with a similar size array initiated to all "0's"...for that I'm getting: "error: invalid operands to binary & (have 'char *' and 'char *')" Do I need to convert these array's into something else before I can shift and compare?





How to consume command line arguments using raw_input() instead of sys.argv

I am new to python I have developed the following code for some online coding submission. Now my problem is this coding site is not accepting sys.argv. How do I convert this code to take raw_input from command line. raw_input is confusing as compared to sys.argv. Please help. Thanks in advance.



import sys
ln = int(sys.argv[1])
#create list of elements which are sum of two command line input
list = []
i = 2
while i <= ln:
sum = int(sys.argv[i]) + int(sys.argv[i+1])
list.append(sum)
i = i + 2
#update list with elements which are sum of the two elements within the list
j = 0
while j < len(list) - 1:
list.append(list[j]+list[j+1])
j = j + 2
#get final sum using addition of all the elements in the list
k = 0
sum = 0
while k < len(list):
sum = sum + list[k]
k = k + 1
print sum




How to allow users to edit a post using the sql UPDATE statement?

I am trying to let users edit the content that they post. The content is seperated into two sections the title and the text. It also has a category but I don't want to let them edit that. So here is the code that is suppose to update any changes to the title:




$sql = "UPDATE



topics



SET topic_subject = " . mysql_real_escape_string($_POST['topic_subject']) . "



WHERE



topic_id = " . mysql_real_escape_string($_GET['id']);




The code that updates the content has the same format.
I get the id from the url of the page and once they click submit on the editing page the form calls the page that contains this code. It gives me this error:




An error occurred while inserting your data. Please try again later.



You have an error in your SQL syntax; check the manual that corresponds to your MySQL
server version for the right syntax to use near 'WHERE topic_id =' at line 4




I am not an expert in SQL and don't know what the problem could be. Thanks in advance.





Java: How do I simulate probability?

I have a set of over 100 different probabilities ranging from 0.007379 all the way to 0.913855 (These probabilities were collected from an actuary table http://www.ssa.gov/oact/STATS/table4c6.html). In Java, how can I use these probabilities to determine whether something will happen or not? Something along these lines...



public boolean prob(double probability){
if (you get lucky)
return true;
return false;
}




multiple automated tasks to run ubuntu 10.04 server

I need to run automated tasks every 15. The tasks is for my server (call it server A, Ubuntu 10.04 LAMP) to query for updates to another server (Server B).



I have multiple users to query for, possibly 14 (or more) users. As of now, the scripts are written in PHP. They do the following:




  1. request Server B for updates on users

  2. If Server B says there are updates, then Server A retrieves the updates

  3. In Server A, update DB with the new data for the users in

  4. run calculations in server A

  5. send prompts to users that I received data updates from.



I know cron jobs might be the way to go, but there could be a scenario where I might have a cron job for every user. Is that reasonable? Or should I force it to be one cron job querying data for all my users?



Also, the server I'm querying has a java api that I can use to query it. Which means I could develop a java servlet to do the same. I've had trouble with this approach but I'm looking for feedback if this is the way to go. I'm not familiar with Tomcat and I don't fully understand it yet.



Summary: I need my server to run tasks automatically every 15 mins, the requests data from another server, updates its DB and then send prompts to users. What's are recommended approaches?



Thanks for your help!





How to use parent viewcontroller to launch uiactionsheet so that it does not get clipped?

Hey so I have a problem where I am inserting an actionsheet into a view that is inside of a scrollview in a different view controller. The actionsheet works just fine, the problem is that if i go down at all in the scrollview the actionsheet gets clipped off. I've tried several solutions with no luck. I think the problem is that the actionsheet is being inserted into the view that is placed inside the scrollview. Anyone have any idea how to launch the action sheet from the view controller that the scrollview is in instead? Here is how I am trying to do it right now:



When a button is touched it calls this method:



- (IBAction)callDP:(id)sender {

UIButton *selectedButton = (UIButton *)sender;

actionSheet = [[UIActionSheet alloc] initWithTitle:nil delegate:nil cancelButtonTitle:nil destructiveButtonTitle:nil otherButtonTitles:nil];

[actionSheet setActionSheetStyle:UIActionSheetStyleBlackTranslucent];

CGRect pickerFrame = CGRectMake(0, 40, 0, 0);

datePickerView = [[UIDatePicker alloc] initWithFrame:pickerFrame];
datePickerView.tag = 10;

[datePickerView addTarget:self action:@selector(changeDate:) forControlEvents:UIControlEventValueChanged];

[actionSheet addSubview:datePickerView];
[actionSheet setTitle:@"Start Date"];
UISegmentedControl *closeButton = [[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObject:@"Done"]];
closeButton.momentary = YES;
closeButton.frame = CGRectMake(260, 7.0f, 50.0f, 30.0f);
closeButton.segmentedControlStyle = UISegmentedControlStyleBar;
closeButton.tintColor = [UIColor blackColor];
[closeButton addTarget:self action:@selector(dismissActionSheet) forControlEvents:UIControlEventValueChanged];
[actionSheet addSubview:closeButton];


datePickerView.datePickerMode = UIDatePickerModeDate;


//THIS IS THE PART THAT I THINK I AM HAVING THE PROBLEM WITH

// [actionSheet showFromToolbar:self.toolbarItems];
//[actionSheet showFromTabBar:self.parentViewController.tabBarController.tabBar];
[actionSheet showInView:self.parentViewController.view];


}


Here is where I insert the view into the scrollview. I have it set up so that I am using a view from a different uiviewcontroller class to control everything. The reason I do that is so that i can have the scrollable part, but be able to visually create everything that I need without having to do it programmatically....I apologize if that is kind of confusing. I can clarify if needs be...but here it is. The viewcontroller class that contains the view I want to put into the scroll view is called registration page. Its inside of registrationPage that it calls the actionSheet. Let me know what you think...



registrationPage = [[RegistrationPageToInsertViewController alloc]init];

viewToInsert = registrationPage.view;

[scrollView addSubview:viewToInsert];
[scrollView setContentSize:viewToInsert.frame.size];
// [scrollView sendSubviewToBack:imgView];

//scrollView.contentSize=CGSizeMake(320,416);
[self.view bringSubviewToFront:scrollView];




Tuesday, April 24, 2012

SQLITE Sql query to get the value while comparing value

There are three table.




Table X

| Field 1 | Field 2



Table Y



| Field 2 | Field 3



Table Z



| Field 3 | Field 4




The idea is to get the row from table Z but need to go from table X comparing a value selected value for field 1.



From Table X field 1, will get the value for field 2. On Table Y the value from field 2 will get the value for field 3.



On Table Z field 3 will get the final value from Field 4.



Any idea on how to do it in sqlite?





"string is not a type" in namespace

I write a program in c++ with two files.



main.cpp



#include "var.hpp"
#include <iostream>
using namespace std;
using namespace YU;

int main()
{
string god = "THL";
age = 10;
cout << age << endl;
cout << god << endl;
return 0;
}


var.hpp



#ifndef __VAR_H__
#define __VAR_H__

#include <string>

namespace YU
{
int age;
string name;
}

Digit/Number Recognition Hand-written

Can anyone recommend a handwritten digit/number recognition library which I could use in c++/OpenGL. I need to recognise the digits/numbers in my OpenGL project written by a user.



Thanks





Asterisk GUI Using php or any other framework

In asterisk I would like to have GUI to add/remove/edit Extensions.
This gui will also enable to update mysql database along with extension.conf add/edit when I add/delete new users. FreePbx can add/remove/edit extensions only.



Is there any framework exists for this purpose or I should purely go to write PHP from scratch ?



Thanks.





Should sensitive data be encrypted through both script and database means?

I don't know too much about encryption, but is there any benefit to encrypting the already encrypted, lets say passwords? I am aware of salts, but before this is done, does it matter or not?





Django: creating form which has relationship

I've prepared a model with a relationship.
I'd like to get a form which will make it possible to create User for that form.



Could someone explain me how it can be resolved?



class UserProfile(models.Model):
user = models.OneToOneField(User, unique=True, primary_key=True)
website = models.URLField(null=True, blank=True)
accepted_rules = models.BooleanField(default=False)
accepted_rules_date = models.DateTimeField(auto_now_add=True)


class UserProfile(ModelForm):
class Meta:
model = UserProfile

@csrf_protect
def register(request):
if request.method == "POST":

form = UserProfile(request.POST or None)
if form.is_valid():
website = form.cleaned_data['website']
accepted_rules = form.cleaned_data['accepted_rules']

username = form.cleaned_data['username']
email = form.cleaned_data['email']
password = form.cleaned_data['password']



formset.save()


print "All Correct"


return TemplateResponse(request, 'base.html', {
'form':form,
}
)




On iOS, why the init in ViewController didn't work?

In the ViewController's interface, I have



@property int count;


and in the implementation, I have



@synthesize count;

-(id) init {
self = [super init];
if (self) {
self.count = 100;
}
return self;
}

-(void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
NSLog(@"%i", self.count++);
}


but for some reason, the first time self.count got printed, it is 0 but not 100?





table based declarative reactive programming

Is there a programming language or package that supports table based reactive declarative programming in memory very similar to the SQL language and trigger facility?



For example, I could define PERSON and JOB tables as functions



name: PERSON -> STRING
female: PERSON -> BOOLEAN
mother: PERSON -> PEOPLE
father: PERSON -> PEOPLE

title: JOB -> STRING
company: JOB -> STRING
salary: JOB -> INTEGER
empoyee: JOB -> PERSON


Then I would like to calculate functions like:



childcount: PERSON -> INTEGER
childcount(P) = |{ Q in PERSON : father(Q) = P or mather(Q) = P }|

income: PERSON -> INTEGER
income(P) = SUM { salary(J) : J in JOB and empoyee(J) = P }

incomeperchild: PERSON -> INTEGER
incomeperchild(P) = income(P) / childcount(P)

parent: PERSON x PERSON -> BOOLEAN
person(P,Q) = (P = father(Q)) or (P = mother(Q))

error: PERSON -> BOOLEAN
error(P) = (female(P) and (exists Q in PERSON)(father(Q) = P))
or (not female(P) and (exists Q in PERSON)(mother(Q) = P))
or (exists Q in PERSON)(parent(P,Q) and error(Q))


So essentially I would like to have calculated columns in tables that are automatically updated whenever values in the tables change. Similar things could be expressed with SQL triggers, but I would like to have such functionality built into a language and executed in memory. The propagation of changes need to be optimized. Are there frameworks to do this?



The observer patter and reactive programming focuses on individual objects. But I do not want to maintain pointers and extra structure for each row in my tables as there could be million of rows. All the rules are generic (although they can refer to different rows via parent/children relations, etc), so some form of recursion is required.





Is there a limit on the number of lines of code you can put in an Eclipse java doument

I have a project I have been working on and all was going well until today. I have close to 6000 lines of code in one java class document. If I try to put one more IF clause into the code, the program throws an exception when the class is called on. I am using eclipse and I have not uploaded my usage yet. Is that the problem. All additional snippets that I have tried to place into the class, cause the class to fail when called on. I have tried to add test code that I know works fine, and they all throw the force close dialog. Trust me there is nothing wrong with the last snippet that I attempt to place into the class. Once I take out the last if statement, there are no errors. Has anyone ever seen this before? The exception is thrown in the emulator, when the class is called. I get the force close alert window. Thanks in advance!





How do I create a centered div of uncertain width containing left-aligned elements?

I have several uniform blue elements (<div style="display: inline-block;">) inside a red div inside a purple div. Mockup (imgur).



I would like the blue elements to be left-aligned (as many in a row as will fit in the purple div width), with a red div shrink-wrapped around them. But then I would like the red div be horizontally centered inside the purple div.



I was hoping to do something like this (jsFiddle), but that only works if the red div has a specified width.





java: about counting in txt file

i want to counting some words in txt file

myfile.txt



ABC,xyzwegwegwe
ABC,12312312312
ABC,sdfsdf3sdfs




how can i count the words"ABC"?

output:"ABC" have: 3



File abcfile = new File("myfile.txt");
Scanner myfile = new Scanner(abcfile);
String line = null;
int words = 0;
while (myfile.hasNextLine()) {
line = myfile.nextLine();
lines.add(line);
if(xxxxx){ //if have ABC, words++
words++;
}
}
System.out.print("\"ABC\" have: "+words);




Knockout.js repeat rows in table for nested model / containerless "foreach" inside table

I'm building an application to track orders of tailor made products. Each product can have many custom details. The screen to add products to an order and customize each one should look like this:



<button>+</button><!-- "Add new product line" button -->
<table>
<thead>
<tr>
<th></th>
<th>Producto</th><!-- The product category or type -->
<th>Modelo</th><!-- The product -->
<th>Cantidad</th><!-- Quantity -->
<th>Unitario</th><!-- Unit Price -->
<th>Mano de Obra</th><!-- The price of the product itself -->
<th>Genero</th><!-- The price of the customization -->
</tr>
</thead>
<tbody>
<tr class="producto"><!-- Product line -->
<td><button>-</button></td><!-- "Remove" button, should remove the product and it's customizations -->
<td><select>Producto</select></td><!-- Choose category -->
<td><select>Modelo</select></td><!-- Choose product -->
<td><input type="text" class="cantidad" /></td><!-- Enter quantity -->
<td><input type="text" class="unitario" /></td><!-- Enter unit price -->
<td>$ <span class="mano_obra"></span></td><!-- Line total. The product lines calculates on this column -->
<td><button>+</button></td><!-- "Add customization" button. Should add a line like the next <tr> -->
</tr>
<tr class="genero"><!-- Customization line -->
<td><button>-</button></td><!-- "Remove" button, should remove only this customization line -->
<td>Genero</td><!-- Fixed text -->
<td><input type="text" class="genero" /></td><!-- Enter customization description -->
<td><input type="text" class="cantidad" /></td><!-- Enter quantity -->
<td><input type="text" class="unitario" /></td><!-- Enter unit price -->
<td>&nbsp;</td><!-- On customizations, this column is empty -->
<td>$ <span class="genero"></span></td><!-- Line total. The customizations calculates on this column -->
</tr>
<tr class="genero">
<!-- Another customization for the first product -->
</tr>
<tr class="genero">
<!-- Another one -->
</tr>
<tr class="producto">
<!-- A different product -->
</tr>
<tr class="genero">
<!-- The new product customization -->
</tr>
<!-- (etc) -->
</tbody>
<tfoot>
<tr>
<td colspan="5">Subtotales</td><!-- Fixed text -->
<td>$ <span class="subtotal_mano_obra"></span></td><!-- SUM of each line total, for products -->
<td>$ <span class="subtotal_genero"></span></td><!-- SUM of each line total, for customizations -->
</tr>
</tfoot>
</table>


I've tried to do this:



<tbody data-bind='foreach: lineas_pedido'>
<tr class="producto">
<!-- All the bindings here works fine -->
</tr>
<!-- ko foreach: generos -->
<tr class="genero">
<!-- ... -->
</tr>
<!-- /ko -->
</tbody>


But after getting errors and looking, came to this: Knockout.js containerless "foreach" not working with <table>



So, I found this plugin: https://github.com/mbest/knockout-repeat
And now my code looks like this:



<tbody data-bind='foreach: lineas_pedido'>
<tr class="producto">
<!-- All the bindings here works fine -->
</tr>
<tr class="genero" data-bind="repeat: {foreach: generos, item: '$genero'}">
<!-- ... -->
</tr>
</tbody>


My question is: Is there any way to avoid using the plugin, and accomplish the same result using native KO templating/bindings?



Thanks in advance.



Edit:



Here is the jsfiddle, I've added a resource linking to my sample data (categories and products).



Here is the actual code on my testing host.



Also, I've used this example as the start point.





Displaying the UK on a Google map

I have created an application in which I have displayed a Google map (version 3.0 tablet).



I need to show the UK, with zoom, when I load it for the first time.



The user should be able to zoom in and zoom out.



How can I do this?





what is the specific re for this

I'm trying to use python re to find a set of the same letter or number repeated a specific number of times. (.) works just fine for identifying what will be repeated, but I cannot find how to keep it from just repeating different characters. here is what I have:



re.search(r'(.){n}', str)


so for example it would match 9999 from 99997 if n = 4, but not if n = 3.

thanks





Javascript/jQuery: Unable to get proper keyCode when capsLock is ON

I'm trying to determine the proper key/char code in javascript when a key is pressed.
It seems that when the CapsLock key is on, lowercase letters are not detectable.



Try the combinations:
1. a = a (97) shift:false
2. Shift+A = A (65) shift:true
3. Capslock,A = A (65) shift:false
4. Capslock, Shift+A = A (65) shift:true -- this should be 'a'


Cases 2 & 4 are indistinguishable.



A simple fiddle to illustrate the problem.
http://jsfiddle.net/sramam/pet5G/3/



OUTPUT:
keypress 'a' shift:false charCode97 keyCode:97 which:97
keypress 'A' shift:true charCode65 keyCode:65 which:65
(CAPSLOCK ON)
keypress 'A' shift:false charCode65 keyCode:65 which:65
keypress 'A' shift:true charCode65 keyCode:65 which:65


I only have a MacPro(Lion) to try this on.
Is it even possible to detect character to be rendered correctly?





Membership testing in a large list that has some wildcards

How do I test whether a phrase is in a large (650k) list of phrases when that list includes special categories?



For instance, I want to test if the phrase ["he", "had", "the", "nerve"] is in the list. It is, but under ["he", "had", "!DETERMINER", "nerve"] where "!DETERMINER" is the name of a wordclass that contains several choices (a, an, the). I have about 350 wordclasses and some of them are quite lengthy, so I don't think it would be feasible to enumerate each item in the list that has one (or more) wordclasses.



I would like to use a set of these phrases instead of slowly working my way through a list, but I don't know how to deal with the variability of the wordclasses. Speed is pretty important, since I need to make this comparison hundreds of thousands of times per go.





Random split list, keeping the original order in new lists

I am having a hard time formulating my question so I'll just show by example.



x = ['abc', 'c', 'w', 't', '3']
a, b = random_split(x, 3) # first list should be length 3
# e.g. a => ['abc', 'w', 't']
# e.g. b => ['c', '3']


Is there an easy way of splitting a list into two random samples while maintaining the original ordering?






edit I know that I could use random.sample and then reorder, but I was hoping for an easy, simple, one line method.





Javascript While loop integers

I have to create a while loop displaying the integers from 1-20 but only 5 integers per line.
I can't get the 5 integers per line part. What is the best way to do that?





Slickgrid add new row on demand

Is there a way to add a new row to a slickgrid on demand? For example, have a button on the page that shows the new row when clicked.





Android listview with multiple controls

I am new to android. I am developing an application in which there is a list view of students with edit and delete buttons. Like







 STUDENT LIST


[ABC]              [edit]              [delete]



[DEF]              [edit]              [delete]







With this code im able to list student details in a <Textview>



public class DataBaseDemoActivity extends ListActivity {
/** Called when the activity is first created. */
SQLiteDatabase db;
Button btnInsert;
ArrayAdapter<String> students;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try{
db=openOrCreateDatabase("StudentDB",SQLiteDatabase.CREATE_IF_NECESSARY,null);

Cursor c=db.rawQuery("SELECT * FROM temp",null);
String[] students = new String[c.getCount()];

if (c.moveToFirst())
{
for (int i = 0; i < c.getCount(); i++)
{
students[i] = c.getString(0).toString()+" "+c.getString(1).toString();
c.moveToNext();
}
}
c.close();

setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item, students));

ListView lv = getListView();
lv.setTextFilterEnabled(true);

lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// When clicked, show a toast with the TextView text
Toast.makeText(getApplicationContext(), ((TextView) view).getText(),
Toast.LENGTH_SHORT).show();
}
});


}catch(SQLException e)
{
}
}


}



I need to store the id of the record with in the list view so that when i click on the edit or delete button, i'll have to find out the id and make changes on the DB. How can i set values to two fields say <TextView>[show details] and <EditText>[visibility: insisible - to save id of the record]. I am able to get the details to the <TextView> using the above code. Any suggestion will be appreciated.





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?





Friday, April 20, 2012

Why I am getting Could not find multi_json-1.3.1 in any of the sources?

Hi folks I have simple Rails application.I want to deploy it in Heroku.When I run the below command



git push heroku master


The below error message is displayed.



 Could not find multi_json-1.3.1 in any of the sources
!
! Failed to install gems via Bundler.
!
! Heroku push rejected, failed to compile Ruby/rails app


Here is my Gemfile



 gem 'rails', '3.2.3'
gem 'pg'
group :assets do
gem 'sass-rails', '~> 3.2.3'
gem 'coffee-rails', '~> 3.2.1'
gem 'therubyracer', :platform => :ruby
gem 'uglifier', '>= 1.0.3'
end
gem 'jquery-rails'


Any help is appreciated.Thank you.





JavaScript to Convert Byte[] to Image in Html page [closed]

I'm creating one application to display the selected image from Windows Phone library to webpage. I have converted the choosen photo to byte[] and then string, passed to html page.



<script type="text/javascript">
function CallBack(jsonstring)
{
var bytes = [];
for (var i = 0; i < jsonstring.length; ++i)
{
bytes.push(jsonstring.charCodeAt(i));
}
var bMap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
document.getElementById('myimg').src =bMap;
}
</script>


But it is not working... getting unknown error.



Could anybody help me please!!!





How to override compiler options for referenced c++ project in visual studio

I am using visual stuido 2010.



I have a static library call "common library". This common library is referenced by many other projects. These projects use the common library by "add new reference" (in project properties -> common properties -> add new reference).



All these projects have their special compiler options/predefined macros. Common library needs to conform their settings, or the compilation fails. Is there any simple way to achieve this?



The current solution is: copy a new "common library" project file for each project, and set the options/macros in the new project file. It is very painful.





SQL Server lock issue (distributed transactions with WCF)

I'm having a problem with distributed transactions.



I'm using SQL Server 2008 R2, Windows 7, .Net 4.0.



Here's what I actually want to do:




  • I have a buffer database (named A)

  • I have another database (named B)

  • I want to send data from database A to database B through a WCF webservice (SOAP over HTTP, A and B not on the same machine)

  • If the data is successfully sent to database B, data is removed from database A



Everything is part of a transaction, so the whole operation is atomic.



Here's what I'm currently trying to do sequentially (everything in a transaction):




  1. I read a chunk from database A (say 50 rows)

  2. I update rows read in step 1 (I actually set the boolean Sent column of rows with the value true, so in the future I know that these rows are sent)

  3. I consume (client side) a WCF webservice (SOAP 1.2, wsHttpBinding) that is part of the transaction flow (blocking synchronous call). The webservice request sends the data read in step 1

  4. The webservice implementation (server side) inserts data in database B (data that is contained in the webservice request)


    • if no exception is received from the server, data with the Sent value as true are removed from database A

    • if a specific FaultException is received from the server, data with the Sent value as true are removed from database A

    • for other FaultExceptions and other exceptions (endpoint not found, or anything else), data with the Sent value as true are not removed from database A




Note: there are actually multiple buffer databases (A1, A2, A3..., AN) and multiple target databases (B1,.... BN). There are N threads to deal with N databases.



If I run my server and my client, everything is working just fine. Data is "transferred" atomically per chunks from database A to database B.
When I brutally stop my client in the middle of the transaction (process killed), most of the time everything is fine (i.e. data is not removed from database A nor added to database B).



But sometimes (this is my actual problem), my database B becomes locked. The only option to unlock it is to terminate the server process.



When the problem occurs, I can see in MSDTC that there is an active transaction (note that in the screenshot there are 3 transactions as I'm currently dealing with 3 buffer databases and 3 target databases, but sometimes there is only 1 transaction even if there are 3 DB).



enter image description here



I see that database B is locked when trying to run a SELECT againt database B. As you can see in the picture below, my SELECT request is blocked by session ID 67 which corresponds to an INSERT in database B by the server process.



enter image description here



The lock remains forever (no transaction timeout, even after 1+ hour) until the server process is terminated. I can't validate or cancel the transaction in MSDTC, I get a warning saying that "it cannot be aborted because it is not "In Doubt"".



Why does the database B remained locked? If the client is terminated, shouldn't the transaction fail and the lock on database B be released after some timeout?



Here's my code for server side:



// Service interface
[ServiceContract]
public interface IService
{
[OperationContract]
[FaultContract(typeof(MyClass))]
[TransactionFlow(TransactionFlowOption.Allowed)]
void SendData(DataClass data);
}

// Service implementation
[ServiceBehavior()]
public partial class Service : IService
{
[OperationBehavior(TransactionScopeRequired = true)]
public void SendData(DataClass data)
{
if (data == null)
{
throw new FaultException<MyClass>(new MyClass());
}

try
{
// Inserts data in database B
using (DBContextManagement ctx = new DBContextManagement())
{
// Inserts data using Entity Framework
// This will add some entities to the context
// then call context.SaveChanges()
ctx.InsertData(data);
}
}
catch (Exception ex)
{
throw new FaultException<MyClass>(new MyClass());
}
}
}


Here's my server side configuration (self-hosted WCF service):



<system.serviceModel>
<services>
<service name="XXXX.MyService">
<endpoint binding="wsHttpBinding" bindingConfiguration="WsHttpBinding_IMyService" contract="XXXX.IMyService" />
</service>
</services>
<bindings>
<wsHttpBinding>
<binding name="WsHttpBinding_IMyService" transactionFlow="true" allowCookies="true" >
<readerQuotas maxDepth="32" maxArrayLength="2147483647" maxStringContentLength="2147483647" />
<security mode="None" />
</binding>
</wsHttpBinding>
</bindings>
<behaviors>
<serviceBehaviors>
<behavior name="">
<serviceTimeouts transactionTimeout="00:00:20" />
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="true" />
<dataContractSerializer maxItemsInObjectGraph="2147483647" />
</behavior>
</serviceBehaviors>
</behaviors>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
</system.serviceModel>


Here's my client code:



try
{
using (DBContextManagement ctx = new DBContextManagement())
{
using (TransactionScope ts = new TransactionScope(TransactionScopeOption.Required, new TransactionOptions { IsolationLevel = System.Transactions.IsolationLevel.ReadUncommitted, Timeout = new TimeSpan(0, 0, 30) }, EnterpriseServicesInteropOption.None))
{
// First of all, retrieves data from database A
// Internally queries the database A through Entity Framework
var data = ctx.GetData();

// Mark data as sent to the server
// Internally updates the database A through Entity Framework
// This actually set the Sent property as true, then call
// context.SaveChanges()
ctx.SetDataAsSent(data);

try
{
// Send data to the server
MyServiceClient proxy = new MyServiceClient();
MyServiceClient.SendData(data);

// If we're here, then data has successfully been sent
// This internally removes sent data (i.e. data with
// property Sent as true) from database A through entity framework
// (entities removed then context.SaveChanges)
ctx.RemoveSentData();
}
catch (FaultException<MyClass> soapError)
{
// SOAP exception received
// We internally remove sent data (i.e. data with
// property Sent as true) from database A through entity framework
// (entities removed then context.SaveChanges)
ctx.RemoveSentData();
}
catch (Exception ex)
{
// Some logging here
return;
}

ts.Complete();
}
}
}
catch (Exception ex)
{
// Some logging here (removed from code)
throw;
}


Here's my client configuration:



<system.serviceModel>
<bindings>
<wsHttpBinding>
<binding name="WsHttpBinding_IMyService"
closeTimeout="00:01:00"
openTimeout="00:01:00"
receiveTimeout="00:10:00"
sendTimeout="00:01:00"
allowCookies="false"
bypassProxyOnLocal="false"
hostNameComparisonMode="StrongWildcard"
transactionFlow="true"
maxBufferPoolSize="2147483647"
maxReceivedMessageSize="2147483647"
messageEncoding="Text"
textEncoding="utf-8"
useDefaultWebProxy="true">

<readerQuotas maxDepth="32"
maxStringContentLength="2147483647"
maxArrayLength="16384"
maxBytesPerRead="4096"
maxNameTableCharCount="16384" />
<security mode="None">
<transport clientCredentialType="None" proxyCredentialType="None" realm="" />
<message clientCredentialType="UserName" algorithmSuite="Default" />
</security>
</binding>
</wsHttpBinding>
</bindings>

<client>
<endpoint address="http://localhost:8080/MyService.svc"
binding="wsHttpBinding"
bindingConfiguration="WsHttpBinding_IMyService"
contract="XXX.IMyService"
name="WsHttpBinding_IMyService" />
</client>

</system.serviceModel>


So my questions are:




  • Is my pattern/design with distributed transactions a valid and robust design?

  • What could cause my database B to be locked for infinite time if my client's transaction is brutally terminated?

  • What should I change (config and/or code and/or design) to make it work as expected (i.e. if my client process dies/crashes, I want the transaction to be aborted so the database B is not locked)?



Thanks.






EDIT



I do think I over-simplified my use case. It looks like I'm actually doing a simple data replication between multiple SQL Server instances. That's not well explained (my bad), that's not what I'm trying to achieve.



I'm not simply duplicating data. I read from A on machine M1 then write to B on machine M2, but what's written is not what I've read but some calculated value that comes from what was read.
I'm pretty sure SQL Server replication services could handle business computation for me, but I can't go this way for some reasons:




  • I can't change the webservices thing because the interface is now defined and fixed.

  • I can't use SQL Server replication because I'm actually not responsible of the server side (which writes to database B). I'm even not sure that there will be SQL Server on the other side (could be a Java backoffice with MySQL, PostgreSQL or anything)

  • I can't use SQL Server service broker or any message-oriented-middleware (which would fit IMO) for same reason (potentially heterogeneous databases and environments)



I'm stuck by WCF, and I can't even change the binding configuration to use MSMQ or whatever because of interoperability requirements. MSMQ is great for sure (I'm already using it in another part of the project), but it's Windows only. SOAP 1.2 is a standard protocol, and SOAP 1.2 transactions are standard too (WS-Atomic implementation).



Maybe the WCF transaction thing is not a good idea, actually.



If I have understood correctly how it actually works (please correct me if I'm wrong), it simply allows to "continue" the transaction scope on server side, which will require a transaction coordinator to be configured on server side, which probably breaks my interoperability needs (again, there could be a database on server side that does not integrate well with the transaction coordinator).