Wednesday, May 23, 2012

filtering non referenced member nodes using XSLT

An OpenStreetMap xml document is composed (among other things) of a set of "node" elements and a set of "way" elements.



The "node" elements can (optionally) nest "tag" elements.



The "way" elements are composed by an ordered list of "node" elements, referenced by the nested elements "nd", with their attribute "ref" pointing to the attribute "id" at the "node" elements.



Here an example:



<?xml version="1.0" encoding="UTF-8"?>
<osm version="0.6" generator="CGImap 0.0.2">
<node id="1726631203" lat="50.8500083" lon="4.3553223" visible="true" version="6" changeset="9938190" timestamp="2011-11-24T22:05:32Z"/>
...
<way id="160611697" user="toSc" uid="246723" visible="true" version="1" changeset="11385198" timestamp="2012-04-22T14:57:19Z">
<nd ref="1726631203"/>
<nd ref="1726631223"/>
<nd ref="1726631213"/>
<nd ref="1726631205"/>
<nd ref="1726631185"/>
<nd ref="1726631203"/>
</way>
...
</osm>


My question is how, using XSLT, could I do the following transformation ?




  • Filtering all the node elements that are not referenced by any way element.

  • Filtering the way elements that reference node elements not included in the source xml document.

  • Changing the attribute "visible" to "false", to any "node" element not having "tag" children elements.



Any other elements should remain in the generated xml.





SQL Compact Edition (CE) and password complexity requirements

In Windows 7 we have group policies enforcing password complexity requirements which demands "better" password for SQL server express.



Does this impact SQL CE as well?





PHPass implementation in java

I want to use PHPass encryption technique in java. Is there any way we can achieve it?





How to sum two lists element-wise

I want to parse a file line by line, each of which containing two integers, then sum these values in two distinct variables. My naive approach was like this:



my $i = 0;
my $j = 0;
foreach my $line (<INFILE>)
{
($i, $j) += ($line =~ /(\d+)\t(\d+)/);
}


But it yields the following warning:




Useless use of private variable in void context




hinting that resorting to the += operator triggers evaluation of the left-hand side in scalar instead of list context (please correct me if I'm wrong on this point).



Is it possible to achieve this elegantly (possibly in one line) without resorting to arrays or intermediate variables?






Related question: How can I sum arrays element-wise in Perl?





Non capturing group issue

Why following return ["vddv"] instead of ["dd"]:



"aaavddv".match(/(?:v).*(?:v)/)




jquery rounded corners on first and last li

How do i create rounded top left and bottom left corners of the first LI and rounded top right and bottom right of the last li using jquery?



I understand that i could use border-radius but that wont be a cross browser solution.



Here is what i have started: http://jsfiddle.net/c7NyZ/1/



If you can add a resource to the jsfiddle and update it id be greatful.



HTML:



<div id="new-menu-upper">
<ul id="top-nav">
<li><a href="/t-topnavlink.aspx">menu item 1</a></li>
<li><a href="/t-topnavlink.aspx">menu item 2</a></li>
<li><a href="/t-topnavlink.aspx">menu item 3</a></li>
<li><a href="/t-topnavlink.aspx">menu item 4</a></li>
<li><a href="/t-topnavlink.aspx">menu item 5</a></li>
<li><a href="/t-topnavlink.aspx">menu item 6</a></li>
</ul>
</div>


CSS:



div#new-menu-upper {
border: 0 solid red;
height: 40px;
margin: 0 5px 10px;
padding-top: 63px;
}
ul#top-nav li {
background-image: url("http://i47.tinypic.com/21nqxjc.png");
background-repeat: repeat;
border-right: 2px solid lightgrey;
float: left;
height: 41px;
width: 156px;
}
ul#top-nav li a {
color: White;
display: inline-block;
font-family: Arial;
font-size: 12px;
font-weight: bold;
letter-spacing: 1px;
padding-left: 38px;
padding-top: 12px;
text-transform: uppercase;
}


EDIT: IT HAS TO BE A CROSS BROWSER SOLUTION, MEANING IT HAS TO WORK WITH MIN IE7
*EDIT: ADDED JQUERY.CORNERS RESOURCE TO JSFIDDLE AND TRIED TO MAKE FIRST LI RENDER WITH CORNER BUT ITS NOT WORKING - PLEASE CAN YOU HELP - http://jsfiddle.net/c7NyZ/4/ *





Using "libs" and "lib" directories?

I use the directory "libs" for a native libs, and "lib" for jars. Ant compilation works fine, if to override the property "jar.libs.dir=lib" in local.properties file. looks good. But a jars from "lib" directory was not included into APK file.



You can see base build.xml (android_sdk/tools/ant/build.xml)



            <classpath>
<fileset dir="${extensible.libs.classpath}" includes="*.jar" />
</classpath>


where extensible.libs.classpath - is jar.libs.dir.



How to fix it? I can't to use only one "libs" dir.



I saw the log file (classes.dex.d), my jars are not included. but if I use "jar.libs.dir=lib" AND move the jars into "libs" - works fine! I don't understand this regularity





Is this thread safe code when I receive multiple client connections?

I am using this code for receiving log messages from my clients I receive more than 1000 connections per minute. I want to increase my log handling. I did with java threading. I have a doubt if it receive multiple client connection what happens. Is this thread safe? Can you give your suggestions. It will help to improve this code.



  public class CentralizedLogging implements Runnable {

/**
* Field logDir - Where the plugin logs can be stored .
*/
public static String logDir;

/**
* Field server - Server Socket .
*/
ServerSocket server = null;
/**
* Field LOGGER.
*/
public static final Logger LOGGER = Logger.getLogger(CentralizedLogging.class.getName());

/**
* @param port - Port which the server is binds .
* @param logDir String
*/
public CentralizedLogging(String logDir , int port){
try {
this.logDir = logDir;
server = new ServerSocket(port);
} catch (IOException e) {
LOGGER.log(Level.SEVERE,"It may be due to given port already binds with another process , reason {0}",new Object[]{e});
}
}

/**
* Extension point for central log server . To start receiving connections from remote end .
*/
public void run(){
while(true){
try{
new LogWriter(server.accept());
}catch (Exception e) {
LogWriter.log("Interrupted exception " + e.getMessage());
}
}
}

/**
* args[0] - logging location .
* args[1] - which port the server can start. It must be a integer.
* @param args
*/
public static void main(String[] args) {
try{
CentralizedLogging logServer = new CentralizedLogging(args[0], Integer.parseInt(args[1]));
}catch(Exception e){
LOGGER.log(Level.SEVERE,"Unable to start log server from this location : {0} , port : {1} , This may be due to given port is not a number or this port is not free exception trace {2}", new Object[]{args[0],args[1],e});
}
}


}



/**
* Used for writing client packets into logs Dir .
*/
class LogWriter implements Runnable{

/**
* Field client - Socket Client .
*/
Socket client;

/**
* Constructor for LogWriter.
* @param client Socket
* @throws IOException
*/
public LogWriter(Socket client) {
this.client = client;
}

public void run(){
write();
try{
this.client.close();
}catch(IOException io){
System.out.println("Error while closing connection , reason "+io);
}
}

/**
* Method write.
*/
public void write(){
try{
String date = new SimpleDateFormat("yyyy_MM_dd").format(new Date());
File file = new File(CentralizedLogging.logDir+client.getInetAddress().getHostName() + "_"+ date+".log");
write(client.getInputStream(),file);
}catch(Exception e){
log("Error in writing logs :: Host Name "+client.getInetAddress().getHostName() +" , Occured Time "+System.currentTimeMillis()+", Reason "+e.getMessage()+"\n\n");
}
}

/**
* Method write.
* @param in InputStream
* @param file File
* @throws Exception
*/
public synchronized static void write(InputStream in , File file) throws Exception{
RandomAccessFile writer = new RandomAccessFile(file, "rw");
writer.seek(file.length()); //append the file content to the existing file or creates a new one .
writer.write(read(in));
writer.close();
}

/**
* This method is used for monitoring errors that will be occured on writing plugin logs .
* @param msg
*/
public static void log(String msg){
File file = new File(CentralizedLogging.logDir+"plugin_error_"+new SimpleDateFormat("yyyy_MM_dd").format(new Date())+".log");
try {
write(new ByteArrayInputStream(msg.getBytes()),file);
} catch (Exception e) {
}
}

/**
* Method read.
* @param in InputStream
* @return byte[]
* @throws IOException
*/
public static byte[] read(InputStream in) throws IOException{
ByteArrayOutputStream out = new ByteArrayOutputStream();
int read = -1;
byte[] buffer = new byte[1024];
while((read = in.read(buffer)) > -1){
out.write(buffer,0,read);
}
return out.toByteArray();
}

/**
* Method close.
* @param stream Object
*/
public static void close(Object stream){
try{
if(stream instanceof Writer){
((Writer)stream).close();
}else if(stream instanceof Reader){
((Reader)stream).close();
}
}catch (Exception e) {
}
}


}





