Saturday, 31 August 2013

How to auto fill a text area with php

How to auto fill a text area with php

I'm trying to auto fill a text area with a PHP that i get from reading a
file however everything i have tried doesn't seem to work. I have tried
<textarea><?php echo $test; ?></textarea>

How to echo multiple rows with data based on checkbox input?

How to echo multiple rows with data based on checkbox input?

Got stuck trying to echo out multiple rows with data based on checkbox
input. As of current code it processes data from only one checkbox, no
matter how many checkboxes are ticked. Please help!
while($row = mysql_fetch_assoc($r))
{
$pals .= '<input type="checkbox" name="pal_num[]"
value="'.$row['pal_num'].'">'.$row['pal_num'].'<br>';
}
if($pal == '') {
echo '';
} else {
echo '<form name="get_pal" action="post2.php" method="POST">';
echo $pals;
echo '<input type="submit" name="post" value="Go!">';
echo '</form>';
}
post2.php:
$w = $_POST['pal_num'];
$rrr = mysql_query("SELECT * FROM pl_tab WHERE pal_num".$w[0]);
while($row = mysql_fetch_array($rrr))
{
echo '<tr><td>'.'&nbsp'.'</td>';
echo '<td rowspan="5">'.$row['descr'].'</td>';
echo '<td><b>'.'Total weight'.'<b></td>';
echo '<td>'.'&nbsp'.'</td><td>'.'&nbsp'.'</td></tr>';
echo '<td>'.'&nbsp'.'</td>';
echo '<td colspan="3">'.'&nbsp'.'</td>';
//this part should multiple based on how many checkboxes are ticked.
echo '<tr><td>'.$row['l_num'].'</td>';
echo '<td>'.$row['pal_num'].'</td>';
echo '<td>'.$row['weight 1'].'</td><td>'.$row['weight 2'].'</td></tr>';
}
echo "</table>";}

Getting Screen Positions of D3 Nodes After Transform

Getting Screen Positions of D3 Nodes After Transform

I'm trying to get the screen position of a node after the layout has been
transformed by d3.behavior.zoom() but I'm not having much luck. How might
I go about getting a node's actual position in the window after
translating and scaling the layout?
mouseOver = function(node) {
screenX = magic(node.x); // Need a magic function to transform node
screenY = magic(node.y); // positions into screen coordinates.
};
Any guidance would be appreciated.

Jquery pagination - Applying class to items

Jquery pagination - Applying class to items

I am trying to design a pagination system in Jquery. The bit I am stuck on
is when I click on different page number links, I want it to move the
"active" class to the newly clicked page.
In the example page "1" has the active class. When I click "2" I want the
active class to move to "2" and be removed from "1".
http://jsfiddle.net/qKyNL/24/
$('a').click(function(event){
event.preventDefault();
var number = $(this).attr('href');
$.ajax({
url: "/ajax_json_echo/",
type: "GET",
dataType: "json",
timeout: 5000,
beforeSend: function () {
$('#content').fadeTo(500, 0.5);
},
success: function (data, textStatus) {
// TO DO: Load in new content
$('html, body').animate({
scrollTop: '0px'
}, 300);
// TO DO: Change URL
// TO DO: Set number as active class
},
error: function (x, t, m) {
if (t === "timeout") {
alert("Request timeout");
} else {
alert('Request error');
}
},
complete: function () {
$('#content').fadeTo(500, 1);
}
});
});
I'm quite new to Jqeury and could do with some help. Can anyone please
give me some guidance on how to do this?

Using jsoup how to get anchor tags that are within div tags with class that have display none style

Using jsoup how to get anchor tags that are within div tags with class
that have display none style

I have a document from which I am trying to extract the a tags. Some of
them are within tags that have the class attribute and the class has the
display:none property set. I want to eliminate those.

ExceptionInInitializerError thrown when creating a new TypefaceSpan object

ExceptionInInitializerError thrown when creating a new TypefaceSpan object

I'm trying to change my ActionBar font in an android application.
Everything works just fine while running my code on a 4.3 device but when
I'm trying to run it on a 2.3.3 device my app crashes.
This is the function that I'm using to change the font:
SpannableString s = new SpannableString("MyActivity");
s.setSpan(new TypefaceSpan(this, "myFont"), 0, s.length(),
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
// Update the action bar title with the TypefaceSpan instance
ActionBar actionBar = getSupportActionBar();
actionBar.setTitle(s);
My app crashes thanks to the new TypefaceSpan line.
08-31 19:00:21.359: E/AndroidRuntime(3874): FATAL EXCEPTION: main
08-31 19:00:21.359: E/AndroidRuntime(3874):
java.lang.ExceptionInInitializerError
08-31 19:00:21.359: E/AndroidRuntime(3874): at
com.blabla.myapp.MainActivity.changeActionBarFont(MainActivity.java:41)
08-31 19:00:21.359: E/AndroidRuntime(3874): at
com.blabla.myapp.MainActivity.setupGUIandListeners(MainActivity.java:27)
08-31 19:00:21.359: E/AndroidRuntime(3874): at
com.blabla.myapp.MainActivity.onCreate(MainActivity.java:23)
08-31 19:00:21.359: E/AndroidRuntime(3874): at
android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
08-31 19:00:21.359: E/AndroidRuntime(3874): at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1623)
08-31 19:00:21.359: E/AndroidRuntime(3874): at
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1675)
08-31 19:00:21.359: E/AndroidRuntime(3874): at
android.app.ActivityThread.access$1500(ActivityThread.java:121)
08-31 19:00:21.359: E/AndroidRuntime(3874): at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:943)
08-31 19:00:21.359: E/AndroidRuntime(3874): at
android.os.Handler.dispatchMessage(Handler.java:99)
08-31 19:00:21.359: E/AndroidRuntime(3874): at
android.os.Looper.loop(Looper.java:130)
08-31 19:00:21.359: E/AndroidRuntime(3874): at
android.app.ActivityThread.main(ActivityThread.java:3768)
08-31 19:00:21.359: E/AndroidRuntime(3874): at
java.lang.reflect.Method.invokeNative(Native Method)
08-31 19:00:21.359: E/AndroidRuntime(3874): at
java.lang.reflect.Method.invoke(Method.java:507)
08-31 19:00:21.359: E/AndroidRuntime(3874): at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:878)
08-31 19:00:21.359: E/AndroidRuntime(3874): at
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:636)
08-31 19:00:21.359: E/AndroidRuntime(3874): at
dalvik.system.NativeStart.main(Native Method)
08-31 19:00:21.359: E/AndroidRuntime(3874): Caused by:
java.lang.NoClassDefFoundError: android.util.LruCache
08-31 19:00:21.359: E/AndroidRuntime(3874): at
com.blabla.myapp.TypefaceSpan.<clinit>(TypefaceSpan.java:34)
08-31 19:00:21.359: E/AndroidRuntime(3874): ... 16 more
08-31 19:00:21.369: E/(186): Dumpstate > /data/log/dumpstate_app_error
I'm setting the font in my onCreate function.
Any help / ideas ?
Thanks in advance

javascript event: get when document is textually fully loaded but scripts haven't ran yet

javascript event: get when document is textually fully loaded but scripts
haven't ran yet

