Monday, April 16, 2012

Can I set viewpager's item width?

I hope I can show 3 items in a page of viewpager, but now I only could set viewpager's padding value and margin value, so it only show one item in a page of viewpager. How can I set the item width? I think if I can set more little width of item, the viewpager will show more items in a page.





Can anyone help me with this logic test?

I was given the following question in an interview, and I came up with the code below to compute the sum the code works and is correct, but I was told that this was a logic question and they weren't looking for the source code, can anyone shed a light on this? did they want me to write the pseudo code perhaps?




  1. Compute the following sum:
    1/2 + 1/4 + 1/8 + ... + 1/1048576



    private static double computeSum()

    {
    double x = 0.0;

    for(double i=2; i<=1048576; i*=2)
    {

    x += (1 / i);

    }

    return x;
    }





ontouch and onclick on a textview not working

have a look at the code below...
i am setting the onclick listener on the textview and the ontouch listener but none of them is working...



what seems to be the problem>....?



    AlertDialog.Builder builder;
AlertDialog a;
TextView text,txtNewUser ;
ImageView image;
View layout;
Button ok;
String pswrd;
LayoutInflater inflater;

@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
final Context mContext = this;
Dialog dialog = new Dialog(mContext);
inflater = (LayoutInflater) mContext
.getSystemService(LAYOUT_INFLATER_SERVICE);
ok = (Button) findViewById(R.id.buttonOK);

dialog.setContentView(R.layout.custom_dialog_private_space);
dialog.setTitle("Password");
dialog.setCancelable(true);
layout = inflater.inflate(R.layout.custom_dialog_private_space,
(ViewGroup) findViewById(R.id.layout));
text = (TextView) dialog.findViewById(R.id.tvDesc);
txtNewUser = (TextView) dialog.findViewById(R.id.tvNewUser);

image = (ImageView) layout.findViewById(R.id.image);
image.setImageResource(R.drawable.lock_symbol_android);

builder = new AlertDialog.Builder(mContext);
builder.setView(layout);

a = builder.create();
a.show();

txtNewUser.setOnTouchListener(new OnTouchListener() {

@Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
if(event.getAction() == MotionEvent.ACTION_UP)
Toast.makeText(mContext, "Clicked", Toast.LENGTH_SHORT).show();
Log.v("AS", "Clicked");
return true;

}
});

txtNewUser.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(mContext, "Clicked", Toast.LENGTH_SHORT).show();
Log.v("AS", "Clicked");
}
});
}


here is the code of textview from the xml of the dialog layout



<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:id="@+id/layout" >

<TextView android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/tvNewUser"
android:text="New User?"
android:layout_gravity="top|left"
android:clickable="true"

/>

<ImageView
android:id="@+id/image"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>

<TextView
android:id="@+id/tvDesc"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:text="Enter password"
android:textAppearance="?android:attr/textAppearanceLarge"
/>



<EditText
android:id="@+id/etPassword"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="100"
android:inputType="textPassword" >


</EditText>

<Button
android:id="@+id/buttonOK"
android:layout_width="100dp"
android:layout_gravity="center"
android:layout_height="fill_parent"
android:text="OK" />

</LinearLayout>




Why postfix milter sends command "A" instead of "Q"?

I'm using milter(from a python library) now, I found when I issue a "QUIT" command in my client, instead of sending "Q" to milter server, it sends an "A"(Abort), Is that normal?





flash is not working in codeignitor

<div id="content1">



AC_FL_RunContent( 'codebase','http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,19,0','width','595','height','305','src','rev_1','quality','high','wmode','transparent','pluginspage','http://www.macromedia.com/go/getflashplayer','movie','rev_1' ); //end AC code









1)this code is not working in the codeigntor
2)this code call a image how to find path of that image
3)plase respnd





Ajax doesn't trigger server action

I am trying to trigger action via ajax but it doesn't call from some reason. Is my js code fine?