Adding capability to convert html into a msword document

I am adding capability in my application to convert html into a msword document.



I am trying to use Apache POI to integrate in my application but I didn't find anything related that help me to integrate the Apache-POI with Ruby ( Ruby-On-Rails application).



If you have any idea or source, then please let me know .



Any help will be really appreciated .





Adding a Google Map marker with Javascript from within <body>

I am trying to add a marker from within the tags and not between the tags. My map is created (succesfully) into the head.Same for markers IF i put the code within .



Problem is that i am using a CMS and need tags to be related pages.



The code below is within the usual tags.



<% control ChildrenOf(montreal) %>
<img ..... (this is the Google Icon whose number is called via $NoOfMarker texfield)
$NameOfVendor
. . .

<script type="application/javascript">
<!-- PROBLEM IS HERE -->
<!-- I want to add a marker specific to that child page using $Latitude and $Longitude textfields in the CMS (this works i checked) -->

marqueurX=new google.maps.LatLng($Latitude, $Longitude);
// go get $Latitude and $Longitude of the child page
myMarkerX = new google.maps.Marker({
position: marqueurX,
map: map,
title: '$Nom',
clickable: true,
icon: 'http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld={$NoOfMarker}|bebe00|000000',
shadow: ombre
});

<!--
this code if placed into the <head> of the mother page, is working
but once placed inside <% control ... %> (or outside or out of <head>
this code does nothing - No errors, no markers either
i suspect a SCOPE or CLOSURE issues
-->
</script>
<% end_control %>


Thanks!





ADO.NET how to use parameter in dataset?

dbDataSet



Where i need initialize parameter, for when form will open, to make it work?



Query:



SELECT id, id_work, name FROM ttz WHERE (id_work = @idwork)


I want @idwork value = textBox1.Text





CSS written after pseudo-element not working

I'm working on Ruby-on-Rails 3.2.1. I've following DOM structure.



UPDATE: removed the </img> tag as mentioned by Gaby. Problem still persists.



<div class="frame">
<img src='SOME_PATH' class="frame-image">
</div>?


And following CSS



.frame { position:relative;border:1px solid #CCC;border-radius:2px;-moz-border-radius:2px; }
.frame:before
{
position:absolute;
content:'';
border:2px solid #F2F2F2;
height:100%;width:100%;
box-sizing:border-box;
-moz-box-sizing:border-box;
-webkit-box-sizing:border-box;
}
img.frame-image /* IT WON't BE APPLIED?! */
{
min-width:30px;min-height:30px;
max-width:200px;max-height:200px;
}?


The problem I'm facing is, CSS applied to img.frame-image is not working/not getting applied. I tried on Chrome 18 and FireFox 12. I don't see the style in Chrome's element inspector or in FireBug. It is also not getting overridden by any other CSS.



For demo I tried to create jsfiddle for this. It works there!



But surprisingly when I write img.frame-image CSS above .frame:before CSS, it works!!



.frame { position:relative;border:1px solid #CCC;border-radius:2px;-moz-border-radius:2px; }
img.frame-image /* NOW IT WILL BE APPLIED */
{
min-width:30px;min-height:30px;
max-width:200px;max-height:200px;
}?
.frame:before
{
position:absolute;
content:'';
border:2px solid #F2F2F2;
height:100%;width:100%;
box-sizing:border-box;
-moz-box-sizing:border-box;
-webkit-box-sizing:border-box;
}


Any idea why is it happening? is it framework (RoR) related issue or CSS semantics?





Ajax request not working (asp.net-mvc)

View:



@{
AjaxOptions ajax = new AjaxOptions() { HttpMethod = "POST", UpdateTargetId = "sub_id" };
Layout = null;
}
<div id="sub_id">
</div>
@using (Ajax.BeginForm(ajax))
{
@Html.TextBox("email");
<input type="submit" value="???????????" />
}


controller:



[HttpPost]
public ContentResult LeftMenuSubscription(string email)
{
return new ContentResult(){Content = "<script>alert('Thanks')</script>"};
}


"Thanks" alert show.



but in div 'sub_id' set all page(...).



<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script> 


- connected.



html:



<html>
<head>
<title>??????? ????????</title>
<link href="/Content/Site.css" rel="stylesheet" type="text/css">
<script src="/Scripts/jquery-1.7.2.min.js" type="text/javascript"></script>
<script src="/Scripts/jquery.unobtrusive-ajax.min.js" type="text/javascript"></script>
<script src="/Scripts/jquery.validate.min.js" type="text/javascript"></script>
<script src="/Scripts/jquery.validate.unobtrusive.min.js" type="text/javascript"></script>
<script src="/Scripts/jQueryFixes.js" type="text/javascript"></script>
</head>
<body>
....
<form action="/" data-ajax="true" data-ajax-method="POST" data-ajax-mode="replace" data-ajax-update="#sub_id" id="form0" method="post">
<input id="email" name="email" type="text" value="">
<input type="submit" value="???????????">
</form>
...
</body>
</html>


what could be the problem?





Patenting a Control Scheme for Touch Screen Game?

I am working on a platform game for ios/android and I've developed a control scheme that allows for precise directional movement and jumping, as well as four action inputs. The control scheme takes advantage of the multi-touch capabilities of ios and android devices. I haven't seen a control scheme like this used in any other games or apps. The concept centers around the a group of icons in fixed positions on the screen and takes up very little screen real estate.



The design is unique and would be effective in other types of games like fps shooters or fighting games, which is has got me thinking; Is it possible to patent a control scheme? The design and implementation is unique and specific, but it uses an multi-touch, a concept I didn't invent on a device I didn't invent. However, I've never seen this particular type of input used to achieve this particular type of character movement.



Would a control scheme be patentable in a circumstance like this?





security risk with setup.exe file

i exract my project setup file with setup factory. But windows internet explorer and Symentec Endpoint Protection acts like a harmful application. What can i do for solve this problem?



enter image description here



enter image description here





C# 3.0 book suggestions

I am learning c# 3.0.



I need books that give a lot of examples in advanced concepts in c#. I currently study using Wrox c# books. They are not sufficient for me. If you are a c# developer, you would know what advanced concepts I would expect. So please suggest a book, you have read and used.





How many levels of pointers can we have?

How many pointers (*) are allowed in a single variable?



Let's consider the following example.



int a = 10;
int *p = &a;


Similarly we can have



int **q = &p;
int ***r = &q;


and so on.



For example,



int ****************zz;




can not generate necessary file when compile IDL file in visual studio 2010

i'm learning about COM through an internet tutorial(http://www.codeguru.com/cpp/com-tech/activex/tutorials/article.php/c5567/Step-by-Step-COM-Tutorial.htm). The first thing is creating a IDL file and compile it to create another 5 files. The detail is after:




  1. Open VS2010

  2. Create Win32 DLL project name AddObj

  3. Add IAdd.idl file with the content




    import "unknwn.idl";



    [
    object,
    uuid(1221db62-f3d8-11d4-825d-00104b3646c0),
    helpstring("interface IAdd is used for implementing a super-fast addition Algorithm")
    ]



    interface IAdd : IUnknown
    {
    HRESULT SetFirstNumber(long nX1);



    HRESULT SetSecondNumber(long nX2);
    HRESULT DoTheAddition([out,retval] long *pBuffer);
    };



    [
    uuid(3ff1aab8-f3d8-11d4-825d-00104b3646c0),
    helpstring("Interfaces for Code Guru algorithm implementations .")
    ]
    library CodeGuruMathLib
    {
    importlib("stdole32.tlb");
    importlib("stdole2.tlb");



    interface IAdd;
    }





After that, follow the tutorial, if i compile IAdd.idl file, it will generate:



--IAdd.h Contains the C++ style interface declarations.



--dlldata.c Contains code for proxy DLL. Useful when invoking the object on a different process/computer.



--IAdd.tlb Binary file , with a well defined format that completely describes our interface IAdd along with all it's methods. This file is to be distributed to all the clients of our COM component.



--IAdd_p.c Contains marshalling code for proxy DLL. Useful while invoking the object on a different process/computer.



--IAdd_i.c Contains the interface IIDs



but when i compile IAdd by right click it and choose compile in shortcut menu, there is no file being generate. But when open view class, i can see IAdd interface with some method.



I also try it by compile it manually by download midl.exe from internet and run in command line but it failed.



I fine a lot of material by google and all said that i can compile idl file by visual studio but i try many time, on my both computer but no file being generate after i compile idl file. I also install new Win7, new visual studio 2010 ultimate but nothing change.





how to find address from lat long in android

Please Help me in finding address from given lat long in android.



As I have put the lat long values from gps service I need to find the user location where the user is standing.





Resizing Silverlight MediaElement Crashes Plugin

I'm building a Silverlight option in my HTML5 video player (using the JavaScript API). Traditionally, with the Flash player and the HTML5 video I would just resize the video to whatever the container size is.



However, with Silverlight, if I resize certain MP4 videos up, it crashes the plugin. Some videos don't do this, but the ones that do, do it every time. I experimented with an even size factor like 1.5x or 2x but that didn't help. Sizing it down has no problems.



Has anyone experienced this? Is it a known bug? Are there workarounds? Besides, "don't do that", for which I'm aware MS recommends not resizing the video at all. I can accept a performance degradation, but crashing is a concern.





Translating SQL query to Doctrine2 DQL

I'm trying to translate this (My)SQL to DQL



SELECT content, created, AVG(rating)
FROM point
GROUP BY DAY(created)
ORDER BY created ASC


And I'm stuck at GROUP BY part, apparently DAY/WEEK/MONTH isn't recognized as valid "function".



[Semantical Error] line 0, col 80 near '(p.created) ORDER': Error: Cannot group by undefined identification variable.



$this->createQueryBuilder('p')
->select('p')
->groupBy('DAY(p.created)')
->orderBy('p.created', 'ASC')


Q: Is it possible to create this kind of query with query builder, or should I use native query?





ASP:CHART legend check box series control

I have a fully functioning Dynamic chart control( just the regular ASP.net Chart ) It works great but I've run into a problem trying to add check boxes to the legend. I'm trying to add them next to the series names so the user can hide or view the respective series data. The chart is plotting data for roughly 42 employees. So being able to select and hide data is very important. I've been researching this for a few days now and I've found examples for 3rd party chart tools but i need to do this in MSVS 2010 standard charting tool.



This is how I create the Chart.



 for (int emp = 1; emp < empRowList.Length; emp++)
{
chartB.Series.Add(empRowList[emp]);
chartB.Series[empRowList[emp]].ChartType = SeriesChartType.Point;
chartB.Series[empRowList[emp]].MarkerSize = 10;
chartB.Series[empRowList[emp]].MarkerStyle = MarkerStyle.Star4;

for (int month = 1; month < 12; month++)
{
chartB.Series[empRowList[emp]].Points.AddXY(mfi.GetMonthName(month), employeeStats[month, emp]);
chartB.Series[empRowList[emp]].Points[chartB.Series[empRowList[emp]].Points.Count - 1].ToolTip = empRowList[emp] + " - " + employeeStats[month, emp];
}
}


Here is how I format the chart



 chartB.DataSource = t.Tables["info"];
chartB.DataBind();
chartB.Legends.Add(new Legend("Legend"));
chartB.Legends["Legend"].Alignment = StringAlignment.Center;
chartB.Legends["Legend"].Docking = Docking.Top;


I looked through this post thinking it could be augmented to help but since his series aren't added dynamically i'm not sure if it is the right direction to pursue.



ASP .net 4 Chart Control Legend formatting is not displaying at all



I've also looked in to using custom legends but read that they aren't linked to the data so i thought that might also be that wrong direction.



If anyone could help it would be greatly appreciated i'm kind of at a stand still till I can figure this out.



Thanks in advance





How to parse bad html?

I am writing a search engine that goes to all my company affiliates websites parse html and stores them in database. These websites are really old and are not html compliant out of 100000 websites around 25% have bad html that makes it difficult to parse. I need to write a c# code that might fix bad html and then parse the contents or come up with a solution that will address above said issue. If you are sitting on idea, an actual hint or code snippet would help.





border-right not showing on first li

I have a specific issue with the following example:
http://jsfiddle.net/c7NyZ/8/



Open it in IE7 or do IE7 mode. The first LI (border-right) seems to have merged with the 2nd li.



I am using a jquery library for the rounded corners.



Can you help me show the border right again like the others?





Selecting stored in variable

Hi I'm trying to create a shopping cart for a college assignment, I'm trying to load a table from the contents of a variable but regardless of what I do it won't recognise its contents.



Here the code snippet



$sql = sprintf("SELECT name, description, price FROM %s WHERE id = %d;",$table, $product_id);
$result = mysql_query($sql);



The table variables contents is being missed out so its looking a nameless table, I've searched Google and found a couple of examples but are working for me.



Does anyone have any ideas?



Thanks Scott.





Tuesday, May 22, 2012

How secure are Cookies when set by an ASP.NET web application?

I want to know how secure a cookie is and if it can be read by other applications other than the one that set it.



I want to set a cookie that will store some sensitive data for my site to read at any time.



Can other applications read cookies that my application sets? If so, do I need to encrypt the data stored in the cookie?



NOTE: I do not have access to SSL.





Android ListView image resize

I have a lazy-loading ListView populated with images gotten over the network. The list rows are set to wrap_content, so once the image loads it resizes and the full scale image will be displayed. It looks great when scrolling down, but when scrolling up the rows resize and force the bottom rows off the screen. How can I prevent this jumpy scrolling while scrolling up?



----- EDIT:



The images are comics of varying sizes. Some are 2 or 3 frames where they aren't very tall. Others are single frame comics where they are much taller. The image needs to take up the full width and the height should not cut off any of the comic.





Can I reference a complete Ruby Net::HTTP request as a string before sending?

I'm using Net::HTTP in Ruby 1.9.2p290 to handle some, obviously, networking calls.



I now have a need to see the complete request that is sent to the server (as one long big String conforming to HTTP 1.0/1.1.



In other words, I want Net::HTTP to handle the heavy lifting of generating the HTTP standard-compliant request+body, but I want to send the string with a custom delivery mechanism.



Net::HTTPRequest doesn't seem to have any helpful methods here -- do I need to go lower down the stack and hijack something?



Does anyone know of a good library, maybe other than Net::HTTP, that could help?



EDIT: I'd also like to do the same going the other way (turning a string response into Net::HTTP::* -- although it seems I may be able to instantiate Net::HTTPResponse by myself?





Can't compile gSOAP with WS-Security support (i.e. wsse-plugin)

On a linux system, I want to create a client app using gSOAP-2.8.8 that interacts with a SOAP service build upon WCF. Therefore, I went through the following:



wsdl2h -t typemap.dat -o myService.h myService.wsdl    
soapcpp2 -Igsoap/import -CLix myService.h


And replaced '#include soapH.h' in wsseapi.h with soapcpp2-generated soapH.h as mentioned in wsseapi.h



Then, the critical step is to manually add the following lines to myService.h



#import "wsse.h"

struct SOAP_ENV__Header"
{
mustUnderstand // must be understood by receiver
_wsse__Security *wsse__Security; ///< TODO: Check element type (imported type)
};


...and compile those files like



g++ -DWITH_DOM -DWITH_OPENSSL -Igsoap -Igsoap/import -Igsoap/plugin -o test \
myService.cpp soapC.cpp soapmyServiceProxy.cpp gsoap/stdsoap2.cpp gsoap/dom.cpp \
gsoap/custom/duration.c gsoap/plugin/wsseapi.cpp gsoap/plugin/smdevp.c gsoap/plugin/mecevp.c \
-L/usr/lib -lssl -lcrypt


I do get object files for all my sources;-) but still end up with two errors at linking stage.



soapC.cpp:203: undefined reference to `soap_in_ns4__duration(soap*, char const*, long long*, char const*)'
soapC.cpp:676: undefined reference to `soap_in_ns4__duration(soap*, char const*, long long*, char const*)'


Edit: As a workaround I currently substitute soap_in_ns4__duration() with soap_in_xsd__duration(), which is implemented in custom/duration.c



Nevertheless, can anyone give me a hint whats going wrong here?! Thanks in advance





how to 'ror 3.2' with 'yui 3.5'?

Trying to write my first RoR application with YUI framework. Was googling for ror+yui manuals with no success. So i went to YUI site. YUI says:



// Put the YUI seed file on your page.
<script src="http://yui.yahooapis.com/3.5.1/build/yui/yui-min.js"></script>


Where it's suppossed to be putted in RoR app?



I've tried to app/assert/javascripts/yui-min.js.

As a result i got <html class="yui3-js-enabled"> in every page. Supposing YUI is working now i've tried to copy-paste "Work with the DOM" example from YUI's page to app/public/index.html. And an error i've received:

Uncaught ReferenceError: YUI is not defined.



Sorry for my English and thanks in advance



P.S.

Tutorial/Suggestions on YUI with Ruby on Rails wasn't helpful for me.





How do i access the information in an hl7 message parsed with nHapi

I am learning how to use nHapi. As many have pointed out, there's not much documentation. Following this doc I've been able to parse a message using the library. But I can't figure out how to access that message using an object model (which is what I really want nHapi to do). Essentially, I want to take an HL7 message as a string and access it using the object model, in the same way that LINQ to SQL takes a database record and lets you access it as an object. I found Parsing an HL7 without apriori messageType knowledge, but it seems to be about something else because the code in the post returns a string instead of an HL7 object (like I need). In the documentation I linked to above they seem to access the parts of a message using a "query"--but I can't find the materials to query IMessages in the library.



Here is the code I'm using, with a line showing what I want to do...



Imports NHapi.Base
Imports NHapi.Base.Parser
Imports NHapi.Base.Model



Module Module1

Sub Main()

Dim msg As String = "MSH|^~\&|SENDING|SENDER|RECV|INST|20060228155525||QRY^R02^QRY_R02|1|P|2.3|QRD|20060228155525|R|I||||10^RD&Records&0126|38923^^^^^^^^&INST|||"
Dim myPipeParser As PipeParser = New PipeParser()
Dim myImsg As IMessage = myPipeParser.Parse(msg)
Dim msgType As String = myImsg.GetStructureName
Dim mySendingFacilityName As String = myImsg.getSendingFacility() //this is what I want

End Sub




How to let a method accept two types of data as argument?

this is somewhat the same question as I've asked some time ago:
How to let a method accept two types of data as argument?



Yet the current situation differs.. a lot.



Take this:



public FormResourceSelector(Dictionary<string, Effect> resourceList, string type)


Alright, nothing wrong with it.
Now I try to run this:



FormResourceSelector frs = new FormResourceSelector(AreaEffect.EFFECTS, "Area effect");
FormResourceSelector frs2 = new FormResourceSelector(DistanceEffect.EFFECTS, "Distance effect");


Both AreaEffect and DistanceEffect (custom classes) derive from Effect.



public class AreaEffect : Effect
{
public static Dictionary<string, AreaEffect> EFFECTS = new Dictionary<string, AreaEffect>();
...
}


For some reason I get the following error while making the new FormResourceSelector instance:



Argument 1: cannot convert from 'System.Collections.Generic.Dictionary<string,SCreator.AreaEffect>' to 'System.Collections.Generic.Dictionary<string,SCreator.Effect>'  


at:



new FormResourceSelector(AreaEffect.EFFECTS, "Area effect");


I suspect the dictonary being a harass, but I don't really know how to fix this.



Thanks for helping me out :).



~ Tgys



EDIT: Easiest would be to allow input of both Dictionary and Dictionary as resourceList in the first code snippet I've given.





Pass parameters to function call in event trigger

Right now I have this



jQuery('.widget-prop').keyup(function() {
var prop = jQuery(this).attr('id');
var val = jQuery(this).val();

stuff;
}


and



jQuery('.widget-prop').click(function() {
var prop = jQuery(this).attr('id');
var val = jQuery(this).val();

stuff;
}


two functions are the same, so I'd like to simplify it by defining external function and calling it with



jQuery('.widget-prop').click('myFunction');


but how would I pass parameters to myFunction?



function myFunction(element) {
stuff;
}


Thanks





Setting up Twitter OAuth without 3rd party libraries

Continuation from Get twitter public timeline, json+C#, no 3rd party libraries



I'm still new to C# and oAuth so please bear with me if I fail to understand anything



I've created a C# class named oAuthClass, and these are the variables I currently have:



    static class oAuthClass
{
public static void run()
{
int oauth_timestamp = GetTimestamp(DateTime.Now);
string oauth_nonce = PseudoRandomStringUsingGUID();
string oauth_consumer_key = "consumer key here";
string oauth_signature_method = "HMAC-SHA1";
string oauth_version = "1.0";
}
}


I've read up on OAuth Signatures, and I chose to use HMAC-SHA1 for now, I don't know how to generate the signature, I'm also extremely confused after reading and seeing stuff like HTTP-Encodings and Base-Strings and whatnot (I've no idea what they mean at all), but my guess is to create a URL that's "Http-encoded", like spaces->"%20"?



In summary:
-What are base-strings?



-Am I right on the spaces->%20 example?



-HMAC-SHA1 involves a message and a key, is the consumer secret the message? Is the consumer key the key then?



-How to create a signature through the use of the HMAC-SHA1 algorithm



-If I do manage to create the signature, how do I pass these values to Twitter?



I could use



http://example.com?consumer_key=asdf&oauth_signature=signaturevalue&etc., 


but I've read and apparantly people use HTTP-Headers or something (again, I don't really know what this is)



Thank you! Again, no 3rd party libraries allowed :(





How to get the id of the user that send the request?

In my app there is a MultiFriendSelector to invite friends.



I want that the recipient see in the canvas page the id of the user that has sent the request via MultiFriendSelector.



I need to get the id without using PHP or other server side language, but I can use javascript or fbml for example.





how to insert and select in mysql with android?

LoginActivity.java



package tn.pack.ordre.enregistrer;


import org.json.JSONException;
import org.json.JSONObject;

import tn.pack.ordre.HomeActivity;
import tn.pack.ordre.R;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

public class LoginActivity extends Activity {

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ecran_accueil);

}

public void btn_enrg(View v){
startActivity(new Intent(getApplicationContext(),EnregistrerActivity.class));
}


public void btn_login(View v) {

EditText u = (EditText) findViewById (R.id.editText_username);
EditText p = (EditText) findViewById (R.id.editText_motdepasse);

String username = u.getText().toString();
String password = p.getText().toString();

UserFunctions userFunction = new UserFunctions();
JSONObject json = userFunction.loginUser(username, password);
Intent home =new Intent(getApplicationContext(),HomeActivity.class) ;

// check for login response
try {
if (json.getString("success") != null) {
// loginErrorMsg.setText("");
String res = json.getString("success");
if (Integer.parseInt(res) == 1) {
// user successfully logged in
// Store user details in SQLite Database
JSONObject json_user = json.getJSONObject("user");
System.out.println(" "+json_user.getString("userName")+" "+json_user.getString("created_at"));
//Bundle pass = new Bundle();
//pass.putString("userName", json_user.getString("userName"));
//pass.putString("created_at", json_user.getString("created_at"));
//home.putExtra("INTENT_EXTRA_STRING", pass);
//Log.d("test","uid:"+json.getString("uid"));
startActivity(home);
finish();
} else {
// Error in login
Toast.makeText(getApplicationContext(), "Erreur login",3000).show();
}
}
} catch (JSONException e) {
System.out.println("Connecter: "+e.toString());
}

}


}


JSONParser.java -parser class to parse api response JSON.



package tn.pack.ordre.enregistrer;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

public class JSONParser {

static InputStream is = null;
static JSONObject jObj = null;
static String json = "";

// constructor
public JSONParser() {

}

public JSONObject getJSONFromUrl(String url, List<NameValuePair> params) {

// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));

HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();

} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
Log.e("JSON", json);
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}

// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}

// return JSON String
return jObj;

}
}