DOMContentLoaded fires after document is loaded and its scripts ran, and
I'd like to run my code before scripts were executed but after
document.body.outerHTML (
document.childNodes[document.childNodes.length-1].outerHTML ) is full
I try this, but looks like it runs many times after is found also so now I
do a timer 200ms job before executing mycode, but i'd like to do it
without timers
var observer = new MutationObserver(function(mutations)
{
if(document.body &&
document.childNodes[document.childNodes.length-1].outerHTML.lastIndexOf("</html>")!=-1)
{
observer.disconnect();
mycode();
}
});
observer.observe(document, {subtree: true, childList: true});
Needs to work in Chrome (so beforescriptexecuted event won't work here)

UItableView get UIScrollView for customization

UItableView get UIScrollView for customization

I have category for UIScrollView for customization
I need get UIScrollView.
I try
UIScrollView *scroll = nil;
for (UIView* subview in self.tableView.subviews) {
NSLog(@"%i", self.tableView.subviews.count);
if ([subview isKindOfClass:[UIScrollView class]]) {
scroll = (UIScrollView *)subview;
//some code
}
}
But it doesn't work. How I can get ScrollView? Thanks

Friday, 30 August 2013

How to record voice using Flash and save to PHP

How to record voice using Flash and save to PHP

The following are done work

Get WAV file => OK
private function renderWav(src, convertToMp3 = false) {
WaveFile.writeBytesToWavFile(myWavFile, myWavData, 44100, 2, 16)
}
Convert to MP3 => OK
private function makeIntoMp3(wav) {
mp3Encoder = new ShineMP3Encoder(wav);
mp3Encoder.start();
}
save MP3 file to Client => OK
private function onWavClick(e:MouseEvent) {
new FileReference().save(mp3Encoder.mp3Data, "MyAudio.mp3");
}
Above, I can get a MP3 file in client side but on my problem that save to
Server side(PHP)
Save to server side => Fail
public function makeMP3File() {
var urlVariables:URLVariables = new URLVariables;
urlVariables.mp3Data = mp3Encoder.mp3Data;
var req:URLRequest = new URLRequest('upload.php');
req.data = urlVariables;
req.method = URLRequestMethod.POST;
var loader:URLLoader = new URLLoader();
loader.load(req);
}
My PHP Code
function strean2audio($audioStream, $filename)
{
$file = fopen($filename . '.mp3', "wb");
fwrite($file, $audioStream);
fclose($file);
}
I was a ActionScript rookie, don't know which part error, thanks for your
help!

Thursday, 29 August 2013

How to change html input multiple value

How to change html input multiple value

I have a html input field like this:
<input name="files[]" id="files" type="file" style="display: none;"
onchange="saveFile();" multiple="true" />
How can i change multiple's value to "false" using javascript?

Wednesday, 28 August 2013

Ruby Net::HTTP end of file reached

Ruby Net::HTTP end of file reached

I'm trying to get an http post request that worked before but anymore to
work again.
def post_params
uri = Addressable::URI.new
uri.query_values = {
from: @from_city_id,
to: @to_city_id,
tmp_from: @from_city,
tmp_to: @to_city,
date: @when_date.strftime('%d.%m.%Y')
}
uri.query
end
http = Net::HTTP.new "www.domain.com"
res = http.post '/', post_params
raise res.inspect
But I end up having a End of file error. One more thing: I'm not trying to
make a https query.
Thanks for your help

Connective Lamp Server to Windows Domain

Connective Lamp Server to Windows Domain

I recently made a centos lamp server running apache mysql and php. I have
wordpress and phpbb3 installed and running on the server. The linux server
is running in the same building as a windows 2003 server. Is there a way
to connect the linux and windows server so that my website and forum is
only viewable once the user logs into his windows account at his/her
computer? As of right now, anyone that is physically in the building and
connected via ethernet will have access to my website and forum. I guess I
want to restrict it to the specified users in the windows domain. I saw
some stuff about ldap and active directory, but it's only confused me so
much more. This is my first time setting up any form of server. Thanks

NIST Randomness Tests requires a sequence of ASCII 0's and 1's but does not accept any trial from MATLAB

NIST Randomness Tests requires a sequence of ASCII 0's and 1's but does
not accept any trial from MATLAB

I am trying to use NIST randomness test suite for randomness tests of my
long 0-1 bit sequences. It requires me to supply either the ASCII zeroes
and ones or a binary file each byte with 8 bits of data. However, I tried
save(...,'-ascii'), fwrite() and some other commands to make it works but
it does not accept and it gives a segmentation error + igamc: UNDERFLOW
error.
If anyone can say how to create the exactly matching format I will be
really happy. In addition if anyone knows MATHEMATICA they created their
own sample files as below from MATHEMATICA , maybe can help about the
format and you can tell what to do in MATLAB.
BinExp[num_,d_] := Module[{n,L},
If[d > $MaxPrecision, $MaxPrecision = d];
n = N[num,d];
L = First[RealDigits[n,2]]
];
SE = BinExp[E,302500];
Save["data.e",{SE}];

JSON parsing in Android using PHP MySQL Null Pointer Exception

JSON parsing in Android using PHP MySQL Null Pointer Exception

Hi i am doing json parsing in android with php but i am getting null
pointer exception , i am using port 8080, please help me: ##
link :
http://fahmirahman.wordpress.com/2011/04/26/the-simplest-way-to-post-parameters-between-android-and-php/
public class MainActivity extends ListActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String result = null;
InputStream is = null;
StringBuilder sb=null;
ArrayList nameValuePairs = new ArrayList();
nameValuePairs.add(new BasicNameValuePair("sku","sku"));
//http post
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new
HttpPost("http://192.168.5.61:8080/KeausMapPolicyDefender/android_json.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Error in http connection"+e.toString());
}
//convert response to string
try{
BufferedReader reader = new BufferedReader(new
InputStreamReader(is,"iso-8859-1"),8);
sb = new StringBuilder();
sb.append(reader.readLine() );
String line="0";
while ((line = reader.readLine()) != null) {
sb.append(line);
}
is.close();
result=sb.toString();
}catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
//paring data
int fd_id;
String fd_name;
try{
JSONArray jArray = new JSONArray(result);
JSONObject json_data=null;
for(int i=0;i<jArray.length();i++){
json_data = jArray.getJSONObject(i);
fd_id=json_data.getInt("sku");
fd_name=json_data.getString("violation_amount");
}
}catch(JSONException e1){
Toast.makeText(getBaseContext(), "No Violation Found",
Toast.LENGTH_LONG).show();
}catch (ParseException e1){
e1.printStackTrace();
}
}
}

Tuesday, 27 August 2013

Automatic Reference Counting Issue in Xcode 4.2

Automatic Reference Counting Issue in Xcode 4.2

Automatic Reference Counting Issue
Receiver type 'JasperMobileAppDelegate' for instance message does not
declare a method with selector 'setResourceClientForControllers:'
- (IBAction)configureServersDone:(id)sender {
[self setResourceClientForControllers:self.resourceClient];
[tabBarController setSelectedIndex:0];
}
How to fix this?
Thank You

R str equivalent in perl

R str equivalent in perl

How do you get the data structure of an object in Perl?
I can easily do this in R using str -
str(data)
I wonder if there is similar one in Perl.

libGDX InputProcessor: How to create one new object per android touch?

libGDX InputProcessor: How to create one new object per android touch?