@Html.ActionLink("LIKE", "LikeComment", "Comments", new { id = 1985 }, new{@class = "likeButton"})

$(document).ready(function () {
$(".likeButton").click(function () {
$.ajax({
url: $(this).data("action-url"),
cache: false,
success: function (html) {
alert('ss');
}
});
return false;
});
});




Execute functions in order

I want to execute 3 functions in a certain order and I do this:



function nextPage() {
var loading_temp = $('#loading_temp');

loading_temp.show()
.queue(function() {
nextPage980()
.queue(function() {
loading_temp.hide();
$(this).dequeue();
});
$(this).dequeue();
});
}


The '#loading_temp' shows up and then the function executes, but the last function (hide the loading gif) does not execute!



Chrome gives this error: Uncaught TypeError: Cannot call method 'queue' of undefined



The nextPage980() function is this:



function nextPage980() {
var ajax_heading = $('#ajax_heading');
var cur_heading = $('#cur_heading');
var temp_heading = $('.temp_heading');
var temp_heading_first = temp_heading.filter(':first');
var loading_temp = $('#loading_temp');

var htmlHeader = "?????????????";

ajax_heading.attr('class', 'next_temp');
cur_heading.css({'margin-right' : '20px'}).after('<div id="cur_heading" class="temp_heading" data-tempPos="2"><h1 class="page_heading"><span class="heading_span">' + htmlHeader + '</span></h1></div>')
.queue(function() {
ajax_heading.animate({'margin-left' : '-1000px'}, 1000, 'easeInExpo')
.queue(function() {
temp_heading_first.remove();
cur_heading.removeAttr('style');
ajax_heading.attr('class', 'cur_temp').removeAttr('style');
$(this).dequeue();
});
$(this).dequeue();
});
}


Thanks in advance!





Android - implement a custom timer/clock

I have an android app where user presses a start button and some function of collecting data is started. I have a custom EditText that shows the time that all this process has taken and is updated every second till user presses stop. I implemented this using an AsyncTask like this below:



    protected class RecTimer extends AsyncTask<Context, Integer, String> 
{
@Override
protected String doInBackground( Context... params )
{
int sec=00;
int min=00;
int hours=00;
timerdata=timer.split(":");
hours=Integer.parseInt(timerdata[0]);
min=Integer.parseInt(timerdata[1]);
sec=Integer.parseInt(timerdata[2]);

while(Recording==true)
{
try{

Thread.sleep( 1000 );
publishProgress( sec , min , hours );
sec++;

if(sec==60){

min++;
sec=0;

if(min==60){
hours++;
min=0;
}
}
} catch( Exception e ){
Log.i("makemachine", e.getMessage() );
}
}
return "COMPLETE!";
}

@Override
protected void onPreExecute()
{
Log.i( "makemachine", "onPreExecute()" );
super.onPreExecute();
}

@Override
protected void onProgressUpdate(Integer... values)
{
super.onProgressUpdate(values);
//Log.i( "makemachine", "onProgressUpdate(): " + String.valueOf( values[0] ) );

String format = String.format("%%0%dd", 2);
String Sec = String.format(format, values[0]);
String Min = String.format(format, values[1]);
String Hours = String.format(format, values[2]);

((EditText) findViewById(R.id.duration1)).setText(Hours + ":"+ Min + ":" + Sec);

}


@Override
protected void onPostExecute( String result )
{
super.onPostExecute(result);
Log.i( "makemachine", "onPostExecute(): " + result );

}
}


It seemed to work fine at first, but now I see that if the app is idle and out of focus the timer may not always count well. I mean that I leave for example the device for 15 minutes and then see that in my "clock" only 5 have passed. Since the view is back on focus everything seems to work normally again.



First of all why does this happen? Shouldn't the AsyncTask be always executed in background? Is there some other better approach I should use to implement this?



Thanks to everybody in advance!