EnregistrerActivity.java



package tn.pack.ordre.enregistrer;

import org.json.JSONException;
import org.json.JSONObject;

import tn.pack.ordre.enregistrer.UserFunctions;

import tn.pack.ordre.R;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

public class EnregistrerActivity extends Activity {


private TextView error;


/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Fixe la mise en page d'une activité
setContentView(R.layout.inscription);

}



public void btn_valider() {

String user=((EditText)findViewById(R.id.et_un)).getText().toString();
String password=((EditText)findViewById(R.id.et_pw)).getText().toString();
String rpassword=((EditText)findViewById(R.id.et_rpw)).getText().toString();
String cin=((EditText) findViewById(R.id.et_cin)).getText().toString();
// String region = ((Spinner) findViewById (R.id.spinner_rg)).getSelectedItem().toString();



UserFunctions userFunction = new UserFunctions();
JSONObject json = userFunction.registerUser(user,password,rpassword,cin);
try {

error=(TextView)findViewById(R.id.textViewerrer);
if (json.getString("success") != null) {

String res = json.getString("success");
if (Integer.parseInt(res) == 1) {

error.setText("enregistrement ok");


} else {
error.setText("erreur pendant l'enregistrement");

}
}
} catch (JSONException e) {
e.printStackTrace();
System.out.println("btnRegister: "+e.toString());
}


}