Within the libGDX InputProcessor's touchDown() I am developing a way to
create a new TouchPoint rectangle object per screen touch.
I have tried put a constraint on the maximum number of TouchPoint
rectangles creatable to two; I only need to work with two screen touches.
Each unique object should be updated to its new screen touch location
within touchDragged(), then deleted on touchUp().
I have successfully been able to create the desired result for single
touches, but not for multiple screen touches. For the second concurrent
touch, the TouchPoint rectangle object disappears from the first touch,
then shows at the second touch location. Upon touchUp() of the second
touch, the object reappears at the touch location of the first touch.
Which piece of code logic contains the error?
How do I fix it?
/*experiment*/
public Vector3 tps[] = new Vector3[2];
/*experiment*/
@Override
public boolean touchDown(int screenX, int screenY, int pointer, int button) {
/*experiment*/
if(pointer < 2){
if(pointer == 0) {
Vector3 touchPosition1 = new Vector3();
tps[pointer] = touchPosition1;
tps[pointer].set(screenX, screenY, 0);
gameScreen.getWorldRenderer().getCamera().unproject(tps[pointer]);
touchPoint1 = new TouchPoint(52, 52, new Vector2(tps[pointer].x - 26,
tps[pointer].y - 26));
gameScreen.getWorld().getTouchPoints().add(touchPoint1);
Gdx.app.log("TOUCH DOWN", "pointer: " + pointer + " x: " +
tps[pointer].x + " y: " + tps[pointer].y);
}
if(pointer == 1) {
Vector3 touchPosition2 = new Vector3();
tps[pointer] = touchPosition2;
tps[pointer].set(screenX, screenY, 0);
gameScreen.getWorldRenderer().getCamera().unproject(tps[pointer]);
touchPoint2 = new TouchPoint(52, 52, new Vector2(tps[pointer].x - 26,
tps[pointer].y - 26));
gameScreen.getWorld().getTouchPoints().add(touchPoint2);
Gdx.app.log("TOUCH DOWN", "pointer: " + pointer + " x: " +
tps[pointer].x + " y: " + tps[pointer].y);
}
}
return false;
}
@Override public boolean touchUp(int screenX, int screenY, int pointer,
int button) { /experiment/
gameScreen.getWorld().getTouchPoints().removeIndex(pointer); //note:
dispose of unused vector3 objects //note: dispose of all other unused
objects /experiment/
return false;
}
@Override public boolean touchDragged(int screenX, int screenY, int
pointer) { /experiment/ tps[pointer].set(screenX, screenY, 0);
gameScreen.getWorldRenderer().getCamera().unproject(tps[pointer]);
for(TouchPoint tp: gameScreen.getWorld().getTouchPoints()) {
tp.moveRectangleToPosition(new Vector2(tps[pointer].x - 26,
tps[pointer].y - 26));
tp.updateRectangleBoundaries();
}
Gdx.app.log("TOUCH DRAGGING", "pointer: " + pointer + " x: " +
tps[pointer].x + " y: " + tps[pointer].y);
/*experiment*/
Furthermore, the program crashes if a third screen touch occurs.
LogCat:
08-27 14:08:31.808: W/dalvikvm(9988): threadid=11: thread exiting with
uncaught exception (group=0x41711438)
08-27 14:08:31.808: E/AndroidRuntime(9988): FATAL EXCEPTION: GLThread 40874
08-27 14:08:31.808: E/AndroidRuntime(9988):
java.lang.IndexOutOfBoundsException: 2
08-27 14:08:31.808: E/AndroidRuntime(9988): at
com.badlogic.gdx.utils.Array.removeIndex(Array.java:229)
08-27 14:08:31.808: E/AndroidRuntime(9988): at
com.multitasckq.controller.InputHandler.touchUp(InputHandler.java:104)
Thanks for your time.

MATLAB enumerated switch statement always goes into first case

MATLAB enumerated switch statement always goes into first case

I am trying to use an enumerated class to dictate behaviour in a switch
statement in another class's constructor. So, what I have is the
following:
From my enumerated class:
classdef(Enumeration) MyScheme
enumeration
Scheme1, Scheme2, Scheme3
end
end
and then the class that uses this:
classdef MyClass < handle
methods
function c = MyClass(scheme, varargin)
switch(scheme)
case MyScheme.Scheme1
% Do stuff with varargin
case MyScheme.Scheme2
% Do different stuff with varargin
case MyScheme.Scheme3
% Do yet something else with varargin
otherwise
err('Not a valid scheme');
end
end
end
end
However, no matter what scheme I pass in to the constructor, it just goes
straight into the first case. When I add a breakpoint and step through and
manually check equality (scheme == MyScheme.Scheme1), it recognizes that
the two are not equal and returns 0 for this check, so I do not understand
at all why it would still enter first case. If I change the order of the
cases it will just enter whichever one is first. As far as I can tell,
this is identical syntax to the Using Enumerations in a Switch Statement
section of this MATLAB help document, but perhaps I am missing something
obvious?

Populate DefaultViewModel["Items"] with Images Windows Metro

Populate DefaultViewModel["Items"] with Images Windows Metro

I'm trying to load a folder of images into my Windows Metro app by
populating a list of objects that encapsulate a Title and Image field and
then assigning this to DefaultViewModel["Items"]. The wrapper class I have
for this information is the following:
public class SlideData
{
// slide collection that will be used to populate app slides page
public List<Slide> Slides = new List<Slide>();
public SlideData(IReadOnlyList<StorageFile> files)
{
int counter = 1;
foreach (StorageFile file in files)
{
Slides.Add(new Slide(counter.ToString(), file.Name));
}
}
public class Slide
{
public Slide(String title, String Image)
{
this.Title = title;
this.Image = Image;
}
private String Title { set; get; }
private String Image { set; get; }
}
}
Then the method in the page I want to assign elements to my GridView to
has this in the LoadState method to load and assign these slides:
protected async override void LoadState(Object navigationParameter,
Dictionary<String, Object> pageState)
{
var folderPicker = new FolderPicker();
folderPicker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
folderPicker.FileTypeFilter.Add(".png");
StorageFolder folder = await folderPicker.PickSingleFolderAsync();
if (folder != null)
{
IReadOnlyList<StorageFile> files = await folder.GetFilesAsync();
SlideData slides = new SlideData(files);
this.DefaultViewModel["Items"] = slides.Slides;
}
}
The good news is in my GridView, I'm getting all of the slides I want to
show up, but they're blank, having no title or image associated with them;
essentially, I just want to load all of the PNGs in a given folder, assign
them the title of 1-N, then display them here in this view before allowing
the user to click on any given one and view it fully. Help is greatly
appreciated!

Q: Superfish sub menu above menu

Q: Superfish sub menu above menu

I have a working superfish navbar, but I would like the sub menu to popup
and not down because of my theme requires it. The superfish navbar example
can be seen here:
http://users.tpg.com.au/j_birch/plugins/superfish/examples/nav-bar/

Constant propagation library for .NET

Constant propagation library for .NET

Whether any open source .NET (C#/F#) library for abstract static analysis
exists? Currently I'm interested in constant propagation algorithm.
It should be abstract (language independed) and open source because I want
to use it as base for custom algorithm implementation.
Thanks.

Monday, 26 August 2013

Taking one column from MySQL joined tables

Taking one column from MySQL joined tables

I have a query in MySQL and i am making a crystal report by using this.
Now inside the query i have a column called scan_mode and it is coming
from gfi_transaction table.This scan_mode i am using in report to suppress
some sections.But some times this value is coming null for some
transaction id's.
So now i want to take this scan_mode as separate query so that it will
work. Can any one please help how i can modify the below query to take
only scan_mode column.
SELECT
cc.cost_center_code AS cccde,
cc.name AS ccnme,gf.scan_mode,
cc.cost_center_id AS ccid,
site.name AS siteme,
crncy.currency_locale AS currency_locale,
cntry.language AS LANGUAGE,
cntry.country_name AS cntrynm,
crncy.decimal_digits AS rnd,
gf.transaction_no AS Serial_No,
brnd.name AS brand_name,
rsn.description AS reason,
gf.comment AS COMMENT,
ts.status_description AS STATUS,
DATE_FORMAT(gf.created_date,'%d/%m/%Y') AS created_date,
gf.created_by AS created_by,
IFNULL(gf.approval_no,'Not authorized') AS Trans_no,
gf.approved_date AS approval_dt,
gf.approved_by AS approved_by,gf.status AS status1,
IFNULL(loc.cost_center_code,cc.cost_center_code) AS cur_location,
gf.document_ref_no,gf.document_ref_type,
,DATE_FORMAT(document_ref_date1,'%d/%m/%Y')) AS invoice_no
FROM
gfi_transaction gf
INNER JOIN gfi_instruction gfn ON (gf.transaction_id=gfn.transaction_id)
INNER JOIN gfi_document_instruction doc ON (gf.ref_transaction_no =
doc.document_instruction_id)
INNER JOIN reason rsn ON (gf.reason_id = rsn.reason_id)
INNER JOIN gfi_status ts ON (gf.status = ts.gfi_status_id)
INNER JOIN transaction_type tt ON (gf.transaction_type_id =
tt.transaction_type_id)
INNER JOIN brand brnd ON(gf.brand_id=brnd.brand_id)
-- cc details
INNER JOIN cost_center cc ON (brnd.parent_brand = cc.brand_id OR
gf.brand_id = cc.brand_id)
INNER JOIN site site ON(cc.site_id = site.site_id)
INNER JOIN country cntry ON (site.country_id = cntry.country_id)
INNER JOIN currency crncy ON (cntry.currency_id=crncy.currency_id)
LEFT OUTER JOIN alshaya_location_details loc ON
(gf.brand_id = loc.brand_id AND loc.cost_center_id =
gf.cost_centre_id)
LEFT OUTER JOIN alshaya_location_details locto ON
(locto.cost_center_id = gf.from_cost_center_id)
WHERE
gf.transaction_id='{?TransID}'
AND rsn.transaction_type_id IN (10,11,14)

Which is the simplest alternative to Google Drive for creating online forms?

Which is the simplest alternative to Google Drive for creating online forms?

How to create an online form without google drive? any options where I can
ask the user to upload photos?

Style table to highligh every other 2 rows

Style table to highligh every other 2 rows

I've been reading about css3's nth-child, but can't figure out how I can
style a table where rows 3,4 | 7,8 | 11,12 | 15,16 etc. are yellow.
Basically every other 2 rows are styled.
Thanks

Tower of Hanoi C++(using recursion)

Tower of Hanoi C++(using recursion)

I wrote the following code as a practice exercise.
I'm getting incorrect output when i print the destination stack.
Can anyone please point out where i'm going wrong ?
//Tower of Hanoi using Stacks!
#include<iostream.h>
#include<conio.h>
#include<stdlib.h>
class Stack
{
private:
int *t;
int length, top;
public:
Stack(int len)
{
length=len;
t= new int[len];
top=-1;
}
~Stack()
{delete []t;}
void push(int d)
{
top++;
t[top]=d;
}
int pop()
{
top--;
return t[top+1];
}
void printstack()
{
int cur=top;
while(cur>-1)
{cout<<t[cur]<<endl;cur--;}
}
};
void MoveTowerofHanoi(int disk, Stack *source, Stack *temp, Stack
*destination)
{
if (disk==0)
{destination->push(source->pop());}
else
{
MoveTowerofHanoi(disk-1,source,temp,destination);
destination->push(source->pop());
MoveTowerofHanoi(disk-1,temp,destination,source);
}
}
void main()
{
clrscr();
int disks;
cout<<"Enter the number of disks!"<<endl;
cin>>disks;
Stack* source=new Stack(disks);
for(int i=0;i<disks;i++){source->push(disks-i);}
cout<<"Printing Source!"<<endl;
source->printstack();
Stack* temp=new Stack(disks);
Stack* destination=new Stack(disks);
MoveTowerofHanoi(disks,source,temp,destination);
cout<<"Printing Destination!"<<endl;
destination->printstack();
getch();
}
Here's the output i'm getting:
Enter the no. of disks!
3
Printing Source!
1
2
3
Printing Destination!
-4

how to add customize select country dropdown arrow in twitter bootstrap

how to add customize select country dropdown arrow in twitter bootstrap

Please can any one help me, I want to add and customize select arrow in
country select dropdown like this arrow image.
I have not enough reputation for posting image with this question so I
have put this only image of problem here
http://taslimk.tk/arrowproblem.html

Sunday, 25 August 2013

MySQL Werid Results

MySQL Werid Results

Ok...
Why on earth should this be happening? I have over a million rows in a
table that records temperature data on my homebrewing activity.
create table temperature (
notes varchar(50)
,temperature decimal(4,1)
,temperature1 decimal(4,1)
,temperature2 decimal(4,1)
) ;
In my notes column, I accidently executed the following:
update temperature set notes = 'xyz' where notes = 'xyz123' ;
When I meant to execute the following:
update temperature set notes = 'x' where notes = 'xyz123' ;
Ok, no problem, I will simply set notes to x where notes = xyz ...
update temperature set notes = 'x' where notes = 'xyz' ;
commit ;
Ok, there should be 0 results for the following:
select count(*) from temperature where notes = 'zyx';
NO: THIS DOESN'T NECESSARILY RETURN 0 !!!!!!!!!
I can execute the previous update and commit as many times as I want. It
doesn't matter. The select count(*) returns the same thing.
I am familiar with Oracle and this is just absurd to me. What possible
reason could exist for an update statement to not update all records
according to the WHERE clause?

Encryption functions in PHP output unexpected characters

Encryption functions in PHP output unexpected characters

I use simple_encrypt to store some sensitive information in the cookie.
When I try to decrypt it with simple_decrypt, it doesn't give the same
string. When I try to output that string after simple_decrypt I get chars
with symbols like &#65533;. What's wrong?
$salt ='sososo222xxxXXsder3FVRE';
function simple_encrypt($text)
{
global $salt;
return mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $salt, $text,
MCRYPT_MODE_ECB);
}
function simple_decrypt($text)
{
global $salt;
return mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $salt, $text,
MCRYPT_MODE_ECB);
}
EDIT: I use setcookie("rt", simple_encrypt($a['rt']), time()+(3600 * 24 *
365)); to store cookie.

Query based on custom fields start and end date

Query based on custom fields start and end date

I have a custom post type called Events, with 2 custom fields, start date
and end date. These fields are stored using a timestamp in the database. I
want to create a custom query based on these 2 values, so i can list
events that are inside the specified date/time range. This is how my code
looks like:
$start_date = strtotime($_POST['start_date']);
$end_date = strtotime($_POST['end_date']);
$args = array(
'post_type' => 'event',
'posts_per_page' => -1,
'orderby' => 'title',
'order' => 'ASC',
'meta_query'=>array(
'relation'=>'AND',
array(
'key' => 'event_start_date',
'value' => $start_date,
'compare' => '<=',
'type' => 'NUMERIC'
),
array(
'key' => 'event_end_date',
'value' => $end_date,
'compare' => '>=',
'type' => 'NUMERIC'
)
)
);
$events = new WP_Query($args);
So i'm using a simple NUMERIC meta_query, since all of my values and keys
stored in a timestamp. The code looks fine for me, but somehow theres no
results in this query. Here is an example:
$star_date = 1343779200 $end_date = 1412121600
And one of my event post has these values as a custom field:
event_start_date = 1375315200 event_end_date = 1377734400
So it should give me at least one result, because the start_date is
smaller and the end_date is higher compared to the event_start_date and
event_end_date.
Any idea whats wrong?

Saturday, 24 August 2013

creating a dynamic menu using two mysql tables

creating a dynamic menu using two mysql tables