Removing specific text from string before entrance into MYSQL

Hi guys i have an PHP array that is coming from an rss feed with 2 sets of data. title's and descriptions.



(example print of array, i want to edit all of the description items in the array not just one index)



[2] => ('Remembrance','Release Date: Thursday 19th April 2012')


How would i manipulate the description string to remove "Release Date: " before its entrance into a mysql table?



This is my other code -
$rss = simplexml_load_file('rss.xml');
$title = $rss->xpath('//title'); //finding the title tags in the xml document and loading into variable
$description = $rss->xpath('//description');



$rows=array();

foreach($result as $title){
$rows[]="('".mysql_real_escape_string($title)."','".mysql_real_escape_string(array_shift($description))."')";
}
mysql_query("INSERT INTO Films (Film_Name, Film_Release) VALUES ".implode(',',$rows));
print_r($rows);




How to transfer large file (File size > Heap Size) over the network?

How to transfer large file (File size > Heap/RAM Size) over the network ?



Lets say I have file (size 10GB) I want to transfer it machine a (RAM 512mb) to machine b
(RAM 512mb).



Want achieve this using java code.



First, is it possible ? Any recommendation on framework. If possible, can we speed this up using threading ? Important criteria: file's data sequence needs to be maintained during transfer. Any example will be great help.





Flex sdk integration with eclipse

I have the following version of eclipse



Eclipse Java EE IDE for Web Developers.
Version: Indigo Service Release 2
Build id: 20120216-1857


And i have downloaded flex_sdk 4.6.My question is that how do i add this plugin for the eclipse in order to use it for flash development.





pass byte array in webservice

I have one webservice to which I want to pass one bytes array.
so how can i pass byte array in soap webservice.



How can I achieve this?
Hope you will give me the right solution.





Using Google API V3, How do I lock map boundaries to a specific location?

How do I lock the map boundaries to a specific location in Google Map API v3? So the user cannot drag to another place, while he can still zoom in and out?



To be more clear, I need my view box to show/view just my country only so the user cannot drag to other countires.



Thanks.





In Azure, Where should I store physical files that need to be accessed by a Worker Role?

In Azure, Where should I store physical files that need to be accessed by a Worker Role?



In my case I would normally store these particular files in my Web Role's App_Data folder but I don't believe that Worker Roles can access that folder.





How come I can't get the exactly result to *pip install* by manually *python setup.py install*?

I like to figure out the myth behind Python's namespace packages by setuptools, and here is what I did test.




  • Make a virtual environment by virtualenv.

  • Find a namespaced package on PyPI.

  • Install that package by pip install.

  • Check the installed file hierarchy.



The package I played with is zope.interface and it worked well with the following file hierarchy on my virtualenv:



~virenv/.../site-packages/zope.interface-3.8.0-py2.6-nspkg.pth
/zope.interface-3.8.0-py2.6.egg-info/
/zope/
/interface/
/...


Everything looked fine and I love the way zope.interface got installed as a real namespaced package (under folder zope).



Then, I did another test and that's the question I would like to ask for your help. I downloaded the tared zope.interface source file. I liked to play it manually again




  • Make a virtual environment by virtualenv.

  • Untar the zope.interface into somewhere.

  • Install the package by python setup.py install.

  • Go check what happened in site-packages.



The site-packages looks like this:



~virenv/../site-packages/zope.interface-...egg/
/zope/
/__init__.py
/interface/
/EGG-INFO/


Q. How come I can't get the exactly result to pip install by manually python setup.py install?





How to compile .bat file using QT Creator

Question: How do I compile a .bat file using QT Creator?



More info: specifically, I am trying to install Windows Image Writer and the download only includes source files. The README.txt tells me to use QT Creator (I have just installed this for this purpose alone) to compile the file compile.bat and I have no clue on how to do this.



Can anybody help me?





Recursively assign each node in a nested list a unique id with jquery