public void Annuler(View v) {

startActivity(new Intent(getApplicationContext(),LoginActivity.class));

}
}


UserFunctions.java -all the functions will interact with JSONParser.



package tn.pack.ordre.enregistrer;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;

public class UserFunctions {

private JSONParser jsonParser;

private static String loginURL = "http://10.0.2.2/webservice/index.php";
private static String registerURL = loginURL;

private static String login_tag = "login";
private static String register_tag = "register";

// constructor
public UserFunctions(){
jsonParser = new JSONParser();
}


public JSONObject loginUser(String userName, String password){
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("tag", login_tag));
params.add(new BasicNameValuePair("userName", userName));
params.add(new BasicNameValuePair("password", password));
JSONObject json = jsonParser.getJSONFromUrl(loginURL, params);
// return json
// Log.e("JSON", json.toString());
return json;
}


public JSONObject registerUser(String userName, String password,String rpassword, String cin){
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("tag", register_tag));
params.add(new BasicNameValuePair("userName", userName));
params.add(new BasicNameValuePair("cin", cin));
params.add(new BasicNameValuePair("password", password));
params.add(new BasicNameValuePair("rpassword", rpassword));
// params.add(new BasicNameValuePair("region", region));


// getting JSON Object
JSONObject json = jsonParser.getJSONFromUrl(registerURL, params);
// return json
return json;
}


}