I have two mysql tables called "parents" and "childs"
in my parents table i have 4 columns (id,link,lable,have_childs)
in my childs table also i have 4 columns (id, c_link, c_lable, parent_id)
and i get the values using a query like this
"SELECT parents.*, childs.* FROM parents, childs WHERE parents.id =
childs.p_id;"
then using a foreach loop i got this result
array(7) { ["id"]=> string(1) "1" ["link"]=> string(3) "veg" ["lable"]=>
string(9) "Vegitable" ["childs"]=> string(1) "1" ["c_link"]=> string(6)
"carrot" ["c_lable"]=> string(6) "carrot" ["p_id"]=> string(1) "1" }
array(7) { ["id"]=> string(1) "2" ["link"]=> string(3) "Fru" ["lable"]=>
string(6) "Fruits" ["childs"]=> string(1) "1" ["c_link"]=> string(6)
"grapes" ["c_lable"]=> string(6) "grapes" ["p_id"]=> string(1) "2" }
array(7) { ["id"]=> string(1) "3" ["link"]=> string(3) "veg" ["lable"]=>
string(9) "Vegitable" ["childs"]=> string(1) "1" ["c_link"]=> string(5)
"beeat" ["c_lable"]=> string(5) "beeat" ["p_id"]=> string(1) "1" }
then i did this
<?php
foreach($result as $myresult){ ?>
<ul>
<li><a href="<?php echo $myresult['link']; ?>"><?php echo
$myresult['lable']; ?></a>
<?php
if($myresult['childs'] == 1){
echo '<div><ul>';
echo '<li><a
href="'.$myresult['c_link'].'">'.$myresult['c_lable'].'</a></li>';
echo '</div></ul>';
}
?>
<?php
}
?>
then i got this result
.Vegitable
carrot
.Fruits
grapes
.Vegitable
beet
but this is not the result i looking for i need both carrot and beet items
go under vegetable.
is there any way to do this?

Android run application in background

Android run application in background

I have an android app that has a ui but also has several service classes
that run in the background and do things like monitor location, texts,
ect. The services are initiated when the app starts from my main activity
(after the configuration is loaded from a web server- initialed by main
activity's "onCreate"). However, I want this configuration to be loaded
and the services to start when the phone is turned on, and since the main
activity initially doesn't launch until the user tells it to, the services
are not started until this point. Does my main activity (one specified in
launcher) need to extend something other than "activity" so that these web
service calls can be made and services started as soon as phone turned on
though not necessarily showing the ui? Thanks

what is the equivalent of substring for an array?

what is the equivalent of substring for an array?

I simply want to extract the values of an array from [1] to the end. Is
this the only (or best) way to do it?
// example with a string
var stringy = "36781"
console.log(stringy.substring(1))
// example with an array
var array2 = [3,6,7,8,1]
array2.shift()
console.log(array2)

Mysql characters encoding LIKE,MATCH, utf8?

Mysql characters encoding LIKE,MATCH, utf8?

My character set is utf8 and table/column is utf8_generali_ci, I am
connecting to the database and right after it executing this code
mysqli_query($con, "SET CHARACTER SET utf8"); so then my czech characters,
if not doing this, then my czech characters are like &#65533;, but I've
found problem in my search LIKE or MATCH...AGAINST, whenever I try execute
a query like this SELECT * FROMuploadedWHEREfile_name_keywordLIKE
'%ø%'with czech characters I get an error Warning: mysqli_fetch_assoc()
expects parameter 1 to be mysqli_result
So the question is: Is it possible to search for czech characters, and
how? Or do I have to convert them before every input to like ø=>r, è=>c,
ì=>e, š=>s ? Thanks in advance.

Java Swing - Changing JLabel.setText of Label changes the location!!! of another label, which is on another JPANEL

Java Swing - Changing JLabel.setText of Label changes the location!!! of
another label, which is on another JPANEL

This is super weird for me! ... here is the thing: I'm working on
university project, My app has several (4) JPanels. Each Panel has
different JComponents (mostly jlabels). I've set a "Parent" for each
JComponent (e.g. the label on my MAP jpanel has "Parent" MAP).
My map panel has 1 label, which I move (with .setLocation) based on ...
different stuff.... The weird thing is that when I change the text
(.setText) of a JLabel, which is located on different jpanel (under the
MAP panel), the location of my MAP label is changed to it's original
one!!! How is that even possible ?! I tried debugging - you must be really
patient for that : )) What I saw is that the location change of my MAP
label happens when my other jpanel label get's repaint()-ed (.setText()
method calls .repaint() at certain point).
So, have you seen something like that, and what is the workaround ?
IDE - netbeans 7.2 Java Swing
Regards, nilux

Android Thread Allocation - growing heap?

Android Thread Allocation - growing heap?

Hi everyone out there,
i am developing an android application against API 7 at the moment in
which i use an activity which need to be restarted. Lets say my activity
looks like this:
public class AllocActivity extends Activity implements OnClickListener{
Button but;
private Handler hand = new Handler();
@Override
protected void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.activity_alloc);
but = (Button) findViewById(R.id.button);
but.setText("RELOAD");
but.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0){
Intent intent = getIntent();
startActivity(intent);
finish();
}
});
}
@Override
protected void onDestroy(){
super.onDestroy();
System.gc();
}
/****** THREADS AND RUNNABLES ******/
final Runnable fullAnim = new Thread(new Runnable(){
@Override
public void run(){
try{
hand.post(anim1);
Thread.sleep(2000);
hand.post(anim2);
Thread.sleep(1000);
// and so on
}catch(InterruptedException ie){ie.printStackTrace();}
}
});
final Runnable anim1 = new Runnable() {
@Override
public void run(){
// non-static method findViewById
ImageView sky = (ImageView)findViewById(R.id.sky);
}
};
}
The problem is that the gc doesnt seem to free the fullAnim thread so that
the heap is growing by ~100K at every restart - till it slows down and
crashes. Declaring fullAnim as static does solve this problem - but as i
use non static references this doesnt work out for me.
So at this point i am kindof lost - and i hope u can advice me where to go
next. Is there something i might be doing wrong or is there a tool i can
use to manage threads to drop and free heap after restart.
kindly regards

Friday, 23 August 2013

Ubuntu - "mv" command renames file to empty file name

Ubuntu - "mv" command renames file to empty file name