This is the original list:



<ol>
<li>
<a href="client.htm">Client</a>
<ol>
<li><a href="client/nokia.htm">Nokia</a></li>
<li><a href="client/microsoft.htm">Microsoft</a></li>
<li><a href="client/sony.htm">Sony</a></li>
<li><a href="client/samsung.htm">Samsung</a></li>
</ol>
</li>
<li><a href="contact.htm">Contact</a></li>
</ol>


I would like to transform it into something like this:



<ol>
<li>
<a id="sitemap-item-1" href="client.htm">Client</a>
<ol>
<li><a id="sitemap-item-1-1" href="client/nokia.htm">Nokia</a></li>
<li><a id="sitemap-item-1-2" href="client/microsoft.htm">Microsoft</a></li>
<li><a id="sitemap-item-1-3" href="client/sony.htm">Sony</a></li>
<li><a id="sitemap-item-1-4" href="client/samsung.htm">Samsung</a></li>

</ol>
</li>
<li><a id="sitemap-item-2" href="contact.htm">Contact</a></li>
</ol>


Notice: the id in is base on its nested level in the list.





Get a set of objects specifyng its ids on a JSON GET call

I'm developing a JSON WCF Web Service with C#.



I've just defined these two urls:



http://localhost:39325/RestServiceImpl.svc/forms

http://localhost:39325/RestServiceImpl.svc/forms/{id}


To retrieve to get all forms or a form with an {id}.



But now, I need to another one: I want to get all forms whose IDs are not included on a set. In other words, on client I will have some forms. I need to get new forms only (those which are not yet on client).



How can I specify an ids list on JSON url?





MSSQL based bar and line graph

i am not familiar with ASP or PHP writing, i am database admin only capable to do simple code changes.



Trying to find any usable/workable copy/paste sample of graph/chart for visulazation of simple two column MSSQL table.





How to make the decimals superscript, or subscript, in PHP?

I have this code:



<?php echo $price; ?>


which gives me this result:



1,500.99


Is there any way I can make the decimals superscript or subscript?



Thanks.





Is it possible to create an object for an interface in java?

In java ,an interface contains only the method type, name and parameters. The actual implementation is done in a class that implements it. Then how is it possible to create an instance of a interface and use it as if it were a class object. There are many such interfaces for eg see this.





Selecting multiple counts grouped by time from same table

I have a table logging application activity.
Each row contains a DateTime ("Time") and an "EventType" column... (And obviously some others that are unimportant here)



I would like to be able to get a count of the number of different EventTypes that occur every hour.



I'm currently getting a basic count of a single EventType with:



select DATEADD(hh, (DATEDIFF(hh,0,Time)),0) as 'hour', count(*) as 'apploads' 
from PlaySessionEvent
where EventType = 0
Group By DATEADD(hh,(DATEDIFF(hh,0,Time)),0)
order by hour


What is the easiest way to extend this to count multiple different EventTypes within the same hour?



::Update



Should have specified, I havn't just grouped by the EventType aswell because I only want a subset of all the EventTypes available. (ie. not boring trace/debug data)
Also, I wanted the different event types as columns, rather than additional rows duplicating the DateTime entries.



Eg...



DateTime           EventType1        EventType2
12:12:12 12/12/12 45 22


Apologies for the inexact initial question!





android WebView: Handle arrow keys in javacript

I have a simple WebView application which I want to control with the keyboard.
Is it possible to catch arrow keys in javascript?



I have tried the following code without any luck:



function handleArrowKeys(evt) {
console.info('key');
}

document.onkeyup = handleArrowKeys;
document.onkedown = handleArrowKeys;
document.onkepress = handleArrowKeys;


javascript is enabled in the webview



WebSettings webSettings = webview.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setDomStorageEnabled(true);




Error:Object reference not set to an instance of an object enterprise architect and visual studio

i get this error when i try to compile my program using Visual Studio and Enterprise Architect.