config.php -This file contains constant variables to connect to database.



<?php

/**
* Database config variables
*/
define("DB_HOST", "localhost");
define("DB_USER", "root");
define("DB_PASSWORD", "");
define("DB_DATABASE", "appactel");
?>


DB_Connect.php -This file is used to connect or disconnect to database.



<?php
class DB_Connect {

// constructor
function __construct() {

}

// destructor
function __destruct() {
// $this->close();
}

// Connecting to database
public function connect() {
require_once 'include/config.php';
// connecting to mysql
$con = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
// selecting database
mysql_select_db(DB_DATABASE);

// return database handler
return $con;
}

// Closing database connection
public function close() {
mysql_close();
}

}

?>


DB_Functions.php -This file contains functions to store user in database, get user from database.



 <?php

class DB_Functions {

private $db;

//put your code here
// constructor
function __construct() {
require_once 'DB_Connect.php';
// connecting to database
$this->db = new DB_Connect();
$this->db->connect();
}

// destructor
function __destruct() {

}

/**
* Storing new user
* returns user details
*/
public function storeUser($userName,$cin , $password, $repassword) {
$uuid = uniqid('', true);
$hash = $this->hashSSHA($password);
$encrypted_password = $hash["encrypted"]; // encrypted password
$salt = $hash["salt"]; // salt
$result = mysql_query("INSERT INTO user_appmobile(unique_id, user_name, cin, encrypted_password,encrypted_repassword, salt, created_at, updated_at) VALUES('$uuid','$userName', $cin,'$encrypted_password', $encrypted_repassword,'$salt', NOW())");
// check for successful store
if ($result) {
// get user details
$uid = mysql_insert_id(); // last inserted id
$result = mysql_query("SELECT * FROM user_appmobile WHERE uid = $uid");
// return user details
return mysql_fetch_array($result);
} else {
return false;
}
}

/**
* Get user by email and password
*/
public function getUserByCinAndPassword($cin, $password) {
$result = mysql_query("SELECT * FROM user_appmobile WHERE cin = '$cin'") or die(mysql_error());
// check for result
$no_of_rows = mysql_num_rows($result);
if ($no_of_rows > 0) {
$result = mysql_fetch_array($result);
$salt = $result['salt'];
$encrypted_password = $result['encrypted_password'];
$hash = $this->checkhashSSHA($salt, $password);
// check for password equality
if ($encrypted_password == $hash) {
// user authentication details are correct
return $result;
}
} else {
// user not found
return false;
}
}

/**
* Get user by userName and password
*/
public function getUserByUserNameAndPassword($userName, $password) {
$result = mysql_query("SELECT * FROM user_appmobile WHERE user_name = '$userName'") or die(mysql_error());
// check for result
$no_of_rows = mysql_num_rows($result);
if ($no_of_rows > 0) {
$result = mysql_fetch_array($result);
$salt = $result['salt'];
$encrypted_password = $result['encrypted_password'];
$hash = $this->checkhashSSHA($salt, $password);
// check for password equality
if ($encrypted_password == $hash) {
// user authentication details are correct
return $result;
}
} else {
// user not found
return false;
}
}

/**
* Check user is existed or not
*/
public function isUserExisted($cin) {
$result = mysql_query("SELECT cin from user_appmobile WHERE cin = '$cin'");
$no_of_rows = mysql_num_rows($result);
if ($no_of_rows > 0) {
// user existed
return true;
} else {
// user not existed
return false;
}
}

/**
* Check user is existed or not
*/
public function isUserNameExisted($userName) {
$result = mysql_query("SELECT username from user_appmobile WHERE username = '$userName'");
$no_of_rows = mysql_num_rows($result);
if ($no_of_rows > 0) {
// user Name existed
return true;
} else {
// user Name not existed
return false;
}
}
public function isCinExisted($cin) {
$result = mysql_query("SELECT username from user_appmobile WHERE cin = '$cin'");
$no_of_rows = mysql_num_rows($result);
if ($no_of_rows > 0) {
// user Name existed
return true;
} else {
// user Name not existed
return false;
}
}

/**
* Encrypting password
* @param password
* returns salt and encrypted password
*/
public function hashSSHA($password) {

$salt = sha1(rand());
$salt = substr($salt, 0, 10);
$encrypted = base64_encode(sha1($password . $salt, true) . $salt);
$hash = array("salt" => $salt, "encrypted" => $encrypted);
return $hash;
}

/**
* Decrypting password
* @param salt, password
* returns hash string
*/
public function checkhashSSHA($salt, $password) {

$hash = base64_encode(sha1($password . $salt, true) . $salt);

return $hash;
}


}
?>


index.php -This file plays role of accepting requests and giving response. GET and POST requests.



<?php

/**
* check for POST request
*/
if (isset($_POST['tag']) && $_POST['tag'] != '') {
// get tag
$tag = $_POST['tag'];

// include db handler
require_once 'include/DB_Functions.php';
$db = new DB_Functions();

// response Array
$response = array("tag" => $tag, "success" => 0, "error" => 0);

// check for tag type
if ($tag == 'login') {
// Request type is check Login
$userName = $_POST['userName'];
$password = $_POST['password'];

// check for user
$user = $db->getUserByUserNameAndPassword($userName, $password);
if ($user != false) {
// user found
// echo json with success = 1
$response["success"] = 1;
$response["uid"] = $user["unique_id"];
$response["user"]["userName"] = $user["user_name"];
$response["user"]["cin"] = $user["cin"];
$response["user"]["created_at"] = $user["created_at"];
$response["user"]["updated_at"] = $user["updated_at"];
echo json_encode($response);
} else {
// user not found
// echo json with error = 1
$response["error"] = 1;
$response["error_msg"] = "Incorrect username or password!";
echo json_encode($response);
}
} else if ($tag == 'register') {
// Request type is Register new user


$userName = $_POST['userName'];
$cin = $_POST['cin'];
$password = $_POST['password'];
$repassword = $_POST['repassword'];
$region = $_POST['region'];

// check if user is already existed a separer (cas cin & cas username )
if ( ($db->isUserNameExisted($userName))&&($db->isCinExisted($cin)) ) {
// user is already existed - error response
$response["error"] = 2;
$response["error_msg"] = "User already existed";
echo json_encode($response);
} else {
// store user
$user = $db->storeUser($userName, $cin, $password, $repassword);
if ($user) {
// user stored successfully
$response["success"] = 1;
$response["uid"] = $user["unique_id"];
$response["user"]["userName"] = $user["user_name"];
$response["user"]["cin"] = $user["cin"];
$response["user"]["created_at"] = $user["created_at"];
$response["user"]["updated_at"] = $user["updated_at"];
echo json_encode($response);
} else {
// user failed to store
$response["error"] = 1;
$response["error_msg"] = "Error occured in Registartion";
echo json_encode($response);
}
}
} else {
echo "Invalid Request";
}
} else {

echo "Access Denied";
}
?>


Data Base:



    -- Base de données: `appactel`
--
-- Structure de la table `user_appmobile`
--