I have a simple script to move files between directories. Basically, it is:
mv /dir/* /dir/proc/
saved into a shell script "mvproc.sh".
For some reason, when I run the script (sh mvproc.sh) the file indeed gets
moved, but it does not retain the filename and instead gets just an empty
filename. When I run the same command at the bash prompt, it works fine
however.
This script used to work fine on Debian but we had a hard drive failure
and I am now migrating everything over to a Ubuntu machine.
Any idea why this is happening? It seems so simple yet I cannot figure it
out.
Many thanks.
edit...
I think I found the solution. For some reason it was putting in carriage
returns and maybe line breaks or something that I could not see while
editing the sh script in either Notepad++ or even gedit. To solve this,
when I open the scripts in gedit, I do a Save As, and select Unix/Linux in
the drop down menu towards the bottom. This hopefully gets rid of the
weird carriage returns even though I could not see them.
Hopefully this helps some poor soul like me in the future pulling their
hair out over this!
Thanks!

SEC7111: HTTPS security is compromised using IE

SEC7111: HTTPS security is compromised using IE

I'm having issues having this image gallery display in IE.
http://www.campchiefouray.org/summer-camp-photos-2013.html Running this
URL through developer tools in Browserstack I'm seeing the following
error. Has anyone had this issue, and if so, where is this coming from ,
and most importantly how can I fix?! Any help would be appreciated.
SEC7111: HTTPS security is compromised
http://www.campchiefouray.org/summer-camp-photos-2013.html

Cross Site Scripting ReflectedHTMLEncoding Request.Form(date)

Cross Site Scripting ReflectedHTMLEncoding Request.Form(date)

I just started a new project where I look for Cross-Site Scripting:
Reflected findings and I mitigate them. This particular page has 2 date
variables (start and finish) that the software has deemed dangerous due to
their potential to send unvalidated data to the browser. With most
variables, I can just wrap an HTMLEncode around the variable like this:
HTMLEncode(string)
and everything will be fine. However, either because it is a date variable
or because it is a Request.Form, this solution won't work. Does anybody
have any suggestions? I tried googling "HTMLEncoding dates" and
"HTMLEncode and Request.Form" but I couldn't find any valuable solutions.
If expDate = "range" Then
start = Request.Form("search_start_dt")
finish = Request.Form("search_end_dt")
msgtxt = "Completion Dates from " & start & " to " & finish

Android - Using Fragments

Android - Using Fragments

I'm very new to Java, and Android development. I want to be able to
display a local page page within my App using the fragments (because I
don't want the entire app to be web based).
So, I've gone into my arview.xml and added a fragment:
<fragment
android:id="@+id/fragment_bbc"
android:name="android.webkit.WebViewFragment"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true" />
Now, I want to place a web page in there (for now, I'll just use the bbc
website).
Within my 'onCreate(Bundle savedInstanceState)' I have this:
webFrag = (WebViewFragment) mGUIView.findViewById(R.id.fragment_bbc);
mWebView = (WebView) mGUIView.findViewById(R.id.fragment_bbc);
myWebView.loadUrl("http://www.bbc.co.uk");
I have errors of all 3 of those lines, all saying they can't be resolved.
Where am I going wrong? Thanks

How to publish a paid app to play sore

How to publish a paid app to play sore

I know how to publish a free app to play store but i don't about paid
app.I found that paid app need some Lib as licence verification
library(LVL) for Paid App and have to integrate this LVL to the App.Please
say the process what are thing to be added to a app to make it published
as paid app.Thanks in Advances

Print Image One by one C#

Print Image One by one C#

I have written below code to get all images from folder.
Below is the code
string[] files = Directory.GetFiles(@"C:\temp", "*.jpeg");
I got all image names in files. Now i want to print all images one by one.
I tried below code
foreach (var i in files)
{
objPrintImage = Image.FromFile(i);
objDimension = new FrameDimension(new System.Guid());
PrintDocument objPrintDoc = new PrintDocument();
objPrintDoc.PrintPage += new
PrintPageEventHandler(this.objPrintDoc_PrintPage);
if (objPrintDoc.PrinterSettings.IsValid)
{
objPrintDoc.Print();
}
}
Here is a PrintPageEventHandler method.
private void objPrintDoc_PrintPage(object sender, PrintPageEventArgs ev)
{
objPrintImage.SelectActiveFrame(FrameDimension.Page, intPage);
intPage++;
ev.Graphics.DrawImage(objPrintImage, 0, 0);
if (intPage < objPrintImage.GetFrameCount(FrameDimension.Page))
{
ev.HasMorePages = true;
}
}
But getting error A generic error occurred in GDI+.
Please help me.
Thanks in advance, Prashant

Thursday, 22 August 2013

Is there a simple formalism in which self-referential definitions can be made safely?

Is there a simple formalism in which self-referential definitions can be
made safely?

Consider the expression $g(f(x)).$ Its easy to draw this in a tree
diagram; the bottom node is $x$, above that is $f$, and above that is $g$.
Now consider the $(D(f))(x),$ for instance imagine that $D$ denotes
differentiation. If you try to draw this as a tree, you'll get "brackets"
in your tree. (Try it!)
To avoid these brackets, the best way is probably to introduce an
"evaluation function" $\mathrm{eval}(*,*)$ such that $\mathrm{eval}(f,x) =
f(x)$ so long as this expression is defined. Then we have $$(D(f))(x) =
\mathrm{eval}(D(f),x)$$
and we can draw this as a tree just fine. Problem solved!
However, to formalize this in ZFC, we'd have to restrict the definition of
$\mathrm{eval}$ to functions $f$ that are 'internal' to the theory. In
particular, theorems like $$\mathrm{eval}(\mathrm{eval},(f,x)) = f(x)$$
aren't even grammatically coherent. This seems moderately wasteful of what
appears to be a perfectly legitimate (though trivial) theorem. Probably,
there are similarly - but less trivial - theorems provable in a
self-referential language that allows these kinds of things.
So, my question is, is there a simple formalism in which self-referential
definitions can be made safely? It would have to be just restrictive
enough to block Russell-like paradoxes, but not so restrictive so as to
block our ability to define self-referential functions like
$\mathrm{eval}, \mathrm{identity}, \mathrm{domain}, \mathrm{range},
\mathrm{kernel}$ etc.



Discussion. What we'd really like is to be able to assert that
$$\mathrm{eval}(f,x) = f(x)$$
for all functions $f,$ including functions like $\mathrm{eval},
\mathrm{identity}, \mathrm{domain}, \mathrm{range}, \mathrm{kernel}$ etc.
However, just allowing definition-by-cases leads to Russell-like
paradoxes. For instance, lets assume that there exists a non-function,
call it $3$ for concreteness (we'll have to assume that $3$ is not a
Church numeral for this argument to work!). Now define a function $g$ by
cases as follows.
$$f(f)=f \rightarrow g(f) = 3$$ $$f(f)\neq f \rightarrow g(f) = f.$$
Try to evaluate $g(g)$ and you'll get a contradiction.

how to suppress page number for subfigures in LOF?

how to suppress page number for subfigures in LOF?

I am using tocloft and subcaption package, and I would like to suppreess
page numbers and dot line for subfigures in LOF.
I know, if one uses tocloft and subfigure package, this can be done with
the next command:
\cftpagenumbersoff{subfigure}
So, I would like to emulate this command with subcaption package. The
point is that I have all the subfigures done with subcaption package, and
I would not like to change the code of all them.

rand() function in with probability in chossing IP's

rand() function in with probability in chossing IP's

Hi I'm working on a project in c
I have 3 IPs and every IP has a weight, I want to return the IP's
according to its weights using the random function,,,, for example if we
have 3 IP's : X with weight 6,Y with weight 4 and Z with weight 2, I want
to return X in 50% of cases and Y in 33% of cases and Z in 17% of cases,
depending on random function in C.
could any one help me with this please ?

ListView inside ScrollView not Showing all items in the in the Adapter

ListView inside ScrollView not Showing all items in the in the Adapter

Ok.. first of all, i know its very much discouraged to not put a listview
in a scrollview, but this time it was out of my hands and i had no choice.
Now going forward, My Listview items are not showing the last few items in
the adapter when it reaches a certain amount. Not treally sure how to
explain it but What i mean is as an example is, items from: Jan 1 - Aug
22, the listview stops at Aug 15, Jan 1 - Aug 17, it stops at Aug 10 Jan 1
- Mar 17, stops at Mar 15 and so on.
Not really sure what the problem is.. i am using a custom Listview like:
public static void setListViewHeight(ListView listview){
ListAdapter listAdapter = listview.getAdapter();
if(listAdapter == null) {
return;
}
int totalHeight = 0;
// int desiredWidth =
MeasureSpec.makeMeasureSpec(listview.getWidth(),
MeasureSpec.AT_MOST);
for(int i = 0; i < listAdapter.getCount(); i++) {
View listItem = listAdapter.getView(i, null, listview);
//listItem.measure(desiredWidth, MeasureSpec.UNSPECIFIED);
listItem.measure(0, 0);
totalHeight += listItem.getMeasuredHeight();
}
ViewGroup.LayoutParams params = listview.getLayoutParams();
params.height = totalHeight +
(listview.getDividerHeight()*(listAdapter.getCount() - 1)) +
totalHeight;
listview.setLayoutParams(params);
//listview.requestLayout();
}
Anybody have any issue like the Listview not showing all the items?... Any
idea how to solve this?.. Much appreciated in advance.

Can the rendering of the JavaFX 2/8 font be improved?

Can the rendering of the JavaFX 2/8 font be improved?

I am using Ubuntu 13.04 and coding an application to display some labels (
using the Label class ). I also tried to use Text class and set the
smoothing type to LCD. The result is the same, the font looks blurry, its
margins are scattered, and you have to set its size to a pretty big number
in order to be readable ( note I have some text paragraph displayed ).
I know JavaFX2 has LCD sub-pixel rendering but still, can something be
done so that the font doesn't look so ugly? ( maybe I'm missing something
for 2.X or don't know of existence of something in 8.X )
Is there any way to check if LCD sub-pixel rendering is active or not?
Regards,

VB.NET Upload Issue - You must write ContentLength bytes

VB.NET Upload Issue - You must write ContentLength bytes

I am getting the following exception thrown when using the function below
to upload a video file to my web server. I am using this function as I
need the memory usage to be low as the video files being uploaded are in
excess of 150MB.
The error that is being thrown is: You must write ContentLength bytes to
the request stream before calling [Begin]GetResponse.
I have looked over the code a few times now & simply cannot seem to notice
where I am going wrong & likely just need a second set of eyes to find my
mistake!
Function:
Friend Function LowMemoryUploader(ByVal FilePath As String) As String
ServicePointManager.ServerCertificateValidationCallback =
(Function(sender, certificate, chain, sslPolicyErrors) True)
Dim oUri As New Uri("http://mysite.com/upload.php")
Dim NowTime As String = DateTime.Now.Ticks.ToString().Substring(0,
14)
Dim strBoundary As String = "-----------------------------" & NowTime
' Set Filename
Dim FileName As String = FilePath.Split(CChar("\")).Last()
' The trailing boundary string
Dim boundaryBytes As Byte() = Encoding.ASCII.GetBytes(vbCr & vbLf
& "--" & strBoundary & vbCr & vbLf)
' The post message header
Dim sb As New StringBuilder()
' Add Variables
sb.Append(strBoundary & vbCrLf & "Content-Disposition: form-data;
name=""upload""" & vbCrLf & vbCrLf & "1" & vbCrLf)
sb.Append(strBoundary & vbCrLf & "Content-Disposition: form-data;
name=""upload_file""; filename=""" & FileName & """" & vbCrLf)
sb.Append("Content-Type: video/" & FilePath.Split(".").Last())
sb.Append(vbCrLf & vbCrLf)
' Set Header Bytes
Dim strPostHeader As String = sb.ToString()
Dim postHeaderBytes As Byte() = Encoding.UTF8.GetBytes(strPostHeader)
' The WebRequest
Dim oWebrequest As HttpWebRequest =
DirectCast(WebRequest.Create(oUri), HttpWebRequest)
' Set Request Settings
System.Net.ServicePointManager.Expect100Continue = False
oWebrequest.Method = "POST"
oWebrequest.UserAgent = Useragent
oWebrequest.Accept =
"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"
oWebrequest.ContentType = "multipart/form-data;
boundary=---------------------------" & NowTime
oWebrequest.AllowAutoRedirect = True
oWebrequest.Timeout = 600000
oWebrequest.CookieContainer = cookies
' This is important, otherwise the whole file will be read to
memory anyway...
oWebrequest.AllowWriteStreamBuffering = False
' Get a FileStream and set the final properties of the WebRequest
Dim oFileStream As New FileStream(FilePath, FileMode.Open,
FileAccess.Read)
Dim length As Long = postHeaderBytes.Length + oFileStream.Length +
boundaryBytes.Length
oWebrequest.ContentLength = length
Dim oRequestStream As Stream = oWebrequest.GetRequestStream()
' Write the post header
oRequestStream.Write(postHeaderBytes, 0, postHeaderBytes.Length)
' Stream the file contents in small pieces (4096 bytes, max).
Dim buffer As Byte() = New Byte(1096) {}
Dim bytesRead As Integer = oFileStream.Read(buffer, 0, buffer.Length)
While bytesRead <> 0
bytesRead = oFileStream.Read(buffer, 0, buffer.Length)
oRequestStream.Write(buffer, 0, bytesRead)
End While
oFileStream.Close()
' Add the trailing boundary
oRequestStream.Write(boundaryBytes, 0, boundaryBytes.Length)
Dim oWResponse As WebResponse = oWebrequest.GetResponse()
Dim s As Stream = oWResponse.GetResponseStream()
Dim sr As New StreamReader(s)
Dim sReturnString As String = sr.ReadToEnd()
' Clean up
oRequestStream.Close()
s.Close()
sr.Close()
Return sReturnString
End Function

Import variable from Python script to Batch file

Import variable from Python script to Batch file

I have a python script containing vraibles example.py
"src = komponent/cool,
komponent/raw" /* path of source files */
and i have a batch file which needs to import the value of "src" for
postporcessing example.bat
--cs-include ='komponent/cool'* --cs-include ='komponent/raw'*
Is there any way to import directly between files (without using any other
conversion) ? "PyBat.bat" is one option but i am trying to figure out a
better choice dont want to add on one more tool (not specifically)...as my
project itself has too different files and interacting source.
Any help is appreciated.. Thank you in advance..!!!

