Iterate through char array and print chars
I am trying to print each char in a variable.
I can print the ANSI char number by changing to this printf("Value: %d\n",
d[i]); but am failing to actually print the string character itself.
What I am doing wrong here?
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
int len = strlen(argv[1]);
char *d = malloc (strlen(argv[1])+1);
strcpy(d,argv[1]);
int i;
for(i=0;i<len;i++){
printf("Value: %s\n", (char)d[i]);
}
return 0;
}
Friday, 27 September 2013
C Socket Programming for stdin
C Socket Programming for stdin
In C socket programming, I have to read from keyboard and accept client
socket creation . The socket connection is created successfully but the
fails to take input from keyboard. Below is code snippet.
int listener; fd_set readfds;
listener=serverConnect(listener,serveraddr,yes);
FD_SET(listener, &readfds);
FD_SET(STDIN, &readfds);
fdmax = listener;
addrlen=sizeof(clientaddr);
for(;;)
{
select(fdmax+1, &readfds, NULL, NULL, NULL);
printf("$");
if(FD_ISSET(listener, &readfds))
{
if((newfd = accept(listener, (struct sockaddr *)&clientaddr,
&addrlen)) == -1)
{
perror("Server-accept() error\n");
}
else printf("Connection is done\n");
}
if (FD_ISSET(STDIN, &readfds))
{
printf("$");
scanf("%s",command1,command2,command3);
printf("The command entered is: %s\n",command1);
if (strcmp(command1, "MYIP")==0)
{
printf("Get ip address\n");
myip();
fflush(stdout);
}
In C socket programming, I have to read from keyboard and accept client
socket creation . The socket connection is created successfully but the
fails to take input from keyboard. Below is code snippet.
int listener; fd_set readfds;
listener=serverConnect(listener,serveraddr,yes);
FD_SET(listener, &readfds);
FD_SET(STDIN, &readfds);
fdmax = listener;
addrlen=sizeof(clientaddr);
for(;;)
{
select(fdmax+1, &readfds, NULL, NULL, NULL);
printf("$");
if(FD_ISSET(listener, &readfds))
{
if((newfd = accept(listener, (struct sockaddr *)&clientaddr,
&addrlen)) == -1)
{
perror("Server-accept() error\n");
}
else printf("Connection is done\n");
}
if (FD_ISSET(STDIN, &readfds))
{
printf("$");
scanf("%s",command1,command2,command3);
printf("The command entered is: %s\n",command1);
if (strcmp(command1, "MYIP")==0)
{
printf("Get ip address\n");
myip();
fflush(stdout);
}
jQuery UI sortable & contenteditable=true not working together
jQuery UI sortable & contenteditable=true not working together
I am creating a list & want to make its item sortable and editable. So i
am doing it like this:
<ul id="ul_list">
<li><span contenteditable="true">A</span></li>
<li><span contenteditable="true">B</span></li>
<li><span contenteditable="true">C</span></li>
</ul>
$("#ul_list").sortable();
http://jsfiddle.net/7jzVa/
But if i use jquery ui sortable then my list item is losing focus for
editing and that's why i am not able to edit them.
So please suggest how can i do this?
I am creating a list & want to make its item sortable and editable. So i
am doing it like this:
<ul id="ul_list">
<li><span contenteditable="true">A</span></li>
<li><span contenteditable="true">B</span></li>
<li><span contenteditable="true">C</span></li>
</ul>
$("#ul_list").sortable();
http://jsfiddle.net/7jzVa/
But if i use jquery ui sortable then my list item is losing focus for
editing and that's why i am not able to edit them.
So please suggest how can i do this?
Html interpretation for different browsers
Html interpretation for different browsers
Recently, I downloaded a JQuery plugin for animation on tabbed content of
a html page. The html defined for Tabs and their respective contents and
animation is obtained by the JQuery. here is a sample html of my tabs.
<ul>
<li><a href="#two">PED</a></li>
<li><a href="#Five">SPDE</a></li>
<li><a href="#one">SDE</a></li>
</ul>
<div class="box-wrapper">
<div id="Seven" class="content-box">
<div class="col-one col">
<a href="" target="_blank" title="Click to go to
Advanced-Design Team Site">
<img src=""/></a>
</div>
<div class="col-two col">
<h3>
<a href="" target="_blank" style="color:
Black; text-decoration: underline"
title="Click to go to Advanced-Design Team
Site">
Advanced Design</a></h3>
<p>
Welcome to Advanced Design Group.</p>
</div>
There are remaining divs as coded above.
I displayed this tabbed html page in another page using an iframe tag.When
I click on any one of the tabs the page auto snaps to the starting of the
content page. This doesn't happen in Firefox, but it displays the content
as expected without snapping. In IE and Chrome, the page snaps to the
starting of the respective tab. We need to re scroll to the top of the
page.
Not sure why this happens, Is there any issue in the way browsers
interpret the HTML or my HTML code is wrong? I don't see any other way
except to use the approach. I know this is causing the issue but is there
any way out to make the page not snap in IE or chrome or do I need to
develop my page with tabbed content without using the approach I did now.
this is kind of Road end for me. Dont know where to go.
Any pointers would be of great help. Thanks,
Recently, I downloaded a JQuery plugin for animation on tabbed content of
a html page. The html defined for Tabs and their respective contents and
animation is obtained by the JQuery. here is a sample html of my tabs.
<ul>
<li><a href="#two">PED</a></li>
<li><a href="#Five">SPDE</a></li>
<li><a href="#one">SDE</a></li>
</ul>
<div class="box-wrapper">
<div id="Seven" class="content-box">
<div class="col-one col">
<a href="" target="_blank" title="Click to go to
Advanced-Design Team Site">
<img src=""/></a>
</div>
<div class="col-two col">
<h3>
<a href="" target="_blank" style="color:
Black; text-decoration: underline"
title="Click to go to Advanced-Design Team
Site">
Advanced Design</a></h3>
<p>
Welcome to Advanced Design Group.</p>
</div>
There are remaining divs as coded above.
I displayed this tabbed html page in another page using an iframe tag.When
I click on any one of the tabs the page auto snaps to the starting of the
content page. This doesn't happen in Firefox, but it displays the content
as expected without snapping. In IE and Chrome, the page snaps to the
starting of the respective tab. We need to re scroll to the top of the
page.
Not sure why this happens, Is there any issue in the way browsers
interpret the HTML or my HTML code is wrong? I don't see any other way
except to use the approach. I know this is causing the issue but is there
any way out to make the page not snap in IE or chrome or do I need to
develop my page with tabbed content without using the approach I did now.
this is kind of Road end for me. Dont know where to go.
Any pointers would be of great help. Thanks,
IE8 opacity animate on a png transparent
IE8 opacity animate on a png transparent
I try to animate the opacity of a div which have a .png background.
<div id="image" style="background:url('background.css') repeat-x";></div>
For that, I use this code :
$("#image").stop().animate({
opacity: 1
}, 1000, "easeInOutSine", function() {
$("#image").stop().animate({
opacity: 0
}, 1000, "easeInOutSine");
});
It's ok for recent browsers. But in IE 7 and 8, the transparence is
black... I looked for a solution but none works. Someone can help me?
Thanks
I try to animate the opacity of a div which have a .png background.
<div id="image" style="background:url('background.css') repeat-x";></div>
For that, I use this code :
$("#image").stop().animate({
opacity: 1
}, 1000, "easeInOutSine", function() {
$("#image").stop().animate({
opacity: 0
}, 1000, "easeInOutSine");
});
It's ok for recent browsers. But in IE 7 and 8, the transparence is
black... I looked for a solution but none works. Someone can help me?
Thanks
Password Regex Validation: Preventing Spaces
Password Regex Validation: Preventing Spaces
Okay, so I'm trying to adhere to the following password rule:
Must be 6 to 15 characters, include at least one lowercase letter, one
uppercase letter and at least one number. It should also contain no
spaces.
Now, for everything but the spaces, I've got:
^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).{6,15}$
Problem is, that allows spaces.
After looking around, I've tried using \s, but that messes up my lowercase
and uppercase requirements. I also seen another suggestion to replace the
* with a +, but that seemed to break the entire thing.
I've created a REFiddle if you want to have a live test.
Okay, so I'm trying to adhere to the following password rule:
Must be 6 to 15 characters, include at least one lowercase letter, one
uppercase letter and at least one number. It should also contain no
spaces.
Now, for everything but the spaces, I've got:
^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).{6,15}$
Problem is, that allows spaces.
After looking around, I've tried using \s, but that messes up my lowercase
and uppercase requirements. I also seen another suggestion to replace the
* with a +, but that seemed to break the entire thing.
I've created a REFiddle if you want to have a live test.
Thursday, 26 September 2013
check the update command, m i doing mistake in its syntax?
check the update command, m i doing mistake in its syntax?
his there all, i'm working on a cms, while trying the update command to
update the records, its not working.
here's m complete code for update,
Dim ID, RegNo, BedNo, BedType, Charges, PatName, PatAge, PatAddr, Phone,
CheckupDate, Disease, BloodGroup, Doctor, Remarks As String
RegNo = txtRegNo.Text
BedNo = CmbBedNo.SelectedItem.ToString()
BedType = CmbBedType.SelectedItem.ToString()
Charges = txtCharges.Text
PatName = txtPatName.Text
PatAge = txtPatAge.Text
PatAddr = txtPatAdd.Text
Phone = txtPhone.Text
CheckupDate = txtDate.Text
Disease = txtDisease.Text
BloodGroup = cmbBloodGrp.SelectedItem.ToString()
Doctor = cmbDoctor.SelectedItem.ToString()
Remarks = txtRemarks.Text
ID = txtRegNo.Text
Dim conStudent As New OleDbConnection
Dim comStudent As New OleDbCommand
conStudent.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data
Source=F:\DBProject\hspms.mdb"
conStudent.Open()
comStudent.CommandText = "UPDATE AdmitPt SET ID =" & ID & ",
Bedcategory='" & BedType & "', BedNo=" & BedNo & ", BedCharges=" &
Charges & ", PtName='" & PatName & "', PtAge=" & PatAge & ",
Address='" & PatAddr & "', PhoneNo='" & Phone & "', Dates='" &
CheckupDate & "', Disease='" & Disease & "', BloodGroup='" &
BloodGroup & "', Doctor='" & Doctor & "', Remarks='" & Remarks & "'
WHERE ID=" & RegNo
comStudent.Connection = conStudent
comStudent.CommandType = CommandType.Text
If (comStudent.ExecuteNonQuery() > 0) Then
MsgBox("record successfully updated")
End If
conStudent.Close()
one thing, that the fields named with ID, BedNo, BedCharges, Age are set
to Number as data type.
his there all, i'm working on a cms, while trying the update command to
update the records, its not working.
here's m complete code for update,
Dim ID, RegNo, BedNo, BedType, Charges, PatName, PatAge, PatAddr, Phone,
CheckupDate, Disease, BloodGroup, Doctor, Remarks As String
RegNo = txtRegNo.Text
BedNo = CmbBedNo.SelectedItem.ToString()
BedType = CmbBedType.SelectedItem.ToString()
Charges = txtCharges.Text
PatName = txtPatName.Text
PatAge = txtPatAge.Text
PatAddr = txtPatAdd.Text
Phone = txtPhone.Text
CheckupDate = txtDate.Text
Disease = txtDisease.Text
BloodGroup = cmbBloodGrp.SelectedItem.ToString()
Doctor = cmbDoctor.SelectedItem.ToString()
Remarks = txtRemarks.Text
ID = txtRegNo.Text
Dim conStudent As New OleDbConnection
Dim comStudent As New OleDbCommand
conStudent.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data
Source=F:\DBProject\hspms.mdb"
conStudent.Open()
comStudent.CommandText = "UPDATE AdmitPt SET ID =" & ID & ",
Bedcategory='" & BedType & "', BedNo=" & BedNo & ", BedCharges=" &
Charges & ", PtName='" & PatName & "', PtAge=" & PatAge & ",
Address='" & PatAddr & "', PhoneNo='" & Phone & "', Dates='" &
CheckupDate & "', Disease='" & Disease & "', BloodGroup='" &
BloodGroup & "', Doctor='" & Doctor & "', Remarks='" & Remarks & "'
WHERE ID=" & RegNo
comStudent.Connection = conStudent
comStudent.CommandType = CommandType.Text
If (comStudent.ExecuteNonQuery() > 0) Then
MsgBox("record successfully updated")
End If
conStudent.Close()
one thing, that the fields named with ID, BedNo, BedCharges, Age are set
to Number as data type.
Wednesday, 25 September 2013
How to administer computer when no inbound connection is possible?
How to administer computer when no inbound connection is possible?
I have to periodically administer my parent's Linux computer, because they
are too old to understand how to do this themselves. Computer is in the
remote location. I always used ssh through the port forwarding on the
router. However, their provider recently removed the ability to make any
inbound connection and my ssh doesn't connect any more.
My question is: what is the next best way to administer it?
I know that VPN can possibly be used. I can (maybe) set up VPN network
with this computer. Also I can make it try to connect with ssh to my home
computer on a particular port for ex. every 15 minutes, establishing the
port forwarding back to it. Custom shell script should be used for this.
But what are the alternatives? Any other, nicer way to be able to connect
to this Linux machine from outside?
I have to periodically administer my parent's Linux computer, because they
are too old to understand how to do this themselves. Computer is in the
remote location. I always used ssh through the port forwarding on the
router. However, their provider recently removed the ability to make any
inbound connection and my ssh doesn't connect any more.
My question is: what is the next best way to administer it?
I know that VPN can possibly be used. I can (maybe) set up VPN network
with this computer. Also I can make it try to connect with ssh to my home
computer on a particular port for ex. every 15 minutes, establishing the
port forwarding back to it. Custom shell script should be used for this.
But what are the alternatives? Any other, nicer way to be able to connect
to this Linux machine from outside?
Thursday, 19 September 2013
How to set up dependency injection using Dagger for other things then Activities and Fragments?
How to set up dependency injection using Dagger for other things then
Activities and Fragments?
I started setting up dependency injection using Dagger as follows. Please
feel encouraged to correct my implementation since I might have mistakes
in there! In the following you can see how I successfully added dependency
injection for Activities and Fragments. I try to keep it easy for now so I
decided to inject Timber as a logger substitution for Android's log util.
import android.app.Application;
import dagger.ObjectGraph;
import com.example.debugging.LoggingModule;
public class ExampleApplication extends Application {
private ObjectGraph mObjectGraph;
@Override public void onCreate() {
super.onCreate();
mObjectGraph = ObjectGraph.create(new LoggingModule());
}
public void inject(Object object) {
mObjectGraph.inject(object);
}
}
I prepared LoggingModule which provides access to Timber.
package com.example.debugging;
import javax.inject.Singleton;
import dagger.Module;
import dagger.Provides;
import com.example.BuildConfig;
import com.example.activities.BaseFragmentActivity;
import com.example.activities.DetailsActivity;
import com.example.fragments.BaseListFragment;
import com.example.fragments.ProfilesListFragment;
import timber.log.Timber;
@Module(injects = {
// Activities
BaseFragmentActivity.class,
DetailsActivity.class,
// Fragments
BaseListFragment.class,
ProfilesListFragment.class
})
public class LoggingModule {
@Provides @Singleton Timber provideTimber() {
return BuildConfig.DEBUG ? Timber.DEBUG : Timber.PROD;
}
}
The base class for Activities injects itself into the object graph ...
package com.example.activities;
import android.os.Bundle;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import javax.inject.Inject;
import com.example.ExampleApplication;
import timber.log.Timber;
public class BaseFragmentActivity extends SherlockFragmentActivity {
@Inject Timber mTimber;
@Override
protected void onCreate(Bundle savedInstanceState) {
// ...
super.onCreate(savedInstanceState);
((ExampleApplication) getApplication()).inject(this);
}
}
... and any sub class benefits from Timber being already present.
package com.example.activities;
import android.os.Bundle;
import com.example.R;
public class DetailsActivity extends BaseFragmentActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details);
mTimber.i("onCreate");
// ...
}
}
Same for Fragments: the base class does the dirty job ...
package com.example.fragments;
import android.os.Bundle;
import com.actionbarsherlock.app.SherlockListFragment;
import javax.inject.Inject;
import com.example.ExampleApplication;
import timber.log.Timber;
public class BaseListFragment extends SherlockListFragment {
@Inject Timber mTimber;
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
((ExampleApplication) getActivity().getApplication()).inject(this);
}
}
... and the sub class benefits from its super class.
package com.example.fragments;
import android.os.Bundle;
public class ProfilesListFragment extends BaseListFragment {
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setEmptyText("No data loaded");
mTimber.i("onActivityCreated");
// ...
}
}
So far so good. But how can inject Timber into BaseCursorAdapter,
BaseContentProvider, BaseSQLiteOpenHelper, BaseService, BaseAsyncTask and
static helper methods?
References:
Dagger
Jesse Wilson - Dagger: A Fast Dependency Injector for Android and Java
Eric Burke - Android App Anatomy
Activities and Fragments?
I started setting up dependency injection using Dagger as follows. Please
feel encouraged to correct my implementation since I might have mistakes
in there! In the following you can see how I successfully added dependency
injection for Activities and Fragments. I try to keep it easy for now so I
decided to inject Timber as a logger substitution for Android's log util.
import android.app.Application;
import dagger.ObjectGraph;
import com.example.debugging.LoggingModule;
public class ExampleApplication extends Application {
private ObjectGraph mObjectGraph;
@Override public void onCreate() {
super.onCreate();
mObjectGraph = ObjectGraph.create(new LoggingModule());
}
public void inject(Object object) {
mObjectGraph.inject(object);
}
}
I prepared LoggingModule which provides access to Timber.
package com.example.debugging;
import javax.inject.Singleton;
import dagger.Module;
import dagger.Provides;
import com.example.BuildConfig;
import com.example.activities.BaseFragmentActivity;
import com.example.activities.DetailsActivity;
import com.example.fragments.BaseListFragment;
import com.example.fragments.ProfilesListFragment;
import timber.log.Timber;
@Module(injects = {
// Activities
BaseFragmentActivity.class,
DetailsActivity.class,
// Fragments
BaseListFragment.class,
ProfilesListFragment.class
})
public class LoggingModule {
@Provides @Singleton Timber provideTimber() {
return BuildConfig.DEBUG ? Timber.DEBUG : Timber.PROD;
}
}
The base class for Activities injects itself into the object graph ...
package com.example.activities;
import android.os.Bundle;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import javax.inject.Inject;
import com.example.ExampleApplication;
import timber.log.Timber;
public class BaseFragmentActivity extends SherlockFragmentActivity {
@Inject Timber mTimber;
@Override
protected void onCreate(Bundle savedInstanceState) {
// ...
super.onCreate(savedInstanceState);
((ExampleApplication) getApplication()).inject(this);
}
}
... and any sub class benefits from Timber being already present.
package com.example.activities;
import android.os.Bundle;
import com.example.R;
public class DetailsActivity extends BaseFragmentActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details);
mTimber.i("onCreate");
// ...
}
}
Same for Fragments: the base class does the dirty job ...
package com.example.fragments;
import android.os.Bundle;
import com.actionbarsherlock.app.SherlockListFragment;
import javax.inject.Inject;
import com.example.ExampleApplication;
import timber.log.Timber;
public class BaseListFragment extends SherlockListFragment {
@Inject Timber mTimber;
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
((ExampleApplication) getActivity().getApplication()).inject(this);
}
}
... and the sub class benefits from its super class.
package com.example.fragments;
import android.os.Bundle;
public class ProfilesListFragment extends BaseListFragment {
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setEmptyText("No data loaded");
mTimber.i("onActivityCreated");
// ...
}
}
So far so good. But how can inject Timber into BaseCursorAdapter,
BaseContentProvider, BaseSQLiteOpenHelper, BaseService, BaseAsyncTask and
static helper methods?
References:
Dagger
Jesse Wilson - Dagger: A Fast Dependency Injector for Android and Java
Eric Burke - Android App Anatomy
what is wrong with this program? 3.31
what is wrong with this program? 3.31
my code is as follows but wont work:
inputStr=input('enter the number of quarters: ')
quarters=int(inputStr)
if inputStr.isdigit() :
total=total+quarters*0.25
print('Total: ', total)
else:
print('input error. ')
What is wrong with this?
my code is as follows but wont work:
inputStr=input('enter the number of quarters: ')
quarters=int(inputStr)
if inputStr.isdigit() :
total=total+quarters*0.25
print('Total: ', total)
else:
print('input error. ')
What is wrong with this?
How to split a string in Python by 2 or 3, etc [duplicate]
How to split a string in Python by 2 or 3, etc [duplicate]
This question already has an answer here:
What is the most "pythonic" way to iterate over a list in chunks? 16 answers
Split python string every nth character? [duplicate] 6 answers
Does anyone know if it's possible in python to split a string, not
necessarily by a space or commas, but just by every other entry in the
string? or every 3rd or 4th etc.
For example if I had "12345678" as my string, is there a way to split it
into "12", "34", "56", 78"?
This question already has an answer here:
What is the most "pythonic" way to iterate over a list in chunks? 16 answers
Split python string every nth character? [duplicate] 6 answers
Does anyone know if it's possible in python to split a string, not
necessarily by a space or commas, but just by every other entry in the
string? or every 3rd or 4th etc.
For example if I had "12345678" as my string, is there a way to split it
into "12", "34", "56", 78"?
Netbeans giving me an error message but it works as I want it
Netbeans giving me an error message but it works as I want it
I have a subclass which contains a function which returns a float. I call
that function in a try catch statement, if the an if statement fails and
the else catches it I want that function to "crash" by returning noting
like this return;
Here is that function:
function calc(... some arguments ...) {
...
if (operator.equals("+")) number = num1+num2;
else if (operator.equals("-")) number = num1-num2;
else if (operator.equals("*")) number = num1*num2;
else if (operator.equals("/")) number = num1/num2;
else return; // Here Netbeans gives me an error saying "Missing return
value"
}
Now this function is getting called in a try and I if the else gets
executed I want the function to "crash" and go to the catch statement and
give the user an error message. This works exactly the way I want it but
why does Netbeans give me an error?? Is there another way to do this?
I have a subclass which contains a function which returns a float. I call
that function in a try catch statement, if the an if statement fails and
the else catches it I want that function to "crash" by returning noting
like this return;
Here is that function:
function calc(... some arguments ...) {
...
if (operator.equals("+")) number = num1+num2;
else if (operator.equals("-")) number = num1-num2;
else if (operator.equals("*")) number = num1*num2;
else if (operator.equals("/")) number = num1/num2;
else return; // Here Netbeans gives me an error saying "Missing return
value"
}
Now this function is getting called in a try and I if the else gets
executed I want the function to "crash" and go to the catch statement and
give the user an error message. This works exactly the way I want it but
why does Netbeans give me an error?? Is there another way to do this?
How can I change my NHibernate mapping involving a composite id to execute the expected sql statement?
How can I change my NHibernate mapping involving a composite id to execute
the expected sql statement?
I'm using FluentNHibernate and building a system where a Customer object
exposes several CustomerProperty objects, basically a per-customer
key-value store.
public class CustomerMap : ClassMap<Customer> {
public CustomerMap() {
Table("Customer");
Id(x => x.Id);
Map(x => x.UserName);
HasMany(x => x.Properties);
}
}
public class CustomerPropertyMap : ClassMap<CustomerProperty> {
public CustomerPropertyMap() {
Table("CustomerProperty");
CompositeId()
.KeyReference(x => x.Customer, MapData<Customer>.KeyColumn)
.KeyProperty(x => x.Key);
Map(x => x.Value);
}
}
This works and generates proper NHibernate mappings. I've exported them
using the built-in capabilities of FluentNHibernate.
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2">
<class xmlns="urn:nhibernate-mapping-2.2" dynamic-update="true"
name="Bazinga.Domain.CustomerProperty, Bazinga.Domain,
Version=0.0.0.0, Culture=neutral, PublicKeyToken=108b91ac50cc98b9"
table="CustomerProperty">
<composite-id>
<key-many-to-one name="Customer"
class="Bazinga.Domain.Customer, Bazinga.Domain,
Version=0.0.0.0, Culture=neutral,
PublicKeyToken=108b91ac50cc98b9">
<column name="CustomerId" />
</key-many-to-one>
<key-property name="Key" type="System.String, mscorlib,
Version=4.0.0.0, Culture=neutral,
PublicKeyToken=b77a5c561934e089">
<column name="Key" />
</key-property>
</composite-id>
<property name="Value" type="System.String, mscorlib,
Version=4.0.0.0, Culture=neutral,
PublicKeyToken=b77a5c561934e089">
<column name="Value" />
</property>
</class>
</hibernate-mapping>
This mapping, however, generates a sql query that does not visually please
me. (I can be pretty pedantic.) NHibernate Profiles shows me that the
following query executes.
SELECT properties0_.CustomerId as CustomerId1_,
properties0_.[Key] as Key2_1_,
properties0_.CustomerId as CustomerId13_0_,
properties0_.[Key] as Key2_13_0_,
properties0_.[Value] as Value3_13_0_
FROM CustomerProperty properties0_
WHERE properties0_.CustomerId = 1337 /* @p0 */
There are duplicate references to the CustomerId and the Key column. How
can I remove these and only return a result of three columns (CustomerId,
Key, Value)?
the expected sql statement?
I'm using FluentNHibernate and building a system where a Customer object
exposes several CustomerProperty objects, basically a per-customer
key-value store.
public class CustomerMap : ClassMap<Customer> {
public CustomerMap() {
Table("Customer");
Id(x => x.Id);
Map(x => x.UserName);
HasMany(x => x.Properties);
}
}
public class CustomerPropertyMap : ClassMap<CustomerProperty> {
public CustomerPropertyMap() {
Table("CustomerProperty");
CompositeId()
.KeyReference(x => x.Customer, MapData<Customer>.KeyColumn)
.KeyProperty(x => x.Key);
Map(x => x.Value);
}
}
This works and generates proper NHibernate mappings. I've exported them
using the built-in capabilities of FluentNHibernate.
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2">
<class xmlns="urn:nhibernate-mapping-2.2" dynamic-update="true"
name="Bazinga.Domain.CustomerProperty, Bazinga.Domain,
Version=0.0.0.0, Culture=neutral, PublicKeyToken=108b91ac50cc98b9"
table="CustomerProperty">
<composite-id>
<key-many-to-one name="Customer"
class="Bazinga.Domain.Customer, Bazinga.Domain,
Version=0.0.0.0, Culture=neutral,
PublicKeyToken=108b91ac50cc98b9">
<column name="CustomerId" />
</key-many-to-one>
<key-property name="Key" type="System.String, mscorlib,
Version=4.0.0.0, Culture=neutral,
PublicKeyToken=b77a5c561934e089">
<column name="Key" />
</key-property>
</composite-id>
<property name="Value" type="System.String, mscorlib,
Version=4.0.0.0, Culture=neutral,
PublicKeyToken=b77a5c561934e089">
<column name="Value" />
</property>
</class>
</hibernate-mapping>
This mapping, however, generates a sql query that does not visually please
me. (I can be pretty pedantic.) NHibernate Profiles shows me that the
following query executes.
SELECT properties0_.CustomerId as CustomerId1_,
properties0_.[Key] as Key2_1_,
properties0_.CustomerId as CustomerId13_0_,
properties0_.[Key] as Key2_13_0_,
properties0_.[Value] as Value3_13_0_
FROM CustomerProperty properties0_
WHERE properties0_.CustomerId = 1337 /* @p0 */
There are duplicate references to the CustomerId and the Key column. How
can I remove these and only return a result of three columns (CustomerId,
Key, Value)?
jQuery .hover() in content
jQuery .hover() in content
i have tried to display the value in title on hover, i faced the problem
when i try to hover on a anchor tag in title it displayed some thing like
this <a href="http://blabla.com/1">one</a> so that i have used the
following code to overcome this..
$('.table1 td, .table2 td').find("a, div, label")
.hover(function() {
$(this).prop('title', $(this).html());
});
Now, what i need means, when i hover other than a, div, label am not able
to get any content of td in hover, i need help.. anyone??
i have tried to display the value in title on hover, i faced the problem
when i try to hover on a anchor tag in title it displayed some thing like
this <a href="http://blabla.com/1">one</a> so that i have used the
following code to overcome this..
$('.table1 td, .table2 td').find("a, div, label")
.hover(function() {
$(this).prop('title', $(this).html());
});
Now, what i need means, when i hover other than a, div, label am not able
to get any content of td in hover, i need help.. anyone??
after upload my site on go daddy this error show pls tell me how to solve it
after upload my site on go daddy this error show pls tell me how to solve it
After uploading my site on go daddy I'm getting the following error error:
Link to database cannot be established: SQLSTATE[HY000] [2002] Can't
connect to local MySQL server through socket '/var/lib/mysql/mysql.sock'
(2)
Can someone tell me how to solve it step by step please?
After uploading my site on go daddy I'm getting the following error error:
Link to database cannot be established: SQLSTATE[HY000] [2002] Can't
connect to local MySQL server through socket '/var/lib/mysql/mysql.sock'
(2)
Can someone tell me how to solve it step by step please?
How to uninstall OpenERP-7 module in ubuntu 12.04 ?
How to uninstall OpenERP-7 module in ubuntu 12.04 ?
I am using OpenERP 7 with Ubuntu 12.04. I have been trying to install Aero
Reports module for creating OpenERP reports. I faced some "XML issues "
during installation.
Now when I try to remove the module it says "Integrity Error
The operation cannot be completed, probably due to the following: -
deletion: you may be trying to delete a record while other records still
reference it" .Plz help me to fix this issue
Hopes for suggestion
I am using OpenERP 7 with Ubuntu 12.04. I have been trying to install Aero
Reports module for creating OpenERP reports. I faced some "XML issues "
during installation.
Now when I try to remove the module it says "Integrity Error
The operation cannot be completed, probably due to the following: -
deletion: you may be trying to delete a record while other records still
reference it" .Plz help me to fix this issue
Hopes for suggestion
Wednesday, 18 September 2013
dynamic memory allocation and memory leak
dynamic memory allocation and memory leak
Does free releases the memory in the below, and how can I verify that
memory is released ?
int *p = malloc(sizeof(int));
int *q = p;
free(q);
How to access MCB structure for a dynamically allocated memory ?
Does free releases the memory in the below, and how can I verify that
memory is released ?
int *p = malloc(sizeof(int));
int *q = p;
free(q);
How to access MCB structure for a dynamically allocated memory ?
Call a javascript function after ajax success
Call a javascript function after ajax success
I am using the below test code to call a javascript function from ajax
method after the success block and pass the success value to a javascript
funtion.It's working fine. Now i want to get javascript return message
from ajax call. It always return null.
function testAjax() {
$.ajax({
url:"getvalue.php",
success:function(data) {
var retval= change_format(data);
alert(retvl);//always return null
I can't get the result
}
});
}
function change_format(data)
{
do something.....
value = "Some Data"; having some data
return value;
}
I am using the below test code to call a javascript function from ajax
method after the success block and pass the success value to a javascript
funtion.It's working fine. Now i want to get javascript return message
from ajax call. It always return null.
function testAjax() {
$.ajax({
url:"getvalue.php",
success:function(data) {
var retval= change_format(data);
alert(retvl);//always return null
I can't get the result
}
});
}
function change_format(data)
{
do something.....
value = "Some Data"; having some data
return value;
}
How do I fix this memory leak in C++?
How do I fix this memory leak in C++?
I'm stuck on a program that is due for a class. I have to complete the
project with the correct output and without any memory leaks. Below is the
.h and .cpp for both LocationStack and LocationStackNode. I currently am
getting a memory leak on LocationStackNode and wondered if anyone could
help me with how I should write the destructor. Valgrind specifically
reports the memory leak when allocating new memory in
LocationStack::push(). I am also not allowed to modify the .h file at all.
stack-proj1.h:
class LocationStack {
public:
LocationStack(void);
~LocationStack();
void push(const Location &loc);
void pop(void);
const Location &getTop(void) const;
bool isEmpty(void) const;
bool isOn(const Location &loc) const;
friend ostream &operator<<(ostream &os, const LocationStack &s);
private:
const LocationStack &operator=(const LocationStack &)
{ assert(false); }
LocationStack(const LocationStack &) { assert(false); }
LocationStackNode *top;
};
class LocationStackNode {
public:
LocationStackNode(const Location &loc, LocationStackNode *next = NULL);
~LocationStackNode();
const Location &getLocation() const;
LocationStackNode *getNextNode() const;
void setNextNode(LocationStackNode *next);
private:
LocationStackNode() { assert(false); }
LocationStackNode(const LocationStackNode &) { assert(false); }
LocationStackNode &operator=(const LocationStackNode &)
{ assert(false); }
Location location;
LocationStackNode *nextNode;
};
stack-proj1.cpp
LocationStack::LocationStack(void){
top = NULL;
}
LocationStack::~LocationStack(){
delete top;
top = NULL;
}
void LocationStack::push(const Location &loc){
top = new LocationStackNode(loc, top);
}
void LocationStack::pop(void){
if(top->getNextNode()){
LocationStackNode *newNode;
newNode = top->getNextNode();
top = newNode;
}
else{
top = NULL;
}
}
const Location& LocationStack::getTop(void) const{
return top->getLocation();
}
bool LocationStack::isEmpty(void) const{
bool isEmpty = false;
if(!top){
isEmpty = true;
}
return isEmpty;
}
bool LocationStack::isOn(const Location &loc) const{
bool isOn = false;
int stackSize = 0;
if(!this->isEmpty()){
LocationStackNode *newNode = top;
LocationStackNode *newNode2 = top;
while(newNode2->getNextNode()){
newNode2 = newNode2->getNextNode();
stackSize++;
}
for(int n = 0; n <= stackSize; n++)/*while(newNode->getNextNode())*/{
if(newNode->getLocation() == loc){
isOn = true;
}
newNode = newNode->getNextNode();
}
}
return isOn;
}
ostream &operator<<(ostream &os, const LocationStack &s){
LocationStackNode *back = s.top;
LocationStackNode *next = s.top->getNextNode();
LocationStackNode *newNode = s.top;
newNode->setNextNode(NULL);
while(next){
newNode = next;
next = newNode->getNextNode();
newNode->setNextNode(back);
back = newNode;
}
while(newNode->getNextNode()){
os << newNode->getLocation() << endl;
newNode = newNode->getNextNode();
}
os << newNode->getLocation() << endl;
return os;
}
LocationStackNode::LocationStackNode(const Location &loc,
LocationStackNode *next){
location = loc;
nextNode = next;
}
LocationStackNode::~LocationStackNode(){
delete nextNode;
}
const Location& LocationStackNode::getLocation() const{
return location;
}
LocationStackNode* LocationStackNode::getNextNode() const{
return nextNode;
}
void LocationStackNode::setNextNode(LocationStackNode *next){
nextNode = next;
}
This is how Nodes are populated:
LocationStack stacks;
stacks.push(Location l); //Location is another class itself
Everything added to the stack uses the push() function of LocationStack.
Sorry there's so much code here. I've been trying to figure this out for a
while and I'm really not sure what the issue is. I just want to make sure
everything is here just in case there's another issue. If you're willing
to look through this for me, I will be so grateful. I just need to finish
this project so I can start on the next one. Thanks in advance for any
help!
I'm stuck on a program that is due for a class. I have to complete the
project with the correct output and without any memory leaks. Below is the
.h and .cpp for both LocationStack and LocationStackNode. I currently am
getting a memory leak on LocationStackNode and wondered if anyone could
help me with how I should write the destructor. Valgrind specifically
reports the memory leak when allocating new memory in
LocationStack::push(). I am also not allowed to modify the .h file at all.
stack-proj1.h:
class LocationStack {
public:
LocationStack(void);
~LocationStack();
void push(const Location &loc);
void pop(void);
const Location &getTop(void) const;
bool isEmpty(void) const;
bool isOn(const Location &loc) const;
friend ostream &operator<<(ostream &os, const LocationStack &s);
private:
const LocationStack &operator=(const LocationStack &)
{ assert(false); }
LocationStack(const LocationStack &) { assert(false); }
LocationStackNode *top;
};
class LocationStackNode {
public:
LocationStackNode(const Location &loc, LocationStackNode *next = NULL);
~LocationStackNode();
const Location &getLocation() const;
LocationStackNode *getNextNode() const;
void setNextNode(LocationStackNode *next);
private:
LocationStackNode() { assert(false); }
LocationStackNode(const LocationStackNode &) { assert(false); }
LocationStackNode &operator=(const LocationStackNode &)
{ assert(false); }
Location location;
LocationStackNode *nextNode;
};
stack-proj1.cpp
LocationStack::LocationStack(void){
top = NULL;
}
LocationStack::~LocationStack(){
delete top;
top = NULL;
}
void LocationStack::push(const Location &loc){
top = new LocationStackNode(loc, top);
}
void LocationStack::pop(void){
if(top->getNextNode()){
LocationStackNode *newNode;
newNode = top->getNextNode();
top = newNode;
}
else{
top = NULL;
}
}
const Location& LocationStack::getTop(void) const{
return top->getLocation();
}
bool LocationStack::isEmpty(void) const{
bool isEmpty = false;
if(!top){
isEmpty = true;
}
return isEmpty;
}
bool LocationStack::isOn(const Location &loc) const{
bool isOn = false;
int stackSize = 0;
if(!this->isEmpty()){
LocationStackNode *newNode = top;
LocationStackNode *newNode2 = top;
while(newNode2->getNextNode()){
newNode2 = newNode2->getNextNode();
stackSize++;
}
for(int n = 0; n <= stackSize; n++)/*while(newNode->getNextNode())*/{
if(newNode->getLocation() == loc){
isOn = true;
}
newNode = newNode->getNextNode();
}
}
return isOn;
}
ostream &operator<<(ostream &os, const LocationStack &s){
LocationStackNode *back = s.top;
LocationStackNode *next = s.top->getNextNode();
LocationStackNode *newNode = s.top;
newNode->setNextNode(NULL);
while(next){
newNode = next;
next = newNode->getNextNode();
newNode->setNextNode(back);
back = newNode;
}
while(newNode->getNextNode()){
os << newNode->getLocation() << endl;
newNode = newNode->getNextNode();
}
os << newNode->getLocation() << endl;
return os;
}
LocationStackNode::LocationStackNode(const Location &loc,
LocationStackNode *next){
location = loc;
nextNode = next;
}
LocationStackNode::~LocationStackNode(){
delete nextNode;
}
const Location& LocationStackNode::getLocation() const{
return location;
}
LocationStackNode* LocationStackNode::getNextNode() const{
return nextNode;
}
void LocationStackNode::setNextNode(LocationStackNode *next){
nextNode = next;
}
This is how Nodes are populated:
LocationStack stacks;
stacks.push(Location l); //Location is another class itself
Everything added to the stack uses the push() function of LocationStack.
Sorry there's so much code here. I've been trying to figure this out for a
while and I'm really not sure what the issue is. I just want to make sure
everything is here just in case there's another issue. If you're willing
to look through this for me, I will be so grateful. I just need to finish
this project so I can start on the next one. Thanks in advance for any
help!
cannot get my datatables drill down to work
cannot get my datatables drill down to work
$(document).ready(function () {
var anOpen = [];
var oTable = $('#table_id').dataTable();
$('#table_id tbody').on('click', 'tr', function (e) {
var nTr = this.parentNode;
var i = $.inArray(nTr, anOpen);
console.log("clicked|" + i);
if (i == -1) {
var nDetailsRow = oTable.fnOpen(nTr, fnFormatDetails(oTable, nTr),
'details');
$('div.innerDetails', nDetailsRow).slideDown();
anOpen.push(nTr);
console.log("open");
}
else {
oTable.fnClose( nTr );
anOpen.splice( i, 1 );
console.log("closed");
}
});
function fnFormatDetails(oTable, nTr) {
var oData = oTable.fnGetData(nTr);
var sOut =
'<div class="innerDetails">' +
'<table cellpadding="5" cellspacing="0" border="0"
style="padding-left:50px;">' +
'<tr><td>Rendering engine:</td><td>' + 'hi' + '</td></tr>' +
'<tr><td>Browser:</td><td>' + 'hi' + '</td></tr>' +
'<tr><td>Platform:</td><td>' + 'hi' + '</td></tr>' +
'<tr><td>Version:</td><td>' + 'hi' + '</td></tr>' +
'<tr><td>Grade:</td><td>' + 'hi' + '</td></tr>' +
'</table>' +
'</div>';
return sOut;
}
Just gave a section of it, When i click on the row it does trigger the if
(i==-1) and then when i click again it triggers the else and works back
and forth the problem is that i cannot get anything to display. The table
just sits and new opens another table below it like it should. No errors
in the console just the proper console logs.
$(document).ready(function () {
var anOpen = [];
var oTable = $('#table_id').dataTable();
$('#table_id tbody').on('click', 'tr', function (e) {
var nTr = this.parentNode;
var i = $.inArray(nTr, anOpen);
console.log("clicked|" + i);
if (i == -1) {
var nDetailsRow = oTable.fnOpen(nTr, fnFormatDetails(oTable, nTr),
'details');
$('div.innerDetails', nDetailsRow).slideDown();
anOpen.push(nTr);
console.log("open");
}
else {
oTable.fnClose( nTr );
anOpen.splice( i, 1 );
console.log("closed");
}
});
function fnFormatDetails(oTable, nTr) {
var oData = oTable.fnGetData(nTr);
var sOut =
'<div class="innerDetails">' +
'<table cellpadding="5" cellspacing="0" border="0"
style="padding-left:50px;">' +
'<tr><td>Rendering engine:</td><td>' + 'hi' + '</td></tr>' +
'<tr><td>Browser:</td><td>' + 'hi' + '</td></tr>' +
'<tr><td>Platform:</td><td>' + 'hi' + '</td></tr>' +
'<tr><td>Version:</td><td>' + 'hi' + '</td></tr>' +
'<tr><td>Grade:</td><td>' + 'hi' + '</td></tr>' +
'</table>' +
'</div>';
return sOut;
}
Just gave a section of it, When i click on the row it does trigger the if
(i==-1) and then when i click again it triggers the else and works back
and forth the problem is that i cannot get anything to display. The table
just sits and new opens another table below it like it should. No errors
in the console just the proper console logs.
String s = "a" "b" "c"; Can anyone tell for this statement how many object will be created
String s = "a" "b" "c"; Can anyone tell for this statement how many object
will be created
String s = "a" + "b" + "c";
I want to know how many object will be create for this statement.
will be created
String s = "a" + "b" + "c";
I want to know how many object will be create for this statement.
Behaviour of back button on ajax and non-ajax page with the same url
Behaviour of back button on ajax and non-ajax page with the same url
I have got two versions of content (ajax and non-ajax) at one url. One
version is with renderred layout for non-ajax requests and the second
ajax-version is just the content itself without the layout. The problem is
that browsers (chrome/firefox) seems not to differentiate between
ajax/non-ajax requests when fetching pages from cache If I click on back
button. There are situations where I load the non-ajax version then I do
some browsing and then when I return back (by clicking back button
repeatedly) I get the ajax ("unformatted") version because that is the
version stored currently in the cache. Is this a known issue? Do I need to
differentiate ajax vs non-ajax requests in urls e.g. by ?ajax=1?
I have got two versions of content (ajax and non-ajax) at one url. One
version is with renderred layout for non-ajax requests and the second
ajax-version is just the content itself without the layout. The problem is
that browsers (chrome/firefox) seems not to differentiate between
ajax/non-ajax requests when fetching pages from cache If I click on back
button. There are situations where I load the non-ajax version then I do
some browsing and then when I return back (by clicking back button
repeatedly) I get the ajax ("unformatted") version because that is the
version stored currently in the cache. Is this a known issue? Do I need to
differentiate ajax vs non-ajax requests in urls e.g. by ?ajax=1?
Writing a string array to file using Java - separate lines.
Writing a string array to file using Java - separate lines.
I'm writing a program that writes sets of observations in the form of a
String array (from User input) to file. I am able to write an observation
to a .txt file and then add a new observation without removing the
previous data, but all my data is on the same line. I need each set of
observations to be on a separate line. Additionally I will need to be able
to access the file later on and read from it.
My code currently looks like this: (observation is the string array)
for(int i = 0; i < observation.length; i++) {
try (BufferedWriter bw = new BufferedWriter(new
FileWriter("birdobservations.txt", true))) {
String s;
s = observation[i];
bw.write(s);
bw.flush();
}
catch(IOException ex) {
}
My output currently looks like this:
CrowMOsloMay2015JayMOsloJune2012CrowMOsloMay2015RobinFBergenMay2012
I would like it to look like this:
Crow M Oslo May2015
Jay M Oslo June2012 ...etc
How do I do this? I assume I need some kind of loop, but I've been stuck
on figuring this out for a while now.
I'm writing a program that writes sets of observations in the form of a
String array (from User input) to file. I am able to write an observation
to a .txt file and then add a new observation without removing the
previous data, but all my data is on the same line. I need each set of
observations to be on a separate line. Additionally I will need to be able
to access the file later on and read from it.
My code currently looks like this: (observation is the string array)
for(int i = 0; i < observation.length; i++) {
try (BufferedWriter bw = new BufferedWriter(new
FileWriter("birdobservations.txt", true))) {
String s;
s = observation[i];
bw.write(s);
bw.flush();
}
catch(IOException ex) {
}
My output currently looks like this:
CrowMOsloMay2015JayMOsloJune2012CrowMOsloMay2015RobinFBergenMay2012
I would like it to look like this:
Crow M Oslo May2015
Jay M Oslo June2012 ...etc
How do I do this? I assume I need some kind of loop, but I've been stuck
on figuring this out for a while now.
PHP Unable to fetch the data from my sql Query
PHP Unable to fetch the data from my sql Query
I am trying to fetch Data from my sql Query but I am getting the wrong
data So can anyone tell me how to do it correctly.
Here Is my code
$result = mysql_query("select
CONCAT_WS(',',
(case when Q1 is not null then 'Q1' else '' end),
(case when Q2 is not null then 'Q2' else '' end),
(case when Q3 is not null then 'Q3' else '' end),
(case when Q4 is not null then 'Q4' else '' end),
(case when Q5 is not null then 'Q5' else '' end),
(case when Q6 is not null then 'Q6' else '' end),
(case when Q7 is not null then 'Q7' else '' end),
(case when Q8 is not null then 'Q8' else '' end),
(case when Q9 is not null then 'Q9' else '' end)
) as NonNullColumns
from $day
where `user` = '$user'") or die(mysql_error());
//echo $result;
if (mysql_num_rows($result) > 1) {
// looping through all results
// products node
$response["Q"] = array();
while ($row = mysql_fetch_assoc($result)) {
// temp user array
$qnumber = array();
$qns= array();
$qnumber["Q".$i] = $row["$Q"];
$i = $i + 1;
// push single product into final response array
array_push($response["Q"], $qnumber);
I am getting the following Output from my SQl query
NonNullColumns
Q1,Q2,Q3,,,,,,
Q1,Q2,Q3,,,,,,
Q1,Q2,Q3,,,,,,
Q1,Q2,Q3,,,,,,
Q1,Q2,Q3,,,,,,
Q1,Q2,Q3,,,,,,
I need to fetch the values Q1, Q2,Q3 from my SQl query output but I am
able to fetch
{"Q":[{"Q":null},{"Q1":null},{"Q2":null},{"Q3":null},{"Q4":null},{"Q5":null}],"success":1}
So Can any one tell me how to obtain the followig output
{"Q":[{Q1},{Q2},{Q3}],"success":1}
I am trying to fetch Data from my sql Query but I am getting the wrong
data So can anyone tell me how to do it correctly.
Here Is my code
$result = mysql_query("select
CONCAT_WS(',',
(case when Q1 is not null then 'Q1' else '' end),
(case when Q2 is not null then 'Q2' else '' end),
(case when Q3 is not null then 'Q3' else '' end),
(case when Q4 is not null then 'Q4' else '' end),
(case when Q5 is not null then 'Q5' else '' end),
(case when Q6 is not null then 'Q6' else '' end),
(case when Q7 is not null then 'Q7' else '' end),
(case when Q8 is not null then 'Q8' else '' end),
(case when Q9 is not null then 'Q9' else '' end)
) as NonNullColumns
from $day
where `user` = '$user'") or die(mysql_error());
//echo $result;
if (mysql_num_rows($result) > 1) {
// looping through all results
// products node
$response["Q"] = array();
while ($row = mysql_fetch_assoc($result)) {
// temp user array
$qnumber = array();
$qns= array();
$qnumber["Q".$i] = $row["$Q"];
$i = $i + 1;
// push single product into final response array
array_push($response["Q"], $qnumber);
I am getting the following Output from my SQl query
NonNullColumns
Q1,Q2,Q3,,,,,,
Q1,Q2,Q3,,,,,,
Q1,Q2,Q3,,,,,,
Q1,Q2,Q3,,,,,,
Q1,Q2,Q3,,,,,,
Q1,Q2,Q3,,,,,,
I need to fetch the values Q1, Q2,Q3 from my SQl query output but I am
able to fetch
{"Q":[{"Q":null},{"Q1":null},{"Q2":null},{"Q3":null},{"Q4":null},{"Q5":null}],"success":1}
So Can any one tell me how to obtain the followig output
{"Q":[{Q1},{Q2},{Q3}],"success":1}
Button not appearing correctly on Android 2.3
Button not appearing correctly on Android 2.3
I have a Button set up like this:
<Button
android:id="@+id/sendBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:text="Send"
android:padding="-5dp"
android:paddingBottom="-10dp"
android:background="@color/red"/>
Here is how it looks like in Android 4.0 and above:
http://i.imgur.com/2P9WEWp.png?1
Here is how it looks like in Android 2.3: http://i.imgur.com/4oXSN2P.png?1
As you can see, the 2.3 button seems squished together and very small. How
can I fix this so new versions and 2.3 atleast have same resemblance?
I have a Button set up like this:
<Button
android:id="@+id/sendBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:text="Send"
android:padding="-5dp"
android:paddingBottom="-10dp"
android:background="@color/red"/>
Here is how it looks like in Android 4.0 and above:
http://i.imgur.com/2P9WEWp.png?1
Here is how it looks like in Android 2.3: http://i.imgur.com/4oXSN2P.png?1
As you can see, the 2.3 button seems squished together and very small. How
can I fix this so new versions and 2.3 atleast have same resemblance?
Tuesday, 17 September 2013
Putting cursor data into an array
Putting cursor data into an array
Being new in Android, I am having trouble dealing with the following:
public String[] getContacts(){
Cursor cursor = getReadableDatabase().rawQuery("SELECT name FROM
contacts", null);
String [] names = {""};
for(int i = 0; i < cursor.getCount(); i ++){
names[i] = cursor.getString(i);
}
cursor.close();
return names;
}
The following gives me the following error:
09-18 10:07:38.616: E/AndroidRuntime(28165): java.lang.RuntimeException:
Unable to start activity
ComponentInfo{com.example.sqllitetrial/com.example.sqllitetrial.InsideDB}:
android.database.CursorIndexOutOfBoundsException: Index -1 requested, with
a size of 5
I am trying to extract the data inside the cursor to an array. Can someone
help me with the implementation.
Being new in Android, I am having trouble dealing with the following:
public String[] getContacts(){
Cursor cursor = getReadableDatabase().rawQuery("SELECT name FROM
contacts", null);
String [] names = {""};
for(int i = 0; i < cursor.getCount(); i ++){
names[i] = cursor.getString(i);
}
cursor.close();
return names;
}
The following gives me the following error:
09-18 10:07:38.616: E/AndroidRuntime(28165): java.lang.RuntimeException:
Unable to start activity
ComponentInfo{com.example.sqllitetrial/com.example.sqllitetrial.InsideDB}:
android.database.CursorIndexOutOfBoundsException: Index -1 requested, with
a size of 5
I am trying to extract the data inside the cursor to an array. Can someone
help me with the implementation.
Named events -- catch-all or specific?
Named events -- catch-all or specific?
I'm developing client- and server-apps (node.js, socket.io for
communication). Messages sent between the client and server have many
different types, and I'd originally thought to include the type in the
transmitted object:
// Client
var data = {
"type" : 5,
"message" : "Hello, world!"
};
socket.emit("generic_event", data);
On the server side, this would be handled as such:
// Server
socket.on("generic_event", function(e){
console.log("Got a generic_event!", e.type);
});
However, there is also the possibility of being more specific with event
types, e.g.:
// Client
socket.emit(data.type, data);
// Server
socket.on(1, function(){
console.log("We got '1'!");
});
// Elsewhere on in the server...
socket.on(5, function(){
console.log("We got '5'!");
});
I'm curious to know what the benefits are of following scheme A (single
generic / catch-all event) vs. scheme B (multiple/many specific named
events). Performance? Personal coding style? Something else?
I'm developing client- and server-apps (node.js, socket.io for
communication). Messages sent between the client and server have many
different types, and I'd originally thought to include the type in the
transmitted object:
// Client
var data = {
"type" : 5,
"message" : "Hello, world!"
};
socket.emit("generic_event", data);
On the server side, this would be handled as such:
// Server
socket.on("generic_event", function(e){
console.log("Got a generic_event!", e.type);
});
However, there is also the possibility of being more specific with event
types, e.g.:
// Client
socket.emit(data.type, data);
// Server
socket.on(1, function(){
console.log("We got '1'!");
});
// Elsewhere on in the server...
socket.on(5, function(){
console.log("We got '5'!");
});
I'm curious to know what the benefits are of following scheme A (single
generic / catch-all event) vs. scheme B (multiple/many specific named
events). Performance? Personal coding style? Something else?
How to find the highest number of times a value is in records?
How to find the highest number of times a value is in records?
For example, in a table I have created called 'likes', there are three
fields: id (irrelevant), user id (the id of the user), and post id (the id
of the post). Say I have numerous records and I want to find out which
post id is in the database the most number of times. To be clear, I am not
asking which record has the biggest number in the post id field. Rather,
I'm looking for which post id is listed the most times. For example, let's
say one post id (222) is in the database 7 times while every other post id
has been used 1 time each. I need to find the post id of 222 in this case.
If possible how could I find the top 5 post id's with the highest amount
of uses within the records?
For example, in a table I have created called 'likes', there are three
fields: id (irrelevant), user id (the id of the user), and post id (the id
of the post). Say I have numerous records and I want to find out which
post id is in the database the most number of times. To be clear, I am not
asking which record has the biggest number in the post id field. Rather,
I'm looking for which post id is listed the most times. For example, let's
say one post id (222) is in the database 7 times while every other post id
has been used 1 time each. I need to find the post id of 222 in this case.
If possible how could I find the top 5 post id's with the highest amount
of uses within the records?
Spring controller not created as singleton
Spring controller not created as singleton
I have a Spring controller that I think is getting instantiated more than
once based on the object ids I see when I debug through the code.
Controller:
@Controller
@RequestMapping("/services/user")
public class UserController{
private UserService userService;
public void setUserService(UserService userService) {
this.userService = userService;
}
public UserService getUserService() {
return userService;
}
@RequestMapping(method = RequestMethod.POST, value = "/createUser")
public @ResponseBody String createUser(@RequestBody User user) throws
UserNotCreatedException {
try {
userService.createUser(user);
return user.getEmail();
} catch (Exception e) {
e.printStackTrace();
throw new UserNotCreatedException("User not created");
}
}
Spring configuration file:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<!-- Scans the classpath of this application for @Components to deploy as
beans -->
<context:component-scan base-package="com.xyz.controller" />
<context:annotation-config />
<bean id="userController" class="com.xyz.UserController">
<property name="userService" ref="userService" />
</bean>
<bean id="userService" class="com.xyz.UserServiceImpl">
<property name="userDao" ref="userDaoMysql" />
</bean>
<bean id="userDaoMysql" class="com.xyz.UserDaoImpl" >
<property name="dataSource" ref="dataSource"></property>
<property name="template" ref="jdbcTemplate"></property>
</bean>
</beans>
I noticed the problem when I realized that userService is null when I make
a request that goes through UserController. However; when I put break
points, I see that userService does get set in another instance of
UserController.
I have a Spring controller that I think is getting instantiated more than
once based on the object ids I see when I debug through the code.
Controller:
@Controller
@RequestMapping("/services/user")
public class UserController{
private UserService userService;
public void setUserService(UserService userService) {
this.userService = userService;
}
public UserService getUserService() {
return userService;
}
@RequestMapping(method = RequestMethod.POST, value = "/createUser")
public @ResponseBody String createUser(@RequestBody User user) throws
UserNotCreatedException {
try {
userService.createUser(user);
return user.getEmail();
} catch (Exception e) {
e.printStackTrace();
throw new UserNotCreatedException("User not created");
}
}
Spring configuration file:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<!-- Scans the classpath of this application for @Components to deploy as
beans -->
<context:component-scan base-package="com.xyz.controller" />
<context:annotation-config />
<bean id="userController" class="com.xyz.UserController">
<property name="userService" ref="userService" />
</bean>
<bean id="userService" class="com.xyz.UserServiceImpl">
<property name="userDao" ref="userDaoMysql" />
</bean>
<bean id="userDaoMysql" class="com.xyz.UserDaoImpl" >
<property name="dataSource" ref="dataSource"></property>
<property name="template" ref="jdbcTemplate"></property>
</bean>
</beans>
I noticed the problem when I realized that userService is null when I make
a request that goes through UserController. However; when I put break
points, I see that userService does get set in another instance of
UserController.
Using SimpleForm with Bootstrap 3?
Using SimpleForm with Bootstrap 3?
I have a Rails application that uses the SimpleForm gem. The current
SimpleForm 3.0.0.rc version provides attractive form styling using
Bootstrap 2.3. But when I use Bootstrap 3.0, I lose the nice form styling.
How do I use SimpleForm with Bootstrap 3?
I have a Rails application that uses the SimpleForm gem. The current
SimpleForm 3.0.0.rc version provides attractive form styling using
Bootstrap 2.3. But when I use Bootstrap 3.0, I lose the nice form styling.
How do I use SimpleForm with Bootstrap 3?
jQuery load a page and add only body part in my current page
jQuery load a page and add only body part in my current page
I'm trying to use both $.ajax or .load() functions to load a page by ajax
and than add its content replacing my current $('body').html(). The
problem is than when I try to do it jquery will add everything (included
the content of <head></head> in my body).
$.ajax({
type: 'GET',
url: '/somepage.html',
success: function(data) {
$('body').html(data);
}
});
or
$('body').load('/somepage.html');
The result will be something like
<body>
<-- Here starts the content of the head -->
<title>....</title>
<script src="..."></script>
<link src="..."></link>
<meta></meta>
<-- Here ends the content of the head -->
<-- Here starts the real body content -->
<div>........</div>
<-- Here ends the body content -->
</body>
How can I avoid this? Am I doing something wrong?
I'm trying to use both $.ajax or .load() functions to load a page by ajax
and than add its content replacing my current $('body').html(). The
problem is than when I try to do it jquery will add everything (included
the content of <head></head> in my body).
$.ajax({
type: 'GET',
url: '/somepage.html',
success: function(data) {
$('body').html(data);
}
});
or
$('body').load('/somepage.html');
The result will be something like
<body>
<-- Here starts the content of the head -->
<title>....</title>
<script src="..."></script>
<link src="..."></link>
<meta></meta>
<-- Here ends the content of the head -->
<-- Here starts the real body content -->
<div>........</div>
<-- Here ends the body content -->
</body>
How can I avoid this? Am I doing something wrong?
Sunday, 15 September 2013
MySQL interests table structure (how-to?)
MySQL interests table structure (how-to?)
I've been figuring my way around MySQL for a while now, reading tutorials
and such but I've got a good idea of how things work, so this time around
I'd like to see if I can do it myself but I'm a little confused on one
part.
I'm trying to create a interests table for users to interact between their
interests. I'm confused on how I'd go about storing the interests
information for the users.
user_interests table:
interest_id | interests_names |
How could I enter specific interests for them to use without them typing
their own into the database such as, sports, life, hobbies, food, music,
games, etc.
should I create another column in the user_interests for each user id to
be stored in there?
I'm lost on the table structure.
I've been figuring my way around MySQL for a while now, reading tutorials
and such but I've got a good idea of how things work, so this time around
I'd like to see if I can do it myself but I'm a little confused on one
part.
I'm trying to create a interests table for users to interact between their
interests. I'm confused on how I'd go about storing the interests
information for the users.
user_interests table:
interest_id | interests_names |
How could I enter specific interests for them to use without them typing
their own into the database such as, sports, life, hobbies, food, music,
games, etc.
should I create another column in the user_interests for each user id to
be stored in there?
I'm lost on the table structure.
Simple regex failing test to determine a 3 digit number
Simple regex failing test to determine a 3 digit number
I have had a difficult time wrapping my head around regular expressions.
In the following code, I used a Regex to determine if the data passed was
a 1 to 3 digit number. The expression worked if the data started with a
number (ex. "200"), but also passed if the data had a letter not in the
first digit (ex. "3A5"). I managed to handle the error with the
INT32.TryParse() method, but it seems there should be an easier way.
if (LSK == MainWindow.LSK6R)
{
int ci;
int length = SP_Command.Length;
if (length > 3) return MainWindow.ENTRY_OUT_OF_RANGE; //Cannot
be greater than 999
String pattern = @"[0-9]{1,3}"; //RegEx pattern for
1 to 3 digit number
if (Regex.IsMatch(SP_Command, pattern)) //Does not check for
^A-Z. See below.
{
bool test = Int32.TryParse(SP_Command, out ci); //Trying
to parse A-Z. Only if
if (test) //it no
letter will it succeed
{
FlightPlan.CostIndex = ci; //Update
the flightplan CI
CI.Text = ci.ToString(); //Update
the Init page
}
else return MainWindow.FORMAT_ERROR; //It
contained a letter
}
else return MainWindow.FORMAT_ERROR; //It
didn't fit the RegEx
}
I have had a difficult time wrapping my head around regular expressions.
In the following code, I used a Regex to determine if the data passed was
a 1 to 3 digit number. The expression worked if the data started with a
number (ex. "200"), but also passed if the data had a letter not in the
first digit (ex. "3A5"). I managed to handle the error with the
INT32.TryParse() method, but it seems there should be an easier way.
if (LSK == MainWindow.LSK6R)
{
int ci;
int length = SP_Command.Length;
if (length > 3) return MainWindow.ENTRY_OUT_OF_RANGE; //Cannot
be greater than 999
String pattern = @"[0-9]{1,3}"; //RegEx pattern for
1 to 3 digit number
if (Regex.IsMatch(SP_Command, pattern)) //Does not check for
^A-Z. See below.
{
bool test = Int32.TryParse(SP_Command, out ci); //Trying
to parse A-Z. Only if
if (test) //it no
letter will it succeed
{
FlightPlan.CostIndex = ci; //Update
the flightplan CI
CI.Text = ci.ToString(); //Update
the Init page
}
else return MainWindow.FORMAT_ERROR; //It
contained a letter
}
else return MainWindow.FORMAT_ERROR; //It
didn't fit the RegEx
}
can't add a integer column to an existing table
can't add a integer column to an existing table
I'm trying to add a column to an existing table, of type integer with a
constraint of 11 number
I'm running this command:
ALTER TABLE pages ADD COLUMN order INTEGER(11);
but I'm getting an ERROR 1064 (42000)
I'm trying to add a column to an existing table, of type integer with a
constraint of 11 number
I'm running this command:
ALTER TABLE pages ADD COLUMN order INTEGER(11);
but I'm getting an ERROR 1064 (42000)
Object screenoff in "onmouseover"
Object screenoff in "onmouseover"
I really don't know anything about Javascript, but my website has these
lines below, that shows a window in onmouseover. I wonder how to make the
window appear on top of the word when the window is screenoff.
Thanks.
function showLayer(obj){
var div = document.getElementById(obj).style;
div.display = "block";
}
I really don't know anything about Javascript, but my website has these
lines below, that shows a window in onmouseover. I wonder how to make the
window appear on top of the word when the window is screenoff.
Thanks.
function showLayer(obj){
var div = document.getElementById(obj).style;
div.display = "block";
}
Jquery Mobile - Display Icon With Bubble Count
Jquery Mobile - Display Icon With Bubble Count
In this JSFiddle, the goal is to display a bubble count next to each icon.
When attempting to display 2 successive icons with bubbles, the icons are
floating left and grouping together.
What CSS is required to display bubble counts immediately after each icon?
HTML
<div style="display: inline-block; white-space: nowrap">
<a href="#" class="ui-nav-icon" data-role="button" data-icon="alert"
data-iconpos="notext">Alerts</a>
<span class="nav-icon ui-li-count ui-btn-up-c ui-btn-corner-all"
style="font-size:10px;position:static">42</span>
<a href="#" class="ui-nav-icon" data-role="button" data-icon="info"
data-iconpos="notext">Information</a>
<span class="nav-icon ui-li-count ui-btn-up-c ui-btn-corner-all">173</span>
</div>
CSS
a.ui-nav-icon {
float: left
}
span.nav-icon {
font-size:11px
}
In this JSFiddle, the goal is to display a bubble count next to each icon.
When attempting to display 2 successive icons with bubbles, the icons are
floating left and grouping together.
What CSS is required to display bubble counts immediately after each icon?
HTML
<div style="display: inline-block; white-space: nowrap">
<a href="#" class="ui-nav-icon" data-role="button" data-icon="alert"
data-iconpos="notext">Alerts</a>
<span class="nav-icon ui-li-count ui-btn-up-c ui-btn-corner-all"
style="font-size:10px;position:static">42</span>
<a href="#" class="ui-nav-icon" data-role="button" data-icon="info"
data-iconpos="notext">Information</a>
<span class="nav-icon ui-li-count ui-btn-up-c ui-btn-corner-all">173</span>
</div>
CSS
a.ui-nav-icon {
float: left
}
span.nav-icon {
font-size:11px
}
Unsupported format character ";". Can't figure this out
Unsupported format character ";". Can't figure this out
I've been stumped on what is probably a very stupid mistake for a while
now. Searching google has not helped me.
I am learning python and trying to create a simple signup page. When I try
to use string substitution I seems to be failing with this error:
'Unsupported format character ";"'
This is the python code.
def write_form(self, username=""):
self.response.out.write(signupform %{'usr': username})
Here is the html:
<form method="post">
<label>Username:</label>
<input type="text" name="username" value="">%(usr)s<br>
I've been stumped on what is probably a very stupid mistake for a while
now. Searching google has not helped me.
I am learning python and trying to create a simple signup page. When I try
to use string substitution I seems to be failing with this error:
'Unsupported format character ";"'
This is the python code.
def write_form(self, username=""):
self.response.out.write(signupform %{'usr': username})
Here is the html:
<form method="post">
<label>Username:</label>
<input type="text" name="username" value="">%(usr)s<br>
C++ mutex for multiple threads
C++ mutex for multiple threads
I am trying to share data between two threads via a queue. One thread
pushes into and the other pops from the queue. I got to know that it is
safe to have synchronization between the threads and hence decided to use
mutex. Every forum i see has a #include "mutex" statement in the code, but
i don't seem to find the Mutex file in my system. Please let me know how
to sort out this issue. Is it available for downloading from any website?
If yes, please post the url OR have i gone wrong anywhere?
I am using a Windows machine and Visual Studio 2005 compiler.
I am trying to share data between two threads via a queue. One thread
pushes into and the other pops from the queue. I got to know that it is
safe to have synchronization between the threads and hence decided to use
mutex. Every forum i see has a #include "mutex" statement in the code, but
i don't seem to find the Mutex file in my system. Please let me know how
to sort out this issue. Is it available for downloading from any website?
If yes, please post the url OR have i gone wrong anywhere?
I am using a Windows machine and Visual Studio 2005 compiler.
Added DataColumns not being saving in Access Database
Added DataColumns not being saving in Access Database
I would like to write code to add a DataColumn to a DataTable, but when I
save the DataTable, it does not include the new DataColumn.
It saves any new DataRows I add, but not the DataColumns.
Can somebody please tell me what I am doing wrong?
public partial class Form1 : Form
{
MyDatabase DB;
DataTable Products;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
DB = new MyDatabase();
DB.Open(@"C:\Users\Grant\Documents\Database.accdb");
Products = DB.GetTable("Products");
AddColumn();
AddRow();
DB.Save(Products);
}
private void AddColumn()
{
DataColumn Column = new DataColumn();
Column.DataType = Type.GetType("System.String");
Column.ColumnName = "TestColumn";
Products.Columns.Add(Column);
}
private void AddRow()
{
DataRow Row;
Row = Products.Rows.Add(1, "B", "C");
}
}
class MyDatabase
{
// The following program has to be installed on the computer
//
http://www.microsoft.com/downloads/en/details.aspx?familyid=7554F536-8C28-4598-9B72-EF94E038C891&displaylang=en
private String provider = "Microsoft.ACE.OLEDB.12.0";
private String source;
private OleDbConnection connection;
private String connectionString;
private DataSet dataSet = new DataSet();
private OleDbDataAdapter adapter;
private OleDbCommandBuilder commandBuilder;
public String Provider
{
get { return provider; }
set { provider = value; }
}
public String Source
{
get { return Source; }
set { source = value; }
}
public void Open(String Filename)
{
connectionString = @"Provider=" + provider + @";Data Source=" +
Filename;
connection = new OleDbConnection(connectionString);
connection.Open();
adapter = new OleDbDataAdapter();
}
public void BuildStrings()
{
commandBuilder = new OleDbCommandBuilder(adapter);
adapter.UpdateCommand = commandBuilder.GetUpdateCommand();
adapter.InsertCommand = commandBuilder.GetInsertCommand();
adapter.DeleteCommand = commandBuilder.GetDeleteCommand();
}
public DataTable GetTable(String TableName)
{
adapter.SelectCommand = new OleDbCommand("SELECT * From " +
TableName, connection);
BuildStrings();
adapter.Fill(dataSet, TableName);
return dataSet.Tables[TableName];
}
public void Save(DataTable Table)
{
adapter.Update(Table);
adapter.Update(dataSet, "Products");
}
}
I would like to write code to add a DataColumn to a DataTable, but when I
save the DataTable, it does not include the new DataColumn.
It saves any new DataRows I add, but not the DataColumns.
Can somebody please tell me what I am doing wrong?
public partial class Form1 : Form
{
MyDatabase DB;
DataTable Products;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
DB = new MyDatabase();
DB.Open(@"C:\Users\Grant\Documents\Database.accdb");
Products = DB.GetTable("Products");
AddColumn();
AddRow();
DB.Save(Products);
}
private void AddColumn()
{
DataColumn Column = new DataColumn();
Column.DataType = Type.GetType("System.String");
Column.ColumnName = "TestColumn";
Products.Columns.Add(Column);
}
private void AddRow()
{
DataRow Row;
Row = Products.Rows.Add(1, "B", "C");
}
}
class MyDatabase
{
// The following program has to be installed on the computer
//
http://www.microsoft.com/downloads/en/details.aspx?familyid=7554F536-8C28-4598-9B72-EF94E038C891&displaylang=en
private String provider = "Microsoft.ACE.OLEDB.12.0";
private String source;
private OleDbConnection connection;
private String connectionString;
private DataSet dataSet = new DataSet();
private OleDbDataAdapter adapter;
private OleDbCommandBuilder commandBuilder;
public String Provider
{
get { return provider; }
set { provider = value; }
}
public String Source
{
get { return Source; }
set { source = value; }
}
public void Open(String Filename)
{
connectionString = @"Provider=" + provider + @";Data Source=" +
Filename;
connection = new OleDbConnection(connectionString);
connection.Open();
adapter = new OleDbDataAdapter();
}
public void BuildStrings()
{
commandBuilder = new OleDbCommandBuilder(adapter);
adapter.UpdateCommand = commandBuilder.GetUpdateCommand();
adapter.InsertCommand = commandBuilder.GetInsertCommand();
adapter.DeleteCommand = commandBuilder.GetDeleteCommand();
}
public DataTable GetTable(String TableName)
{
adapter.SelectCommand = new OleDbCommand("SELECT * From " +
TableName, connection);
BuildStrings();
adapter.Fill(dataSet, TableName);
return dataSet.Tables[TableName];
}
public void Save(DataTable Table)
{
adapter.Update(Table);
adapter.Update(dataSet, "Products");
}
}
Saturday, 14 September 2013
Apache Avro vs Messagepack performance 2013
Apache Avro vs Messagepack performance 2013
I have been reading a lot about Avro and Messagepack these days. Not sure
which one to use when?
I have also read post on the stackoverflow but nobody has explain when we
should use Apache Avro and when we should use Messagepack.
Currently, what we are doing is - we are serializing the JSON document
using Jackson and then writing that serialize JSON document into Cassandra
for each row key/user id. Then we have a REST service that reads the whole
JSON document using the row key and then deserialize it and use it
further.
Now we were thinking to have more compact representation of data as
compared to JSON and then write that serialize data into Cassandra. So not
sure what benefit, I will get, if I am going with Apache Avro or
Messagepack?
Our JSON document will look like this for a particular column family-
{"lv":[{"v":{"cateId":222625,"steqId":77111}},{"v":{"cateId":29322,"steqId":7711}},{"v":{"cateId":222619,"steqId":444477}}],"lmd":1379213614465}
But the properties and its value inside the above JSON document will get
changed depending on the column names as we have the metadata for that.
Can anyone provide some sort of suggestion which one I should go for? And
what benefit I will get if I choose Apache Avro or Messagepack? And which
one is better in terms of performance as well?
Thanks.
I have been reading a lot about Avro and Messagepack these days. Not sure
which one to use when?
I have also read post on the stackoverflow but nobody has explain when we
should use Apache Avro and when we should use Messagepack.
Currently, what we are doing is - we are serializing the JSON document
using Jackson and then writing that serialize JSON document into Cassandra
for each row key/user id. Then we have a REST service that reads the whole
JSON document using the row key and then deserialize it and use it
further.
Now we were thinking to have more compact representation of data as
compared to JSON and then write that serialize data into Cassandra. So not
sure what benefit, I will get, if I am going with Apache Avro or
Messagepack?
Our JSON document will look like this for a particular column family-
{"lv":[{"v":{"cateId":222625,"steqId":77111}},{"v":{"cateId":29322,"steqId":7711}},{"v":{"cateId":222619,"steqId":444477}}],"lmd":1379213614465}
But the properties and its value inside the above JSON document will get
changed depending on the column names as we have the metadata for that.
Can anyone provide some sort of suggestion which one I should go for? And
what benefit I will get if I choose Apache Avro or Messagepack? And which
one is better in terms of performance as well?
Thanks.
addClass is not adding class to tr
addClass is not adding class to tr
I am using following ajax request...
$.ajax({
type: "POST",
async : false,
url: req_url,
data : {
id : account_id
},
success : function(data) {
if(data == 'banned'){
$(this).closest('tr').addClass('danger');
alert('updated');
}
else{
alert(data);
}
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
alert(XMLHttpRequest + " : " + textStatus + " : " + errorThrown);
}
});
$('.act').live('click', function(){
But its not adding danger class to tr on success, please help me to
resolve, thanks.
I am using following ajax request...
$.ajax({
type: "POST",
async : false,
url: req_url,
data : {
id : account_id
},
success : function(data) {
if(data == 'banned'){
$(this).closest('tr').addClass('danger');
alert('updated');
}
else{
alert(data);
}
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
alert(XMLHttpRequest + " : " + textStatus + " : " + errorThrown);
}
});
$('.act').live('click', function(){
But its not adding danger class to tr on success, please help me to
resolve, thanks.
Wepay buttons not showing up in Chrome
Wepay buttons not showing up in Chrome
I cannot figure out why my wepay button (as a widget) works in IE, but it
won't work in chrome as my main browser. In IE it shows the whole widget,
but in Chrome it only displays the button, nothing else.
Some notes. -It doesn't work in regular or incognito. -I have kaspersky
safe money installed, but tried disabling the extension and it made no
difference. -I have no extensions that function in incognito mode.
-Pictures attached.
This is in chrome-Not working http://i.imgur.com/SBU0y4L.png
Exact same piece working in internet explorer http://i.imgur.com/yATPRlW.png
I cannot figure out why my wepay button (as a widget) works in IE, but it
won't work in chrome as my main browser. In IE it shows the whole widget,
but in Chrome it only displays the button, nothing else.
Some notes. -It doesn't work in regular or incognito. -I have kaspersky
safe money installed, but tried disabling the extension and it made no
difference. -I have no extensions that function in incognito mode.
-Pictures attached.
This is in chrome-Not working http://i.imgur.com/SBU0y4L.png
Exact same piece working in internet explorer http://i.imgur.com/yATPRlW.png
Comment some lines in powershell script file Programmatically
Comment some lines in powershell script file Programmatically
How to comment multiple line in a powershell script Programmatically. I
need to execute a powershell script which will copy some .ps files from
share location & comment out some lines in those copied powershell script.
How to comment multiple line in a powershell script Programmatically. I
need to execute a powershell script which will copy some .ps files from
share location & comment out some lines in those copied powershell script.
Redirecting domain.com/folder to www.domain.com/folder in Apache?
Redirecting domain.com/folder to www.domain.com/folder in Apache?
OK using this solution I'm able to redirect domain.com to www.domain.com.
But i want to redirect domain.com/folder to www.domain.com/folder too.
When I try domain.com/folder I'm getting redirected like this
www.domain.comfolder. How to fix this?
My redirect configuration in .htaccsess
RewriteEngine on
RewriteCond %{HTTP_HOST} ^domain\.com
RewriteRule ^(.*)$ http://www.domain.com/$1 [R=permanent,L]
OK using this solution I'm able to redirect domain.com to www.domain.com.
But i want to redirect domain.com/folder to www.domain.com/folder too.
When I try domain.com/folder I'm getting redirected like this
www.domain.comfolder. How to fix this?
My redirect configuration in .htaccsess
RewriteEngine on
RewriteCond %{HTTP_HOST} ^domain\.com
RewriteRule ^(.*)$ http://www.domain.com/$1 [R=permanent,L]
Radio button, check box and group box are not properly painted with WM_CTLCOLORSTATIC handler
Radio button, check box and group box are not properly painted with
WM_CTLCOLORSTATIC handler
INTRODUCTION AND RELEVANT INFORMATION:
I have 2 dialog boxes created via Resource editor.
Since I use Microsoft Visual Studio Express edition, I had to download
free resource editor to create them.
Resource editor is ResEdit, x32 version, and I have downloaded it from here:
http://www.resedit.net/
In my program, I have visual styles enabled like this:
#include <commctrl.h>
#pragma comment( lib, "comctl32.lib")
#pragma comment( linker, "/manifestdependency:\"type='win32' \
name='Microsoft.Windows.Common-Controls'
version='6.0.0.0' \
processorArchitecture='*'
publicKeyToken='6595b64144ccf1df' \
language='*'\"")
As far as I know, check box, radio button, and group box get
WM_CTLCOLORSTATIC message for painting their text.
This is what I have coded for the first dialog box:
case WM_CTLCOLORSTATIC:
{
SetBkMode( (HDC)wParam, TRANSPARENT );
SetTextColor( (HDC)wParam, RGB( 0, 0, 0 ) );
return (INT_PTR)( (HBRUSH)GetStockObject(NULL_BRUSH) );
}
I just want those controls to have transparent background and black color
of their text.
THE PROBLEM:
Bellow is the image of what I get in dialog boxes:
On Windows XP, here is the result for first dialog:
Group box has blue text, and brown border, while check box has everything
black.
On Windows 7, after starting yhe same program, I get this:
Here, group box and check box have proper text color, yet background of
the check box and the border of the group box are wrong.
In my dialog box, I have static controls and they are painted properly.
WHAT HAVE I TRIED SO FAR:
I have browsed through SO archive, but haven't found anything I could use
to modify my WM_CTLCOLORSTATIC handler.
I have found an example which removes visual styles from those controls,
so it can achieve the desired result, but I need to keep the visual style
and make the background of the text transparent, thus this solution can
not satisfy me.
At this moment I still keep searching online, but at the moment I ahve no
luck, I guess I'm a poor Googler.
THE QUESTION:
How can I modify my WM_CTLCOLORSTATIC handler to fix my problem ?
If the above is not possible, can I get the desired effect with
NM_CUSTOMDRAW ?
WM_CTLCOLORSTATIC handler
INTRODUCTION AND RELEVANT INFORMATION:
I have 2 dialog boxes created via Resource editor.
Since I use Microsoft Visual Studio Express edition, I had to download
free resource editor to create them.
Resource editor is ResEdit, x32 version, and I have downloaded it from here:
http://www.resedit.net/
In my program, I have visual styles enabled like this:
#include <commctrl.h>
#pragma comment( lib, "comctl32.lib")
#pragma comment( linker, "/manifestdependency:\"type='win32' \
name='Microsoft.Windows.Common-Controls'
version='6.0.0.0' \
processorArchitecture='*'
publicKeyToken='6595b64144ccf1df' \
language='*'\"")
As far as I know, check box, radio button, and group box get
WM_CTLCOLORSTATIC message for painting their text.
This is what I have coded for the first dialog box:
case WM_CTLCOLORSTATIC:
{
SetBkMode( (HDC)wParam, TRANSPARENT );
SetTextColor( (HDC)wParam, RGB( 0, 0, 0 ) );
return (INT_PTR)( (HBRUSH)GetStockObject(NULL_BRUSH) );
}
I just want those controls to have transparent background and black color
of their text.
THE PROBLEM:
Bellow is the image of what I get in dialog boxes:
On Windows XP, here is the result for first dialog:
Group box has blue text, and brown border, while check box has everything
black.
On Windows 7, after starting yhe same program, I get this:
Here, group box and check box have proper text color, yet background of
the check box and the border of the group box are wrong.
In my dialog box, I have static controls and they are painted properly.
WHAT HAVE I TRIED SO FAR:
I have browsed through SO archive, but haven't found anything I could use
to modify my WM_CTLCOLORSTATIC handler.
I have found an example which removes visual styles from those controls,
so it can achieve the desired result, but I need to keep the visual style
and make the background of the text transparent, thus this solution can
not satisfy me.
At this moment I still keep searching online, but at the moment I ahve no
luck, I guess I'm a poor Googler.
THE QUESTION:
How can I modify my WM_CTLCOLORSTATIC handler to fix my problem ?
If the above is not possible, can I get the desired effect with
NM_CUSTOMDRAW ?
Xcode Compile Error "expected method to read array element not found on object of type NSArray"
Xcode Compile Error "expected method to read array element not found on
object of type NSArray"
I am new to xcode, and I try to play with UITableView to show content in
array.
I try to put some array inside Feed, and try to show them in table.
but the error is hinted at this instances
(UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath
on cell.textLabel.text = self.imageTitleArray[indexPath.row];
it says expected method to read array element not found on object of type
NSArray
this is my H files
#import <UIKit/UIKit.h>
@interface FeedTableViewController : UITableViewController
@property (strong, nonatomic) NSArray *imageTitleArray;
@end
and this is my M files
#import "FeedTableViewController.h"
@interface FeedTableViewController ()
@end
@implementation FeedTableViewController
- (id) initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle
*)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
self.title = @"Feed";
self.imageTitleArray = @[@"Image 1",@"Image 2",@"Image 3", @"Image
4",@"Image 5"];
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
}
- (void)viewDidUnload
{
[super viewDidUnload];
}
-
(BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView
numberOfRowsInSection:(NSInteger)section
{
return self.imageTitleArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
// static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView
dequeueReusableCellWithIdentifier:@"Cell"];
if(cell==nil){
cell= [[UITableViewCell alloc]
initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:@"Cell"];
}
cell.textLabel.text = self.imageTitleArray[indexPath.row];
return cell;
}
- (void)tableView:(UITableView *)tableView
didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
}
@end
object of type NSArray"
I am new to xcode, and I try to play with UITableView to show content in
array.
I try to put some array inside Feed, and try to show them in table.
but the error is hinted at this instances
(UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath
on cell.textLabel.text = self.imageTitleArray[indexPath.row];
it says expected method to read array element not found on object of type
NSArray
this is my H files
#import <UIKit/UIKit.h>
@interface FeedTableViewController : UITableViewController
@property (strong, nonatomic) NSArray *imageTitleArray;
@end
and this is my M files
#import "FeedTableViewController.h"
@interface FeedTableViewController ()
@end
@implementation FeedTableViewController
- (id) initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle
*)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
self.title = @"Feed";
self.imageTitleArray = @[@"Image 1",@"Image 2",@"Image 3", @"Image
4",@"Image 5"];
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
}
- (void)viewDidUnload
{
[super viewDidUnload];
}
-
(BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView
numberOfRowsInSection:(NSInteger)section
{
return self.imageTitleArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
// static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView
dequeueReusableCellWithIdentifier:@"Cell"];
if(cell==nil){
cell= [[UITableViewCell alloc]
initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:@"Cell"];
}
cell.textLabel.text = self.imageTitleArray[indexPath.row];
return cell;
}
- (void)tableView:(UITableView *)tableView
didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
}
@end
Friday, 13 September 2013
Insert values into table at the end of the query
Insert values into table at the end of the query
In my query im using for loop. Each and every time when for loop is
executed, at the end some values has to be inserted into table. This is
time consuming because for loop has many records. Due to this each and
every time when for loop is executed, insertion is happening. Is there any
other way to perform insertion at the end after the for loop is executed.
In my query im using for loop. Each and every time when for loop is
executed, at the end some values has to be inserted into table. This is
time consuming because for loop has many records. Due to this each and
every time when for loop is executed, insertion is happening. Is there any
other way to perform insertion at the end after the for loop is executed.
My Null pointer exception
My Null pointer exception
I am working on a simple program for my intro to Object Oriented
programing class, where I have 3 classes: Account ATM and the main/Runner
class I am experiencing a null pointer exception error in the constructor
of the ATM class when I am trying to initialize the array of Accounts
using a loop. I am new to JAVA so I don't really know what happens. here
is the code.
import java.util.Date;
public class Account {
private int account_id;
private double account_balance;
private static double annual_interest_rate;
private Date date_Created;
Account(){
account_id = 0;
account_balance=0;
annual_interest_rate = 0;
date_Created = new Date();
}
Account(int account_id_in, double account_balance_in, double
annual_interest_rate_in){
account_id = account_id_in;
account_balance = account_balance_in;
annual_interest_rate = annual_interest_rate_in;
date_Created = new Date();
}
int get_account_id(){
return account_id;
}
double get_account_balance(){
return account_balance;
}
double get_annual_interest_rate(){
return annual_interest_rate;
}
Date get_date_created(){
return date_Created;
}
void set_account_id(int account_id_in){
account_id = account_id_in;
}
void set_account_balance(double account_balance_in){
account_balance = account_balance_in;
}
void set_annual_interest_rate(double annual_interest_rate_in){
annual_interest_rate = annual_interest_rate_in;
}
double get_monthly_interest_rate(){
return annual_interest_rate/12;
}
double get_monthly_interest(){
return (account_balance * get_monthly_interest_rate())/100;
}
void perform_deposit(double deposit_in){
account_balance += deposit_in;
}
void perform_withdraw(double withdraw_amount){
account_balance -= withdraw_amount;
}
}
public class ATM {
private Account[] acct = new Account [10];
public ATM(){
//acct = new Account[10];
for(int i = 0; i<10 ; i++){
acct[i].set_account_id(i+1);
acct[i].set_account_balance(100); // here iam getting an error.
}
//you must set their ids to values as specified in the assignment
} //these are the teacher's comments and instructions.
public void displayMenu(){
System.out.println("ATM Menu:");
System.out.println("\tenter 1 for viewing the current balance");
System.out.println("\tenter 2 for withdrawing money");
System.out.println("\tenter 3 for for depositing money");
System.out.println("\tenter 4 for exiting the main menu");
}
public boolean checkID(int id){
for(int i = 0; i<10 ; i++){
if(acct[i].get_account_id() == id){
return true;
}
}
return false;
}
public double checkBalance(int idToSearch){
int indexOfAccountToReturn = 0;
for(int i = 0; i<10; i++){
if(acct[i].get_account_id() == idToSearch){
indexOfAccountToReturn = i;
break;
}
}
return acct[indexOfAccountToReturn].get_account_balance();
}
public void withdrawFunds(int id, double amount){
for(int i=0; i<10; i++){
if(acct[i].get_account_id() == id){
acct[i].perform_withdraw(amount);
break;
}
}
}
public void depositFunds(int id, double amount){
for(int i=0; i<10; i++){
if(acct[i].get_account_id() == id){
acct[i].perform_deposit(amount);
break;
}
}
}
}
import java.util.Scanner;
import javax.swing.JOptionPane;
public class Banking_Finance_Main {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
ATM atm = new ATM();
Scanner input = new Scanner(System.in);
do{
System.out.println("Account ID?");
int id = input.nextInt();
while(!(atm.checkID(id))){
String entry = JOptionPane.showInputDialog("Incorrect
Input");
id = Integer.parseInt(entry);
}
//prevent user to proceed without the correct id; use checkID
method and store appropriately
do{
atm.displayMenu();
System.out.println("Your choice?");
int choice = input.nextInt();
while((choice >4) || (choice <1)){
String entry = JOptionPane.showInputDialog("Incorrect Imput");
choice = Integer.parseInt(entry);
}
//prevent user to proceed without the correct choice 1-4;
if(choice==1){
System.out.println("Enter the Account id to check the balance: ");
int idToSearch = input.nextInt();
System.out.println("The balance in this ACccount is: $" +
atm.checkBalance(idToSearch));
}else if(choice==2){
System.out.println("Enter the Account id to perform withdrawal: ");
int idToSearch = input.nextInt();
System.out.println("Enter the amount to be withdrawn: ");
double amountToWithdraw = input.nextDouble();
atm.withdrawFunds(idToSearch, amountToWithdraw);
}else if(choice==3){
System.out.println("Enter the Account id to perform deposit: ");
int idToSearch = input.nextInt();
System.out.println("Enter the amount to be deposited: ");
double amountToDeposit = input.nextDouble();
atm.depositFunds(idToSearch, amountToDeposit);
}else{
break;
}
}while(true);
}while(true);
}
}
I am sorry if I am using this site inappropriately, this is my first
question here so bear with me please.
I am working on a simple program for my intro to Object Oriented
programing class, where I have 3 classes: Account ATM and the main/Runner
class I am experiencing a null pointer exception error in the constructor
of the ATM class when I am trying to initialize the array of Accounts
using a loop. I am new to JAVA so I don't really know what happens. here
is the code.
import java.util.Date;
public class Account {
private int account_id;
private double account_balance;
private static double annual_interest_rate;
private Date date_Created;
Account(){
account_id = 0;
account_balance=0;
annual_interest_rate = 0;
date_Created = new Date();
}
Account(int account_id_in, double account_balance_in, double
annual_interest_rate_in){
account_id = account_id_in;
account_balance = account_balance_in;
annual_interest_rate = annual_interest_rate_in;
date_Created = new Date();
}
int get_account_id(){
return account_id;
}
double get_account_balance(){
return account_balance;
}
double get_annual_interest_rate(){
return annual_interest_rate;
}
Date get_date_created(){
return date_Created;
}
void set_account_id(int account_id_in){
account_id = account_id_in;
}
void set_account_balance(double account_balance_in){
account_balance = account_balance_in;
}
void set_annual_interest_rate(double annual_interest_rate_in){
annual_interest_rate = annual_interest_rate_in;
}
double get_monthly_interest_rate(){
return annual_interest_rate/12;
}
double get_monthly_interest(){
return (account_balance * get_monthly_interest_rate())/100;
}
void perform_deposit(double deposit_in){
account_balance += deposit_in;
}
void perform_withdraw(double withdraw_amount){
account_balance -= withdraw_amount;
}
}
public class ATM {
private Account[] acct = new Account [10];
public ATM(){
//acct = new Account[10];
for(int i = 0; i<10 ; i++){
acct[i].set_account_id(i+1);
acct[i].set_account_balance(100); // here iam getting an error.
}
//you must set their ids to values as specified in the assignment
} //these are the teacher's comments and instructions.
public void displayMenu(){
System.out.println("ATM Menu:");
System.out.println("\tenter 1 for viewing the current balance");
System.out.println("\tenter 2 for withdrawing money");
System.out.println("\tenter 3 for for depositing money");
System.out.println("\tenter 4 for exiting the main menu");
}
public boolean checkID(int id){
for(int i = 0; i<10 ; i++){
if(acct[i].get_account_id() == id){
return true;
}
}
return false;
}
public double checkBalance(int idToSearch){
int indexOfAccountToReturn = 0;
for(int i = 0; i<10; i++){
if(acct[i].get_account_id() == idToSearch){
indexOfAccountToReturn = i;
break;
}
}
return acct[indexOfAccountToReturn].get_account_balance();
}
public void withdrawFunds(int id, double amount){
for(int i=0; i<10; i++){
if(acct[i].get_account_id() == id){
acct[i].perform_withdraw(amount);
break;
}
}
}
public void depositFunds(int id, double amount){
for(int i=0; i<10; i++){
if(acct[i].get_account_id() == id){
acct[i].perform_deposit(amount);
break;
}
}
}
}
import java.util.Scanner;
import javax.swing.JOptionPane;
public class Banking_Finance_Main {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
ATM atm = new ATM();
Scanner input = new Scanner(System.in);
do{
System.out.println("Account ID?");
int id = input.nextInt();
while(!(atm.checkID(id))){
String entry = JOptionPane.showInputDialog("Incorrect
Input");
id = Integer.parseInt(entry);
}
//prevent user to proceed without the correct id; use checkID
method and store appropriately
do{
atm.displayMenu();
System.out.println("Your choice?");
int choice = input.nextInt();
while((choice >4) || (choice <1)){
String entry = JOptionPane.showInputDialog("Incorrect Imput");
choice = Integer.parseInt(entry);
}
//prevent user to proceed without the correct choice 1-4;
if(choice==1){
System.out.println("Enter the Account id to check the balance: ");
int idToSearch = input.nextInt();
System.out.println("The balance in this ACccount is: $" +
atm.checkBalance(idToSearch));
}else if(choice==2){
System.out.println("Enter the Account id to perform withdrawal: ");
int idToSearch = input.nextInt();
System.out.println("Enter the amount to be withdrawn: ");
double amountToWithdraw = input.nextDouble();
atm.withdrawFunds(idToSearch, amountToWithdraw);
}else if(choice==3){
System.out.println("Enter the Account id to perform deposit: ");
int idToSearch = input.nextInt();
System.out.println("Enter the amount to be deposited: ");
double amountToDeposit = input.nextDouble();
atm.depositFunds(idToSearch, amountToDeposit);
}else{
break;
}
}while(true);
}while(true);
}
}
I am sorry if I am using this site inappropriately, this is my first
question here so bear with me please.
Error in IOS App xcode Expected Identifier
Error in IOS App xcode Expected Identifier
I am getting an error in Xcode when adding some labelLoading code in the
.m file. Hoping someone can help me out and point out the error in the
code. Don't beat me up too bad as I am learning. I just can't get past
this error.
@interface ViewController ()
@end
@implementation ViewController
@synthesize viewWeb;
@synthesize labelLoading;
@synthesize tqwWeb;
@synthesize blogWeb;
@synthesize eventsWeb;
@synthesize resWeb;
@synthesize homeWeb;
- (void)viewDidLoad
{
[viewWeb setDelegate:self];
}
- (void)webViewDidStartLoad:(UIWebView *)webView {
[labelLoading setHidden:NO];
}
- (void)webViewDidFinishLoad:(UIWebView *)webView {
[labelLoading setHidden:YES];
}
{ **This is where the error Expected identifier or "(" occurs**
[super viewDidLoad];
NSString *fullURL = @"http://www.rtics.com/DC1/";
NSURL *url = [NSURL URLWithString:fullURL];
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
[viewWeb loadRequest:requestObj];
[super viewDidLoad];
NSString *afullURL = @"http://www.rtics.com/DC2";
NSURL *aurl = [NSURL URLWithString:afullURL];
NSURLRequest *arequestObj = [NSURLRequest requestWithURL:aurl];
[tqwWeb loadRequest:arequestObj];
[super viewDidLoad];
NSString *bfullURL = @"http:/www.rtics.com/DC3/";
NSURL *burl = [NSURL URLWithString:bfullURL];
NSURLRequest *brequestObj = [NSURLRequest requestWithURL:burl];
[blogWeb loadRequest:brequestObj];
[super viewDidLoad];
NSString *cfullURL = @"https://www.rtics.com/DC4";
NSURL *curl = [NSURL URLWithString:cfullURL];
NSURLRequest *crequestObj = [NSURLRequest requestWithURL:curl];
[eventsWeb loadRequest:crequestObj];
[super viewDidLoad];
NSString *dfullURL = @"http://www.rtics.com/DC5";
NSURL *durl = [NSURL URLWithString:dfullURL];
NSURLRequest *drequestObj = [NSURLRequest requestWithURL:durl];
[resWeb loadRequest:drequestObj];
[super viewDidLoad];
NSString *efullURL = @"http://www.rtics.com/";
NSURL *eurl = [NSURL URLWithString:efullURL];
NSURLRequest *erequestObj = [NSURLRequest requestWithURL:eurl];
[homeWeb loadRequest:erequestObj];
}
- (void)viewDidUnload
{
[self setViewWeb:nil];
[self setLabelLoading:nil];
[self setWebView:nil];
[super viewDidUnload];
}
-
(BOOL)shouldAutorotateToInterfaceOrientation(UIInterfaceOrientation)interfaceOrientation
{
if ([[UIDevice currentDevice] userInterfaceIdiom] ==
UIUserInterfaceIdiomPhone) {
return (interfaceOrientation !=
UIInterfaceOrientationPortraitUpsideDown);
} else {
return YES;
}
}
@end
I am getting an error in Xcode when adding some labelLoading code in the
.m file. Hoping someone can help me out and point out the error in the
code. Don't beat me up too bad as I am learning. I just can't get past
this error.
@interface ViewController ()
@end
@implementation ViewController
@synthesize viewWeb;
@synthesize labelLoading;
@synthesize tqwWeb;
@synthesize blogWeb;
@synthesize eventsWeb;
@synthesize resWeb;
@synthesize homeWeb;
- (void)viewDidLoad
{
[viewWeb setDelegate:self];
}
- (void)webViewDidStartLoad:(UIWebView *)webView {
[labelLoading setHidden:NO];
}
- (void)webViewDidFinishLoad:(UIWebView *)webView {
[labelLoading setHidden:YES];
}
{ **This is where the error Expected identifier or "(" occurs**
[super viewDidLoad];
NSString *fullURL = @"http://www.rtics.com/DC1/";
NSURL *url = [NSURL URLWithString:fullURL];
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
[viewWeb loadRequest:requestObj];
[super viewDidLoad];
NSString *afullURL = @"http://www.rtics.com/DC2";
NSURL *aurl = [NSURL URLWithString:afullURL];
NSURLRequest *arequestObj = [NSURLRequest requestWithURL:aurl];
[tqwWeb loadRequest:arequestObj];
[super viewDidLoad];
NSString *bfullURL = @"http:/www.rtics.com/DC3/";
NSURL *burl = [NSURL URLWithString:bfullURL];
NSURLRequest *brequestObj = [NSURLRequest requestWithURL:burl];
[blogWeb loadRequest:brequestObj];
[super viewDidLoad];
NSString *cfullURL = @"https://www.rtics.com/DC4";
NSURL *curl = [NSURL URLWithString:cfullURL];
NSURLRequest *crequestObj = [NSURLRequest requestWithURL:curl];
[eventsWeb loadRequest:crequestObj];
[super viewDidLoad];
NSString *dfullURL = @"http://www.rtics.com/DC5";
NSURL *durl = [NSURL URLWithString:dfullURL];
NSURLRequest *drequestObj = [NSURLRequest requestWithURL:durl];
[resWeb loadRequest:drequestObj];
[super viewDidLoad];
NSString *efullURL = @"http://www.rtics.com/";
NSURL *eurl = [NSURL URLWithString:efullURL];
NSURLRequest *erequestObj = [NSURLRequest requestWithURL:eurl];
[homeWeb loadRequest:erequestObj];
}
- (void)viewDidUnload
{
[self setViewWeb:nil];
[self setLabelLoading:nil];
[self setWebView:nil];
[super viewDidUnload];
}
-
(BOOL)shouldAutorotateToInterfaceOrientation(UIInterfaceOrientation)interfaceOrientation
{
if ([[UIDevice currentDevice] userInterfaceIdiom] ==
UIUserInterfaceIdiomPhone) {
return (interfaceOrientation !=
UIInterfaceOrientationPortraitUpsideDown);
} else {
return YES;
}
}
@end
Form validation for select element IE9
Form validation for select element IE9
Community, after some extensive research I discovered that IE9 does not
take too kindly to "required" because it is not compatible for HTML5 like
IE10. I currently have a moderately basic form, but with a drop down menu
that needs an option selected whose value does NOT equal 0. I am extremely
new to jquery and am not quite sure where to begin should I need to take
that route. I'm hoping there is a simpler solution using javascript alone.
I tried using the jquery.js and jquery.validate.js plugins, but had some
extreme difficulty.
Thanks
Community, after some extensive research I discovered that IE9 does not
take too kindly to "required" because it is not compatible for HTML5 like
IE10. I currently have a moderately basic form, but with a drop down menu
that needs an option selected whose value does NOT equal 0. I am extremely
new to jquery and am not quite sure where to begin should I need to take
that route. I'm hoping there is a simpler solution using javascript alone.
I tried using the jquery.js and jquery.validate.js plugins, but had some
extreme difficulty.
Thanks
Phone 5 tab bar not working - iOS7 and Xcode GM's
Phone 5 tab bar not working - iOS7 and Xcode GM's
My app builds fine on my 4s and the Simulator for 3.5" screens but the tab
bar doesn't function at all when I build on the iPhone 5 and the
Simulator. There are no relevant diagnostics and yes the builds succeed.
Any idea where to start figuring out this new problem? My app is ready to
submit to the App Store other than this issue.
My app builds fine on my 4s and the Simulator for 3.5" screens but the tab
bar doesn't function at all when I build on the iPhone 5 and the
Simulator. There are no relevant diagnostics and yes the builds succeed.
Any idea where to start figuring out this new problem? My app is ready to
submit to the App Store other than this issue.
C++ implementation of ORDER BY on struct
C++ implementation of ORDER BY on struct
i searched a lot here and on other sites as well but i have not found
something satisfying.
what i need is quite simple task - substantially to construct ORDER BY
operator in c++. this means i have struct with a number of various data
type members and i need a comparator for it with members and orderings
configurable. here is my pseudocode idea:
comparator.add(&MyStruct::member1, std::less);
comparator.add(&MyStruct::member2, std::greater);
std::sort(my_vector.begin(), my_vector.end(), comparator);
and i get data sorted by member1 and if it is equal member2 decides, and
so on.
i am not too good in stl and templates, but i can read and decipher some
code and found this as very appropriate solution:
http://stackoverflow.com/a/11167563
unfortunately in my work i have to use c++ builder with faulty 32bit
compiler that refuses to compile this correct code. it does support almost
nothing from c++11, it has boost 1.39 available.
does someone have any solution that could work for me with my resources
available? thank you in advance
EDIT:
i got very specialised solutions with hard-written comparison operators
which i am aware of and which do not work here too good. i missed this in
my question. my struct has at least 15 members and as i wrote, i need to
often change individual sort directions for members/columns (asc, desc).
too, i need to often change set of sorted members, just like in order by
operator in sql, for example. also i cannot use something like stable_sort
as i am just writing comparator for something like OnCompare event of some
class.
i searched a lot here and on other sites as well but i have not found
something satisfying.
what i need is quite simple task - substantially to construct ORDER BY
operator in c++. this means i have struct with a number of various data
type members and i need a comparator for it with members and orderings
configurable. here is my pseudocode idea:
comparator.add(&MyStruct::member1, std::less);
comparator.add(&MyStruct::member2, std::greater);
std::sort(my_vector.begin(), my_vector.end(), comparator);
and i get data sorted by member1 and if it is equal member2 decides, and
so on.
i am not too good in stl and templates, but i can read and decipher some
code and found this as very appropriate solution:
http://stackoverflow.com/a/11167563
unfortunately in my work i have to use c++ builder with faulty 32bit
compiler that refuses to compile this correct code. it does support almost
nothing from c++11, it has boost 1.39 available.
does someone have any solution that could work for me with my resources
available? thank you in advance
EDIT:
i got very specialised solutions with hard-written comparison operators
which i am aware of and which do not work here too good. i missed this in
my question. my struct has at least 15 members and as i wrote, i need to
often change individual sort directions for members/columns (asc, desc).
too, i need to often change set of sorted members, just like in order by
operator in sql, for example. also i cannot use something like stable_sort
as i am just writing comparator for something like OnCompare event of some
class.
Thursday, 12 September 2013
Accel Sensor update on button push
Accel Sensor update on button push
I made this program for Sensor output with two buttons, One button start
registerListener, Off SensorEventListener and unregisterListener. Another
button (Update) i want it to display (output) the sensor position at the
moment i pushed it? thank you for help. Main.xml is:
package jp.dsc.sensoraccel;
import android.app.Activity;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.os.Handler;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
public class MainActivity extends Activity implements SensorEventListener {
private SensorManager sensorManager;
TextView xCoor; // declare X axis object
TextView yCoor; // declare Y axis object
TextView zCoor; // declare Z axis object
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
xCoor = (TextView) findViewById(R.id.xcoor); // create X axis object
yCoor = (TextView) findViewById(R.id.ycoor); // create Y axis object
zCoor = (TextView) findViewById(R.id.zcoor); // create Z axis object
sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is
present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
public void onSensorChanged(SensorEvent event) {
// check sensor type
if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
// assign directions
float x = event.values[0];
float y = event.values[1];
float z = event.values[2];
xCoor.setText("Accel X: " + x);
yCoor.setText("Accel Y: " + y);
zCoor.setText("Accel Z: " + z);
}
}
public void onButtonClicked(View v) {
//Tost declaration
Context context = getApplicationContext();
CharSequence msg = "Sensor Updated!";
int duration = Toast.LENGTH_SHORT;
sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
sensorManager.registerListener(this,
sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
SensorManager.SENSOR_DELAY_FASTEST);
final SensorEventListener listener = this;
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
sensorManager.unregisterListener(listener);
}
}, 200);
Toast toast = Toast.makeText(context, msg, duration);
toast.show();
}
public void onToggleClicked(View view) {
// Check if the toggleButton is on?
boolean on = ((ToggleButton) view).isChecked();
//Tost declaration
Context context = getApplicationContext();
CharSequence msg1 = "Continue!", msg2 = "Update Stopped!";
int duration = Toast.LENGTH_SHORT;
if (on) {
sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
sensorManager.registerListener(this,
sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
SensorManager.SENSOR_DELAY_FASTEST);
Toast toast = Toast.makeText(context, msg1, duration);
toast.show();
Button btn=(Button)findViewById(R.id.button1);
btn.setEnabled(false);
}
else {
final SensorEventListener listener = this;
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
sensorManager.unregisterListener(listener);
}
}, 200);
Toast toast = Toast.makeText(context, msg2, duration);
toast.show();
Button btn=(Button)findViewById(R.id.button1);
btn.setEnabled(true);
}
}
}
I made this program for Sensor output with two buttons, One button start
registerListener, Off SensorEventListener and unregisterListener. Another
button (Update) i want it to display (output) the sensor position at the
moment i pushed it? thank you for help. Main.xml is:
package jp.dsc.sensoraccel;
import android.app.Activity;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.os.Handler;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
public class MainActivity extends Activity implements SensorEventListener {
private SensorManager sensorManager;
TextView xCoor; // declare X axis object
TextView yCoor; // declare Y axis object
TextView zCoor; // declare Z axis object
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
xCoor = (TextView) findViewById(R.id.xcoor); // create X axis object
yCoor = (TextView) findViewById(R.id.ycoor); // create Y axis object
zCoor = (TextView) findViewById(R.id.zcoor); // create Z axis object
sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is
present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
public void onSensorChanged(SensorEvent event) {
// check sensor type
if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
// assign directions
float x = event.values[0];
float y = event.values[1];
float z = event.values[2];
xCoor.setText("Accel X: " + x);
yCoor.setText("Accel Y: " + y);
zCoor.setText("Accel Z: " + z);
}
}
public void onButtonClicked(View v) {
//Tost declaration
Context context = getApplicationContext();
CharSequence msg = "Sensor Updated!";
int duration = Toast.LENGTH_SHORT;
sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
sensorManager.registerListener(this,
sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
SensorManager.SENSOR_DELAY_FASTEST);
final SensorEventListener listener = this;
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
sensorManager.unregisterListener(listener);
}
}, 200);
Toast toast = Toast.makeText(context, msg, duration);
toast.show();
}
public void onToggleClicked(View view) {
// Check if the toggleButton is on?
boolean on = ((ToggleButton) view).isChecked();
//Tost declaration
Context context = getApplicationContext();
CharSequence msg1 = "Continue!", msg2 = "Update Stopped!";
int duration = Toast.LENGTH_SHORT;
if (on) {
sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
sensorManager.registerListener(this,
sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
SensorManager.SENSOR_DELAY_FASTEST);
Toast toast = Toast.makeText(context, msg1, duration);
toast.show();
Button btn=(Button)findViewById(R.id.button1);
btn.setEnabled(false);
}
else {
final SensorEventListener listener = this;
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
sensorManager.unregisterListener(listener);
}
}, 200);
Toast toast = Toast.makeText(context, msg2, duration);
toast.show();
Button btn=(Button)findViewById(R.id.button1);
btn.setEnabled(true);
}
}
}
Cordova 3.0 White Screen Flash
Cordova 3.0 White Screen Flash
I build an app using Cordova 3.0 and every time my app loads the splash
screen a white screen is displayed for a few seconds before my app
actually loads. I search online and it said to set the
"AutoHideSplashScreen" to "False" which i did but after I create my .ipa
file again and run it on my iphone I still get the white flash screen. Any
idea as to what I may be missing thanks...
I build an app using Cordova 3.0 and every time my app loads the splash
screen a white screen is displayed for a few seconds before my app
actually loads. I search online and it said to set the
"AutoHideSplashScreen" to "False" which i did but after I create my .ipa
file again and run it on my iphone I still get the white flash screen. Any
idea as to what I may be missing thanks...
Wednesday, 11 September 2013
Windows 8,launch outlook from metro application
Windows 8,launch outlook from metro application
I am trying to open out look from metro application (vs2012, windows store
app).I used the following code:
var mailto = new Uri("mailto:?rbethamcharla@hotmail.com");
await Windows.System.Launcher.LaunchUriAsync(mailto);
But I am always getting access denied error.Could some one please let know
how to enable this acess of outlook from windows 8 store app
programmatically.
Thanks & Regards Ravi Kumar B
I am trying to open out look from metro application (vs2012, windows store
app).I used the following code:
var mailto = new Uri("mailto:?rbethamcharla@hotmail.com");
await Windows.System.Launcher.LaunchUriAsync(mailto);
But I am always getting access denied error.Could some one please let know
how to enable this acess of outlook from windows 8 store app
programmatically.
Thanks & Regards Ravi Kumar B
How to validate dependent parameters in PowerShell cmdlet
How to validate dependent parameters in PowerShell cmdlet
What's the best way to do PowerShell cmdlet validation on dependent
parameters? For example, in the sample cmdlet below I need to run
validation that Low is greater than High but that doesn't seem to be
possible with validation attributes.
[Cmdlet(VerbsCommon.Get, "FakeData")]
public class GetFakeData : PSCmdlet
{
[Parameter(Mandatory = true)]
[ValidateNotNullOrEmpty]
public int Low { get; set; }
[Parameter(Mandatory = true)]
[ValidateNotNullOrEmpty]
public int High { get; set; }
protected override void BeginProcessing()
{
if (Low >= High)
{
// Is there a better exception to throw here?
throw new CmdletInvocationException("Low must be less than
High");
}
base.BeginProcessing();
}
protected override void OnProcessRecord()
{
// Do stuff...
}
}
Is there is a better way to do this? The main thing I don't like about the
solution above is that I can't throw a ParameterBindingException like the
validation attributes would do since it's an internal class. I could throw
ArgumentException or PSArgumentException but those are really for Methods
not cmdlets.
What's the best way to do PowerShell cmdlet validation on dependent
parameters? For example, in the sample cmdlet below I need to run
validation that Low is greater than High but that doesn't seem to be
possible with validation attributes.
[Cmdlet(VerbsCommon.Get, "FakeData")]
public class GetFakeData : PSCmdlet
{
[Parameter(Mandatory = true)]
[ValidateNotNullOrEmpty]
public int Low { get; set; }
[Parameter(Mandatory = true)]
[ValidateNotNullOrEmpty]
public int High { get; set; }
protected override void BeginProcessing()
{
if (Low >= High)
{
// Is there a better exception to throw here?
throw new CmdletInvocationException("Low must be less than
High");
}
base.BeginProcessing();
}
protected override void OnProcessRecord()
{
// Do stuff...
}
}
Is there is a better way to do this? The main thing I don't like about the
solution above is that I can't throw a ParameterBindingException like the
validation attributes would do since it's an internal class. I could throw
ArgumentException or PSArgumentException but those are really for Methods
not cmdlets.
Using ParseKit to parse nested rules
Using ParseKit to parse nested rules
I'm trying to create a strict CSS parser with ParseKit which supports
nested rules like those found in SASS and LESS. I'm trying to adapt and
learn from the sample CSS and JSON grammar to build my grammar.
the grammar so far:
@symbols = '//';
@singleLineComments = '//';
@multiLineComments = '/*' '*/';
@wordState = '-' '@';
@start
@before {
PKTokenizer *t = self.tokenizer;
// symbols
[t.symbolState add:@"/*"];
[t.symbolState add:@"*/"];
[t.symbolState add:@"//"];
[t.symbolState add:@"url("];
[t.symbolState add:@"URL("];
[t.symbolState add:@"Url("];
// word chars -moz, -webkit, @media, #id, .class, :hover
[t setTokenizerState:t.wordState from:'-' to:'-'];
[t setTokenizerState:t.wordState from:'@' to:'@'];
[t setTokenizerState:t.wordState from:'.' to:'.'];
[t setTokenizerState:t.wordState from:'#' to:'#'];
[t.wordState setWordChars:YES from:'-' to:'-'];
[t.wordState setWordChars:YES from:'@' to:'@'];
[t.wordState setWordChars:YES from:'.' to:'.'];
[t.wordState setWordChars:YES from:'#' to:'#'];
// comments
[t setTokenizerState:t.commentState from:'/' to:'/'];
[t.commentState setFallbackState:t.symbolState from:'/' to:'/'];
[t.commentState addSingleLineStartMarker:@"//"];
[t.commentState addMultiLineStartMarker:@"/*" endMarker:@"*/"];
t.commentState.reportsCommentTokens = YES;
// urls
[t setTokenizerState:t.delimitState from:'u' to:'u'];
[t setTokenizerState:t.delimitState from:'U' to:'U'];
[t.delimitState addStartMarker:@"url(" endMarker:@")"
allowedCharacterSet:nil];
[t.delimitState addStartMarker:@"URL(" endMarker:@")"
allowedCharacterSet:nil];
[t.delimitState addStartMarker:@"Url(" endMarker:@")"
allowedCharacterSet:nil];
}
= ruleset*;
ruleset = selectors openCurly ( decls | selector )
closeCurly;
selectors = selector commaSelector*;
selector = (selectorWord | hashSym | dot | colon | gt |
openBracket | closeBracket | eq | selectorQuotedString | tilde | pipe)+;
selectorWord = Word;
selectorQuotedString = QuotedString;
commaSelector = comma selector;
decls = Empty | actualDecls;
actualDecls = decl decl*;
decl = property colon expr important? semi;
property = Word;
expr = (string | constant | num | url | openParen |
closeParen | comma | nonTerminatingSymbol)+;
url = urlLower | urlUpper;
urlLower = %{'url(', ')'};
urlUpper = %{'URL(', ')'};
nonTerminatingSymbol = {return NE(LS(1), @";") && NE(LS(1), @"!");}?
fwdSlash | Symbol;
important = bang Word;
string = QuotedString;
constant = Word;
openCurly = '{';
closeCurly = '}';
openBracket = '[';
closeBracket = ']';
eq = '=';
comma = ',';
colon = ':';
semi = ';';
openParen = '(';
closeParen = ')';
gt = '>';
tilde = '~';
pipe = '|';
fwdSlash = '/';
hashSym = '#';
dot = '.';
at = '@';
bang = '!';
num = Number;
I thought the key to enabling nested rules was the
ruleset = selectors openCurly ( decls | selector )
closeCurly;
line, allowing a nested selector like the JSON grammar does. But when I
feed in a string like
.myClass1 {
.content {}
}
.myClass2 {}
the assembly stack only shows ['.', 'myClass1', '.', 'content']. It seems
to skip entirely .myClass2.
Why does this grammar stop parsing when it finds a nested selector? How
can I make it correctly parse the entire stylesheet? How can I keep track
of the ancestry of each selector and rule?
info: here is my class which sets up the PKParser and delegate selectors.
I'm trying to create a strict CSS parser with ParseKit which supports
nested rules like those found in SASS and LESS. I'm trying to adapt and
learn from the sample CSS and JSON grammar to build my grammar.
the grammar so far:
@symbols = '//';
@singleLineComments = '//';
@multiLineComments = '/*' '*/';
@wordState = '-' '@';
@start
@before {
PKTokenizer *t = self.tokenizer;
// symbols
[t.symbolState add:@"/*"];
[t.symbolState add:@"*/"];
[t.symbolState add:@"//"];
[t.symbolState add:@"url("];
[t.symbolState add:@"URL("];
[t.symbolState add:@"Url("];
// word chars -moz, -webkit, @media, #id, .class, :hover
[t setTokenizerState:t.wordState from:'-' to:'-'];
[t setTokenizerState:t.wordState from:'@' to:'@'];
[t setTokenizerState:t.wordState from:'.' to:'.'];
[t setTokenizerState:t.wordState from:'#' to:'#'];
[t.wordState setWordChars:YES from:'-' to:'-'];
[t.wordState setWordChars:YES from:'@' to:'@'];
[t.wordState setWordChars:YES from:'.' to:'.'];
[t.wordState setWordChars:YES from:'#' to:'#'];
// comments
[t setTokenizerState:t.commentState from:'/' to:'/'];
[t.commentState setFallbackState:t.symbolState from:'/' to:'/'];
[t.commentState addSingleLineStartMarker:@"//"];
[t.commentState addMultiLineStartMarker:@"/*" endMarker:@"*/"];
t.commentState.reportsCommentTokens = YES;
// urls
[t setTokenizerState:t.delimitState from:'u' to:'u'];
[t setTokenizerState:t.delimitState from:'U' to:'U'];
[t.delimitState addStartMarker:@"url(" endMarker:@")"
allowedCharacterSet:nil];
[t.delimitState addStartMarker:@"URL(" endMarker:@")"
allowedCharacterSet:nil];
[t.delimitState addStartMarker:@"Url(" endMarker:@")"
allowedCharacterSet:nil];
}
= ruleset*;
ruleset = selectors openCurly ( decls | selector )
closeCurly;
selectors = selector commaSelector*;
selector = (selectorWord | hashSym | dot | colon | gt |
openBracket | closeBracket | eq | selectorQuotedString | tilde | pipe)+;
selectorWord = Word;
selectorQuotedString = QuotedString;
commaSelector = comma selector;
decls = Empty | actualDecls;
actualDecls = decl decl*;
decl = property colon expr important? semi;
property = Word;
expr = (string | constant | num | url | openParen |
closeParen | comma | nonTerminatingSymbol)+;
url = urlLower | urlUpper;
urlLower = %{'url(', ')'};
urlUpper = %{'URL(', ')'};
nonTerminatingSymbol = {return NE(LS(1), @";") && NE(LS(1), @"!");}?
fwdSlash | Symbol;
important = bang Word;
string = QuotedString;
constant = Word;
openCurly = '{';
closeCurly = '}';
openBracket = '[';
closeBracket = ']';
eq = '=';
comma = ',';
colon = ':';
semi = ';';
openParen = '(';
closeParen = ')';
gt = '>';
tilde = '~';
pipe = '|';
fwdSlash = '/';
hashSym = '#';
dot = '.';
at = '@';
bang = '!';
num = Number;
I thought the key to enabling nested rules was the
ruleset = selectors openCurly ( decls | selector )
closeCurly;
line, allowing a nested selector like the JSON grammar does. But when I
feed in a string like
.myClass1 {
.content {}
}
.myClass2 {}
the assembly stack only shows ['.', 'myClass1', '.', 'content']. It seems
to skip entirely .myClass2.
Why does this grammar stop parsing when it finds a nested selector? How
can I make it correctly parse the entire stylesheet? How can I keep track
of the ancestry of each selector and rule?
info: here is my class which sets up the PKParser and delegate selectors.
ListView SimpleCursorAdapter Checkbox
ListView SimpleCursorAdapter Checkbox
Well i searched for over 1 Hour now and didnt find a working solution for
my problem. I got a SimpleCursor Adapter for a ListView and want to
implement a Checkbox. Everything works fine except that the Checkbox is
randomly (mirrored) checked on my ListView. I know it has to do with
recycled ListView rows, but i cant get it to work. Here my code:
private void displayListView() {
Cursor cursor = dbHelper.fetch...
// The desired columns to be bound
String[] columns = new String[] {
ProduktAdapter.KEY_CODE,
ProduktAdapter.KEY_NAME,
ProduktAdapter.KEY_CONTINENT,
ProduktAdapter.KEY_REGION,
ProduktAdapter.KEY_PHOTO
};
// the XML defined views which the data will be bound to
int[] to = new int[] {
R.id.code,
R.id.name,
R.id.continent,
R.id.region,
R.id.list_image
};
// create the adapter using the cursor pointing to the desired data
//as well as the layout information
dataAdapter = new SimpleCursorAdapter(
this, R.layout.produkt_info,
cursor,
columns,
to,
0);
dataAdapter.setViewBinder(new SimpleCursorAdapter.ViewBinder() {
public boolean setViewValue(View view, Cursor cursor,
int columnIndex) {
if (view.getId() == R.id.list_image) {
String _name = cursor.getString(columnIndex);
File file = new File(Environment.getExternalStorageDirectory()
.......
Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
((ImageView) view).setImageBitmap(bitmap);
return true;
} else {
return false;
}
}});
final ListView listView = (ListView) findViewById(R.id.listView1);
// Assign adapter to ListView
listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
listView.setAdapter(dataAdapter);
I got a CHOICE_MODE_MULTIPLE layout, and tried to save the Checkbox State
to an array, (with getView) but still dont get it working. (Something like
that):
public View getView(final int pos, View inView, ViewGroup parent) {
if (inView == null) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
inView = inflater.inflate(R.layout.kuehlschrankliste, null);
}
final CheckBox cBox = (CheckBox) inView.findViewById(R.id.check);
cBox.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if(cBox.isChecked()) {
itemChecked.set(pos, true);
// do some operations here
}
else{
itemChecked.set(pos, false);
// do some operations here
}
}
});
cBox.setChecked(itemChecked.get(pos));
return inView;
}
Can you help me ?
Well i searched for over 1 Hour now and didnt find a working solution for
my problem. I got a SimpleCursor Adapter for a ListView and want to
implement a Checkbox. Everything works fine except that the Checkbox is
randomly (mirrored) checked on my ListView. I know it has to do with
recycled ListView rows, but i cant get it to work. Here my code:
private void displayListView() {
Cursor cursor = dbHelper.fetch...
// The desired columns to be bound
String[] columns = new String[] {
ProduktAdapter.KEY_CODE,
ProduktAdapter.KEY_NAME,
ProduktAdapter.KEY_CONTINENT,
ProduktAdapter.KEY_REGION,
ProduktAdapter.KEY_PHOTO
};
// the XML defined views which the data will be bound to
int[] to = new int[] {
R.id.code,
R.id.name,
R.id.continent,
R.id.region,
R.id.list_image
};
// create the adapter using the cursor pointing to the desired data
//as well as the layout information
dataAdapter = new SimpleCursorAdapter(
this, R.layout.produkt_info,
cursor,
columns,
to,
0);
dataAdapter.setViewBinder(new SimpleCursorAdapter.ViewBinder() {
public boolean setViewValue(View view, Cursor cursor,
int columnIndex) {
if (view.getId() == R.id.list_image) {
String _name = cursor.getString(columnIndex);
File file = new File(Environment.getExternalStorageDirectory()
.......
Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
((ImageView) view).setImageBitmap(bitmap);
return true;
} else {
return false;
}
}});
final ListView listView = (ListView) findViewById(R.id.listView1);
// Assign adapter to ListView
listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
listView.setAdapter(dataAdapter);
I got a CHOICE_MODE_MULTIPLE layout, and tried to save the Checkbox State
to an array, (with getView) but still dont get it working. (Something like
that):
public View getView(final int pos, View inView, ViewGroup parent) {
if (inView == null) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
inView = inflater.inflate(R.layout.kuehlschrankliste, null);
}
final CheckBox cBox = (CheckBox) inView.findViewById(R.id.check);
cBox.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if(cBox.isChecked()) {
itemChecked.set(pos, true);
// do some operations here
}
else{
itemChecked.set(pos, false);
// do some operations here
}
}
});
cBox.setChecked(itemChecked.get(pos));
return inView;
}
Can you help me ?
Long strings in data statements
Long strings in data statements
I'd like to initialize a long string in Fortran 77 in a DATA statement,
like this:
DATA Lipsum /
*'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendi
*sse tincidunt, velit id hendrerit bibendum, erat nisl dignissim ar
*cu'/
but the internal policy of the program I'm contributing to does not like
it as it prohibits lines with an odd number of quote marks.
I can "fool" the policy checker by using double quotes instead, or using '
as the continuation character (in the first and last line), but I'd like
to know if there is some other way to have long strings in DATA
statements, where the concatenation operator // does not seem to be
allowed.
I'd like to initialize a long string in Fortran 77 in a DATA statement,
like this:
DATA Lipsum /
*'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendi
*sse tincidunt, velit id hendrerit bibendum, erat nisl dignissim ar
*cu'/
but the internal policy of the program I'm contributing to does not like
it as it prohibits lines with an odd number of quote marks.
I can "fool" the policy checker by using double quotes instead, or using '
as the continuation character (in the first and last line), but I'd like
to know if there is some other way to have long strings in DATA
statements, where the concatenation operator // does not seem to be
allowed.
How to concatenate table name with variable within for loop in sql
How to concatenate table name with variable within for loop in sql
I am trying to write a one time (as in never to be run again) script to
collect information about usage of certain features of our product. Here
is a simplified script that I have right now:
begin
for db in (select owner from dba_tables where
table_name='feature_table') loop
begin
for info in (select * from db.owner.feature_table where
something='important') loop
begin
dbms_output.put_line(db.owner||' , '||info.type||' ,
'||info.source);
end;
end loop;
end;
end loop;
end;
I get an error in the inner loop at "db.owner.feature_table". I also tried
passing it as concatenated string, but to no avail. What do I need to do
to get this to work?
I am trying to write a one time (as in never to be run again) script to
collect information about usage of certain features of our product. Here
is a simplified script that I have right now:
begin
for db in (select owner from dba_tables where
table_name='feature_table') loop
begin
for info in (select * from db.owner.feature_table where
something='important') loop
begin
dbms_output.put_line(db.owner||' , '||info.type||' ,
'||info.source);
end;
end loop;
end;
end loop;
end;
I get an error in the inner loop at "db.owner.feature_table". I also tried
passing it as concatenated string, but to no avail. What do I need to do
to get this to work?
Prevent Timer from Stopping in case of error
Prevent Timer from Stopping in case of error
I am coding a WinForm on VB.net and I have a timer ticking that retrieves
data from database every specific interval of time.
I don't want the timer to stop ticking in case of error.
What is the best way to do this?
I am coding a WinForm on VB.net and I have a timer ticking that retrieves
data from database every specific interval of time.
I don't want the timer to stop ticking in case of error.
What is the best way to do this?
Joining 2 tables in which the common row has different data formats
Joining 2 tables in which the common row has different data formats
i have 2 tables in my database, one is tablea, and the other is tableb.
select *
from tablea
results in
ip mac
1.10.0.0.97 00 14 2A 2F 72 FE
1.10.0.0.98 08 CC 68 71 A1 C0
select * from tableb
results in
mac port
0:14:2a:2f:72:fe 24
8:cc:68:71:a1:c0 7
I now want to create a third table , which joins tablea and table c and
has 3 columns displaying ip,mac and port. the table has already been
created and this is what i have in mind;
INSERT INTO tablec
SELECT a.ip,a.mac,b.port
FROM tablea a,tableb b
WHERE a.mac=replace('replace('b.mac',':',' ')','0','00')
The query gives me an error
ERROR 1064(42000): You have an error in your SQL syntax; check the manual
that corresponds to your mysql server version for the right syntax to use
near 'b.mac',':',' ')','0','00')
I have checked the manual and i could not identify where my error is . And
also my replace function can be able to convert 0:14:2a:2f:72:fe to 00 14
2A 2F 72 FE but it will not work if tried for 8:cc:68:71:a1:c0. I would
really appreciate any help i can get in creating this 3rd table
i have 2 tables in my database, one is tablea, and the other is tableb.
select *
from tablea
results in
ip mac
1.10.0.0.97 00 14 2A 2F 72 FE
1.10.0.0.98 08 CC 68 71 A1 C0
select * from tableb
results in
mac port
0:14:2a:2f:72:fe 24
8:cc:68:71:a1:c0 7
I now want to create a third table , which joins tablea and table c and
has 3 columns displaying ip,mac and port. the table has already been
created and this is what i have in mind;
INSERT INTO tablec
SELECT a.ip,a.mac,b.port
FROM tablea a,tableb b
WHERE a.mac=replace('replace('b.mac',':',' ')','0','00')
The query gives me an error
ERROR 1064(42000): You have an error in your SQL syntax; check the manual
that corresponds to your mysql server version for the right syntax to use
near 'b.mac',':',' ')','0','00')
I have checked the manual and i could not identify where my error is . And
also my replace function can be able to convert 0:14:2a:2f:72:fe to 00 14
2A 2F 72 FE but it will not work if tried for 8:cc:68:71:a1:c0. I would
really appreciate any help i can get in creating this 3rd table
Tuesday, 10 September 2013
Customize order (merge product page and checkout) with Magento
Customize order (merge product page and checkout) with Magento
The scenario is:
No actual product on the backend
Order has to be created (just for handling the default Magento way of
transaction)
All order details will be handled by a separate custom module which only
references the order id.
I have a customer form on the frontend taking in the details of the orders
(more precisely product, i.e, choosing among various options). The cost of
the product(by evaluation of the options) is generated by jQuery for now.
Now, I need to make the form: the product page as well as the checkout
page (i.e. client should be able to place an order in one step, fill in
the form and order).
What are my options?
Make configurable product?
Customize order process(one step checkout)? How to make this flexible?
The scenario is:
No actual product on the backend
Order has to be created (just for handling the default Magento way of
transaction)
All order details will be handled by a separate custom module which only
references the order id.
I have a customer form on the frontend taking in the details of the orders
(more precisely product, i.e, choosing among various options). The cost of
the product(by evaluation of the options) is generated by jQuery for now.
Now, I need to make the form: the product page as well as the checkout
page (i.e. client should be able to place an order in one step, fill in
the form and order).
What are my options?
Make configurable product?
Customize order process(one step checkout)? How to make this flexible?
What's wrong with my delete method in Rails?
What's wrong with my delete method in Rails?
I'm new to Rails so this is probably easy. Can you take a look at the
delete method in my code and let me know what's wrong? I've done some
searching but am not finding exactly what I need to do. Basically I'm
creating a twitter type site to post statuses as I'm learning.
Thanks!
<div class="page-header"><h1>All Statuses</h1></div>
<% @statuses.each do |status| %>
<div>
<strong><%= status.name %></strong>
<p><%= status.content %></p>
</div>
<div class="meta"><%= link_to 'Show', status %></div>
<div class="admin"><%= link_to 'Edit', edit_status_path(status) %> | <%=
link_to 'Delete', admin_status_path(status.id), :method=>delete,
:class=>destroy, :confirm=>"Are you sure you want to delete this
status?" %></div>
<% end %>
I'm new to Rails so this is probably easy. Can you take a look at the
delete method in my code and let me know what's wrong? I've done some
searching but am not finding exactly what I need to do. Basically I'm
creating a twitter type site to post statuses as I'm learning.
Thanks!
<div class="page-header"><h1>All Statuses</h1></div>
<% @statuses.each do |status| %>
<div>
<strong><%= status.name %></strong>
<p><%= status.content %></p>
</div>
<div class="meta"><%= link_to 'Show', status %></div>
<div class="admin"><%= link_to 'Edit', edit_status_path(status) %> | <%=
link_to 'Delete', admin_status_path(status.id), :method=>delete,
:class=>destroy, :confirm=>"Are you sure you want to delete this
status?" %></div>
<% end %>
group by two columns and adding new key per type in array
group by two columns and adding new key per type in array
Here's my table:
date | capacity
10/09/13 | 100
10/09/13 | 50
10/09/13 | 100
08/09/13 | 100
Low capacity is 50 and high capacity is 100.
I'm trying to retrieve an average capacity per day per capacity type. So
the expected result is:
10/09/13-
low capacity average: 50
high capacity average: 100
08/09/13-
low capacity average: 0
high capacity average: 100
My query at the moment is: SELECT date, capacity FROM table GROUP BY date,
capacity
What should I add in order to present the customized capacity types (low,
high) in array?
something like:
$array =
[['date'=>'10/09/13','high_capacity'=>100,'low_capacity'=>50],['date'=>'08/09/13','high_capacity'=>100,'low_capacity'=>0]];
Thanks!
Here's my table:
date | capacity
10/09/13 | 100
10/09/13 | 50
10/09/13 | 100
08/09/13 | 100
Low capacity is 50 and high capacity is 100.
I'm trying to retrieve an average capacity per day per capacity type. So
the expected result is:
10/09/13-
low capacity average: 50
high capacity average: 100
08/09/13-
low capacity average: 0
high capacity average: 100
My query at the moment is: SELECT date, capacity FROM table GROUP BY date,
capacity
What should I add in order to present the customized capacity types (low,
high) in array?
something like:
$array =
[['date'=>'10/09/13','high_capacity'=>100,'low_capacity'=>50],['date'=>'08/09/13','high_capacity'=>100,'low_capacity'=>0]];
Thanks!
How do I get containsignorecase for java?
How do I get containsignorecase for java?
I am trying to use contains for strings coinciding with the search
symbols. However, seems like contains does not have an ignore case unlike
equals. Is there any way to go around ?
The following line of code is where I am using the same (I have heard of
pattern, but how do I use the same in my case? )
searchSymbol.contains(mSearchView.getText().toString()
Thanks! Justin
I am trying to use contains for strings coinciding with the search
symbols. However, seems like contains does not have an ignore case unlike
equals. Is there any way to go around ?
The following line of code is where I am using the same (I have heard of
pattern, but how do I use the same in my case? )
searchSymbol.contains(mSearchView.getText().toString()
Thanks! Justin
Matlab extend plot over all axis range
Matlab extend plot over all axis range
I'm trying to use Matlab for some data plotting. In particular I need to
plot a series of lines, some times given two points belonging to it, some
times given the orthogonal vector.
I've used the following to obtain the plot of the line:
Line given two points A = [A(1), A(2)] B = [B(1), B(2)]:
plot([A(1),B(1)],[A(2),B(2)])
Line given the vector W = [W(1), W(2)]':
if( W(1) == 0 )
plot( [W(1), rand(1)] ,[W(2), W(2)])
else
plot([W(1), W(1) + (W(2)^2 / W(1))],[W(2),0])
end
where I'm calculating the intersection between the x-axis and the line
using the second theorem of Euclid on the triangle rectangle formed by the
vector W and the line.
My problem as you can see from the picture above is that the line will
only be plotted between the two points and not on all the range of my
axis.
I have 2 questions:
How can I have a line going across the whole axis range?
Is there a more easy and direct way (maybe a function?) to plot the line
perpendicular to a vector? (An easier and more clean way to solve point 2
above.)
Thanks in advance.
I'm trying to use Matlab for some data plotting. In particular I need to
plot a series of lines, some times given two points belonging to it, some
times given the orthogonal vector.
I've used the following to obtain the plot of the line:
Line given two points A = [A(1), A(2)] B = [B(1), B(2)]:
plot([A(1),B(1)],[A(2),B(2)])
Line given the vector W = [W(1), W(2)]':
if( W(1) == 0 )
plot( [W(1), rand(1)] ,[W(2), W(2)])
else
plot([W(1), W(1) + (W(2)^2 / W(1))],[W(2),0])
end
where I'm calculating the intersection between the x-axis and the line
using the second theorem of Euclid on the triangle rectangle formed by the
vector W and the line.
My problem as you can see from the picture above is that the line will
only be plotted between the two points and not on all the range of my
axis.
I have 2 questions:
How can I have a line going across the whole axis range?
Is there a more easy and direct way (maybe a function?) to plot the line
perpendicular to a vector? (An easier and more clean way to solve point 2
above.)
Thanks in advance.
How to position an element dead center in fluid layout with variable height?
How to position an element dead center in fluid layout with variable height?
Need to position box-inside div dead center to the wrapper div, where the
wrapper div's height depends on the sidebar div height. The box-inside div
was positioned absolute in relative to the wrapper div, and sets a
variable width and height which is respective to the images and content
inside it.
This can be accomplish by giving width and height to the box-inside div,
but have to do with variable width and height.(the box-inside div have to
be in same dimension as the img with padding)
The jsFiddle code here
This is the HTML code:
<body>
<div class="wrapper">
<div class="sidebar"></div>
<div class="inside-box">
<img src="badge.gif" />
</div>
</div>
</body>
The CSS
* {
margin: 0;
}
html,body {
height: 100%;
}
body {
background: white;
display: block;
font-family: Tahoma, Geneva, sans-serif;
margin: 0;
padding: 0;
}
.wrapper {
position:relative;
height: auto;
width:70%;
margin: 0 auto ;
background:green;
}
.sidebar {
height: 500px;
width:30%;
background: red;
clear:both;
}
.inside-box {
margin: auto;
position: absolute;
top: 0; left: 0; bottom: 0; right: 0;
background:yellow;
min-width:275px; min-height:183px;
padding:10px;
}
Currently
Expected Output
Need to position box-inside div dead center to the wrapper div, where the
wrapper div's height depends on the sidebar div height. The box-inside div
was positioned absolute in relative to the wrapper div, and sets a
variable width and height which is respective to the images and content
inside it.
This can be accomplish by giving width and height to the box-inside div,
but have to do with variable width and height.(the box-inside div have to
be in same dimension as the img with padding)
The jsFiddle code here
This is the HTML code:
<body>
<div class="wrapper">
<div class="sidebar"></div>
<div class="inside-box">
<img src="badge.gif" />
</div>
</div>
</body>
The CSS
* {
margin: 0;
}
html,body {
height: 100%;
}
body {
background: white;
display: block;
font-family: Tahoma, Geneva, sans-serif;
margin: 0;
padding: 0;
}
.wrapper {
position:relative;
height: auto;
width:70%;
margin: 0 auto ;
background:green;
}
.sidebar {
height: 500px;
width:30%;
background: red;
clear:both;
}
.inside-box {
margin: auto;
position: absolute;
top: 0; left: 0; bottom: 0; right: 0;
background:yellow;
min-width:275px; min-height:183px;
padding:10px;
}
Currently
Expected Output
Fast Scrolling Thumb appears only from top
Fast Scrolling Thumb appears only from top
I am stuck with a problem regarding Fast scrolling with section Indexer in
list view. The thumb only appears from top in xhdpi devices and working
very slow. Where as it worked properly in other devices. Please give me
any solution.
I am stuck with a problem regarding Fast scrolling with section Indexer in
list view. The thumb only appears from top in xhdpi devices and working
very slow. Where as it worked properly in other devices. Please give me
any solution.
Subscribe to:
Comments (Atom)