CREATE TABLE IF NOT EXISTS `user_appmobile` (
`uid` int(11) NOT NULL AUTO_INCREMENT,
`unique_id` varchar(23) NOT NULL,
`user_name` varchar(20) NOT NULL,
`cin` int(10) NOT NULL,
`password` varchar(20) NOT NULL,
`repassword` varchar(20) NOT NULL,
`salt` varchar(10) NOT NULL,
`created_at` datetime DEFAULT NULL,
`updated_at` datetime DEFAULT NULL,
PRIMARY KEY (`uid`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ;


the problem:



enter image description here



enter image description here



enter image description here



05-21 14:34:01.185: D/ddm-heap(223): Got feature list request
05-21 14:34:01.405: D/dalvikvm(223): GC freed 515 objects / 46800 bytes in 91ms
05-21 14:34:35.785: D/AndroidRuntime(223): Shutting down VM
05-21 14:34:35.785: W/dalvikvm(223): threadid=3: thread exiting with uncaught exception (group=0x4001b188)
05-21 14:34:35.785: E/AndroidRuntime(223): Uncaught handler: thread main exiting due to uncaught exception
05-21 14:34:35.835: E/AndroidRuntime(223): java.lang.IllegalStateException: Could not find a method btn_valider(View) in the activity
05-21 14:34:35.835: E/AndroidRuntime(223): at android.view.View$1.onClick(View.java:2020)
05-21 14:34:35.835: E/AndroidRuntime(223): at android.view.View.performClick(View.java:2364)
05-21 14:34:35.835: E/AndroidRuntime(223): at android.view.View.onTouchEvent(View.java:4179)
05-21 14:34:35.835: E/AndroidRuntime(223): at android.widget.TextView.onTouchEvent(TextView.java:6541)
05-21 14:34:35.835: E/AndroidRuntime(223): at android.view.View.dispatchTouchEvent(View.java:3709)
05-21 14:34:35.835: E/AndroidRuntime(223): at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:884)
05-21 14:34:35.835: E/AndroidRuntime(223): at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:884)
05-21 14:34:35.835: E/AndroidRuntime(223): at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:884)
05-21 14:34:35.835: E/AndroidRuntime(223): at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:884)
05-21 14:34:35.835: E/AndroidRuntime(223): at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:884)
05-21 14:34:35.835: E/AndroidRuntime(223): at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:884)
05-21 14:34:35.835: E/AndroidRuntime(223): at com.android.internal.policy.impl.PhoneWindow$DecorView.superDispatchTouchEvent(PhoneWindow.java:1659)
05-21 14:34:35.835: E/AndroidRuntime(223): at com.android.internal.policy.impl.PhoneWindow.superDispatchTouchEvent(PhoneWindow.java:1107)
05-21 14:34:35.835: E/AndroidRuntime(223): at android.app.Activity.dispatchTouchEvent(Activity.java:2061)
05-21 14:34:35.835: E/AndroidRuntime(223): at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchTouchEvent(PhoneWindow.java:1643)
05-21 14:34:35.835: E/AndroidRuntime(223): at android.view.ViewRoot.handleMessage(ViewRoot.java:1691)
05-21 14:34:35.835: E/AndroidRuntime(223): at android.os.Handler.dispatchMessage(Handler.java:99)
05-21 14:34:35.835: E/AndroidRuntime(223): at android.os.Looper.loop(Looper.java:123)
05-21 14:34:35.835: E/AndroidRuntime(223): at android.app.ActivityThread.main(ActivityThread.java:4363)
05-21 14:34:35.835: E/AndroidRuntime(223): at java.lang.reflect.Method.invokeNative(Native Method)
05-21 14:34:35.835: E/AndroidRuntime(223): at java.lang.reflect.Method.invoke(Method.java:521)
05-21 14:34:35.835: E/AndroidRuntime(223): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:860)
05-21 14:34:35.835: E/AndroidRuntime(223): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
05-21 14:34:35.835: E/AndroidRuntime(223): at dalvik.system.NativeStart.main(Native Method)
05-21 14:34:35.835: E/AndroidRuntime(223): Caused by: java.lang.NoSuchMethodException: btn_valider
05-21 14:34:35.835: E/AndroidRuntime(223): at java.lang.ClassCache.findMethodByName(ClassCache.java:308)
05-21 14:34:35.835: E/AndroidRuntime(223): at java.lang.Class.getMethod(Class.java:1014)
05-21 14:34:35.835: E/AndroidRuntime(223): at android.view.View$1.onClick(View.java:2017)
05-21 14:34:35.835: E/AndroidRuntime(223): ... 23 more
05-21 14:34:35.875: I/dalvikvm(223): threadid=7: reacting to signal 3
05-21 14:34:35.895: I/dalvikvm(223): Wrote stack trace to '/data/anr/traces.txt'
05-21 14:34:39.275: I/Process(223): Sending signal. PID: 223 SIG: 9
05-21 14:34:39.924: D/dalvikvm(232): GC freed 542 objects / 47816 bytes in 84ms
05-21 14:35:15.314: W/ActivityThread(254): Application tn.pack.ordre is waiting for the debugger on port 8100...
05-21 14:35:15.326: I/System.out(254): Sending WAIT chunk
05-21 14:35:15.878: I/dalvikvm(254): Debugger is active
05-21 14:35:16.005: I/System.out(254): Debugger has connected
05-21 14:35:16.005: I/System.out(254): waiting for debugger to settle...
05-21 14:35:16.215: I/System.out(254): waiting for debugger to settle...
05-21 14:35:16.443: I/System.out(254): waiting for debugger to settle...
05-21 14:35:16.645: I/System.out(254): waiting for debugger to settle...
05-21 14:35:16.866: I/System.out(254): waiting for debugger to settle...
05-21 14:35:17.126: I/System.out(254): waiting for debugger to settle...
05-21 14:35:17.348: I/System.out(254): waiting for debugger to settle...
05-21 14:35:17.585: I/System.out(254): waiting for debugger to settle...
05-21 14:35:17.829: I/System.out(254): waiting for debugger to settle...
05-21 14:35:18.077: I/System.out(254): waiting for debugger to settle...
05-21 14:35:18.300: I/System.out(254): waiting for debugger to settle...
05-21 14:35:18.511: I/System.out(254): waiting for debugger to settle...
05-21 14:35:18.721: I/System.out(254): waiting for debugger to settle...
05-21 14:35:18.930: I/System.out(254): waiting for debugger to settle...
05-21 14:35:19.159: I/System.out(254): waiting for debugger to settle...
05-21 14:35:19.366: I/System.out(254): waiting for debugger to settle...
05-21 14:35:19.576: I/System.out(254): waiting for debugger to settle...
05-21 14:35:19.795: I/System.out(254): debugger has settled (1483)




Compare Lists with custom objects, which have a common superclass

I have a Metamodel that's built like this:



class ModelElement
{
string id;
}

class Package : ModelElement
{
List<Package> nestedPackages;
List<Class> ownedClasses;
}

class Class : ModelElement
{
}


Now I've built two Models and I want to check if they're identical. I'd like to compare the ID's of the Elements and I don't want to write a method for any type of Element.



Package a; //pretend both have classes
Package b; //and nested packages
compare(a.nestedPackages, b.nestedPackages);
compare(a.ownedClasses; b.OwnedClasses);


Since Class and Package both inherit from ModelElement, both have IDs. So I want to write a Function "compare" which compares the IDs. I thought of using Generics but the generic datatype doesn't have the attribute "id". Any ideas?





Image format to put inside PDF's to have fast rendering

I would like to know which image format inside PDF's is rendered fastest. I tested mupdf code and I figured out that image decoding takes an important part in rendering time. So I would like to know if there are image formats that would not impact very much on cpu load.





C macro: how do I concatenate a name and a number which is result of a math operation (done also by preprocessor)?

Consider the following code:



1. #define SUFFIX 5-5
2. #define XFUNC_0( x ) (100 * x)
3. #define XFUNC_1( x ) (101 * x)
4. #define XFUNC_2( x ) (102 * x)
5. #define CATX( x, y ) x##y
6. #define CAT( x, y ) CATX( x, y )
7. #define XFUNC CAT( XFUNC_, SUFFIX )
8. #if XFUNC(2) == 200
...... etc
N.

How to access an association in view from one POCO with several references to another

Sorry about the title; couldn't think of a better one.



Any way, I'm accessing an associated property in my view like so:



@Model.Company.CompanyName // No problems here...


The model is a viewmodel mapped to an EF POCO. The Model has several properties associated to the Company table. Only one of the properties in the model share the same name as the PK in the Company table. All the other properties reference the same table:



public class MyModelClass 
{
public int Id { get; set; }
public int CompanyId { get; set; }
public int AnotherCompanyId { get; set; } // References CompanyId
public int AndAnotherCompanyId { get; set; } // References CompanyId

public Company Company { get; set; }
}

public class Company
{
public int CompanyId { get; set; }
public string CompanyName { get; set; }
public string Address { get; set; }
}


I'm obviously missing something here.



How can I get the names of the other companies in my Model?



Any help is greatly appreciated.





You don't have permission to access /schema/beans/spring-beans-3.1.xsd on this server

I am using spring framework in one of my application. It was working fine till now. But today in morning when I tried to run my application, it was throwing errors for not able to intialise spring framework. So I tried loading xsd files in the browser but in vain because it was showing forbidden page to me. And the page contains "You don't have permission to access /schema/beans/spring-beans-3.0.xsd on this server". I even tried loading 3.1 xsd, 2.5 xsd but not able to access any of them and showing same error page.



I know, I must download xsd and put them into my classpath but i haven't done and now i got this.



Can anyone please help me out of this? Or if any body has 3.0 xsd then can you please give it to me.



I want following xsds:




  1. spring-beans-3.0.xsd

  2. spring-context-3.0.xsd

  3. spring-mvc-3.0.xsd



and xsds that are being called by the above one internally.



Thank you every one.





Iphone : Applying strechable images to a button disables it

I am sure I am doing something stupid here. I build a category on top of UIButton which I want it to take all of the background images assigned to it (different states) and convert them to stretchable versions and reapply them back to the button.