Wednesday, 21 August 2013

To increment and loop till the end of file?

To increment and loop till the end of file?

consider the following code:
history_begins = 1; history_ends = 5000
historyjobs = []; targetjobs = []
listsub = []; listrun = [];
def check(inputfile):
f = open(inputfile,'r')
lines = f.readlines()
for line in lines:
job = line.split()
if( int(job[0]) < history_ends ):
historyjobs.append(job) #appends all lines to the
historyjobs list from inputfile whose col1 value is < 5000
else:
targetjobs.append(job) #appends all lines to the
historyjobs list from inputfile whose col1 value is > 5000
print targetjobs[0] #To print the first list in targetjobs list
j = 0
for i in range(len(historyjobs)):
if( (int(historyjobs[i][3]) == int(targetjobs[j][3])) and
(int(historyjobs[i][4]) == int(targetjobs[j][4])) and
(int(historyjobs[i][5]) == int(targetjobs[j][5])) ): #comparing
the item 3,4,5 of all the lists in historyjobs list with the
item 3,4,5 of the first list in targetjobs list
listsub.append(historyjobs[i][1])
listrun.append(historyjobs[i][2])
print listsub
print len(listsub)
print listrun
def main():
check('newfileinput')
if __name__ == '__main__':
main()
The result i obtained was:
['5000', '1710390', '930', '8', '9', '2']
['767220', '769287', '770167', '770276', '770791', '770835', '771926',
'1196500', '1199789', '1201485', '1206331', '1206467', '1210929',
'1213184', '1213204', '1213221', '1361867', '1361921', '1361949',
'1364886', '1367224', '1368005', '1368456', '1368982', '1369000',
'1370365', '1370434', '1370551', '1371492', '1471407', '1709408',
'1710264', '1710308', '1710322', '1710350', '1710365', '1710375']
37
['2717', '184', '188', '163', '476', '715', '1099', '716', '586',
'222', '456', '457', '582', '418', '424', '425', '177', '458', '236',
'2501', '3625', '1526', '299', '1615', '1632', '1002', '379', '3626',
'1003', '1004', '3625', '1002', '1019', '1037', '1066', '998', '977']
Now what i need to do is to increment the history_ends value i,e
history_ends = 5000 initial assignment and prints the results
next history_ends = 5001
next history_ends = 5002-------------------till the end of the input file
so that the result i need is:
['5000', '1710390', '930', '8', '9', '2'] #when history_ends=5000
['767220', '769287', '770167', '770276', '770791', '770835', '771926',
'1196500', '1199789', '1201485', '1206331', '1206467', '1210929',
'1213184', '1213204', '1213221', '1361867', '1361921', '1361949',
'1364886', '1367224', '1368005', '1368456', '1368982', '1369000',
'1370365', '1370434', '1370551', '1371492', '1471407', '1709408',
'1710264', '1710308', '1710322', '1710350', '1710365', '1710375']
37
['2717', '184', '188', '163', '476', '715', '1099', '716', '586', '222',
'456', '457', '582', '418', '424', '425', '177', '458', '236', '2501',
'3625', '1526', '299', '1615', '1632', '1002', '379', '3626', '1003',
'1004', '3625', '1002', '1019', '1037', '1066', '998', '977']
['5001', '1710554', '4348', '8', '9', '2'] #when history_ends=5001
['767220', '769287', '770167', '770276', '770791', '770835', '771926',
'1196500', '1199789', '1201485', '1206331', '1206467', '1210929',
'1213184', '1213204', '1213221', '1361867', '1361921', '1361949',
'1364886', '1367224', '1368005', '1368456', '1368982', '1369000',
'1370365', '1370434', '1370551', '1371492', '1471407', '1709408',
'1710264', '1710308', '1710322', '1710350', '1710365', '1710375',
'1710390']
38
['2717', '184', '188', '163', '476', '715', '1099', '716', '586', '222',
'456', '457', '582', '418', '424', '425', '177', '458', '236', '2501',
'3625', '1526', '299', '1615', '1632', '1002', '379', '3626', '1003',
'1004', '3625', '1002', '1019', '1037', '1066', '998', '977', '930']
['5002', '1710791', '18047', '32', '137', '3'] #when history_ends=5002
['1302665', '1364654', '1385017']
3
['17285', '61465', '17961']
''''''''''''''''''''''''''''''''''
''''''''''''''''''''''''''''''''''''
''''''''''''''''''''''''''''''''''''''''''
''''''''''''''''''''''''''''''''''''''''''''''''''''
''''''''''''''''''''''''''''''''''''''''''''''
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'''''''''''''''''''''''''''''''''''''''''''''''''''''''
Till the end of the file
can any one suggest how i can modify my code to be able to do this in
python.It would be helpful............

Python - random.randint () issue

Python - random.randint () issue

After randomly generating a number, I check to see if the user's input
matches. If it does, print one line, if not, print another. Even if the
user guesses correctly, the other line prints.
chosenNumber = input ("Choose a number: ")
int (chosenNumber)
diceRoll = random.randint (1,3)
print ("The number rolled is: ",diceRoll)
if diceRoll == chosenNumber:
print ("WINNER")
else:
print ("LOSER")
Thank you for any help.

I've never logged into Linkedin and receive update notifications

I've never logged into Linkedin and receive update notifications

I've never subscribed to Linkedin. To me it's a Virus. A past employee,
whom is no longer with out company, had placed my name in his distribution
list of updates. I don't know how to get in touch with this person nor do
I wish to. He is a complete Jackass. I will not sign into Linkedin to mail
him to remove my name as I don't have an account nor do I want one.
HOW DO I STOP THESE. In outlook I have placed them in SPAM but they still
get into my junk email and I cannot stop this.
Please help. I can supply the name of the individual if Customer service
can go in and block or delete my name from his list.
AGAIN..... PLEASE HELP
Frustrated Hard Working Employee

Stop the focus change on autopostback= true

Stop the focus change on autopostback= true

Hey guys I am having a tough one. I have a radgrid that contains a list of
checkboxes. Now when the user changes the check box the checkbox does a
postback and changes the text and color of the row. Now when it does this
it yanks the focus to that row. So if I check the box and scroll up to the
top of the page it will yank me back to the bottom. I would like to make
it so it doesn't change any focus and just does an async postback.
Here is just the checkbox pulled from the grid
<asp:CheckBox runat="server" ID="isChecked" Checked='<%# Eval("active")
%>' AutoPostBack="true"
OnCheckedChanged="CheckChanged"
ToolTip="Activate/In-activate
relationship between Event and
Category" />
Now here is the whole grid with the checkbox code inside. Again I just
want to stop the focus change. I want the user to be able to uncheck a box
and scroll without worrying about their focus yanking back to the row they
changed.
<telerik:RadGrid ID="RadGrid1" runat="server" AllowPaging="True"
AllowSorting="True"
CssClass="mdmGrid active" CellSpacing="0"
DataSourceID="eventsINcategories" GridLines="None"
Width="80%" OnItemDataBound="RadGrid1_ItemDataBound">
<ClientSettings AllowColumnsReorder="True"
ReorderColumnsOnClient="True">
<Selecting AllowRowSelect="True" />
</ClientSettings>
<MasterTableView AutoGenerateColumns="False"
DataSourceID="eventsINcategories">
<CommandItemSettings ExportToPdfText="Export to
PDF"></CommandItemSettings>
<RowIndicatorColumn Visible="True"
FilterControlAltText="Filter RowIndicator column">
</RowIndicatorColumn>
<ExpandCollapseColumn Visible="True"
FilterControlAltText="Filter ExpandColumn column">
</ExpandCollapseColumn>
<Columns>
<telerik:GridTemplateColumn UniqueName="ActiveDisabled"
HeaderText="Status" AllowFiltering="false">
<ItemTemplate>
<asp:CheckBox runat="server" ID="isChecked"
Checked='<%# Eval("active") %>'
AutoPostBack="true"
OnCheckedChanged="CheckChanged"
ToolTip="Activate/In-activate
relationship between Event and
Category" />
<asp:Label ID="Label2" runat="server"
ForeColor='<%# (bool)Eval("active") ?
System.Drawing.Color.Green :
System.Drawing.Color.Red %>'
Text='<%# string.Format("{0}",
(bool)Eval("active") ? "Active" :
"In-Active") %>'></asp:Label>
<asp:Label runat="server" ID="hidd_CategoryID"
Text='<%# Eval("categoryID") %>' Style="display:
none; color:Red;"></asp:Label>
<asp:Label runat="server" ID="hidd_eventID"
Text='<%# Eval("eventID") %>' Style="display:
none;"></asp:Label>
<asp:Label runat="server"
ID="hide_EventActivation" Text='<%#
DataBinder.Eval(Container.DataItem,
"eventActivation") %>'
Visible="false"></asp:Label>
</ItemTemplate>
<ItemStyle Width="100px" />
</telerik:GridTemplateColumn>
<telerik:GridBoundColumn DataField="eventDetail"
FilterControlAltText="Filter eventDetail column"
HeaderText="Event and Event
Codes" ReadOnly="True"
SortExpression="eventDetail"
UniqueName="eventDetail">
<ItemStyle Width="200px" />
</telerik:GridBoundColumn>
<telerik:GridBoundColumn DataField="categoryName"
FilterControlAltText="Filter categoryName column"
HeaderText="Category"
SortExpression="categoryName"
UniqueName="categoryName">
<ItemStyle Width="100px" />
</telerik:GridBoundColumn>
<telerik:GridTemplateColumn UniqueName="NotifyOptions"
HeaderText="Notify Options" AllowFiltering="true"
SortExpression="NotifyOptions">
<ItemTemplate>
<asp:Label ID="notifyOptionsText" runat="server"
Text=""></asp:Label>
<asp:Label runat="server" ID="notifyEmail"
Text='<%# DataBinder.Eval(Container.DataItem,
"notifyEmail") %>' Visible="false"></asp:Label>
<asp:Label runat="server" ID="notifyTextMessage"
Text='<%# DataBinder.Eval(Container.DataItem,
"notifyTextMessage") %>'
Visible="false"></asp:Label>
</ItemTemplate>
<ItemStyle Width="100px" />
</telerik:GridTemplateColumn>
</Columns>
<EditFormSettings>
<EditColumn FilterControlAltText="Filter EditCommandColumn
column">
</EditColumn>
</EditFormSettings>
<BatchEditingSettings EditType="Cell" />
<PagerStyle PageSizeControlType="RadComboBox"
AlwaysVisible="true"></PagerStyle>
</MasterTableView>
<PagerStyle PageSizeControlType="RadComboBox" />
<FilterMenu EnableImageSprites="False">
</FilterMenu>
</telerik:RadGrid>
I greatly appreciate any help you guys can provide on this one.

is there any way to get current username and mobile number in android?

is there any way to get current username and mobile number in android?

is there any way to get current username and mobile number in android ?
I want to get the user information of current phone number and username in
android.
Any body have a code or idea,help me..Thank you..

Tuesday, 20 August 2013

Why Default constructor need to declare in POJO file which has Parameterized Constructor while instantiating Object?

Why Default constructor need to declare in POJO file which has
Parameterized Constructor while instantiating Object?

Suppose I have one POJO class User with a constuctor public User(int id,
String name){...}. But when I instantiate the User object like User u=new
User() with no parameter Eclipse gives error like The constructor User()
is undefined. But it works fine when I have no parameterized Constructor.
Can someone please explain why It requires to define default constructor?

Get a css value from Bootstrap css with JavaScript/ jQuery?

Get a css value from Bootstrap css with JavaScript/ jQuery?

I want to get the font sizes of headings h1,h2,h3,h4,h5,h6 which are
respectively 36px, 30px, 24px, 18px, 14px, 12px respectively [in
bootstrap.css] and alert them in the console. The jQuery method I've seen
is $('element').css('property'), but this is not working for external css
[i.e bootstrap.css]. Should I have to include any more lines of code.

Angular.js's $compile doesn't replace values

Angular.js's $compile doesn't replace values

I'm build an Angular.js app that uses a third-party library. The library
requires me to pass in a string containing HTML. This HTML is complex and
requires several values to be injected. I'd like to use Angular's build in
$compile service to compile that data. Here's an example:
// create the template
var template = "<p>{{ test }}</p>";
// set up the scope
var scope = $rootScope.$new();
scope.test = "hello";
// compile the template
var htmlString = $compile(template)(scope)[0].outerHTML;
When I run this code, I would expect htmlString to be <p>hello</p>, but
instead it's <p class="ng-scope ng-binding">{{ test }}</p>. I understand
Angular is setting up its bindings, but I want static content. Is there
any way to achieve the behavior I want?

SQL Decision statement

SQL Decision statement

I am trying to create a decision statement to determine if the 5 variables
(@skill1, @skill2, @skill3, @skill4, @skill5) are not null or empty.
The people_skills table contains different skills for each person. So
there may be more than 1 record for a person. The lkp_skills contains the
names of those skills.
Based on the 5 different skill fields, I want to ignore the empty string.
I also want to search for the strings within the lkp_skills table. If the
variable matches the s.skill field of that table then i want it to return
that record. If there are multiple skills then I want it to return records
that have Both of those skills.
What is the best way of doing this?
DECLARE @zip char(5) = '61265', -- Zip Code
@skill1 varchar(50) = 'sql', -- Job Skill 1
@skill2 varchar(50) = 'css', -- Job Skill 2
@skill3 varchar(50) = '', -- Job Skill 3
@skill4 varchar(50) = '', -- Job Skill 4
@skill5 varchar(50) = '', -- Job Skill 5
@distance int = 5 -- Distance in miles
SELECT p.people_id, p.first_name, p.last_name, p.address_1, p.address_2,
p.city, p.[state],
p.zip_code, (dbo.sp_getDistance(@zip, zip_code)) AS miles, s.skill
FROM people p
INNER JOIN people_skills ps ON ps.people_id = p.people_id
INNER JOIN lkp_skills s ON ps.skill_id = s.skill_id
WHERE (ISNUMERIC(p.zip_code) = 1 AND LEN(RTRIM(LTRIM(p.zip_code))) = 5)
AND p.ROLE_ID <= 4
AND ((dbo.sp_getDistance(@zip, zip_code)) <= @distance)
AND
-- DECISION STATEMENT GOES HERE --
ORDER BY miles

Adding a text link to a hyperlink on a email

Adding a text link to a hyperlink on a email

I am working on a notification message in Java that sends a message and a
hyperlink. Now the hyperlink is way too long depending and was asked to
make it like a link text similar to how its done on html and on hotmail.
<'a href="http://www.hello_world.com/"'> Hello world</a>
Now the email i am sending can't be sent as a html page just text. Is
there a way of making this happen on text to where when the user just
see's the word "here" or something and it goes to the hyperlink?

Using and running Tortoise svnsync in Windows via command line

Using and running Tortoise svnsync in Windows via command line

I have a local repository and I have just signed up to unfuddle and want
to sync my local repository to the new one I have created on there.
I was told to run the following command:
svnsync init --username USERNAME
http://username.unfuddle.com/svn/username-rep http://SOURCE_REPO_URL
Firstly, I assume I can remove the username stuff if the source repository
doesn't require authentication?
Secondly, when I run that command my system doesn't recognize it. I
assumed svnsync needed to be added somewhere in Windows so that it could
be run via it's name only, but not only do I not know how to do that I
don't know what program to add...... I cannot find any svnsync.exe or
anything locate din my TortoiseSVN folder.
What do I need to do here?

Woocommerce get products using multiple category ID's

Woocommerce get products using multiple category ID's

I'm trying display products from muliple categories using the category
ID's, I've managed to display the product category name (which was a pain)
and this works fine if I wanted to get products from a single category but
obviously dosn't work if the product is in multiple categories. I need
help getting the product category ID and making this work with getting all
posts within this category no matter if it is in multiple categories or
not. Any help, advice or tips would greatly be appreciated.
<?php
global $post, $product;
$categ = $product->get_categories();
$categ2 = preg_replace('/<a href=\"(.*?)\">(.*?)<\/a>/',"\\2",
$categ);
echo $categ2; /* TEST */
?>
<?php
global $product;
$args = array( 'post_type' => 'product', 'posts_per_page' =>
'999', 'product_cat' => $categ2, );
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post(); global $product;
?>

Monday, 19 August 2013

Keep Shared Preferences even the application package of android have been uninstall in offline mode

Keep Shared Preferences even the application package of android have been
uninstall in offline mode

I found out the backup can restored the shared preferences after the
application been uninstall, just wondering is there anyway to keep
SharedPreferences in device even the application have been uninstall in
offline mode?

Is there a GIT api that can tell if a specific line of a file has a whitespace only change

Is there a GIT api that can tell if a specific line of a file has a
whitespace only change

Is there a GIT api that can tell if a specific line (say given line no.)
of a file has a whitespace only change? I'm writing a rule in lint
(ArcanistLinter) that would alert if certain lines have only whitespace
changes, and they're not adjacent to any real change (say they got
modified by the editor).

Use gmaps4rails from json

Use gmaps4rails from json

I am working on small project and need use google map. I decide to use gem
'gmaps4rails' to easier map implementation. The problem is all
documentation showing how to get json object from model and DB and I have
to use json as data:
{"listings":[
{ "id":1001, "name":"home1", "description":"home 1 description!",
"street":"45 Broadway", "city":"New
York","state":"NY","zipcode":"11011","country":"US"},
{ "id":1002, "name":"home2", "description":"home 2 description!",
"street":"45 Madison Ave", "city":"New
York","state":"NY","zipcode":"11006","country":"US"} ]}
I want to get the map attributes only from it and pass it through
controller and display it to the view, I pretty new on using json so if
somebody can guide me through this problem I will really appreciated.

Parsing JSON in Controller w/ HTTParty

Parsing JSON in Controller w/ HTTParty

In my controller I have the following code...
response = HTTParty.get('https://graph.facebook.com/zuck')
logger.debug(response.body.id)
I am getting a NoMethodError / undefined method `id'
If I do...
logger.debug(response.body)
It outputs as it should...
{"id":"4","name":"Mark
Zuckerberg","first_name":"Mark","last_name":"Zuckerberg","link":"http:\/\/www.facebook.com\/zuck","username":"zuck","gender":"male","locale":"en_US"}
One would think it's response.body.id, but obviously that's not working.
Thanks in advance!

How does one calculate product pricing to cover processing fees from $5 - $5,000 while maintaining a profit?

How does one calculate product pricing to cover processing fees from $5 -
$5,000 while maintaining a profit?

Credit card processor charges, for each transaction, 2.9% + $0.30.
I need to find an amount that covers that cost, from $$5 to $5,000, on a
per item basis, all while maintaining a small profit.
For example, a customer may want to purchase 3 items. Each item has a
different price and possibly a different fee structure based on whether or
not it's a for-profit purchase or non-profit purchase.
Item 1 is $$10 and for-profit so we need to account for the processing fee
plus a 5% profit.
Item 2 is $$80 and for-profit so we need to account for the processing fee
plus a 5% profit.
Item 3 is $$25 and non-profit so we need to account for the processing fee
only- no profit.
What I cannot determine is a full-proof way to account for the fees all
the way up to $5,000 without losing money on the processing fees.

Sunday, 18 August 2013

how to check exist value attribute with jQuery

how to check exist value attribute with jQuery

I want to check value of attribute html tag and if that element not exist
with value of attribute append certain element in my html.
for example I have many li tags like this:
<ul id="friend-list">
<li id="1"></li>
<li id="2"></li>
<li id="3"></li>
<li id="4"></li>
<li id="5"></li>
<li id="6"></li>
</ul>
I want when click on any li run this jQuery code and append one element :
append element :
var conversation ='<div class="conversation stream" id='+ conversationID
+'><div class="timeline"><ul class="all-msg"><li class="me typing"><div
id="chat-text" contenteditable="true"></div><div id="upload-f"></div><div
id="upload-p"></div><div id="chat-arrow"></div></li></ul></div></div>';
$('body').append(conversation);
jQuery code:
$(document).on('click','#friend-list li',function(){
var getID = $(this).attr('id');
var conversationID = 'Conver-' + getID;
console.log(conversationID);
if(/* don't exist element with attribute and value*/){
// append that element
var conversation ='<div class="conversation stream" id='+
conversationID +'><div class="timeline"><ul class="all-msg"><li
class="me typing"><div id="chat-text"
contenteditable="true"></div><div id="upload-f"></div><div
id="upload-p"></div><div
id="chat-arrow"></div></li></ul></div></div>';
$('body').append(conversation);
}
});
so I want first check exist that I want append it. if this element not
exist so append this Otherwise don't append this.
thanks a lot guys.

free web hosting supports php and Matlab

free web hosting supports php and Matlab

I am working now on a web project and I have MATLAB code and I need to
integrate this code with my web project So is there any one know a free
web hosting supports MATLAB. I ran this this project locally but I need it
to host it on a server.
Any help will be appreciated. Thanks In advance.

NS2: simulating nodes running two different mac protocol

NS2: simulating nodes running two different mac protocol

I wanted to simulate nodes, running different mac protocols so that they
can co exist/ transfer packet b/n each other with out causing any problem
on each other..how can I do that...especially how can I modify simple
wireless simulation code
example if macs are like 1. set val(mac1) Mac/802_3 ;# MAC type just
example 2.set val(mac2) Mac/802_11 ;# the other mac protocol
JUST POINT OUT WHERE/HOW SHALL I MODIFY THE CODE

Finding all $x$ such that $|\tan x | \leq 2\sin x$

Finding all $x$ such that $|\tan x | \leq 2\sin x$

I need to find all real numbers x that satisfy: $$|\tan x | \leq 2\sin x
\;\; and\;\; x \in [ -\pi, \pi]$$ in terms of unions of intervals.
I know it's equivalent to: $-2\sin x \leq \tan x \leq 2 \sin x $
I tried dividing into cases where $\sin x = 0 $ or $\sin x \neq0$ .
and also, $\cos x \gt 0 $ or $\cos x \lt 0 $. But alas, my attempts to
solve this failed.
Perhaps I'm missing something?
In addition, I'm struggling with these types of questions (finding
solution sets) as it's hard for me to see whether the attempted solution
shows a double inclusion or a single one. In other words whether each step
of inference is an equivalence or just an implication.
Thanks.

Default values of local variables?

Default values of local variables?

In Java, why class variables gets initiliazed to default value. But local
variables are not.?
Can anyone explain?

Issue creating a custom ListView in Android

Issue creating a custom ListView in Android

I was trying to design a custom array adapter for the ArrayList for a
android application.
What I require is a list of items to be displayed, where in each item
consists of a checkbox and a descriptive text. I figured that i would need
to implement a extention of baseAdapter to do this. I am not able to get
it to work. Please point out my mistake.
The following is my main activity screen, simply consists of a button and
a listView, both of with have been packed in a RelativeLayout.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/background"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".HomeActivity" >
<Button
android:id="@+id/addTaskButton"
android:textSize="30sp"
style="@style/bottomButton"
android:text="@string/addTaskButtonText"/>
<ListView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_above="@id/addTaskButton"
android:id="@+id/list">
</ListView>
</RelativeLayout>
The following is the layout for a single item in a listView for the above
screen.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/singleItemContainer"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10dip">
<CheckBox
android:id="@+id/taskDoneCheckBox"
android:layout_alignParentLeft="true">
</CheckBox>
<TextView
android:id="@+id/taskDescriptionTextView"
android:layout_toRightOf="@+id/taskDoneCheckBox"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10dip"/>
</RelativeLayout>
The following is the custom adapter I have created.
public class MyListAdapter extends BaseAdapter {
private Activity activity;
private ArrayList<HashMap<String, String>> data;
private static LayoutInflater inflater=null;
public MyListAdapter(Activity a, ArrayList<HashMap<String, String>> d) {
activity = a;
data=d;
inflater =
(LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount() {
return data.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi=convertView;
if(convertView==null)
vi = inflater.inflate(R.layout.list_item, null);
CheckBox taskDoneCheckBox = (CheckBox)
vi.findViewById(R.id.taskDoneCheckBox);
TextView taskDescriptionTextView =
(TextView)vi.findViewById(R.id.taskDescriptionTextView);
HashMap<String, String> task = new HashMap<String, String>();
task = data.get(position);
// Setting all values in listview
if(task.get(HomeActivity.IS_TASK_DONE) == "false")
taskDoneCheckBox.setChecked(false);
else
taskDoneCheckBox.setChecked(true);
taskDescriptionTextView.setText(task.get(HomeActivity.TASK_DESCRIPTION));
return vi;
}
}
And lastly the following is the mainActivity class. I have marked the line
whose presence crashes the application.
public class HomeActivity extends Activity {
public static final String IS_TASK_DONE = "isTaskDone";
public static final String TASK_DESCRIPTION = "taskDescription";
MyListAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
//setting up font for the "add task" button.
Typeface tf =
Typeface.createFromAsset(getAssets(),"Fonts/doridrobot.ttf");
Button addTaskButton = (Button) findViewById(R.id.addTaskButton);
addTaskButton.setTypeface(tf);
// storing string resources into HashMap
ArrayList<HashMap<String,String>> taskList = new
ArrayList<HashMap<String,String>>();
HashMap<String,String> task = new HashMap<String,String>();
task.put(IS_TASK_DONE, "false");
task.put(TASK_DESCRIPTION, "Let this be task 1");
taskList.add(task);
HashMap<String,String> task1 = new HashMap<String,String>();
task1.put(IS_TASK_DONE, "true");
task1.put(TASK_DESCRIPTION, "Let this be task 2");
taskList.add(task1);
ListView itemList = (ListView) findViewById(R.id.list);
adapter = new MyListAdapter(this,taskList);
itemList.setAdapter(adapter); //<----- THIS IS THE ONE
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is
present.
getMenuInflater().inflate(R.menu.home, menu);
return true;
}
}
Removing the last line in the OnCreate function "helps" the app to not
crash, but then the list remains empty... how can i solve this issue?

why are the two object equals?

why are the two object equals?

i've ran this code
#include <stdio.h>
#include <string.h>
main()
{
int i = 4;
int arr[10];
printf("%d", arr[i]==i[arr]);
}
and got the output 1, as part of a job interview i had that asked what's
the output. i'm scratching thinking that i understand why it is compiling,
but i was certain it would be a segmentation fault or ate least 0 because
the address of i[arr] isn't known...
where am i gone wrong? is it every address considered 0 until initialized?

Saturday, 17 August 2013

A Guide to Install Ubuntu 13.04 using a RAID 0

A Guide to Install Ubuntu 13.04 using a RAID 0

Getting the error: Unable to install grub in /dev/sda? Because you are
using a BIOS/fakeRAID0?
If you manage to find this thread consider yourself in luck. I spent the
last 48 hours trying to figure how the easiest way to configure Ubuntu
13.04 using fakeRAID 0 or BIOS RAID 0, whatever you want to call it after
reading different options from many different forums.
Others tell you oh software RAID is better than fakeRAID, and why are you
using RAID 0?
If you are like me and ignoring them follow my instructions below and I
promise you this will be the easiest way to install U13.04 on a fakeRAID0
without jumping through hoops with a lot of terminal commands and reading
a crap load of forums.
Disclaimer: I installed U13.04 by wiping both HDD's. This is NOT a dual
boot scenario. If you can create an additional RAID Volume in your BIOS
utility and use this working aid, go right ahead.
Necessities: U13.04 Live CD & 2 HDD's
Power on PC.
Configure BIOS to boot from Live CD, by pressing whatever your BIOS setup
button is F2, F9, F12, DEL, ESC, save your settings once you've changed
your boot order to CD/DVD-ROM.
Insert U13.04 Live CD
Access your Raid Array Utility, for me it was CTRL + I
Delete any old RAID volume's you currently have to wipe the slate clean
Create a new RAID 0 volume, name it whatever you like, save changes, exit.
At this point your 2 disks should be united as one and your boot screen
should show them members of 0 (or whatever your volume number is) and you
should boot into the Live CD.
Select: Install Ubuntu 13.04, follow all your desired options to complete
installation.
When you get the error Unable to install grub at the end of the
installation, continue without the bootloader.
Restart PC.
At this point the system has Ubuntu on it, you just don't have a way to
get to it.
So insert your Ubuntu disc again, since the system probably kicked it out.
Boot from Live CD again then select: Try Ubuntu
Connect to the internet, WiFi is in top right corner.
Top left corner is an Ubuntu icon, click it.
Search for 'Terminal', hit Enter.
Type the following: sudo add-apt-repository ppa:yannubuntu/boot-repair &&
sudo apt-get update, hit Enter.
Once the terminal finishes downloading the boot-repair from the repository
type the following:
sudo apt-get install -y boot-repair && (boot-repair &), hit Enter.
The boot-repair window should open.
Select: Recommend Repair
Do NOT select any other option.
When you get the successful screen, record the
"http://paste.ubuntu.com/XXXXX" in the event the boot-repair didn't work
so you could contact the guys that supplied the boot-repair option which
is listed in the link below:
https://help.ubuntu.com/community/Boot-Repair#A2nd_option_%3a_install_Boot-Repair_in_Ubuntu
Hope this helps.
And I guess since I am suppose to prompt a question in this forum, here it
is: Why didn't Ubuntu 13.04 come with an easier way to install RAID0, or
better yet accommodate fakeRAID by allowing the installation to install
GRUB in the first place?