I'm writing a tool for Enterprise Architect, and i have to make a graph, and i continue to get this error, i don't know what to do.



The code that i have problem with is:



    public Graph(EA.Repository repository)
{

EA.Diagram maindiagram;
this.modelRepository = repository;
maindiagram = repository.GetCurrentDiagram(); //recupero del diagramma
this.diagramId = maindiagram.DiagramID; //identificativo del diagramma

//inizializzazione nodi
Collection nodeCollection = maindiagram.DiagramObjects;
nodeList = new ArrayList();


foreach (DiagramObject diagram in maindiagram.DiagramObjects)
{
diagramList.Add(diagram);
foreach (Element element in diagramList)
{
if (element.Type == "Class"|| element.Type == "Component"||element.Type == "Package")
{ nodeList.Add(new Node(diagram, ref repository)); }

}

}

//inizializzazione archi
Collection linkCollection = maindiagram.DiagramLinks;
linkList = new ArrayList();

foreach (DiagramLink edge in maindiagram.DiagramLinks)
{
edgeList.Add(edge);
foreach(Connector connector in edgeList)
if (connector.Type == "Association" || connector.Type == "Aggregation" || connector.Type == "Compose" || connector.Type == "Dependency"
|| connector.Type == "Generalization" || connector.Type == "Realization")
{ linkList.Add(new Link (edge, ref repository));}
}


Please help if you know how.



Thank you a lot!





how to achieve this result

I am working on small project using Python 2.6. Finally my list is like this.



data = ['1:Rammmm,mmmm', '2:surr.rrrrr', '3:Sam ttttt',
'1:qqqq qqqqqqq', '2:wwwwwwwwwww', '3:eeeeeeeee','4:tttttttt',
'1:zzzzzzzzzzzzz', '2:xxxxxxxxx']


Here, I want to display all 1's in one line, all 2's in one line, etc., with pipe"|" as separator. It should be like this with sorting order.



{Rammmm,mmmm|qqqq qqqqqqq|zzzzzzzzzzzzz}
{surr.rrrrr|wwwwwwwwwww|xxxxxxxxx}
{Sam ttttt|eeeeeeeee}
{tttttttt}


How can this be achieved in Python?





Confusion over the value of a variable after running a PHP program

I'm studying for my finals and I came across this question:




consider this following PHP code, write the output after executing it



<?php
$a=3;
$b=$a++;
IF($a>$b)
{
echo "a>$b";
}
else if ($a == $b)
{
echo "a=$b";
}
else
{
echo "a < $b";
}
?>



When I output it in my text editor I get a < 3, but I don't understand why though?



I thought a is assigned to 3 and also b is assigned to a++ 3 and 3==3 so should a==3 be printed out?





optimize heap size on android

I'm experiencing troubles issue with an android APP running into outOfMemory.



After dig and searching for memory leak, I discover that - I think - problem is that:




  • my initial Heap size is 11 MB (98% used).

  • After calling CAMERA intent, the heap size is increased to 34 MB, 99.5% used (one times crashed cause outOfMemory).

  • After rotating the screen my app goes - sometimes to 52 MB using 70% and sometimes crash with same OutOfMemory.



I read many threads and someone want to increase initial heap size but i read also that should be deprecated soon and it's not a good idea cause increase memory usage even if you don't need it.
Moreover, how can I know how much heap memory my app need? I should still monitor the working and increase time by time with min. step?



My questions is: what is the best way to handle heap size and avoid this kind of outOfMemory exception?



I tried with many version of my code and with samples doing only picture with camera, it's always the same. Just for your reference, this is the posted code



Take picture with android camera (intent) out of memory error





jquery click function and "new page"

i use jQuery "click" function. If use simple click on img is everything ok, but when on this image is link with tag 'target="_blank"' or user click right button, then 'open in new window', this function don't work.



How made that click function work, when user open link in new window?



My code:



$('.button_img').live('click', function(){
alert('new');
//do something
});

<a href="http://www.google.com" target="_blank">
<img class="button_img" src="img.png" />
</a>




Questions on GWT and other "Web Application Frameworks"

I have to develop a web application with database connection. So I checked on Wikipedia's "Web application comparison"



Here I was mainly looking for Java based frameworks. The first thing that looked interesting to me was "GWT". But there are some points that are not clear to me.




  1. The page doesn't contain any information on whether GWT uses the MVC-pattern. Does it?


  2. Further it doesn't say anything about push or pull functionalities. So what does GWT use?


  3. On "DB migration frameworks" it says, "via java". Does that mean that I can use any database that I can connect with Java?


  4. Is it a reasonable decision to choose GWT to implement a web based application with database connection which is used in a company network? Or are there any arguments which would make me consider any other frameworks?


  5. I am originaly a .Net (C#) developer and I also heard about the .NET "StockTrader" sample application. What would be pros & cons vs GWT? Or are those two different things?




As you can see I am totaly new to this things and I would strongly appreciate it if that question doesn't get closed because it is about forming an opinion. I am openminded for any advice or suggestions on other frameworks.



Greets,
BC++





Generalizing LINQ Model

I have a problem with model design in MVC pattern and I am stuck with the statically type of C#.



What I want to do is just to make a group of classes that do all database insert, update, delete operations. This group consists of a subgroup of classes that is mapped from each table in database and a subgroup of table-model classes that access the table classes.



I am using LINQ mapping to create the table class:



using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

using System.Data.Linq.Mapping;
using Iris.Libraries;

namespace Iris.Models.Tables
{
[Table]
public class Users
{
[Column(IsPrimaryKey = true)]
public string User_Id;

[Column]
public string Name;

[Column]
public string Password;

[Column]
public int Userlevel_Id;

public Users()
{
}
}
}


The table then accessed by the model class:



using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

using System.Data.Linq;
using Iris.Models.Tables;
using Iris.Models.DataContexts;

namespace Iris.Models
{
public class UserModel
{
private UserDataContext dataContext;
private Table<Users> users;

public UserModel()
{
this.dataContext = new UserDataContext(Config.CONNECTION_STRING);

this.users = this.dataContext.GetTable<Users>();
}

public List<Users> Select()
{
var data = from user in this.users select user;

return data.ToList<Users>();
}

public Users Select(object id)
{
var data = from user in this.users where user.User_Id.ToString() == id.ToString() select user;

return data.ToList<Users>()[0];
}

public void Insert (Users user)
{
this.dataContext.Users.InsertOnSubmit(user);

this.dataContext.SubmitChanges();
}

public void Update(Users user)
{
var queryableData = from row in this.dataContext.Users where row.User_Id == user.User_Id select row;

var editedData = queryableData.Single<Users>();

editedData.User_Id = user.User_Id;
editedData.Name = user.Name;
editedData.Password = user.Password;
editedData.Userlevel_Id = user.Userlevel_Id;

this.dataContext.SubmitChanges();
}

public void Delete(Users user)
{
var queryableData = from row in this.dataContext.Users where row.User_Id == user.User_Id select row;

var deletedData = queryableData.Single<Users>();

this.dataContext.Users.DeleteOnSubmit(deletedData);

this.dataContext.SubmitChanges();
}
}
}


Above pair of codes works fine without any problem but I want to avoid writing the 'almost same' code for model class again and again since there are a lot of table in the database. To achieve that purpose, I try to make a generalized class of model and every table-model extended from it.



public class Users : Model {}


The problem comes from



private Table<Users> users;


Which is the class in Table<> always different for each table. I've been searching around for days and didn't find any answer to solve this problem.



Is it really impossible to generalize the table-model like mine above? Or there are any other way to avoid writing same code repeatedly? Anyone, please help me.. :(