- (void)enableBackgroundImageStrechingWithLeftCapWidth:(float)leftCapWidth withTopCapHeight:(float)topCapHeight;
{

UIImage *backgroundimageNormal = [self backgroundImageForState:UIControlStateNormal];

if (backgroundimageNormal != nil)
{
UIImage *stretchImage = [backgroundimageNormal stretchableImageWithLeftCapWidth:leftCapWidth topCapHeight:topCapHeight];
[self setBackgroundImage:stretchImage forState:UIControlStateNormal];
}

UIImage *backgroundimageSelected = [self backgroundImageForState:UIControlStateSelected];

if (backgroundimageSelected != nil)
{
UIImage *stretchImage = [backgroundimageSelected stretchableImageWithLeftCapWidth:leftCapWidth topCapHeight:topCapHeight];
[self setBackgroundImage:stretchImage forState:UIControlStateSelected];
}

UIImage *backgroundimageHighlighted = [self backgroundImageForState:UIControlStateHighlighted];

if (backgroundimageHighlighted != nil)
{
UIImage *stretchImage = [backgroundimageHighlighted stretchableImageWithLeftCapWidth:leftCapWidth topCapHeight:topCapHeight];
[self setBackgroundImage:stretchImage forState:UIControlStateHighlighted];
}

UIImage *backgroundimageDisabled = [self backgroundImageForState:UIControlStateDisabled];

if (backgroundimageDisabled != nil)
{
UIImage *stretchImage = [backgroundimageDisabled stretchableImageWithLeftCapWidth:leftCapWidth topCapHeight:topCapHeight];
[self setBackgroundImage:stretchImage forState:UIControlStateDisabled];
}
}


Seems to work except the button is now not clickable





How to count items per category?

I want to make a filtering of products on a site.
Something like this:



Department
- lassics (13,395)
- Literary (111,399)
- History (68,606)
...

Format
- HTML (3,637)
- PDF (8)
- Audio CD (443)
...

Language
- English (227,175)
- German (10,843)
- French (10,488)
...


How to count products per category? A separate SQL-query for each category would be too slow because there are too many products and categories. I suggest caching is not an option too.



Maybe it makes sense to use MySQL EXPLAIN queries (though it not always provide adequate information)? Or maybe using sphinx search engine for counting?... What is the best way to do this? Thanks.





Git: how to specify file names containing octal notation on the command line

For non-ASCII characters in file names, Git will output them in octal notation. For example:



> git ls-files
"\337.txt"


If such a byte sequence does not represent a legal encoding (for the command line's current encoding), I'm not able to enter the corresponding String on command line. How can I still invoke Git commands on these files? Obviously, using the String which is displayed by git ls-files does not work:



> git rm "\337.txt"
fatal: pathspec '337.txt' did not match any files


Tested on Windows, with msysgit 1.7.10 (git version 1.7.10.msysgit.1)





How to tell gcc to stop using built-in functions?

I am using my own modified glibc. I saw in the compiled code that compiler was not using many standard library functions from my glibc when I linked with it. Then I put -fno-builtin flag. Things got better and I could see that many functions which were not taken from glibc were now taken from there, such as malloc.



However, still for many functions, such as mmap, the compiler is using some built-in-code. Now how can I ask the compiler to please exclusively use the code from glibc rather than using its built-in-functions?





Monday, May 21, 2012

How to "Insert text from file" using OpenXml SDK 2.0

Using Word 2010 GUI, there is an option to "Insert text from file...", which does exactly that: It insert the text in the main part of a document to the current location in your document.



I would like to do the same using C# and the OpenXml SDK 2.0



using (var mainDocument = WordprocessingDocument.Open("MainFile.docx", true);
{
var mainPart = mainDocument.MainDocumentPart;
var bookmarkStart = mainPart
.Document
.Body
.Descendants<BookmarkStart>()
.SingleOrDefault(b => b.Name == "ExtraContentBookmark");
var extraContent = GetTextFromFile("ExtraFile.docx");

bookmarkStart.InsertAfterSelf(extraContent);
}


I have tried using plain Xml (XElement), using OpenXmlElement (MainDocumentPart.Document.Body.Descendants), and using AltChunk. Every alternative so far has yielded a non-conformant docx-file.



What should the method GetTextFromFile look like?





UIWebView copy/paste

Hy.
I have a single view application that only contains a web view and a text field which acts like an address bar. After selecting part of a web page, i want to push a button to copy it(all of the selection including text and pictures) and automatically paste it into another view.
I can add a button to the edit menu (although i don't know how to remove the copy and paste buttons), but i don't know how to get the selection.



I have tried to use gesture recognizers to do this but i cannot find a way to get the selection. I set my view controller as a UIWebViewDelegate and an UIGestureRecognizerDelegate and tried to implement touchesBegan, touchesMoved and touchesEnded, but they don't get called when starting selection. Do you know an example with something like this or at least point me in the good direction? Thank you!





How to do i resolve "Resource interpreted as Script but transferred with MIME type text/html"

I use Django for my applications, and for some strange reasons a new project am working on has started mis-behaving with the following error when I try to load the page on a browser.




Resource interpreted as Script but transferred with MIME type text/html: "http://127.0.0.1:8000/site_media/js/jquery-1.7.js"




my view looks like this;



@csrf_exepmt
def home(request):
render_to_response("myapp/home.html",{}, context_instance=RequestContext(request))


My HTML template:



<!DOCTYPE HTML>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Home</title>
<script type="text/javascript" src="jquery-1.7.js"></script>
</head>
<body>
<h1>Welcome Home!</h1>
</body>
</html>


I have never seen anything like this in the past for any of my projects.



I am testing on Windows, Chrome 18.0. I have also tried on FF6 and Firebug is throwing some error on the first line of my html file.



All the suggestions from the net that I am trying are not working.



I have also tried to use the technique of supplying the MIME type manually via the django render shortcut but with no luck.



What am I missing? My other projects are working normally, even without the MIME settings.



Note: If I leave the "src" attribute of the script tag empty, the page loads well.





security problems with passing javascript variable to a php variable

i've found a way to pass my javascript variables to a php variable by using this:



window.location.href = ".../gameover.php?points=" + points+"&speed="+window.speed;


in the gameover.php site i use



$_GET[speed]   // and 
$_GET[points]


to access my variables.
these values then get stored into a database as hiscores. but here comes my problem:
if the user just types for example



.../gameover.php?points=500000&speed=85


in the address bar it also stores these variables.



i have found something that helps avoiding this but you can still get around it. on my main page i make a cookie 'notcheated' and if the user visits the page and notcheated isset then it destroys the cookie and stores the values in my hiscores but if the user visits the main page and then enters the above address for example then the cookie isset but he hasn't played the game and then the values are also stored.



does someone have any suggestions to secure my site so that people can't just enter their own hiscores.





spring beans and sessionFactory in different xml files

We have 3 applications using 3 different spring configuration files. But we have one database and one datasource, so one session factory.Hhow can we import the session factory bean into the 3 different spring config files?





NUnit: Unit testing, recommendations on storing test data files

I've started working on an OpenXml based engine, and we are using a lot of pptx files for testing purpose. we do not want these files to be stored in the source control. is there any recommendations on this. may be storing in a network share or a mapped drive etc?





Silverlight 4 - Out of Browser Applications

Does a Silverlight 4 out of browser application have access to the .NET Framework?





how to auto convert nil to [NSNull null] when add it to array(dict)?

how to auto convert nil to [NSNull null] when add it to array(dict)?



I have some values need to be added to a array (initwithobjects), and encode to JSON string later.



As everyone knows, when array meet a nil, it will stop read next value.



As convention of JSON Array, the nil should be act as an null in ordered position.



Should I check every value, and manually convert it to [NSNull null] before add it to array?





Showing progress in command-line application

Ok, i am a bit embarrassed to ask such a simple thing but still.



I have command line utility application and need to implement showing progress to the user.



I could write progress into cout, like this:



std::cout << "10%\n";
...
std::cout << "20%\n";
...
std::cout << "30%\n";


... but as a result user will see:



some line printed before
10%
20%
30%
...


... but what i really need is that percentage got updated
, like this at the beginning:



some line printed before
10%
...


... and after update:



some line printed before
20%
...


... and after second update:



some line printed before
30%
...


How should i manage this?





Delegate invoke

I want to change a Form control property from a process thread event fire in a class, I have the following code but I received this exception:




the calling thread cannot access this object because a different
thread owns it.




Code:



public partial class main : Window
{
public main()
{
InitializeComponent();
}

public void change()
{
label1.Content = "hello";
}

private void button1_Click(object sender, RoutedEventArgs e)
{
nmap nmap = new nmap(this);
nmap.test("hello");
}
}

class nmap
{
private main _frm;
private Process myprocess;

public nmap(main frm)
{
_frm = frm;
}

public void test(object obj)
{
string s1 = Convert.ToString(obj);
ProcessStartInfo startInfo = new ProcessStartInfo();
myprocess = new Process();
myprocess.StartInfo.FileName = "C:\\nmap\\nmap.exe";
myprocess.EnableRaisingEvents = true;
myprocess.Exited += new EventHandler(myProcess_Exited);

myprocess.Start();
}

private void myProcess_Exited(object sender, System.EventArgs e)
{
try
{
_frm.change();
}
catch{}
}
}


Please help me on this, I think delegate invoke must be work



My project is a WPF C# project.





Tic Tac Toe with Minimax: Computer sometimes losing when Player goes first; works otherwise

I am working on a Minimax algorithm for unbeatable Tic Tac Toe. I need it to work both for when the Computer goes first as well as when the Player goes first. With the current version, the Computer will never lose when going first. However, it seems that Minimax never finds a best move (always returns -1 as the score) if the Player goes first.



What is causing the Minimax score returned to be -1 for the Computer if the Player makes the first move?



Example:



board.addMark( 1, Mark2.PLAYER ); // add a 'PLAYER' mark to an arbitrary location
Minimax.minimax( board, Mark2.COMPUTER ); // will always return -1


Here's the 'Minimax' class:



public class Minimax {
public static int minimax( Board board, Mark2 currentMark ) {
int score = (currentMark == Mark2.COMPUTER) ? -1 : 1;
int[] availableSpaces = board.getAvailableSpaces();

if ( board.hasWinningSolution() )
score = (board.getWinningMark() == Mark2.COMPUTER) ? 1 : -1;
else if ( availableSpaces.length != 0 ) {
Mark2 nextMark = (currentMark == Mark2.COMPUTER) ? Mark2.PLAYER : Mark2.COMPUTER;

for ( int availableIndex = 0; availableIndex < availableSpaces.length; availableIndex++ ) {
board.addMark( availableSpaces[availableIndex], currentMark );
int nextScore = minimax( board, nextMark );
board.eraseMark( availableSpaces[availableIndex] );

if ( currentMark == Mark2.COMPUTER && nextScore > score
|| currentMark == Mark2.PLAYER && nextScore < score )
score = nextScore;
}
}

return score;
}
}


Here is the 'Board' class:



public class Board {
private Mark2 gameBoard[];
private int blankSpaces;

private boolean solutionFound;
private Mark2 winningMark;

public final static int winSets[][] = {
{ 0, 1, 2 }, { 3, 4, 5 },
{ 6, 7, 8 }, { 0, 3, 6 },
{ 1, 4, 7 }, { 2, 5, 8 },
{ 0, 4, 8 }, { 2, 4, 6 }
};

public Board() {
gameBoard = new Mark2[9];
blankSpaces = 9;

for ( int boardIndex = 0; boardIndex < gameBoard.length; boardIndex++ ) {
gameBoard[boardIndex] = Mark2.BLANK;
}
}

public void addMark( int spaceIndex, Mark2 mark ) {
if ( gameBoard[spaceIndex] != mark ) {
gameBoard[spaceIndex] = mark;

if ( mark == Mark2.BLANK ) {
blankSpaces++;
} else {
blankSpaces--;
}
}
}

public void eraseMark( int spaceIndex ) {
if ( gameBoard[spaceIndex] != Mark2.BLANK ) {
gameBoard[spaceIndex] = Mark2.BLANK;
blankSpaces++;
}
}

public int[] getAvailableSpaces() {
int spaces[] = new int[blankSpaces];
int spacesIndex = 0;

for ( int boardIndex = 0; boardIndex < gameBoard.length; boardIndex++ )
if ( gameBoard[boardIndex] == Mark2.BLANK )
spaces[spacesIndex++] = boardIndex;

return spaces;
}

public Mark2 getMarkAtIndex( int spaceIndex ) {
return gameBoard[spaceIndex];
}

public boolean hasWinningSolution() {
this.solutionFound = false;
this.winningMark = Mark2.BLANK;

for ( int setIndex = 0; setIndex < winSets.length && !solutionFound; setIndex++ )
checkSpacesForWinningSolution( winSets[setIndex][0], winSets[setIndex][1], winSets[setIndex][2] );

return solutionFound;
}

public Mark2 getWinningMark() {
return this.winningMark;
}

private void checkSpacesForWinningSolution( int first, int second, int third ) {
if ( gameBoard[first] == gameBoard[second] && gameBoard[third] == gameBoard[first]
&& gameBoard[first] != Mark2.BLANK ) {
solutionFound = true;
winningMark = gameBoard[first];
}
}

public void printBoard() {
System.out.printf( " %c | %c | %c\n", getMarkCharacter( gameBoard[0] ), getMarkCharacter( gameBoard[1] ),
getMarkCharacter( gameBoard[2] ) );
System.out.println( "------------" );
System.out.printf( " %c | %c | %c\n", getMarkCharacter( gameBoard[3] ), getMarkCharacter( gameBoard[4] ),
getMarkCharacter( gameBoard[5] ) );
System.out.println( "------------" );
System.out.printf( " %c | %c | %c\n", getMarkCharacter( gameBoard[6] ), getMarkCharacter( gameBoard[7] ),
getMarkCharacter( gameBoard[8] ) );
}

public char getMarkCharacter( Mark2 mark ) {
char result = (mark == Mark2.PLAYER) ? 'O' : ' ';
result = (mark == Mark2.COMPUTER) ? 'X' : result;
return result;
}
}


And here's the 'Mark2' class if there was any confusion:



public enum Mark2 {
BLANK,
PLAYER,
COMPUTER
}




How to update UI onActivityResult in android

I need value from the new activity to old existing activity and based on the value i need to update the UI. Please help me How to use onActivityResult to update the UI





Cycling pipelining

I have a matrix: Array2D and a function



let DivideAndSubstract value index (matrix: float[,]) = 
//something that returns a matrix


so I need to apply this function n times to my matrix like that:



matrix  
|> DivideAndSubstract matrix.[0,0] 0
|> DivideAndSubstract matrix.[1,1] 1
|> DivideAndSubstract matrix.[2,2] 2
....
|> DivideAndSubstract matrix.[n,n] n


where n = Array2D.length1 matrix - 1

How can I implement this pipelining?





MSDEPLOY Install CLR Assembly into SQL server

I'm writing my first MSDEPLOY package to deploy our website. It uses an SQL CLR .DLL which needs to be installed into the database as part of deployment.



This is nominally very simple. I just need to deploy the DLL onto the destination server and then execute an SQL Command to have it add the assembly. When the SQL command is executed it must be given the path to the assembly to add to the SQL Server.



Their are two choices out of the box. One is to use the runCommand provider to execute a command script to install it. The other is to add an SQL script using the Package/Publish SQL tab in Visual Studio 2010.



What I can't determine after much searching is how to pass the deployment path of the DLL to either the command script or the SQL or the Package/Publish SQL.



I could declare a new parameter in the parameters.xml file and force the user to provide the installation path in a seperate parameter and then use parameterEntry to write the update to the SQL script. However it seems a little odd to have to provide information to MSDEPLOY that it already knows.



Having scripts know where the deployed resources were actually deployed seems like a fundamentally basic concern that I wonder if there is something really basic that I've missed.





Javascript regular expressions for Query Builder

This may have been asked in the past but I couldnt find a suitable answer. What I am looking for is a method to extract parameters from an sql query such as below. The queries will always be an EXEC statement followed by the query name, and possible parameters.



Here is an example of what I may recieve



EXEC [dbo].[myProcedure] @Param1


This could also be as follows



EXEC [dbo].[myProcedure] @Param1, @Param2, @Param3


Those are the only types of queries that the input will take. As for why I am doing this, well thats another question all together, and I am pretty set on going down this route.



What I am looking for is to be able to take the above strings and produce an array of values such as



['@Param1','@Param2','@Param3',....]


I originally tried to just parese using a simple while statement but I seem to have huge issues there.



I hope this question makes sense,



Cheers,



Nico





Coding templates - auto property at top of code file

It might seem like a small problem, but I was wondering if there is any support from either Visual Studio or a 3rd party application to configure where Visual Studio places certain auto-generated code.



When I am programming, I try to be as efficient as possible, and use 'Ctrl+.' a lot to automatically implement interfaces, fields, properties etc.. and one of the issues i have is that EVERY time I want to create a property in a class file (by typing in the usage first, then Ctrl+. the red invalid text, choosing Generate Property Stub when prompted) is Visual Studio places the code at the very bottom of the class file.



This is not how I structure my code files, and for better or worse I would much prefer it if the Auto-Properties were generated at the top.



So instead of (as would happen on auto-generation)



public class ObjectProvider
{
public ObjectProvider(Object o)
{
this.Object = o;
}

public object Object { get; private set; }
}


I would prefer



public class ObjectProvider
{
public object Object { get; private set; }

public ObjectProvider(Object o)
{
this.Object = o;
}
}


A small change I know, but when I am coding (at the least!) 5 days a week, for about 40 hours - I think this would actually save me a lot of time!