Padding is invalid and cannot be removed in C# licensing method
in my project I'm Doing a licensing method where after the user enters the
license key his product will be activated. Im using the following code but
I'm getting an exception thrown saying "Padding is invalid and cannot be
removed". The following is my code
public void ValidateProductKey()
{
RSACryptoServiceProvider _cryptoService = new
RSACryptoServiceProvider();
string productKey = "G7MA4Z5VR5R3LG001AS1N5HA3YHX05";
byte[] keyBytes =
Base32Converter.FromBase32String(productKey);
//Base32Converter is my customized method which returns byte
of values;
byte[] signBytes = new byte[2];
byte[] hiddenBytes = new byte[16];
using (MemoryStream stream = new MemoryStream(keyBytes))
{
stream.Read(hiddenBytes, 0, 8);
stream.Read(signBytes, 0, 2);
stream.Read(hiddenBytes, 8, hiddenBytes.Length - 8);
keyBytes = stream.ToArray();
}
byte[] sign = _cryptoService.SignData(signBytes, new
SHA1CryptoServiceProvider());
byte[] rkey = new byte[32];
byte[] rjiv = new byte[16];
Array.Copy(sign, rkey, 32);
Array.Copy(sign, 32, rjiv, 0, 16);
SymmetricAlgorithm algorithm = new RijndaelManaged();
try
{
hiddenData = algorithm.CreateDecryptor(rkey,
rjiv).TransformFinalBlock(hiddenBytes,0,hiddenBytes.Length);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
When reaching the "hiddenData" variable I get an exception thrown as
"Padding is invalid and cannot be removed". Any help would be really
appreciated.
Thursday, 3 October 2013
Wednesday, 2 October 2013
Collection and toArray in Scala
Collection and toArray in Scala
Java code:
Collection<MethodInfo> items = getItems();
MethodInfo[] itemsArray = methods.toArray(new MethodInfo[methods.size()]);
I wonder, what would be the equivalent code in Scala?
val items: Seq[MethodInfo] = getItems
val itemsArray: Array[MethodInfo] = ???
Java code:
Collection<MethodInfo> items = getItems();
MethodInfo[] itemsArray = methods.toArray(new MethodInfo[methods.size()]);
I wonder, what would be the equivalent code in Scala?
val items: Seq[MethodInfo] = getItems
val itemsArray: Array[MethodInfo] = ???
Very basic Java nested for loop issue
Very basic Java nested for loop issue
I'm having a hard time trying to get this code to start at 5 spaces and
reduce to 0 spaces, subtracting a space every line.
public class Prob3 {
public static void main(String[]args) {
for (int x=1; x<=5; x++)
{
for (int y=5; y>=1; y--)
{
System.out.print(" ");
}
System.out.println(x);
}
}
}
Current output is (should be 5 spaces):
5
4
3
2
1
I'm happy with the progress so far but I need to get something closer to
this:
1
2
3
4
5
I feel like I'm pretty close
Edit got it.
public class Prob3 {
public static void main(String[]args) {
for (int x=1; x<=5; x++)
{
for (int y=5; y>=x; y--)
{
System.out.print(" ");
}
System.out.println(x);
}
}
}
I'm having a hard time trying to get this code to start at 5 spaces and
reduce to 0 spaces, subtracting a space every line.
public class Prob3 {
public static void main(String[]args) {
for (int x=1; x<=5; x++)
{
for (int y=5; y>=1; y--)
{
System.out.print(" ");
}
System.out.println(x);
}
}
}
Current output is (should be 5 spaces):
5
4
3
2
1
I'm happy with the progress so far but I need to get something closer to
this:
1
2
3
4
5
I feel like I'm pretty close
Edit got it.
public class Prob3 {
public static void main(String[]args) {
for (int x=1; x<=5; x++)
{
for (int y=5; y>=x; y--)
{
System.out.print(" ");
}
System.out.println(x);
}
}
}
too few arguments in function call error
too few arguments in function call error
Doing an assignment to calculate the area and volume of different shapes.
Stuck is an understatement. Get an error claiming 'showMenu': function
does not take 0 arguments & a also a too few arguments in function call
error. Any pointers on how to fix this?
#include <iostream>
#include <iomanip>
using namespace std;
//Functions
void showMenu(int &);
double area (double, double);
double area (double);
double volume (double, double, double);
double volume (double);
const double PI = 3.14;
int main()
{
int choice;
double area, volume, length, width, radius, height;
const double PI = 3.14;
do
{
showMenu();
cin >> choice;
if (choice < 1 || choice > 5 )
{
cout << "Please select a valid choice of 1-5: " << endl;
cin >> choice;
}
else if (choice == 1)
{
double tarea(area);
cout << "Enter the length: ";
cin >> length;
cout << "Enter the width: ";
cin >> width;
cout << "The area of the rectangle is: " << tarea << endl;
}
else if (choice == 2)
{
double tarea(area);
cout << "Enter the radius: ";
cin >> radius;
cout << "The area of the circle is: " << tarea << endl;
}
else if (choice == 3)
{
double tvolume (volume);
cout << "Enter the length: ";
cin >> length;
cout << "Enter the width: ";
cin >> width;
cout << "Enter the height: ";
cin >> height;
cout << "The volume for a box is: " << tvolume << endl;
}
else if (choice == 4)
{
double tvolume (volume);
cout << "Enter the radius: ";
cin >> radius;
cout << "The volume of a sphere is: " << endl;
}
}
while (choice != 5);
return 0;
}
void ShowMenu(int &choice)
{
cout << "1. Calculate the area of a rectangle";
cout << "2. Calculate the area of a circle";
cout << "3. Calculate the volume for a box";
cout << "4. Calculate the volume of a sphere";
cout << "5. Quit";
}
double area (double length, double width)
{
double tarea = length * width;
return tarea;
}
double area (double radius)
{
double tarea = PI * (radius * radius);
return tarea;
}
double volume (double length, double width, double height)
{
double tvolume = length * width * height;
return tvolume;
}
double volume (double radius)
{
double tvolume = (4/3) * PI * (radius * radius * radius);
return tvolume;
}
Doing an assignment to calculate the area and volume of different shapes.
Stuck is an understatement. Get an error claiming 'showMenu': function
does not take 0 arguments & a also a too few arguments in function call
error. Any pointers on how to fix this?
#include <iostream>
#include <iomanip>
using namespace std;
//Functions
void showMenu(int &);
double area (double, double);
double area (double);
double volume (double, double, double);
double volume (double);
const double PI = 3.14;
int main()
{
int choice;
double area, volume, length, width, radius, height;
const double PI = 3.14;
do
{
showMenu();
cin >> choice;
if (choice < 1 || choice > 5 )
{
cout << "Please select a valid choice of 1-5: " << endl;
cin >> choice;
}
else if (choice == 1)
{
double tarea(area);
cout << "Enter the length: ";
cin >> length;
cout << "Enter the width: ";
cin >> width;
cout << "The area of the rectangle is: " << tarea << endl;
}
else if (choice == 2)
{
double tarea(area);
cout << "Enter the radius: ";
cin >> radius;
cout << "The area of the circle is: " << tarea << endl;
}
else if (choice == 3)
{
double tvolume (volume);
cout << "Enter the length: ";
cin >> length;
cout << "Enter the width: ";
cin >> width;
cout << "Enter the height: ";
cin >> height;
cout << "The volume for a box is: " << tvolume << endl;
}
else if (choice == 4)
{
double tvolume (volume);
cout << "Enter the radius: ";
cin >> radius;
cout << "The volume of a sphere is: " << endl;
}
}
while (choice != 5);
return 0;
}
void ShowMenu(int &choice)
{
cout << "1. Calculate the area of a rectangle";
cout << "2. Calculate the area of a circle";
cout << "3. Calculate the volume for a box";
cout << "4. Calculate the volume of a sphere";
cout << "5. Quit";
}
double area (double length, double width)
{
double tarea = length * width;
return tarea;
}
double area (double radius)
{
double tarea = PI * (radius * radius);
return tarea;
}
double volume (double length, double width, double height)
{
double tvolume = length * width * height;
return tvolume;
}
double volume (double radius)
{
double tvolume = (4/3) * PI * (radius * radius * radius);
return tvolume;
}
How to run remote ssh session from Jenkins with sudo rights?
How to run remote ssh session from Jenkins with sudo rights?
Using 'Execute shell script on remote host using ssh' option and need sudo
rights on remote server to change permissions and remove protected files.
How to run session with this rights?
Getting message
sudo: sorry, you must have a tty to run sudo
when trying to run sudo command.
Using 'Execute shell script on remote host using ssh' option and need sudo
rights on remote server to change permissions and remove protected files.
How to run session with this rights?
Getting message
sudo: sorry, you must have a tty to run sudo
when trying to run sudo command.
Tuesday, 1 October 2013
Convert MySQL query from a nested select to an inner join
Convert MySQL query from a nested select to an inner join
I have a nested select statement that works as it should, the only problem
is that it takes too long to run. I converted one of my other queries to
an inner join and it is much much faster. I'm trying to convert this query
to an inner join.
Current working query:
select date(datetime), req_origin, count( distinct session_id)
from LOG L1
where((datetime >= str_to_date('2013-01-01 00:00:00','%Y-%m-%d %H:%i:%s'))
and (datetime < str_to_date('2013-01-05 00:00:00','%Y-%m-%d %H:%i:%s'))
and code_subcode in ('1001111','1001112','1001113','1001114'))
and ((
select count(*) from LOG L2 where L2.session_id = L1.session_id and
date(L2.datetime)
= date(L1.datetime)
and code_subcode in ('1001111','1001112','1001113','1001114')
) = 4)
group by date(datetime),req_origin order by date(datetime),req_origin;
This is what I've got for an inner join but it isn't working properly. It
only returns data when check for 1 matching code. When I query for 4
matching codes the query doesn't return anything.
select date(l1.datetime), l1.req_origin, count(distinct l1.session_id)
from LOG l1
INNER JOIN LOG l2 on l2.SESSION_ID = l1.SESSION_ID
where((l1.datetime >= str_to_date('2013-01-01 00:00:00','%Y-%m-%d %H:%i:%s'))
and (l1.datetime < str_to_date('2013-01-05 00:00:00','%Y-%m-%d %H:%i:%s'))
and l1.code_subcode in ('1001111','1001112','1001113','1001114')
and l2.code_subcode in ('1001111','1001112','1001113','1001114') = 4)
group by date(l1.datetime), l1.req_origin order by date(l1.datetime),
l1.req_origin;
Thanks in advance for any help!
I have a nested select statement that works as it should, the only problem
is that it takes too long to run. I converted one of my other queries to
an inner join and it is much much faster. I'm trying to convert this query
to an inner join.
Current working query:
select date(datetime), req_origin, count( distinct session_id)
from LOG L1
where((datetime >= str_to_date('2013-01-01 00:00:00','%Y-%m-%d %H:%i:%s'))
and (datetime < str_to_date('2013-01-05 00:00:00','%Y-%m-%d %H:%i:%s'))
and code_subcode in ('1001111','1001112','1001113','1001114'))
and ((
select count(*) from LOG L2 where L2.session_id = L1.session_id and
date(L2.datetime)
= date(L1.datetime)
and code_subcode in ('1001111','1001112','1001113','1001114')
) = 4)
group by date(datetime),req_origin order by date(datetime),req_origin;
This is what I've got for an inner join but it isn't working properly. It
only returns data when check for 1 matching code. When I query for 4
matching codes the query doesn't return anything.
select date(l1.datetime), l1.req_origin, count(distinct l1.session_id)
from LOG l1
INNER JOIN LOG l2 on l2.SESSION_ID = l1.SESSION_ID
where((l1.datetime >= str_to_date('2013-01-01 00:00:00','%Y-%m-%d %H:%i:%s'))
and (l1.datetime < str_to_date('2013-01-05 00:00:00','%Y-%m-%d %H:%i:%s'))
and l1.code_subcode in ('1001111','1001112','1001113','1001114')
and l2.code_subcode in ('1001111','1001112','1001113','1001114') = 4)
group by date(l1.datetime), l1.req_origin order by date(l1.datetime),
l1.req_origin;
Thanks in advance for any help!
Cannot figure out an Excel formula
Cannot figure out an Excel formula
I have tried every answer I could find on the boards and I could not get
this to work....
I want to check for a cell match in another column on a different
worksheet and if it finds one it will copy the cells from the same row
from four specific columns to four specific columns.
Here is the logic: If Sheet1 B2 is equal to Sheet2 Column K Any Row in
then return Sheet2 Column A,B,C,E from the same row of the match to Sheet1
I2,J2,K2,L2
Thank you so very much for any guidence you can give me! ~Brian
I have tried every answer I could find on the boards and I could not get
this to work....
I want to check for a cell match in another column on a different
worksheet and if it finds one it will copy the cells from the same row
from four specific columns to four specific columns.
Here is the logic: If Sheet1 B2 is equal to Sheet2 Column K Any Row in
then return Sheet2 Column A,B,C,E from the same row of the match to Sheet1
I2,J2,K2,L2
Thank you so very much for any guidence you can give me! ~Brian
StackOverflow is not your Programming 101 Teacher meta.stackoverflow.com
StackOverflow is not your Programming 101 Teacher – meta.stackoverflow.com
I would like to help my fellow professionals and amateurs more on
StackOverflow, but it's become impossible to find questions worth spending
time on beneath the inundation of "teach me to program" ...
I would like to help my fellow professionals and amateurs more on
StackOverflow, but it's become impossible to find questions worth spending
time on beneath the inundation of "teach me to program" ...
Ubuntu 13.04 unable to mount my lumia 720
Ubuntu 13.04 unable to mount my lumia 720
I shifted permanently from the windows 8 to the Ubuntu, but I have a
windows phone and I need to sync music pictures books. But in Ubuntu 13.04
I cannot mount the device and displays error.
Foremost I need to mount the device to perform any action.
I shifted permanently from the windows 8 to the Ubuntu, but I have a
windows phone and I need to sync music pictures books. But in Ubuntu 13.04
I cannot mount the device and displays error.
Foremost I need to mount the device to perform any action.
Monday, 30 September 2013
Any reference ,$f(x)=x*e^x-2$? [on hold]
Any reference ,$f(x)=x*e^x-2$? [on hold]
$f(x)=x*e^{x}-2$
$f(0)=-2$
$f(1)=e-2$
$x_{1}=x_{0}-\frac{f(x)}{f^{'}(x)}$
A better book to refer for this.
$f(x)=x*e^{x}-2$
$f(0)=-2$
$f(1)=e-2$
$x_{1}=x_{0}-\frac{f(x)}{f^{'}(x)}$
A better book to refer for this.
How to configure Single-Server Private Network in Xenserver without using VLAN?
How to configure Single-Server Private Network in Xenserver without using
VLAN?
I would like to create a Single Server private Network on a Xenserver
which will be used for communication between the host and the VMs. I am
able to achive this by creating a vlan and configuring the pif.
But when looking at the XenCenter, there is an explicit option to create
such a network without the VLAN stuff. Where would I configure it using xe
or Xencenter commands? I can see it in network-list, ifconfig and brctl,
but where would I set the local IPs?
VLAN?
I would like to create a Single Server private Network on a Xenserver
which will be used for communication between the host and the VMs. I am
able to achive this by creating a vlan and configuring the pif.
But when looking at the XenCenter, there is an explicit option to create
such a network without the VLAN stuff. Where would I configure it using xe
or Xencenter commands? I can see it in network-list, ifconfig and brctl,
but where would I set the local IPs?
Android selector draw doesn't overlap
Android selector draw doesn't overlap
My problem is when my checkableLinearLayout is checked my draw from the
selector can´t overlap the unchecked image.
My checkableLinearLayout
public class CheckableLinearLayout extends LinearLayout implements
Checkable {
private boolean mChecked;
private static final String TAG = CheckableLinearLayout.class
.getCanonicalName();
private static final int[] CHECKED_STATE_SET = {
android.R.attr.state_checked };
public CheckableLinearLayout(final Context context) {
super(context);
setClickable(true);
setLongClickable(true);
}
public CheckableLinearLayout(final Context context, final AttributeSet
attrs) {
super(context, attrs);
setClickable(true);
setLongClickable(true);
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
public CheckableLinearLayout(final Context context,
final AttributeSet attrs, final int defStyle) {
super(context, attrs, defStyle);
setClickable(true);
setLongClickable(true);
}
@Override
public void setChecked(final boolean checked) {
mChecked = checked;
refreshDrawableState();
}
@Override
protected int[] onCreateDrawableState(final int extraSpace) {
final int[] drawableState = super.onCreateDrawableState(extraSpace + 1);
if (isChecked())
mergeDrawableStates(drawableState, CHECKED_STATE_SET);
return drawableState;
}
@Override
protected void drawableStateChanged() {
super.drawableStateChanged();
final Drawable drawable = getBackground();
if (drawable != null) {
final int[] myDrawableState = getDrawableState();
drawable.setState(myDrawableState);
invalidate();
}
}
@Override
public boolean performClick() {
Toast.makeText(getContext(), "click", Toast.LENGTH_SHORT).show();
if (isChecked()) {
toggle();
return false;
} else
return super.performClick();
}
@Override
public boolean performLongClick() {
toggle();
Toast.makeText(getContext(), "long click", Toast.LENGTH_SHORT).show();
return super.performLongClick();
}
@Override
public boolean isChecked() {
return mChecked;
}
@Override
public void toggle() {
setChecked(!mChecked);
}
@Override
public Parcelable onSaveInstanceState() {
// Force our ancestor class to save its state
final Parcelable superState = super.onSaveInstanceState();
final SavedState savedState = new SavedState(superState);
savedState.checked = isChecked();
return savedState;
}
@Override
public void onRestoreInstanceState(final Parcelable state) {
final SavedState savedState = (SavedState) state;
super.onRestoreInstanceState(savedState.getSuperState());
setChecked(savedState.checked);
requestLayout();
}
// /////////////
// SavedState //
// /////////////
private static class SavedState extends BaseSavedState {
boolean checked;
@SuppressWarnings("unused")
public static final Parcelable.Creator<SavedState> CREATOR;
static {
CREATOR = new Parcelable.Creator<SavedState>() {
@Override
public SavedState createFromParcel(final Parcel in) {
return new SavedState(in);
}
@Override
public SavedState[] newArray(final int size) {
return new SavedState[size];
}
};
}
SavedState(final Parcelable superState) {
super(superState);
}
private SavedState(final Parcel in) {
super(in);
checked = (Boolean) in.readValue(null);
}
@Override
public void writeToParcel(final Parcel out, final int flags) {
super.writeToParcel(out, flags);
out.writeValue(checked);
}
@Override
public String toString() {
return TAG + ".SavedState{"
+ Integer.toHexString(System.identityHashCode(this))
+ " checked=" + checked + "}";
}
}
}
My layout.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/topics_preview_main_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<LinearLayout
android:id="@+id/favorites_header_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="6dp"
android:layout_marginRight="6dp"
android:layout_marginTop="2dp"
android:orientation="vertical" >
<TextView
android:id="@+id/favorites_header_title"
style="@style/CardText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="4dp"
android:layout_marginLeft="6dp"
android:layout_marginRight="6dp"
android:layout_marginTop="4dp"
android:background="@drawable/card"
android:gravity="left"
android:paddingBottom="10dp"
android:paddingLeft="5dp"
android:paddingTop="10dp"
android:text="@string/favorites_header" />
<ui.CheckableLinearLayout
android:id="@+id/favorites_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="4dp"
android:layout_marginLeft="6dp"
android:layout_marginRight="6dp"
android:layout_marginTop="4dp"
android:background="@drawable/card_selector_w_shadow"
android:clickable="true"
android:longClickable="true"
android:orientation="vertical"
android:paddingBottom="16dp" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:paddingLeft="8dp"
android:paddingRight="8dp" >
<TextView
android:id="@+id/favorites_title"
style="@style/CardTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="title" />
</LinearLayout>
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_marginTop="4dp"
android:background="@color/C_Favorites_Pink" />
<LinearLayout
android:id="@+id/favorites_description_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:orientation="vertical"
android:padding="4dp" >
<TextView
android:id="@+id/favorites_description"
style="@style/CardText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="8dp"
android:ellipsize="end"
android:maxLines="4"
android:text="Lorem ipsum ..." />
</LinearLayout>
</ui.CheckableLinearLayout>
</LinearLayout>
My drawable -> this draw will call the selector
<?xml version="1.0" encoding="utf-8"?>
<item>
<shape
android:dither="true"
android:shape="rectangle" >
<corners android:radius="2dp" />
<solid android:color="#ccc" />
</shape>
</item>
<item android:bottom="2dp">
<shape
android:dither="true"
android:shape="rectangle" >
<corners android:radius="2dp" />
<solid android:color="@android:color/white" />
<padding
android:bottom="8dp"
android:left="8dp"
android:right="8dp"
android:top="8dp" />
</shape>
</item>
<item android:drawable="@drawable/drawable_states"/>
My selector xml
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/checked_background"
android:state_checked="true"/>
This is whats happening:
This is what i pretend:
My problem is when my checkableLinearLayout is checked my draw from the
selector can´t overlap the unchecked image.
My checkableLinearLayout
public class CheckableLinearLayout extends LinearLayout implements
Checkable {
private boolean mChecked;
private static final String TAG = CheckableLinearLayout.class
.getCanonicalName();
private static final int[] CHECKED_STATE_SET = {
android.R.attr.state_checked };
public CheckableLinearLayout(final Context context) {
super(context);
setClickable(true);
setLongClickable(true);
}
public CheckableLinearLayout(final Context context, final AttributeSet
attrs) {
super(context, attrs);
setClickable(true);
setLongClickable(true);
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
public CheckableLinearLayout(final Context context,
final AttributeSet attrs, final int defStyle) {
super(context, attrs, defStyle);
setClickable(true);
setLongClickable(true);
}
@Override
public void setChecked(final boolean checked) {
mChecked = checked;
refreshDrawableState();
}
@Override
protected int[] onCreateDrawableState(final int extraSpace) {
final int[] drawableState = super.onCreateDrawableState(extraSpace + 1);
if (isChecked())
mergeDrawableStates(drawableState, CHECKED_STATE_SET);
return drawableState;
}
@Override
protected void drawableStateChanged() {
super.drawableStateChanged();
final Drawable drawable = getBackground();
if (drawable != null) {
final int[] myDrawableState = getDrawableState();
drawable.setState(myDrawableState);
invalidate();
}
}
@Override
public boolean performClick() {
Toast.makeText(getContext(), "click", Toast.LENGTH_SHORT).show();
if (isChecked()) {
toggle();
return false;
} else
return super.performClick();
}
@Override
public boolean performLongClick() {
toggle();
Toast.makeText(getContext(), "long click", Toast.LENGTH_SHORT).show();
return super.performLongClick();
}
@Override
public boolean isChecked() {
return mChecked;
}
@Override
public void toggle() {
setChecked(!mChecked);
}
@Override
public Parcelable onSaveInstanceState() {
// Force our ancestor class to save its state
final Parcelable superState = super.onSaveInstanceState();
final SavedState savedState = new SavedState(superState);
savedState.checked = isChecked();
return savedState;
}
@Override
public void onRestoreInstanceState(final Parcelable state) {
final SavedState savedState = (SavedState) state;
super.onRestoreInstanceState(savedState.getSuperState());
setChecked(savedState.checked);
requestLayout();
}
// /////////////
// SavedState //
// /////////////
private static class SavedState extends BaseSavedState {
boolean checked;
@SuppressWarnings("unused")
public static final Parcelable.Creator<SavedState> CREATOR;
static {
CREATOR = new Parcelable.Creator<SavedState>() {
@Override
public SavedState createFromParcel(final Parcel in) {
return new SavedState(in);
}
@Override
public SavedState[] newArray(final int size) {
return new SavedState[size];
}
};
}
SavedState(final Parcelable superState) {
super(superState);
}
private SavedState(final Parcel in) {
super(in);
checked = (Boolean) in.readValue(null);
}
@Override
public void writeToParcel(final Parcel out, final int flags) {
super.writeToParcel(out, flags);
out.writeValue(checked);
}
@Override
public String toString() {
return TAG + ".SavedState{"
+ Integer.toHexString(System.identityHashCode(this))
+ " checked=" + checked + "}";
}
}
}
My layout.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/topics_preview_main_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<LinearLayout
android:id="@+id/favorites_header_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="6dp"
android:layout_marginRight="6dp"
android:layout_marginTop="2dp"
android:orientation="vertical" >
<TextView
android:id="@+id/favorites_header_title"
style="@style/CardText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="4dp"
android:layout_marginLeft="6dp"
android:layout_marginRight="6dp"
android:layout_marginTop="4dp"
android:background="@drawable/card"
android:gravity="left"
android:paddingBottom="10dp"
android:paddingLeft="5dp"
android:paddingTop="10dp"
android:text="@string/favorites_header" />
<ui.CheckableLinearLayout
android:id="@+id/favorites_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="4dp"
android:layout_marginLeft="6dp"
android:layout_marginRight="6dp"
android:layout_marginTop="4dp"
android:background="@drawable/card_selector_w_shadow"
android:clickable="true"
android:longClickable="true"
android:orientation="vertical"
android:paddingBottom="16dp" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:paddingLeft="8dp"
android:paddingRight="8dp" >
<TextView
android:id="@+id/favorites_title"
style="@style/CardTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="title" />
</LinearLayout>
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_marginTop="4dp"
android:background="@color/C_Favorites_Pink" />
<LinearLayout
android:id="@+id/favorites_description_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:orientation="vertical"
android:padding="4dp" >
<TextView
android:id="@+id/favorites_description"
style="@style/CardText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="8dp"
android:ellipsize="end"
android:maxLines="4"
android:text="Lorem ipsum ..." />
</LinearLayout>
</ui.CheckableLinearLayout>
</LinearLayout>
My drawable -> this draw will call the selector
<?xml version="1.0" encoding="utf-8"?>
<item>
<shape
android:dither="true"
android:shape="rectangle" >
<corners android:radius="2dp" />
<solid android:color="#ccc" />
</shape>
</item>
<item android:bottom="2dp">
<shape
android:dither="true"
android:shape="rectangle" >
<corners android:radius="2dp" />
<solid android:color="@android:color/white" />
<padding
android:bottom="8dp"
android:left="8dp"
android:right="8dp"
android:top="8dp" />
</shape>
</item>
<item android:drawable="@drawable/drawable_states"/>
My selector xml
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/checked_background"
android:state_checked="true"/>
This is whats happening:
This is what i pretend:
Continue slideshow with Unslider
Continue slideshow with Unslider
I'm using Unslider at the moment and I'm wondering if there is any way to
make the slideshow continue to the right when switching from the last
slide to the first one. At the moment it goes through all the slides from
right to left when jumping to the first one from the last.
If that isn't possible, is it possible to make it go backwards from the
last one instead? Like this:
1 - 2 - 3 - 4 // 4 - 3 - 2 - 1 // 1 - 2 - 3...
Really appreciate answers! Thanks!
I'm using Unslider at the moment and I'm wondering if there is any way to
make the slideshow continue to the right when switching from the last
slide to the first one. At the moment it goes through all the slides from
right to left when jumping to the first one from the last.
If that isn't possible, is it possible to make it go backwards from the
last one instead? Like this:
1 - 2 - 3 - 4 // 4 - 3 - 2 - 1 // 1 - 2 - 3...
Really appreciate answers! Thanks!
Sunday, 29 September 2013
Onchange 1st date picker, 2nd datepicker will change
Onchange 1st date picker, 2nd datepicker will change
in my form, i have 2 datepicker (eg : date1, date2). Date1 is approval
deadline and date2 is confirmation daedline. Approval deadline should be
equal or more than confirmation deadline.
So. I want if user change date2, date1 will automatically change
accordingly (same as input for date2). But whenever date1 is change, it
will effect itself only (only date1 change). Hopefully you can understand
this situation.
I think that this can be done using jquery, but i'am new in jquery, i hope
that you guys can help me. Thanks.
in my form, i have 2 datepicker (eg : date1, date2). Date1 is approval
deadline and date2 is confirmation daedline. Approval deadline should be
equal or more than confirmation deadline.
So. I want if user change date2, date1 will automatically change
accordingly (same as input for date2). But whenever date1 is change, it
will effect itself only (only date1 change). Hopefully you can understand
this situation.
I think that this can be done using jquery, but i'am new in jquery, i hope
that you guys can help me. Thanks.
Global variable not staying set, maybe caused by fork()
Global variable not staying set, maybe caused by fork()
I'm trying to write a very very simple unix shell in C, and I have the
basics of what I need working, except support for a history command. I
have a global 2D char array that holds the history of all entered
commands. Commands are added before the fork() system call, and I was
originally printing out the value of the history global array after
strings were added, and they were printing out correctly, so I'm not sure
why it doesn't print out when the command "history" is used at the shell.
Thank to anyone who takes a look.
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include "myhistory.h"
int BUFFER_SIZE = 1024;
char history[100][80];
int command_index = 0;
int main(int argc, char *argv[]){
int status = 0;
int num_args;
pid_t pid;
while(1){
char *buffer_input, *full_input;
char command[BUFFER_SIZE];
char *args[BUFFER_SIZE];
printf("myshell> ");
buffer_input = fgets(command, 1024, stdin);
full_input = malloc(strlen(buffer_input)+1);
strcpy(full_input, buffer_input);
if (command_index >= 100) {
command_index = 0;
}
strncpy(history[command_index], full_input, strlen(full_input) + 1);
command_index += 1;
parse_input(command, args, BUFFER_SIZE, &num_args);
//check exit and special command conditions
if (num_args==0)
continue;
if (!strcmp(command, "quit" )){
exit(0);
}
if(!strcmp(command, "history")){
int i;
fprintf(stderr,"%d\n",(int)pid);
for(i = 0; i < command_index; i++){
fprintf(stdout, "%d: %s\n",i+1,history[command_index]);
}
continue;
}
errno = 0;
pid = fork();
if(errno != 0){
perror("Error in fork()");
}
if (pid) {
pid = wait(&status);
} else {
if( execvp(args[0], args)) {
perror("executing command failed");
exit(1);
}
}
}
return 0;
}
void parse_input(char *input, char** args,
int args_size, int *nargs){
char *buffer[BUFFER_SIZE];
buffer[0] = input;
int i = 0;
while((buffer[i] = strtok(buffer[i], " \n\t")) != NULL){
i++;
}
for(i = 0; buffer[i] != NULL; i++){
args[i] = buffer[i];
}
*nargs = i;
args[i] = NULL;
}
I'm trying to write a very very simple unix shell in C, and I have the
basics of what I need working, except support for a history command. I
have a global 2D char array that holds the history of all entered
commands. Commands are added before the fork() system call, and I was
originally printing out the value of the history global array after
strings were added, and they were printing out correctly, so I'm not sure
why it doesn't print out when the command "history" is used at the shell.
Thank to anyone who takes a look.
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include "myhistory.h"
int BUFFER_SIZE = 1024;
char history[100][80];
int command_index = 0;
int main(int argc, char *argv[]){
int status = 0;
int num_args;
pid_t pid;
while(1){
char *buffer_input, *full_input;
char command[BUFFER_SIZE];
char *args[BUFFER_SIZE];
printf("myshell> ");
buffer_input = fgets(command, 1024, stdin);
full_input = malloc(strlen(buffer_input)+1);
strcpy(full_input, buffer_input);
if (command_index >= 100) {
command_index = 0;
}
strncpy(history[command_index], full_input, strlen(full_input) + 1);
command_index += 1;
parse_input(command, args, BUFFER_SIZE, &num_args);
//check exit and special command conditions
if (num_args==0)
continue;
if (!strcmp(command, "quit" )){
exit(0);
}
if(!strcmp(command, "history")){
int i;
fprintf(stderr,"%d\n",(int)pid);
for(i = 0; i < command_index; i++){
fprintf(stdout, "%d: %s\n",i+1,history[command_index]);
}
continue;
}
errno = 0;
pid = fork();
if(errno != 0){
perror("Error in fork()");
}
if (pid) {
pid = wait(&status);
} else {
if( execvp(args[0], args)) {
perror("executing command failed");
exit(1);
}
}
}
return 0;
}
void parse_input(char *input, char** args,
int args_size, int *nargs){
char *buffer[BUFFER_SIZE];
buffer[0] = input;
int i = 0;
while((buffer[i] = strtok(buffer[i], " \n\t")) != NULL){
i++;
}
for(i = 0; buffer[i] != NULL; i++){
args[i] = buffer[i];
}
*nargs = i;
args[i] = NULL;
}
Call to constant pointer-to-member function not being inlined
Call to constant pointer-to-member function not being inlined
Now, I know there are no guarantees for inlining, but...
Given the following:
struct Base {
virtual int f() = 0;
};
struct Derived : public Base {
virtual int f() final override {
return 42;
}
};
extern Base* b;
We have that:
int main() {
return static_cast<Derived*>(b)->f();
}
Compiles down to:
main:
movl $42, %eax
ret
Yet...
int main() {
return (static_cast<Derived*>(b)->*(&Derived::f))();
}
Compiles down to:
main:
pushl %ebp
movl %esp, %ebp
andl $-16, %esp
subl $16, %esp
movl b, %eax
movl (%eax), %edx
movl %eax, (%esp)
call *(%edx)
leave
ret
Which is really saddening.
Why is that call to PMF not being inlined? The PMF is a constant expression!
Now, I know there are no guarantees for inlining, but...
Given the following:
struct Base {
virtual int f() = 0;
};
struct Derived : public Base {
virtual int f() final override {
return 42;
}
};
extern Base* b;
We have that:
int main() {
return static_cast<Derived*>(b)->f();
}
Compiles down to:
main:
movl $42, %eax
ret
Yet...
int main() {
return (static_cast<Derived*>(b)->*(&Derived::f))();
}
Compiles down to:
main:
pushl %ebp
movl %esp, %ebp
andl $-16, %esp
subl $16, %esp
movl b, %eax
movl (%eax), %edx
movl %eax, (%esp)
call *(%edx)
leave
ret
Which is really saddening.
Why is that call to PMF not being inlined? The PMF is a constant expression!
Why do certain numbers throw ArrayIndexOutOfBoundsException?
Why do certain numbers throw ArrayIndexOutOfBoundsException?
I have a very quick question: why do certain numbers throw an
ArrayIndexOutOfBoundsException 1? I'm not sure if this is a problem with
Java or my code.
If I have a string that looks something like this:
10:64
This will work fine when parsing those two integers.
String string = "10:64";
String[] split = string.split(":");
int first = 0;
int second = 0;
try {
first = Integer.parseInt(split[0]);
second = Integer.parseInt(split[1]);
} catch (NumberFormatException a) {
a.printStackTrace();
}
But it seems like if the integer 'second' is (I've tried only a couple
numbers) is something like 10, it throws the exception.. why?
Edit: Here is a part of my code:
for (String str : getConfig().getStringList("itemstack")) {
String[] split = str.split(":");
Item item = null;
int size = 0;
try {
item = Item.byId[Integer.parseInt(split[0])];
} catch (NumberFormatException a) {
a.printStackTrace();
return;
}
try {
size = Integer.parseInt(split[1]);
} catch (NumberFormatException b) {
b.printStackTrace();
return;
}
}
The error is referring to the line:
size = Integer.parseInt(split[1]);
Edit 2: and here is what I have in the yaml file:
itemstack:
- 282:10
I have a very quick question: why do certain numbers throw an
ArrayIndexOutOfBoundsException 1? I'm not sure if this is a problem with
Java or my code.
If I have a string that looks something like this:
10:64
This will work fine when parsing those two integers.
String string = "10:64";
String[] split = string.split(":");
int first = 0;
int second = 0;
try {
first = Integer.parseInt(split[0]);
second = Integer.parseInt(split[1]);
} catch (NumberFormatException a) {
a.printStackTrace();
}
But it seems like if the integer 'second' is (I've tried only a couple
numbers) is something like 10, it throws the exception.. why?
Edit: Here is a part of my code:
for (String str : getConfig().getStringList("itemstack")) {
String[] split = str.split(":");
Item item = null;
int size = 0;
try {
item = Item.byId[Integer.parseInt(split[0])];
} catch (NumberFormatException a) {
a.printStackTrace();
return;
}
try {
size = Integer.parseInt(split[1]);
} catch (NumberFormatException b) {
b.printStackTrace();
return;
}
}
The error is referring to the line:
size = Integer.parseInt(split[1]);
Edit 2: and here is what I have in the yaml file:
itemstack:
- 282:10
Saturday, 28 September 2013
Bootstrap text input length automatically adjust
Bootstrap text input length automatically adjust
How do I set the length of a textbox input When I set it like in ASP.net MVC
<div class="form-group">
@Html.TextBoxFor(m => m.FirstName, new { style = "width:550px",
@class = "form-control" })
</div>
the length is set to 550px, put on mobile display the textbox doesn't
shrink. If I remove the 550px, the text input is 100% long all the way
across the screen and it adjusts on mobile screen.
I want the input at a reasonable length at 550px and I want it to shrink
on a mobile display automatically.
Is there a way to automatically shrink this input box on mobile display in
Twitter Bootstrap?
How do I set the length of a textbox input When I set it like in ASP.net MVC
<div class="form-group">
@Html.TextBoxFor(m => m.FirstName, new { style = "width:550px",
@class = "form-control" })
</div>
the length is set to 550px, put on mobile display the textbox doesn't
shrink. If I remove the 550px, the text input is 100% long all the way
across the screen and it adjusts on mobile screen.
I want the input at a reasonable length at 550px and I want it to shrink
on a mobile display automatically.
Is there a way to automatically shrink this input box on mobile display in
Twitter Bootstrap?
Python file read, split, and sort by item
Python file read, split, and sort by item
I am trying to read a file of grades, names, and assignments. All of the
items are mixed in the files and in no way sorted. I am trying to find a
code that allows me to split the list, sort the list, then print the list
in an ordered way sorted by columns and with the averages of the students
grades present. Also, if a student received a zero on an assignment, no
number is present in the file, but a "0" needs to be present in the print.
THANK YOU!
I am trying to read a file of grades, names, and assignments. All of the
items are mixed in the files and in no way sorted. I am trying to find a
code that allows me to split the list, sort the list, then print the list
in an ordered way sorted by columns and with the averages of the students
grades present. Also, if a student received a zero on an assignment, no
number is present in the file, but a "0" needs to be present in the print.
THANK YOU!
MediaCodec - How to handle screen orientation?
MediaCodec - How to handle screen orientation?
Folks,
I have created an application to play video using MediaCodec and
MediaExtractor classes. This application is based on the sample from
https://vec.io/posts/android-hardware-decoding-with-mediacodec.
The video seems to play fine. However, as soon as the orientation changes,
the video starts from the beginning. This is because the activity gets
recreated and the background thread, the extractor and the decoder are all
instantiated once again.
For my needs, I cannot disable the orientation.
I have looked at other messages related to MediaCodec but couldn't find
how developers are dealing with screen orientation (except for disabling
orientation which is not an option for me).
One thought I had was to persist the seek position of the extractor during
activity destruction. This way, on activity recreation, I could just seek
to the right position. However, I couldn't find any method on the
extractor to return the seek position (although there is a method to seek
to a location).
I am wondering if someone can enlighten me on how I could achieve
continuous video playback on screen orientation.
Thank you in advance for your help.
Regards,
Peter
Folks,
I have created an application to play video using MediaCodec and
MediaExtractor classes. This application is based on the sample from
https://vec.io/posts/android-hardware-decoding-with-mediacodec.
The video seems to play fine. However, as soon as the orientation changes,
the video starts from the beginning. This is because the activity gets
recreated and the background thread, the extractor and the decoder are all
instantiated once again.
For my needs, I cannot disable the orientation.
I have looked at other messages related to MediaCodec but couldn't find
how developers are dealing with screen orientation (except for disabling
orientation which is not an option for me).
One thought I had was to persist the seek position of the extractor during
activity destruction. This way, on activity recreation, I could just seek
to the right position. However, I couldn't find any method on the
extractor to return the seek position (although there is a method to seek
to a location).
I am wondering if someone can enlighten me on how I could achieve
continuous video playback on screen orientation.
Thank you in advance for your help.
Regards,
Peter
Why trie is also called "prefix tree"?
Why trie is also called "prefix tree"?
I was reading this article on Wikipedia and stumbled on the line which
says "trie is also called prefix tree".
I know the usage of trie but why is it called "prefix tree"?
I was reading this article on Wikipedia and stumbled on the line which
says "trie is also called prefix tree".
I know the usage of trie but why is it called "prefix tree"?
Friday, 27 September 2013
Modify AssemblyInfo.cs with NAnt instead of Creating a new one
Modify AssemblyInfo.cs with NAnt instead of Creating a new one
I've used in NAnt to create AssemblyInfo files from scratch. However, in
this case, I would like to just modify one line in the file
(AssemblyVersion). Any ideas on how to do this?
I've used in NAnt to create AssemblyInfo files from scratch. However, in
this case, I would like to just modify one line in the file
(AssemblyVersion). Any ideas on how to do this?
BindingList of Interface Type
BindingList of Interface Type
Working with VB.NET.
I've been having a bit of difficulty with data bindings. I have a
BindingList(of IDataItem), the list is populated with two class types that
both implement the IDataItem interface but only one implements the
INotifyPropertyChange interface. As you can guess I am using a
DataGridView control bound to the BindingList to display the data. I am
having a problem where any property changes make behind the scenes are not
being reflected by the DataGridView control unless the control is redrawn.
Any suggestions? Do both classes need to implement the
INotifyPropertyChange interface? Does the BindingList not work with an
interface type, must a class type be used?
Working with VB.NET.
I've been having a bit of difficulty with data bindings. I have a
BindingList(of IDataItem), the list is populated with two class types that
both implement the IDataItem interface but only one implements the
INotifyPropertyChange interface. As you can guess I am using a
DataGridView control bound to the BindingList to display the data. I am
having a problem where any property changes make behind the scenes are not
being reflected by the DataGridView control unless the control is redrawn.
Any suggestions? Do both classes need to implement the
INotifyPropertyChange interface? Does the BindingList not work with an
interface type, must a class type be used?
Regex mach letters inside statement to make a word
Regex mach letters inside statement to make a word
So I am trying to write a java program that will match (example : eat) in
the string
asdasdjhaskldhlasdklsadeaadsasdkljhasdklhjt
So what would happen is
asdasdjhaskldhlasdklsad_**E**__**A**_adsasdkljhasdklhj_**T**_
So what i have got so far in regex is matching the first letter...
^([e]+) - E
But I so not know how to allow letters and spaces between the matches.
So I am trying to write a java program that will match (example : eat) in
the string
asdasdjhaskldhlasdklsadeaadsasdkljhasdklhjt
So what would happen is
asdasdjhaskldhlasdklsad_**E**__**A**_adsasdkljhasdklhj_**T**_
So what i have got so far in regex is matching the first letter...
^([e]+) - E
But I so not know how to allow letters and spaces between the matches.
Inserting a hard-coded UUID via CQLsh (Cassandra)
Inserting a hard-coded UUID via CQLsh (Cassandra)
Would like to populate some static test data via a CQLsh script.
This doesn't work: (device_id is UUID)
insert into devices (device_id, geohash,name, external_identifier,
measures, tags)
values
('c37d661d-7e61-49ea-96a5-68c34e83db3a','9q9p3yyrn1', 'Acme1', '936',
{'aparPower','actPower','actEnergy'},{'make':'Acme'});
Bad Request: Invalid STRING constant
(c37d661d-7e61-49ea-96a5-68c34e83db3a) for device_id of type uuid
I can't seem to find any CQL function to convert to proper type. Do I need
to do this from a python script?
Thanks, Chris
Would like to populate some static test data via a CQLsh script.
This doesn't work: (device_id is UUID)
insert into devices (device_id, geohash,name, external_identifier,
measures, tags)
values
('c37d661d-7e61-49ea-96a5-68c34e83db3a','9q9p3yyrn1', 'Acme1', '936',
{'aparPower','actPower','actEnergy'},{'make':'Acme'});
Bad Request: Invalid STRING constant
(c37d661d-7e61-49ea-96a5-68c34e83db3a) for device_id of type uuid
I can't seem to find any CQL function to convert to proper type. Do I need
to do this from a python script?
Thanks, Chris
Why is System.nanoTime() way slower (in performance) than System.currentTimeMillis()?
Why is System.nanoTime() way slower (in performance) than
System.currentTimeMillis()?
Today I did a little quick Benchmark to test speed performance of
System.nanoTime() and System.currentTimeMillis():
long startTime = System.nanoTime();
for(int i = 0; i < 1000000; i++) {
long test = System.nanoTime();
}
long endTime = System.nanoTime();
System.out.println("Total time: "+(endTime-startTime));
This are the results:
System.currentTimeMillis(): average of 12,7836022 / function call
System.nanoTime(): average of 34,6395674 / function call
Why are the differences in running speed so large?
System.currentTimeMillis()?
Today I did a little quick Benchmark to test speed performance of
System.nanoTime() and System.currentTimeMillis():
long startTime = System.nanoTime();
for(int i = 0; i < 1000000; i++) {
long test = System.nanoTime();
}
long endTime = System.nanoTime();
System.out.println("Total time: "+(endTime-startTime));
This are the results:
System.currentTimeMillis(): average of 12,7836022 / function call
System.nanoTime(): average of 34,6395674 / function call
Why are the differences in running speed so large?
How to deploy CherryPy on pythonanywhere.com
How to deploy CherryPy on pythonanywhere.com
I have a python app developed on Flask. Everything works fine offline, I
tried deploying on CherryPy successfully too. Now, I'm trying to deploy
the same on www.pythonanywhere.com.
Here's the deploy.py I use for deploying the Flask app on CherryPy
from cherrypy import wsgiserver
from appname import app
def initiate():
app_list = wsgiserver.WSGIPathInfoDispatcher({'/appname': app})
server = wsgiserver.CherryPyWSGIServer(
('http://username.pythonanywhere.com/'), app_list)
try:
server.start()
except KeyboardInterrupt:
server.stop()
print "Server initiated..."
initiate()
print "Ended"
I created a "manual configuration" app on pythonanywhere.com. Here's the
configuration file (username_pythonanywhere_com_wsgi.py):
import sys
path = '/home/username/muplan'
if path not in sys.path:
sys.path.append(path)
import deploy
deploy.initiate()
Now I'm pretty sure that it "almost worked", because in the server logs I
could see my "Server initiated..." message.
2013-09-27 09:57:16 +0000 username.pythonanywhere.com - *** Operational
MODE: single process ***
Server initiated...
Now the problem, when I try to view my app
username.pyhtonanywhere.com/about, it times out. This I believe is caused
due to incorrect port given while starting the CherryPy server (in
deploy.py).
Could anyone please tell how I can properly initiate the CherryPy server?
I have a python app developed on Flask. Everything works fine offline, I
tried deploying on CherryPy successfully too. Now, I'm trying to deploy
the same on www.pythonanywhere.com.
Here's the deploy.py I use for deploying the Flask app on CherryPy
from cherrypy import wsgiserver
from appname import app
def initiate():
app_list = wsgiserver.WSGIPathInfoDispatcher({'/appname': app})
server = wsgiserver.CherryPyWSGIServer(
('http://username.pythonanywhere.com/'), app_list)
try:
server.start()
except KeyboardInterrupt:
server.stop()
print "Server initiated..."
initiate()
print "Ended"
I created a "manual configuration" app on pythonanywhere.com. Here's the
configuration file (username_pythonanywhere_com_wsgi.py):
import sys
path = '/home/username/muplan'
if path not in sys.path:
sys.path.append(path)
import deploy
deploy.initiate()
Now I'm pretty sure that it "almost worked", because in the server logs I
could see my "Server initiated..." message.
2013-09-27 09:57:16 +0000 username.pythonanywhere.com - *** Operational
MODE: single process ***
Server initiated...
Now the problem, when I try to view my app
username.pyhtonanywhere.com/about, it times out. This I believe is caused
due to incorrect port given while starting the CherryPy server (in
deploy.py).
Could anyone please tell how I can properly initiate the CherryPy server?
Thursday, 26 September 2013
showing run time error 3134 in access from
showing run time error 3134 in access from
it is giving me an run time error 3134 syntax error in insert into
statement while clicking on the control.
Private Sub CmdAddNew_Click()
'add data to table
CurrentDb.Execute "INSERT INTO
tblemployee(,firstname,lastname,Address,city)" & _
"VALUES('" & Me.txtfirstname & "','" & Me.txtlastname & "','" &
Me.txtaddress & "','" & Me.txtcity & "')"
it is giving me an run time error 3134 syntax error in insert into
statement while clicking on the control.
Private Sub CmdAddNew_Click()
'add data to table
CurrentDb.Execute "INSERT INTO
tblemployee(,firstname,lastname,Address,city)" & _
"VALUES('" & Me.txtfirstname & "','" & Me.txtlastname & "','" &
Me.txtaddress & "','" & Me.txtcity & "')"
Thursday, 19 September 2013
How can I save the indice of a row of matrix in one column and distance of that rows to a specific vector in second column in MATLAB?
How can I save the indice of a row of matrix in one column and distance of
that rows to a specific vector in second column in MATLAB?
I have a matrix of 2000*784 and a random row vector (1*784) . I need to
compute the distances of each rows of this matrix to this random row
vector. then save the indices of each rows in first column and their
distances into second column; than sort this 2000*2 matrix by the second
column (means by their distances)? Thanks
that rows to a specific vector in second column in MATLAB?
I have a matrix of 2000*784 and a random row vector (1*784) . I need to
compute the distances of each rows of this matrix to this random row
vector. then save the indices of each rows in first column and their
distances into second column; than sort this 2000*2 matrix by the second
column (means by their distances)? Thanks
How would i find what column and row the mouse is in?
How would i find what column and row the mouse is in?
I need to find what column and row the mouse location is in. To simplify
this question, lets only find the column. I will write in pseudocode.
I have a map (a grid of rows and columns, made up by square cells) with a
pixel width. I have a cell size which makes up each columns pixel width.
eg map.width / cell size = map.NumberOfColumns.
From this we can get what column the mouse is on.
Eg if ( mouse.X > cellSize ) {col is definitely > 1} (i have not used zero
indexing in this example).
So if anyone here loves maths, i would very much appreciate some help.
Thanks.
I need to find what column and row the mouse location is in. To simplify
this question, lets only find the column. I will write in pseudocode.
I have a map (a grid of rows and columns, made up by square cells) with a
pixel width. I have a cell size which makes up each columns pixel width.
eg map.width / cell size = map.NumberOfColumns.
From this we can get what column the mouse is on.
Eg if ( mouse.X > cellSize ) {col is definitely > 1} (i have not used zero
indexing in this example).
So if anyone here loves maths, i would very much appreciate some help.
Thanks.
Rotate Right - How to deal with signed numbers?
Rotate Right - How to deal with signed numbers?
int rotateRight(int x, int n) {
int temp = x;
x >>= n;
temp = temp << (32+((~n)+1));
// Now need to find a way to deal with two's comp numbers
// Since x has been shifted right, if it is neg than it has been
// Sign extended....have to AND the n shifted bits with 0 before
// or'ing with temp.
//int signFix = ....
return x | temp;
}
// Legal ops: ~ & ^ | + << >>
// Max ops: 25
The problem is sign extension causes an issue for signed numbers... The
amount of spaces shifted right in a signed number would be replaced by
1's. I need to and those numbers with 0 before or'ing with temp... How can
I accomplish this?? Any help would greatly be appreciated. I can only use
bitwise ops.
int rotateRight(int x, int n) {
int temp = x;
x >>= n;
temp = temp << (32+((~n)+1));
// Now need to find a way to deal with two's comp numbers
// Since x has been shifted right, if it is neg than it has been
// Sign extended....have to AND the n shifted bits with 0 before
// or'ing with temp.
//int signFix = ....
return x | temp;
}
// Legal ops: ~ & ^ | + << >>
// Max ops: 25
The problem is sign extension causes an issue for signed numbers... The
amount of spaces shifted right in a signed number would be replaced by
1's. I need to and those numbers with 0 before or'ing with temp... How can
I accomplish this?? Any help would greatly be appreciated. I can only use
bitwise ops.
How to call a function in all servers in Web Farm (Like a broadcast)
How to call a function in all servers in Web Farm (Like a broadcast)
I have a WCF service hosted in a web farm with 4 servers. These servers
are not fixed and will be added more later on. I have a resource intensive
singleton which might need to change once a week. When that changes I need
to call a update function in my WCF which will recompute some values. What
I need to know is how do I call the update function on all the servers in
the web farm framework. Any ideas are strongly appreciated.
Thanks,
Phani.
I have a WCF service hosted in a web farm with 4 servers. These servers
are not fixed and will be added more later on. I have a resource intensive
singleton which might need to change once a week. When that changes I need
to call a update function in my WCF which will recompute some values. What
I need to know is how do I call the update function on all the servers in
the web farm framework. Any ideas are strongly appreciated.
Thanks,
Phani.
cucumber testing scenario fails while using before filter?
cucumber testing scenario fails while using before filter?
I have referred link
http://railscasts.com/episodes/155-beginning-with-cucumber for testing.
But when i use before_filter :authenticate_user! in my controller my all
cases are failing and when i commented the before filter my all test cases
are passing. I am getting following error.
Scenario: Create Valid Article
Given I have no articles
And I am on the list of articles
When I follow "New Article"
Unable to find link "New Article" (Capybara::ElementNotFound)
./features/step_definitions/article_steps.rb:25:in `/^I follow
"([^\"]*)"$/'
features/manage_articles.feature:15:in `When I follow "New Article"'
And I fill in "article[title]" with "Spuds"
And I fill in "Content" with "Delicious potato wedges!"
And I press "Create"
Then I should see "New article created."
And I should see "Spuds"
And I should see "Delicious potato wedges!"
And I should have 1 article
Failing Scenarios:
cucumber features/manage_articles.feature:12 # Scenario: Create Valid
Article
2 scenarios (1 failed, 1 passed) 14 steps (1 failed, 7 skipped, 6 passed)
I have referred link
http://railscasts.com/episodes/155-beginning-with-cucumber for testing.
But when i use before_filter :authenticate_user! in my controller my all
cases are failing and when i commented the before filter my all test cases
are passing. I am getting following error.
Scenario: Create Valid Article
Given I have no articles
And I am on the list of articles
When I follow "New Article"
Unable to find link "New Article" (Capybara::ElementNotFound)
./features/step_definitions/article_steps.rb:25:in `/^I follow
"([^\"]*)"$/'
features/manage_articles.feature:15:in `When I follow "New Article"'
And I fill in "article[title]" with "Spuds"
And I fill in "Content" with "Delicious potato wedges!"
And I press "Create"
Then I should see "New article created."
And I should see "Spuds"
And I should see "Delicious potato wedges!"
And I should have 1 article
Failing Scenarios:
cucumber features/manage_articles.feature:12 # Scenario: Create Valid
Article
2 scenarios (1 failed, 1 passed) 14 steps (1 failed, 7 skipped, 6 passed)
manyToMany or oneToMany
manyToMany or oneToMany
I have 2 Entites, User and Orders.
There are many users and many orders.
A user can have many orders.
In my Entities I have the following:
Orders.php
/**
*
* @ORM\OneToOne(targetEntity="BM\UserBundle\Entity\User")
* @ORM\JoinColumn(name="user_id", referencedColumnName="id")
*/
protected $user;
But looking at the db, this creates a user_id field that is unique, so I
can't create anymore orders because the user_id is already in the db.
I know that this is wrong.
Do I need a oneToMany or manyToMany etc relationship so that I can have
multiple orders per user?
Thanks
I have 2 Entites, User and Orders.
There are many users and many orders.
A user can have many orders.
In my Entities I have the following:
Orders.php
/**
*
* @ORM\OneToOne(targetEntity="BM\UserBundle\Entity\User")
* @ORM\JoinColumn(name="user_id", referencedColumnName="id")
*/
protected $user;
But looking at the db, this creates a user_id field that is unique, so I
can't create anymore orders because the user_id is already in the db.
I know that this is wrong.
Do I need a oneToMany or manyToMany etc relationship so that I can have
multiple orders per user?
Thanks
Pop up charts in VBA Excel
Pop up charts in VBA Excel
I was wondering if there is a way to create pop-up charts in Excel with
press of a button, based on values found in a specific worksheet? The best
way would be to be able to do it in VBA.
I have been scooping around a bit but can't find any real solutions to my
problem.
Any suggestions?
BR, Niklas
I was wondering if there is a way to create pop-up charts in Excel with
press of a button, based on values found in a specific worksheet? The best
way would be to be able to do it in VBA.
I have been scooping around a bit but can't find any real solutions to my
problem.
Any suggestions?
BR, Niklas
Wednesday, 18 September 2013
C# Wpf Datagrid Horizontal Scrollbar Not Showing When Any Column Width="*"
C# Wpf Datagrid Horizontal Scrollbar Not Showing When Any Column Width="*"
All i want is, when i click any row on the datagrid, i want that row be
selected and change it's color.
But thanks to auto generated column on the right side, i cant select all
the row. Some space in right side stays unselected.
Because of this, i set last column's width to "*" and got rid of auto
generated column and i can select all the row.
But now, the last column always stays at screen, by the way i cant resize
other columns after some point.(horizontal scroll bar never appears)
How can i make datagrid not generating an extra column, and make all the
columns infinitely resizable?
All i want is, when i click any row on the datagrid, i want that row be
selected and change it's color.
But thanks to auto generated column on the right side, i cant select all
the row. Some space in right side stays unselected.
Because of this, i set last column's width to "*" and got rid of auto
generated column and i can select all the row.
But now, the last column always stays at screen, by the way i cant resize
other columns after some point.(horizontal scroll bar never appears)
How can i make datagrid not generating an extra column, and make all the
columns infinitely resizable?
Devise and Multisite
Devise and Multisite
This is namely a multi-site or multiple domain issue, using Ruby on Rails
and Devise gem.
My Environment:
I'm developing a rails application for an enterprise, with multiple
companies inside the corporate structure. The enterprise has its in-house
legacy authentication system. In order to make use of it, I implemented a
remote_authenticatable module according to this.
http://4trabes.com/2012/10/31/remote-authentication-with-devise/
Problem:
Here is the case, there are two legacy systems, located in two domains,
namely
mydomain1.com
mydomain2.com
What I need to do, is to build a single system, that serves login from two
domains
login.mydomain1.com/users/sign_in
login.mydomain2.com/users/sign_in
and based on the domain using, use corresponding Devise strategy and
legacy login, and I will know where the user comes from and do the
following actions accordingly.
Questions:
Is it possible to build such a system?
One Rails, with two domains
Use corresponding strategy, based on the incoming domain
This is namely a multi-site or multiple domain issue, using Ruby on Rails
and Devise gem.
My Environment:
I'm developing a rails application for an enterprise, with multiple
companies inside the corporate structure. The enterprise has its in-house
legacy authentication system. In order to make use of it, I implemented a
remote_authenticatable module according to this.
http://4trabes.com/2012/10/31/remote-authentication-with-devise/
Problem:
Here is the case, there are two legacy systems, located in two domains,
namely
mydomain1.com
mydomain2.com
What I need to do, is to build a single system, that serves login from two
domains
login.mydomain1.com/users/sign_in
login.mydomain2.com/users/sign_in
and based on the domain using, use corresponding Devise strategy and
legacy login, and I will know where the user comes from and do the
following actions accordingly.
Questions:
Is it possible to build such a system?
One Rails, with two domains
Use corresponding strategy, based on the incoming domain
Replaceing Backbone sync on an Application level -- not via Model or Xollection
Replaceing Backbone sync on an Application level -- not via Model or
Xollection
How does one replace Backbone.sync using backbone.basicauth library found
here.
Can that be done on an Application level -- on App.init in main.js for
example -- and avoid overriding the "synch" on every Model or Collection
project
source
Xollection
How does one replace Backbone.sync using backbone.basicauth library found
here.
Can that be done on an Application level -- on App.init in main.js for
example -- and avoid overriding the "synch" on every Model or Collection
project
source
C - How can I sort and print an array in a method but have the prior unsorted array not be affected
C - How can I sort and print an array in a method but have the prior
unsorted array not be affected
This is for a Deal or No Deal game.
So in my main function I'm calling my casesort method as such:
casesort(cases);
My method looks like this, I already realize it's not the most efficient
sort but I'm going with what I know:
void casesort(float cases[10])
{
int i;
int j;
float tmp;
float zero = 0.00;
for (i = 0; i < 10; i++)
{
for (j = 0; j < 10; j++)
{
if (cases[i] < cases[j])
{
tmp = cases[i];
cases[i] = cases[j];
cases[j] = tmp;
}
}
}
//Print out box money amounts
printf("\n\nHidden Amounts: ");
for (i = 0; i < 10; i++)
{
if (cases[i] != zero)
printf("[$%.2f] ", cases[i]);
}
}
So when I get back to my main it turns out the array is sorted. I thought
void would prevent the method returning a sorted array. I need to print
out actual case numbers, I do this by just skipping over any case that is
populated with a 0.00. But after the first round of case picks I get "5,
6, 7, 8, 9, 10" printing out back in my MAIN. I need it to print the cases
according to what has been picked. I feel like it's a simple fix, its just
that my knowledge of the specifics of C is still growing. Any ideas?
unsorted array not be affected
This is for a Deal or No Deal game.
So in my main function I'm calling my casesort method as such:
casesort(cases);
My method looks like this, I already realize it's not the most efficient
sort but I'm going with what I know:
void casesort(float cases[10])
{
int i;
int j;
float tmp;
float zero = 0.00;
for (i = 0; i < 10; i++)
{
for (j = 0; j < 10; j++)
{
if (cases[i] < cases[j])
{
tmp = cases[i];
cases[i] = cases[j];
cases[j] = tmp;
}
}
}
//Print out box money amounts
printf("\n\nHidden Amounts: ");
for (i = 0; i < 10; i++)
{
if (cases[i] != zero)
printf("[$%.2f] ", cases[i]);
}
}
So when I get back to my main it turns out the array is sorted. I thought
void would prevent the method returning a sorted array. I need to print
out actual case numbers, I do this by just skipping over any case that is
populated with a 0.00. But after the first round of case picks I get "5,
6, 7, 8, 9, 10" printing out back in my MAIN. I need it to print the cases
according to what has been picked. I feel like it's a simple fix, its just
that my knowledge of the specifics of C is still growing. Any ideas?
Why, when I add a bunch of event listeners in a loop, does every element trigger the last listener added?
Why, when I add a bunch of event listeners in a loop, does every element
trigger the last listener added?
On a page, I have an SVG map of the US and Canada, and an HTML list of
provinces and states. Hovering over any province, either its name in the
list OR its depiction on the map, should make Arkansas on both list AND
map turn a different color. All the names and paths have logical
IDs/classes on them already.
Here's a fiddle with my code. (It's a horrible procedural mess at the
moment, so please forgive me.)
jQuery's event functions don't work on SVG, and though I know there's a
jQuery plugin that supposedly helps, I thought this would be a good
opportunity to use a larger proportion of vanilla Javascript than I'm used
to.
The most relevant part of the code is the makeMapInteractive function on
lines 46 through 69 of the Javascript:
function makeMapInteractive(provinces) {
for(var province in provinces) { // Iterate over every state/province
code
var $HTMLtargets = $('ul.provinces li.' + province);
var $SVGtargets = $('path#{0}, g#{0} path'.format(province));
var $allTargets = $HTMLtargets.add($SVGtargets);
// I tried it first with $().each(); when that didn't work,
// I commented it out and tried without it. Neither one works.
/* $allTargets.each(function() {
this.addEventListener('mouseover', function(e) {
console.log(e);
$HTMLtargets.css('color', '#990000');
$SVGtargets.attr('fill', '#990000');
}, false)
}); */
for(var i = 0; i < $allTargets.length; i++) {
$allTargets.get(i).addEventListener('mouseover', function(e) {
$HTMLtargets.css('color', '#990000');
$SVGtargets.attr('fill', '#990000');
}, false);
}
}
}
What I'm trying to tell it to do is to add a mouseover listener to every
element, that triggers a change on all elements involved in that element's
province.
What actually happens is that hovering over anything on the whole page
triggers the very last event listener added, the one for Wyoming. It's
like when I change the $allTargets variable, it changes all the
previously-added listeners to the elements contained in its new value. But
I can't see how that's happening, since I'm applying the event listeners
to the DOM elements inside that variable, not the jQuery object itself.
Can someone explain exactly what is going on here? I know I'm using jQuery
a bit here, but I'd like the answer to use no more than I'm already using;
it's my vanilla Javascript skill that needs increasing.
trigger the last listener added?
On a page, I have an SVG map of the US and Canada, and an HTML list of
provinces and states. Hovering over any province, either its name in the
list OR its depiction on the map, should make Arkansas on both list AND
map turn a different color. All the names and paths have logical
IDs/classes on them already.
Here's a fiddle with my code. (It's a horrible procedural mess at the
moment, so please forgive me.)
jQuery's event functions don't work on SVG, and though I know there's a
jQuery plugin that supposedly helps, I thought this would be a good
opportunity to use a larger proportion of vanilla Javascript than I'm used
to.
The most relevant part of the code is the makeMapInteractive function on
lines 46 through 69 of the Javascript:
function makeMapInteractive(provinces) {
for(var province in provinces) { // Iterate over every state/province
code
var $HTMLtargets = $('ul.provinces li.' + province);
var $SVGtargets = $('path#{0}, g#{0} path'.format(province));
var $allTargets = $HTMLtargets.add($SVGtargets);
// I tried it first with $().each(); when that didn't work,
// I commented it out and tried without it. Neither one works.
/* $allTargets.each(function() {
this.addEventListener('mouseover', function(e) {
console.log(e);
$HTMLtargets.css('color', '#990000');
$SVGtargets.attr('fill', '#990000');
}, false)
}); */
for(var i = 0; i < $allTargets.length; i++) {
$allTargets.get(i).addEventListener('mouseover', function(e) {
$HTMLtargets.css('color', '#990000');
$SVGtargets.attr('fill', '#990000');
}, false);
}
}
}
What I'm trying to tell it to do is to add a mouseover listener to every
element, that triggers a change on all elements involved in that element's
province.
What actually happens is that hovering over anything on the whole page
triggers the very last event listener added, the one for Wyoming. It's
like when I change the $allTargets variable, it changes all the
previously-added listeners to the elements contained in its new value. But
I can't see how that's happening, since I'm applying the event listeners
to the DOM elements inside that variable, not the jQuery object itself.
Can someone explain exactly what is going on here? I know I'm using jQuery
a bit here, but I'd like the answer to use no more than I'm already using;
it's my vanilla Javascript skill that needs increasing.
Accessing class member pointers
Accessing class member pointers
Suppose I have the following definition of List and Node:
template <class T>
class List {
public:
class Iterator;
class ConstIterator;
//Constructors and Destructors.
List() : head(NULL), tail(NULL), size(0) {}
List(const List& list);
~List();
//Methods
Iterator begin();
ConstIterator begin() const;
Iterator end();
ConstIterator end() const;
void insert(const T& data);
void insert(const T& data, const Iterator& iterator);
void remove(const Iterator& iterator);
int getSize() const;
Iterator find(const T& item);
ConstIterator find(const T& item) const;
void sort();
//Operators
List operator = (const List& list);
private:
class Node;
Node* head;
Node* tail;
int size;
};
template <class T>
class List<T>::Node
{
public:
//Constructors and destructors
Node(const T& _data, const Node* _next) : data(_data), next(_next) {}
~Node(); //Destructor
//Methods
//Operators
Node operator = (const Node& node);
private:
T data;
Node* next;
};
I'm writing a function to insert data into a list like this:
template<class T>
void List<T>::insert(const T& data)
{
Node newNode = new Node(data, NULL);
if (head == NULL)
{
head = &newNode;
tail = &newNode;
}
else
{
(*tail)->next = &newNode;
tail = &newNode;
}
size++;
}
However what I find strange is that if I swap (*tail)->next = &newNode; to
(*tail).next = &newNode; it still compiles. Why, and what is the correct
way of doing it?
Suppose I have the following definition of List and Node:
template <class T>
class List {
public:
class Iterator;
class ConstIterator;
//Constructors and Destructors.
List() : head(NULL), tail(NULL), size(0) {}
List(const List& list);
~List();
//Methods
Iterator begin();
ConstIterator begin() const;
Iterator end();
ConstIterator end() const;
void insert(const T& data);
void insert(const T& data, const Iterator& iterator);
void remove(const Iterator& iterator);
int getSize() const;
Iterator find(const T& item);
ConstIterator find(const T& item) const;
void sort();
//Operators
List operator = (const List& list);
private:
class Node;
Node* head;
Node* tail;
int size;
};
template <class T>
class List<T>::Node
{
public:
//Constructors and destructors
Node(const T& _data, const Node* _next) : data(_data), next(_next) {}
~Node(); //Destructor
//Methods
//Operators
Node operator = (const Node& node);
private:
T data;
Node* next;
};
I'm writing a function to insert data into a list like this:
template<class T>
void List<T>::insert(const T& data)
{
Node newNode = new Node(data, NULL);
if (head == NULL)
{
head = &newNode;
tail = &newNode;
}
else
{
(*tail)->next = &newNode;
tail = &newNode;
}
size++;
}
However what I find strange is that if I swap (*tail)->next = &newNode; to
(*tail).next = &newNode; it still compiles. Why, and what is the correct
way of doing it?
awk script to print records from every two files in a line
awk script to print records from every two files in a line
Im trying to have awk script that read 8 inputs file and each file
contains 4 lines: File 1 cointains: file 1 line 1 file 1 line 2 file 1
line 3 file 1 line 4 and all others have the same ..
So the required output will be:
pe co test 1 test 2
1 3 file 1 line 1 file 2 line 1 file 1 line 2 file 2 line 2 file 1 line 3
file 2 line 3 file 1 line 4 file 2 line 4
2 6 file 3 line 1 file 4 line 1 file 3 line 2 file 4 line 2 file 3 line 3
file 4 line 3 file 3 line 4 file 4 line 4
3 9 file 5 line 1 file 6 line 1 file 5 line 2 file 6 line 2 file 5 line 3
file 6 line 3 file 5 line 4 file 6 line 4
any help how to produce such output ?
thanks
Im trying to have awk script that read 8 inputs file and each file
contains 4 lines: File 1 cointains: file 1 line 1 file 1 line 2 file 1
line 3 file 1 line 4 and all others have the same ..
So the required output will be:
pe co test 1 test 2
1 3 file 1 line 1 file 2 line 1 file 1 line 2 file 2 line 2 file 1 line 3
file 2 line 3 file 1 line 4 file 2 line 4
2 6 file 3 line 1 file 4 line 1 file 3 line 2 file 4 line 2 file 3 line 3
file 4 line 3 file 3 line 4 file 4 line 4
3 9 file 5 line 1 file 6 line 1 file 5 line 2 file 6 line 2 file 5 line 3
file 6 line 3 file 5 line 4 file 6 line 4
any help how to produce such output ?
thanks
How to use static block to initialize spring hibernate query function
How to use static block to initialize spring hibernate query function
I am new to Spring Hibernate, so I am having this problem that cause by a
function that initialize in a static block.
This is my DAO class:
private static HibernateTemplate hibernateTemplate;
public void setSessionFactory(SessionFactory sessionFactory) {
hibernateTemplate = new HibernateTemplate(sessionFactory);
}
static{
loadAllProvince();
}
public static void loadAllProvince () {
List regionList = hibernateTemplate.find("FROM regions");
if (regionList.size() > 0 ) {
for (int i=0; i<regionList.size(); i++) {
Object[] obj = (Object[]) regionList.get(i) ;
mapRegion.put(obj[1].toString(), obj[0].toString());
}
}
}
This is the bean configuration in my applicationContext.xml:
<bean id="regionDAOBean" class="com.dao.RegionDAO">
<property name="sessionFactory" ref="sessionFactoryBean"/>
</bean>
When I run my application, the exception say:
org.springframework.beans.factory.BeanCreationException: Error creating
bean with name 'regionDAOBean' defined in class path resource
[applicationContext.xml]:
Instantiation of bean failed; nested exception is
java.lang.ExceptionInInitializerError
It was working find until I initialize the function in the static block,
so what should I do in order to initialize the function in static block?
I am new to Spring Hibernate, so I am having this problem that cause by a
function that initialize in a static block.
This is my DAO class:
private static HibernateTemplate hibernateTemplate;
public void setSessionFactory(SessionFactory sessionFactory) {
hibernateTemplate = new HibernateTemplate(sessionFactory);
}
static{
loadAllProvince();
}
public static void loadAllProvince () {
List regionList = hibernateTemplate.find("FROM regions");
if (regionList.size() > 0 ) {
for (int i=0; i<regionList.size(); i++) {
Object[] obj = (Object[]) regionList.get(i) ;
mapRegion.put(obj[1].toString(), obj[0].toString());
}
}
}
This is the bean configuration in my applicationContext.xml:
<bean id="regionDAOBean" class="com.dao.RegionDAO">
<property name="sessionFactory" ref="sessionFactoryBean"/>
</bean>
When I run my application, the exception say:
org.springframework.beans.factory.BeanCreationException: Error creating
bean with name 'regionDAOBean' defined in class path resource
[applicationContext.xml]:
Instantiation of bean failed; nested exception is
java.lang.ExceptionInInitializerError
It was working find until I initialize the function in the static block,
so what should I do in order to initialize the function in static block?
JavaFX analogs for Java 6
JavaFX analogs for Java 6
I really want to use JavaFX in my project, but there is a big problem - my
developer machine works under Mac OS X 10.6, so I cannot install Java 7
there, and JavaFX 2.2 support only 10.7 and higher versions of Mac OS.
Is there any libraries with the same functionality (rendering layout from
XML, scripting etc)?
I really want to use JavaFX in my project, but there is a big problem - my
developer machine works under Mac OS X 10.6, so I cannot install Java 7
there, and JavaFX 2.2 support only 10.7 and higher versions of Mac OS.
Is there any libraries with the same functionality (rendering layout from
XML, scripting etc)?
Tuesday, 17 September 2013
How to get the length of array div tag using javascript?
How to get the length of array div tag using javascript?
I want to get the length of div using javascript.
<div id="div1">1</div>
<div id="div2">2</div>
<div id="div3">3</div>
<div id="div4">4</div>
<div id="div5">5</div>
Can any one help me how to get the length.
Thanks,
I want to get the length of div using javascript.
<div id="div1">1</div>
<div id="div2">2</div>
<div id="div3">3</div>
<div id="div4">4</div>
<div id="div5">5</div>
Can any one help me how to get the length.
Thanks,
How to read image file from disk location
How to read image file from disk location
How to read image file from disk location and edit it's height width and
save to same location in asp.net C#
How to read image file from disk location and edit it's height width and
save to same location in asp.net C#
Returning Data from the listview in the activity
Returning Data from the listview in the activity
From the start activity
Intent intent = new Intent(StartActivity.this, MarkersActivity.class);
startActivityForResult(intent, GoMarkerReturn);
call other activity in which there is CustomListAdapter extends
BaseAdapter. The listviewhas a picture, when clicked, to close the current
activity and return the result to the starting activity
public class CustomListAdapter extends BaseAdapter {
...
public View getView(int position, View convertView, ViewGroup parent) {
holder.imggo.setOnClickListener(new View.OnClickListener() {
...
@Override
public void onClick(View v) {
int clickedPosition = (Integer)v.getTag();
NewsItem newsItem = (NewsItem)listData.get(clickedPosition);
Long goID = newsItem.getID();
Intent myIntent = new Intent(v.getContext(),
StartActivity.class);
myIntent.putExtra("goID", goID);
setResult(0, myIntent);
setResult(0, myIntent) dont work!
From the start activity
Intent intent = new Intent(StartActivity.this, MarkersActivity.class);
startActivityForResult(intent, GoMarkerReturn);
call other activity in which there is CustomListAdapter extends
BaseAdapter. The listviewhas a picture, when clicked, to close the current
activity and return the result to the starting activity
public class CustomListAdapter extends BaseAdapter {
...
public View getView(int position, View convertView, ViewGroup parent) {
holder.imggo.setOnClickListener(new View.OnClickListener() {
...
@Override
public void onClick(View v) {
int clickedPosition = (Integer)v.getTag();
NewsItem newsItem = (NewsItem)listData.get(clickedPosition);
Long goID = newsItem.getID();
Intent myIntent = new Intent(v.getContext(),
StartActivity.class);
myIntent.putExtra("goID", goID);
setResult(0, myIntent);
setResult(0, myIntent) dont work!
Outbound URL Rewriting - Only possible in IIS URL Rewrite module?
Outbound URL Rewriting - Only possible in IIS URL Rewrite module?
Nobody using Apache mod_rewrite seems to understand what Outbound rule
writing is, so I'm confused with this matter.
When developing a web application, you are naturally going to have long
'ugly' links because otherwise your IDE will not have a clue which files
you are trying to link to. But when the webpages are being served to the
user, you want them all to be presented in user-friendly URLs.
How are you supposed to include user-friendly URLs within your webpage
before they are served to the user by the web server? If you manually have
to change these types of links:
<a href="http://mysite.com?article=1§ion=5">Article 1, Chapter 5</a>
into these type of links:
<a href="http://mysite.com/article-1/section-5">Article 1, Chapter 5</a>
then you will mess up your entire application. Links will appear broken
when you try validate the site and the site may look a mess.
So how are people including user friendly URLs in their applications
without using Outbound rules?
Nobody using Apache mod_rewrite seems to understand what Outbound rule
writing is, so I'm confused with this matter.
When developing a web application, you are naturally going to have long
'ugly' links because otherwise your IDE will not have a clue which files
you are trying to link to. But when the webpages are being served to the
user, you want them all to be presented in user-friendly URLs.
How are you supposed to include user-friendly URLs within your webpage
before they are served to the user by the web server? If you manually have
to change these types of links:
<a href="http://mysite.com?article=1§ion=5">Article 1, Chapter 5</a>
into these type of links:
<a href="http://mysite.com/article-1/section-5">Article 1, Chapter 5</a>
then you will mess up your entire application. Links will appear broken
when you try validate the site and the site may look a mess.
So how are people including user friendly URLs in their applications
without using Outbound rules?
How does String.Format work in this situation
How does String.Format work in this situation
I have a website where you can buy stuff, and we want to format the
orderID that goes to our portal in certain way. I am using the
string.format method to format it like this:
Portal.OrderID = string.Format("{0}{1:0000000}-{2:000}", "Z"
,this.Order.OrderID, "000");
So we want it to look like this basically Z0545698-001. My question is, if
I am using string.format will it blow up if this.Order.OrderID is greater
than 7 characters?
If so, how can I keep the same formatting (i.e. Z 1234567 - 000) but have
the first set of numbers (the 1-7) be a minimum of 7 (with any numbers
less than 7 in length have leading 0's). And then have anything greater
than 7 in length just extend the formatting so I could get an order number
like Z12345678-001?
I have a website where you can buy stuff, and we want to format the
orderID that goes to our portal in certain way. I am using the
string.format method to format it like this:
Portal.OrderID = string.Format("{0}{1:0000000}-{2:000}", "Z"
,this.Order.OrderID, "000");
So we want it to look like this basically Z0545698-001. My question is, if
I am using string.format will it blow up if this.Order.OrderID is greater
than 7 characters?
If so, how can I keep the same formatting (i.e. Z 1234567 - 000) but have
the first set of numbers (the 1-7) be a minimum of 7 (with any numbers
less than 7 in length have leading 0's). And then have anything greater
than 7 in length just extend the formatting so I could get an order number
like Z12345678-001?
Google bigquery update rows
Google bigquery update rows
So can anyone give ideas on how to update a set of rows?
I understand the concept of query -> new table, then dumping the "old"
table and re-naming the "new", but to be honest this is very hokey.
I don't see anything in the documentation, web, or in the new ideas that
will lead me to believe in the appearance of an "update" statement either.
Thoughts anyone?
So can anyone give ideas on how to update a set of rows?
I understand the concept of query -> new table, then dumping the "old"
table and re-naming the "new", but to be honest this is very hokey.
I don't see anything in the documentation, web, or in the new ideas that
will lead me to believe in the appearance of an "update" statement either.
Thoughts anyone?
Sunday, 15 September 2013
jQuery offset().top not working properly
jQuery offset().top not working properly
I am trying to get a div to stick once it is scrolled out of view.
var jQ = jQuery.noConflict();
jQ(document).ready(function() {
var win = jQ(window);
var navTop = jQ('#navbar').offset().top;
win.scroll(function() {
jQ('#navbar').toggleClass('sticky', win.scrollTop() > navTop);
});
});
The problem is that with this code, navTop is not calculated correctly. If
I calculate navTop in the scroll function it works as expected but with a
horrible flickering effect which I assume is due to recalculating the
value many times.
Why does it not calculate the value correctly after document is loaded?
I am trying to get a div to stick once it is scrolled out of view.
var jQ = jQuery.noConflict();
jQ(document).ready(function() {
var win = jQ(window);
var navTop = jQ('#navbar').offset().top;
win.scroll(function() {
jQ('#navbar').toggleClass('sticky', win.scrollTop() > navTop);
});
});
The problem is that with this code, navTop is not calculated correctly. If
I calculate navTop in the scroll function it works as expected but with a
horrible flickering effect which I assume is due to recalculating the
value many times.
Why does it not calculate the value correctly after document is loaded?
How to refactor this Haskell random generator?
How to refactor this Haskell random generator?
I'm trying to generate random data at fast speed inside Haskell, but it
when I try to use any idiomatic approach I get low speed and big GC
overhead.
Here is the short code:
import qualified System.Random.Mersenne as RM
import qualified Data.ByteString.Lazy as BL
import qualified System.IO as SI
import Data.Word
main = do
r <- RM.newMTGen Nothing :: IO RM.MTGen
rnd <- RM.randoms r :: IO [Word8]
BL.hPutStr SI.stdout $ BL.pack rnd
Here is the fast code:
import qualified System.Random.Mersenne as RM
import qualified Data.ByteString as B
import qualified Data.ByteString.Lazy as BL
import qualified Data.Binary.Put as DBP
import qualified System.IO as SI
import Data.List
import Control.Monad (void, forever)
import Data.Word
main = do
r <- RM.newMTGen Nothing :: IO RM.MTGen
forever $ do
x0 <- RM.random r :: IO Word32
x1 <- RM.random r :: IO Word32
x2 <- RM.random r :: IO Word32
x3 <- RM.random r :: IO Word32
x4 <- RM.random r :: IO Word32
x5 <- RM.random r :: IO Word32
x6 <- RM.random r :: IO Word32
x7 <- RM.random r :: IO Word32
x8 <- RM.random r :: IO Word32
x9 <- RM.random r :: IO Word32
xA <- RM.random r :: IO Word32
xB <- RM.random r :: IO Word32
xC <- RM.random r :: IO Word32
xD <- RM.random r :: IO Word32
xE <- RM.random r :: IO Word32
xF <- RM.random r :: IO Word32
c0 <- RM.random r :: IO Word32
c1 <- RM.random r :: IO Word32
c2 <- RM.random r :: IO Word32
c3 <- RM.random r :: IO Word32
c4 <- RM.random r :: IO Word32
c5 <- RM.random r :: IO Word32
c6 <- RM.random r :: IO Word32
c7 <- RM.random r :: IO Word32
c8 <- RM.random r :: IO Word32
c9 <- RM.random r :: IO Word32
cA <- RM.random r :: IO Word32
cB <- RM.random r :: IO Word32
cC <- RM.random r :: IO Word32
cD <- RM.random r :: IO Word32
cE <- RM.random r :: IO Word32
cF <- RM.random r :: IO Word32
v0 <- RM.random r :: IO Word32
v1 <- RM.random r :: IO Word32
v2 <- RM.random r :: IO Word32
v3 <- RM.random r :: IO Word32
v4 <- RM.random r :: IO Word32
v5 <- RM.random r :: IO Word32
v6 <- RM.random r :: IO Word32
v7 <- RM.random r :: IO Word32
v8 <- RM.random r :: IO Word32
v9 <- RM.random r :: IO Word32
vA <- RM.random r :: IO Word32
vB <- RM.random r :: IO Word32
vC <- RM.random r :: IO Word32
vD <- RM.random r :: IO Word32
vE <- RM.random r :: IO Word32
vF <- RM.random r :: IO Word32
b0 <- RM.random r :: IO Word32
b1 <- RM.random r :: IO Word32
b2 <- RM.random r :: IO Word32
b3 <- RM.random r :: IO Word32
b4 <- RM.random r :: IO Word32
b5 <- RM.random r :: IO Word32
b6 <- RM.random r :: IO Word32
b7 <- RM.random r :: IO Word32
b8 <- RM.random r :: IO Word32
b9 <- RM.random r :: IO Word32
bA <- RM.random r :: IO Word32
bB <- RM.random r :: IO Word32
bC <- RM.random r :: IO Word32
bD <- RM.random r :: IO Word32
bE <- RM.random r :: IO Word32
bF <- RM.random r :: IO Word32
BL.hPutStr SI.stdout $ DBP.runPut $ do
DBP.putWord32be x0
DBP.putWord32be x1
DBP.putWord32be x2
DBP.putWord32be x3
DBP.putWord32be x4
DBP.putWord32be x5
DBP.putWord32be x6
DBP.putWord32be x7
DBP.putWord32be x8
DBP.putWord32be x9
DBP.putWord32be xA
DBP.putWord32be xB
DBP.putWord32be xC
DBP.putWord32be xD
DBP.putWord32be xE
DBP.putWord32be xF
DBP.putWord32be c0
DBP.putWord32be c1
DBP.putWord32be c2
DBP.putWord32be c3
DBP.putWord32be c4
DBP.putWord32be c5
DBP.putWord32be c6
DBP.putWord32be c7
DBP.putWord32be c8
DBP.putWord32be c9
DBP.putWord32be cA
DBP.putWord32be cB
DBP.putWord32be cC
DBP.putWord32be cD
DBP.putWord32be cE
DBP.putWord32be cF
DBP.putWord32be v0
DBP.putWord32be v1
DBP.putWord32be v2
DBP.putWord32be v3
DBP.putWord32be v4
DBP.putWord32be v5
DBP.putWord32be v6
DBP.putWord32be v7
DBP.putWord32be v8
DBP.putWord32be v9
DBP.putWord32be vA
DBP.putWord32be vB
DBP.putWord32be vC
DBP.putWord32be vD
DBP.putWord32be vE
DBP.putWord32be vF
DBP.putWord32be b0
DBP.putWord32be b1
DBP.putWord32be b2
DBP.putWord32be b3
DBP.putWord32be b4
DBP.putWord32be b5
DBP.putWord32be b6
DBP.putWord32be b7
DBP.putWord32be b8
DBP.putWord32be b9
DBP.putWord32be bA
DBP.putWord32be bB
DBP.putWord32be bC
DBP.putWord32be bD
DBP.putWord32be bE
DBP.putWord32be bF
The short code outputs about 6 megabytes of random bytes per second on my
computer. The fast code - about 150 megabytes per seccond.
If I reduce number of that variables from 64 to 16 in the fast code, the
speed drops to about 78 megabytes per second.
How to make this code compact and idiomatic without slowing it down?
I'm trying to generate random data at fast speed inside Haskell, but it
when I try to use any idiomatic approach I get low speed and big GC
overhead.
Here is the short code:
import qualified System.Random.Mersenne as RM
import qualified Data.ByteString.Lazy as BL
import qualified System.IO as SI
import Data.Word
main = do
r <- RM.newMTGen Nothing :: IO RM.MTGen
rnd <- RM.randoms r :: IO [Word8]
BL.hPutStr SI.stdout $ BL.pack rnd
Here is the fast code:
import qualified System.Random.Mersenne as RM
import qualified Data.ByteString as B
import qualified Data.ByteString.Lazy as BL
import qualified Data.Binary.Put as DBP
import qualified System.IO as SI
import Data.List
import Control.Monad (void, forever)
import Data.Word
main = do
r <- RM.newMTGen Nothing :: IO RM.MTGen
forever $ do
x0 <- RM.random r :: IO Word32
x1 <- RM.random r :: IO Word32
x2 <- RM.random r :: IO Word32
x3 <- RM.random r :: IO Word32
x4 <- RM.random r :: IO Word32
x5 <- RM.random r :: IO Word32
x6 <- RM.random r :: IO Word32
x7 <- RM.random r :: IO Word32
x8 <- RM.random r :: IO Word32
x9 <- RM.random r :: IO Word32
xA <- RM.random r :: IO Word32
xB <- RM.random r :: IO Word32
xC <- RM.random r :: IO Word32
xD <- RM.random r :: IO Word32
xE <- RM.random r :: IO Word32
xF <- RM.random r :: IO Word32
c0 <- RM.random r :: IO Word32
c1 <- RM.random r :: IO Word32
c2 <- RM.random r :: IO Word32
c3 <- RM.random r :: IO Word32
c4 <- RM.random r :: IO Word32
c5 <- RM.random r :: IO Word32
c6 <- RM.random r :: IO Word32
c7 <- RM.random r :: IO Word32
c8 <- RM.random r :: IO Word32
c9 <- RM.random r :: IO Word32
cA <- RM.random r :: IO Word32
cB <- RM.random r :: IO Word32
cC <- RM.random r :: IO Word32
cD <- RM.random r :: IO Word32
cE <- RM.random r :: IO Word32
cF <- RM.random r :: IO Word32
v0 <- RM.random r :: IO Word32
v1 <- RM.random r :: IO Word32
v2 <- RM.random r :: IO Word32
v3 <- RM.random r :: IO Word32
v4 <- RM.random r :: IO Word32
v5 <- RM.random r :: IO Word32
v6 <- RM.random r :: IO Word32
v7 <- RM.random r :: IO Word32
v8 <- RM.random r :: IO Word32
v9 <- RM.random r :: IO Word32
vA <- RM.random r :: IO Word32
vB <- RM.random r :: IO Word32
vC <- RM.random r :: IO Word32
vD <- RM.random r :: IO Word32
vE <- RM.random r :: IO Word32
vF <- RM.random r :: IO Word32
b0 <- RM.random r :: IO Word32
b1 <- RM.random r :: IO Word32
b2 <- RM.random r :: IO Word32
b3 <- RM.random r :: IO Word32
b4 <- RM.random r :: IO Word32
b5 <- RM.random r :: IO Word32
b6 <- RM.random r :: IO Word32
b7 <- RM.random r :: IO Word32
b8 <- RM.random r :: IO Word32
b9 <- RM.random r :: IO Word32
bA <- RM.random r :: IO Word32
bB <- RM.random r :: IO Word32
bC <- RM.random r :: IO Word32
bD <- RM.random r :: IO Word32
bE <- RM.random r :: IO Word32
bF <- RM.random r :: IO Word32
BL.hPutStr SI.stdout $ DBP.runPut $ do
DBP.putWord32be x0
DBP.putWord32be x1
DBP.putWord32be x2
DBP.putWord32be x3
DBP.putWord32be x4
DBP.putWord32be x5
DBP.putWord32be x6
DBP.putWord32be x7
DBP.putWord32be x8
DBP.putWord32be x9
DBP.putWord32be xA
DBP.putWord32be xB
DBP.putWord32be xC
DBP.putWord32be xD
DBP.putWord32be xE
DBP.putWord32be xF
DBP.putWord32be c0
DBP.putWord32be c1
DBP.putWord32be c2
DBP.putWord32be c3
DBP.putWord32be c4
DBP.putWord32be c5
DBP.putWord32be c6
DBP.putWord32be c7
DBP.putWord32be c8
DBP.putWord32be c9
DBP.putWord32be cA
DBP.putWord32be cB
DBP.putWord32be cC
DBP.putWord32be cD
DBP.putWord32be cE
DBP.putWord32be cF
DBP.putWord32be v0
DBP.putWord32be v1
DBP.putWord32be v2
DBP.putWord32be v3
DBP.putWord32be v4
DBP.putWord32be v5
DBP.putWord32be v6
DBP.putWord32be v7
DBP.putWord32be v8
DBP.putWord32be v9
DBP.putWord32be vA
DBP.putWord32be vB
DBP.putWord32be vC
DBP.putWord32be vD
DBP.putWord32be vE
DBP.putWord32be vF
DBP.putWord32be b0
DBP.putWord32be b1
DBP.putWord32be b2
DBP.putWord32be b3
DBP.putWord32be b4
DBP.putWord32be b5
DBP.putWord32be b6
DBP.putWord32be b7
DBP.putWord32be b8
DBP.putWord32be b9
DBP.putWord32be bA
DBP.putWord32be bB
DBP.putWord32be bC
DBP.putWord32be bD
DBP.putWord32be bE
DBP.putWord32be bF
The short code outputs about 6 megabytes of random bytes per second on my
computer. The fast code - about 150 megabytes per seccond.
If I reduce number of that variables from 64 to 16 in the fast code, the
speed drops to about 78 megabytes per second.
How to make this code compact and idiomatic without slowing it down?
Creating and storing new points on a core plot graph
Creating and storing new points on a core plot graph
So far I have made a graph with core plot and I now need to put the data
points in. My biggest problem is I am getting new data, about every 10 or
so minutes. I don't want to overload the app so I have configured the
graph to just show 10 at a time, but the user will be able to scroll to
see more. Here's where my question is. I need to add a number to an array
every time I receive more data. Is this possible? Am I going to have to
physically make 1,000 objects in an array and set them each? This would
seem like a cumbersome process and it seem like their would be another
simpler way. This leads me to my next problem. I will need to start
erasing data after 1,000 or so data points have been made. Will this mean
I will have to physically alter each point one back? Or if it is possible
to add new points automatically without making 1,000 separate objects for
an array, could I just dump the last one and make a new one? Sorry if this
seems really complicated. I am not looking for tons of code, just an idea
to make new objects in an array and saving them, without actually adding
1,000 separate objects. If you need, I can upload my graph (I have not
done it because its pretty big, but if it will help add a comment)
Cheers
So far I have made a graph with core plot and I now need to put the data
points in. My biggest problem is I am getting new data, about every 10 or
so minutes. I don't want to overload the app so I have configured the
graph to just show 10 at a time, but the user will be able to scroll to
see more. Here's where my question is. I need to add a number to an array
every time I receive more data. Is this possible? Am I going to have to
physically make 1,000 objects in an array and set them each? This would
seem like a cumbersome process and it seem like their would be another
simpler way. This leads me to my next problem. I will need to start
erasing data after 1,000 or so data points have been made. Will this mean
I will have to physically alter each point one back? Or if it is possible
to add new points automatically without making 1,000 separate objects for
an array, could I just dump the last one and make a new one? Sorry if this
seems really complicated. I am not looking for tons of code, just an idea
to make new objects in an array and saving them, without actually adding
1,000 separate objects. If you need, I can upload my graph (I have not
done it because its pretty big, but if it will help add a comment)
Cheers
Preserve Scroll Position When Pushing ViewController In Code in a Storyboard App
Preserve Scroll Position When Pushing ViewController In Code in a
Storyboard App
I have a storyboard app that has a few view controller that need to get
pushed on the navigation stack programmatically, instead of with segues.
I'm using the following code to do it:
POCollectionViewController* vc = [self.storyboard
instantiateViewControllerWithIdentifier:@"categoryView"];
POCategory* destination = (POCategory*)self.collections[indexPath.row];
[vc setShowingCollection:destination];
[self.navigationController pushViewController:vc animated:YES];
My problem is that when I use segues to push view controllers and I press
the 'back' button, the scroll position is preserved, but when I use the
above code and press the 'back' button, my previous view controller
appears with the scroll bar at the top.
Is it re-instantiating a view controller that is supposed to be already on
the navigation stack? How can I preserve the scroll position?
Storyboard App
I have a storyboard app that has a few view controller that need to get
pushed on the navigation stack programmatically, instead of with segues.
I'm using the following code to do it:
POCollectionViewController* vc = [self.storyboard
instantiateViewControllerWithIdentifier:@"categoryView"];
POCategory* destination = (POCategory*)self.collections[indexPath.row];
[vc setShowingCollection:destination];
[self.navigationController pushViewController:vc animated:YES];
My problem is that when I use segues to push view controllers and I press
the 'back' button, the scroll position is preserved, but when I use the
above code and press the 'back' button, my previous view controller
appears with the scroll bar at the top.
Is it re-instantiating a view controller that is supposed to be already on
the navigation stack? How can I preserve the scroll position?
App crashs on opening the PDF for second time
App crashs on opening the PDF for second time
I have method which generates a pdf and opens it when the method is called.
generate_pdf()
file_location =
File.join(Rho::RhoApplication.get_app_path('public')+'pdfs/',
File110.pdf')
System.open_url(file_location)
Now on the generate_pdf() i have,
pdf = PDF::Writer.new
x = pdf.absolute_left_margin - 10
y = pdf.absolute_top_margin - 10
pdf.add_text(x,y,"Hello World",20)
file_location =
File.join(Rho::RhoApplication.get_app_path('public')+'pdfs/',
File110.pdf')
pdf.save_as(file_location)
So the above code runs only for the first time. On second click the app
crashes. What's wrong with the code ?
I have method which generates a pdf and opens it when the method is called.
generate_pdf()
file_location =
File.join(Rho::RhoApplication.get_app_path('public')+'pdfs/',
File110.pdf')
System.open_url(file_location)
Now on the generate_pdf() i have,
pdf = PDF::Writer.new
x = pdf.absolute_left_margin - 10
y = pdf.absolute_top_margin - 10
pdf.add_text(x,y,"Hello World",20)
file_location =
File.join(Rho::RhoApplication.get_app_path('public')+'pdfs/',
File110.pdf')
pdf.save_as(file_location)
So the above code runs only for the first time. On second click the app
crashes. What's wrong with the code ?
Insert a value in iFrame
Insert a value in iFrame
I've got this structure and I want to change the values of the form based
on the form before. Problem is, the iframe got no ID and I can't set one
as it is a plugin that retrieves the data from another domain.
...<input type="button"
onclick="document.getElementById('betterplace').style.display='block';
var betterplace =
document.getElementById('betterplace')[0];betterplace.getElementsByTagName('iframe')[0].document.getElementById('donation_presenter_address_first_name').value=document.getElementById('_vorname').value;
" style="border:none; height: 50px; width: 250px;
font-weight:bold; font-size: 14pt;
background-color:#94C119;color:white;cursor: pointer;"
value="Ihre Spende abschließen"/>
<div id="betterplace" style="display:none;">
<div
style="width:500px;height:2px;margin-bottom:5px;background-color:
#94c119"/>
<br/>
<script type="text/javascript">
...
I've got this structure and I want to change the values of the form based
on the form before. Problem is, the iframe got no ID and I can't set one
as it is a plugin that retrieves the data from another domain.
...<input type="button"
onclick="document.getElementById('betterplace').style.display='block';
var betterplace =
document.getElementById('betterplace')[0];betterplace.getElementsByTagName('iframe')[0].document.getElementById('donation_presenter_address_first_name').value=document.getElementById('_vorname').value;
" style="border:none; height: 50px; width: 250px;
font-weight:bold; font-size: 14pt;
background-color:#94C119;color:white;cursor: pointer;"
value="Ihre Spende abschließen"/>
<div id="betterplace" style="display:none;">
<div
style="width:500px;height:2px;margin-bottom:5px;background-color:
#94c119"/>
<br/>
<script type="text/javascript">
...
Complexity of lists in haskell in Data.map
Complexity of lists in haskell in Data.map
Sorry if this seems like an obvious question.
I was creating a Data.map of lists {actually a tuple of an integer and a
list (Integer, [(Integer, Integer)])} for implementing a priority queue +
adjacency list for some graph algorithms like Dijkstras and Prims,
The Data.map is implemented using binary trees(I read that) so I just want
to confirm that when doing the map operations (I believe they will be
rotations) the interpreter does not do deep copies of the list just
shallow copies of the references of lists right?
Thanks in advance.
Sorry if this seems like an obvious question.
I was creating a Data.map of lists {actually a tuple of an integer and a
list (Integer, [(Integer, Integer)])} for implementing a priority queue +
adjacency list for some graph algorithms like Dijkstras and Prims,
The Data.map is implemented using binary trees(I read that) so I just want
to confirm that when doing the map operations (I believe they will be
rotations) the interpreter does not do deep copies of the list just
shallow copies of the references of lists right?
Thanks in advance.
Saturday, 14 September 2013
Android simulator failed to load the application
Android simulator failed to load the application
I am using phonegap3.0 to develop android/wp7 apps.
For android i installed lastest adt bundle and installed avd simulator and
configured AVD to run application. Whenever i run the application its very
slow cannot load a sample page in android. I am using windows 7 machine
with 4GB memory. Find the following error.
[2013-09-15 10:07:48 - samplePhonegapKendo] ------------------------------
[2013-09-15 10:07:48 - samplePhonegapKendo] Android Launch!
[2013-09-15 10:07:48 - samplePhonegapKendo] adb is running normally.
[2013-09-15 10:07:48 - samplePhonegapKendo] Performing
org.samplePhonegapKendo.samplePhonegapKendo activity launch
[2013-09-15 10:07:52 - samplePhonegapKendo] Launching a new emulator
with Virtual Device 'AVD2.3.3'
[2013-09-15 10:07:57 - Emulator] emulator: Failed to open the HAX device!
[2013-09-15 10:07:57 - Emulator]
[2013-09-15 10:07:57 - Emulator] emulator: Open HAX device failed
[2013-09-15 10:07:57 - Emulator]
[2013-09-15 10:07:57 - Emulator] HAX is not working and emulator runs
in emulation mode
[2013-09-15 10:07:59 - Emulator] emulator: emulator window was out of
view and was recentered
[2013-09-15 10:07:59 - Emulator]
[2013-09-15 10:07:59 - samplePhonegapKendo] New emulator found:
emulator-5554
[2013-09-15 10:07:59 - samplePhonegapKendo] Waiting for HOME
('android.process.acore') to be launched...
[2013-09-15 10:08:50 - samplePhonegapKendo] HOME is up on device
'emulator-5554'
[2013-09-15 10:08:50 - samplePhonegapKendo] Uploading
samplePhonegapKendo.apk onto device 'emulator-5554'
[2013-09-15 10:09:14 - samplePhonegapKendo] Failed to install
samplePhonegapKendo.apk on device 'emulator-5554': timeout
[2013-09-15 10:09:14 - samplePhonegapKendo] Launch canceled!
I am using phonegap3.0 to develop android/wp7 apps.
For android i installed lastest adt bundle and installed avd simulator and
configured AVD to run application. Whenever i run the application its very
slow cannot load a sample page in android. I am using windows 7 machine
with 4GB memory. Find the following error.
[2013-09-15 10:07:48 - samplePhonegapKendo] ------------------------------
[2013-09-15 10:07:48 - samplePhonegapKendo] Android Launch!
[2013-09-15 10:07:48 - samplePhonegapKendo] adb is running normally.
[2013-09-15 10:07:48 - samplePhonegapKendo] Performing
org.samplePhonegapKendo.samplePhonegapKendo activity launch
[2013-09-15 10:07:52 - samplePhonegapKendo] Launching a new emulator
with Virtual Device 'AVD2.3.3'
[2013-09-15 10:07:57 - Emulator] emulator: Failed to open the HAX device!
[2013-09-15 10:07:57 - Emulator]
[2013-09-15 10:07:57 - Emulator] emulator: Open HAX device failed
[2013-09-15 10:07:57 - Emulator]
[2013-09-15 10:07:57 - Emulator] HAX is not working and emulator runs
in emulation mode
[2013-09-15 10:07:59 - Emulator] emulator: emulator window was out of
view and was recentered
[2013-09-15 10:07:59 - Emulator]
[2013-09-15 10:07:59 - samplePhonegapKendo] New emulator found:
emulator-5554
[2013-09-15 10:07:59 - samplePhonegapKendo] Waiting for HOME
('android.process.acore') to be launched...
[2013-09-15 10:08:50 - samplePhonegapKendo] HOME is up on device
'emulator-5554'
[2013-09-15 10:08:50 - samplePhonegapKendo] Uploading
samplePhonegapKendo.apk onto device 'emulator-5554'
[2013-09-15 10:09:14 - samplePhonegapKendo] Failed to install
samplePhonegapKendo.apk on device 'emulator-5554': timeout
[2013-09-15 10:09:14 - samplePhonegapKendo] Launch canceled!
bitnami, wordpress, changing Auto-login username and adding a password
bitnami, wordpress, changing Auto-login username and adding a password
I can access my instance correctly and without any trouble.
I have had some web designers overseas create a website and they needed my
FTP details. In order to edit my website, I had to send them my PPK code
which was generated when I first created my instance on Amazon ec2.
My question is: how to I change the Auto-login username and add a password
so every time I start an SSH, I can feel at ease that the people who
created my website cannot access it any further?
Cheers
I can access my instance correctly and without any trouble.
I have had some web designers overseas create a website and they needed my
FTP details. In order to edit my website, I had to send them my PPK code
which was generated when I first created my instance on Amazon ec2.
My question is: how to I change the Auto-login username and add a password
so every time I start an SSH, I can feel at ease that the people who
created my website cannot access it any further?
Cheers
Font layout algorithm, Win32
Font layout algorithm, Win32
I'm trying to come up with a platform independent way to render unicode
text to some platform specific surface, but assuming that most platforms
support something at least kinda similar, maybe we can talk in terms of
the win32 API. I'm most interested in rendering LARGE buffers and
supporting rich text, so while I definitely don't want to ever look inside
a unicode buffer, I'd like to be told myself what to draw and be hinted
where to draw it, so if the buffer is modified, I might properly ask for
updates on partial regions of the buffer.
So the actual questions. GetTextExtentExPointA clearly allows me to get
the widths of each character, how do I get the width of a nonbreaking
extent of text? If I have some long word, he should probably be put on a
new line rather than splitting the word. How can I tell where to break the
text? Will I need to actually look inside the unicode buffer? This seems
very dangerous. Also, how do I figure how far each baseline should be
while rendering?
Finally, this is already looking like it's going to be extremely
complicated. Are there alternative strategies for doing what I'm trying to
do? I really would not at all like to rerender a HUGE buffer each time I
change tiny chunks of it. Something between looking at individual glyphs
and just giving a box to spat text in.
I'm trying to come up with a platform independent way to render unicode
text to some platform specific surface, but assuming that most platforms
support something at least kinda similar, maybe we can talk in terms of
the win32 API. I'm most interested in rendering LARGE buffers and
supporting rich text, so while I definitely don't want to ever look inside
a unicode buffer, I'd like to be told myself what to draw and be hinted
where to draw it, so if the buffer is modified, I might properly ask for
updates on partial regions of the buffer.
So the actual questions. GetTextExtentExPointA clearly allows me to get
the widths of each character, how do I get the width of a nonbreaking
extent of text? If I have some long word, he should probably be put on a
new line rather than splitting the word. How can I tell where to break the
text? Will I need to actually look inside the unicode buffer? This seems
very dangerous. Also, how do I figure how far each baseline should be
while rendering?
Finally, this is already looking like it's going to be extremely
complicated. Are there alternative strategies for doing what I'm trying to
do? I really would not at all like to rerender a HUGE buffer each time I
change tiny chunks of it. Something between looking at individual glyphs
and just giving a box to spat text in.
Using Antlr4 with C#
Using Antlr4 with C#
I am trying to make antlr4 working with c# in Visual Studio 2012 (I have
antlr extension), but when I try to compile my project, error appears
(Unkown build error: Object reference not set to an instance of an
object). When I try to run antlr jar on my grammar, null pointer exception
appears.
I am trying to make antlr4 working with c# in Visual Studio 2012 (I have
antlr extension), but when I try to compile my project, error appears
(Unkown build error: Object reference not set to an instance of an
object). When I try to run antlr jar on my grammar, null pointer exception
appears.
Images being served with django server but not getting dispalyed on webpage
Images being served with django server but not getting dispalyed on webpage
im creating a website and everything was working fine until yesterday when
suddenly images on the webpage stopped getting displayed. The server seems
to GET the images but they are not getting displayed and I cant figure out
why. When i load the webpage, i get a placeholder for the image like its
going to load but then it goes away.
These are my configurations:
settings.py
CACHES = {
'default' : {
'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
'LOCATION': '127.0.0.1:11211',
}
}
MEDIA_ROOT = '/home/hammad/virt_env/virt1/gccFishing/media'
MEDIA_URL = '/media/'
Im using sorl-thumbnail, a django package for dispalying images. Using
this, I display an image in a template like this:
template.html
{% load thumbnail %}
{% thumbnail user.image "200x200" crop="center" as im %}
<img src="{{im.url}}" width="{{ im.width }}" height="{{ im.height }}">
{% endthumbnail %}
These are server messages when i load a webpage:
[14/Sep/2013 15:41:45] "GET / HTTP/1.1" 200 159218
[14/Sep/2013 15:41:45] "GET
/media/cache/c0/17/c017021609e735bdc53f402ae6009bae.jpg HTTP/1.1" 200
155657
[14/Sep/2013 15:41:47] "GET /saudi-arabia/ HTTP/1.1" 200 284186
[14/Sep/2013 15:41:47] "GET
/media/cache/e9/25/e925347688cc973ecc997f00b6ee0b83.jpg HTTP/1.1" 200
156198
[14/Sep/2013 15:41:47] "GET
/media/cache/a4/ac/a4aca3c7a23aeada770062e9519a8daa.jpg HTTP/1.1" 200
156731
[14/Sep/2013 15:41:47] "GET
/media/cache/0a/21/0a2118ecac84d6451f3dd39cd881d8bb.jpg HTTP/1.1" 200
156728
The images were working fine before i restarted my computer. After the
restart, this problem started, and along with this problem I started
getting these errors:
[14/Sep/2013 15:41:48] "GET
/media/cache/0a/21/0a2118ecac84d6451f3dd39cd881d8bb.jpg HTTP/1.1" 500 59
----------------------------------------
Exception happened during processing of request from ('127.0.0.1', 46531)
Traceback (most recent call last):
File "/usr/lib/python2.7/SocketServer.py", line 593, in
process_request_thread
self.finish_request(request, client_address)
File "/usr/lib/python2.7/SocketServer.py", line 334, in finish_request
self.RequestHandlerClass(request, client_address, self)
File
"/home/hammad/virt_env/virt1/local/lib/python2.7/site-packages/django/core/servers/basehttp.py",
line 150, in __init__
super(WSGIRequestHandler, self).__init__(*args, **kwargs)
File "/usr/lib/python2.7/SocketServer.py", line 651, in __init__
self.finish()
File "/usr/lib/python2.7/SocketServer.py", line 710, in finish
self.wfile.close()
File "/usr/lib/python2.7/socket.py", line 279, in close
self.flush()
File "/usr/lib/python2.7/socket.py", line 303, in flush
self._sock.sendall(view[write_offset:write_offset+buffer_size])
error: [Errno 32] Broken pipe
I googled for the error and found out its something of a browser issue.
Please give me your views as to what is happening here.
Thanks in advance
im creating a website and everything was working fine until yesterday when
suddenly images on the webpage stopped getting displayed. The server seems
to GET the images but they are not getting displayed and I cant figure out
why. When i load the webpage, i get a placeholder for the image like its
going to load but then it goes away.
These are my configurations:
settings.py
CACHES = {
'default' : {
'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
'LOCATION': '127.0.0.1:11211',
}
}
MEDIA_ROOT = '/home/hammad/virt_env/virt1/gccFishing/media'
MEDIA_URL = '/media/'
Im using sorl-thumbnail, a django package for dispalying images. Using
this, I display an image in a template like this:
template.html
{% load thumbnail %}
{% thumbnail user.image "200x200" crop="center" as im %}
<img src="{{im.url}}" width="{{ im.width }}" height="{{ im.height }}">
{% endthumbnail %}
These are server messages when i load a webpage:
[14/Sep/2013 15:41:45] "GET / HTTP/1.1" 200 159218
[14/Sep/2013 15:41:45] "GET
/media/cache/c0/17/c017021609e735bdc53f402ae6009bae.jpg HTTP/1.1" 200
155657
[14/Sep/2013 15:41:47] "GET /saudi-arabia/ HTTP/1.1" 200 284186
[14/Sep/2013 15:41:47] "GET
/media/cache/e9/25/e925347688cc973ecc997f00b6ee0b83.jpg HTTP/1.1" 200
156198
[14/Sep/2013 15:41:47] "GET
/media/cache/a4/ac/a4aca3c7a23aeada770062e9519a8daa.jpg HTTP/1.1" 200
156731
[14/Sep/2013 15:41:47] "GET
/media/cache/0a/21/0a2118ecac84d6451f3dd39cd881d8bb.jpg HTTP/1.1" 200
156728
The images were working fine before i restarted my computer. After the
restart, this problem started, and along with this problem I started
getting these errors:
[14/Sep/2013 15:41:48] "GET
/media/cache/0a/21/0a2118ecac84d6451f3dd39cd881d8bb.jpg HTTP/1.1" 500 59
----------------------------------------
Exception happened during processing of request from ('127.0.0.1', 46531)
Traceback (most recent call last):
File "/usr/lib/python2.7/SocketServer.py", line 593, in
process_request_thread
self.finish_request(request, client_address)
File "/usr/lib/python2.7/SocketServer.py", line 334, in finish_request
self.RequestHandlerClass(request, client_address, self)
File
"/home/hammad/virt_env/virt1/local/lib/python2.7/site-packages/django/core/servers/basehttp.py",
line 150, in __init__
super(WSGIRequestHandler, self).__init__(*args, **kwargs)
File "/usr/lib/python2.7/SocketServer.py", line 651, in __init__
self.finish()
File "/usr/lib/python2.7/SocketServer.py", line 710, in finish
self.wfile.close()
File "/usr/lib/python2.7/socket.py", line 279, in close
self.flush()
File "/usr/lib/python2.7/socket.py", line 303, in flush
self._sock.sendall(view[write_offset:write_offset+buffer_size])
error: [Errno 32] Broken pipe
I googled for the error and found out its something of a browser issue.
Please give me your views as to what is happening here.
Thanks in advance
After my app launches Play Store it returns immediately to the app
After my app launches Play Store it returns immediately to the app
I have the rate app button in the app which lunches Play Store application
where the user can rate my app. I'm using standard code:
try {
String appPackageName = getPackageName();
Intent marketIntent = new Intent(Intent.ACTION_VIEW,
Uri.parse("market://details?id=" + appPackageName));
startActivity(marketIntent);
} catch (Exception e) {
}
The problem is that from time to time (but not every time), Play Store
application closes after few seconds and the phone returns to my
application. In this case the user won't manage to rate my app.
I have the rate app button in the app which lunches Play Store application
where the user can rate my app. I'm using standard code:
try {
String appPackageName = getPackageName();
Intent marketIntent = new Intent(Intent.ACTION_VIEW,
Uri.parse("market://details?id=" + appPackageName));
startActivity(marketIntent);
} catch (Exception e) {
}
The problem is that from time to time (but not every time), Play Store
application closes after few seconds and the phone returns to my
application. In this case the user won't manage to rate my app.
Can't get right syntax for JavaScript variables inside php print
Can't get right syntax for JavaScript variables inside php print
What is wrong with the following code, that I produced for testing the
content of the button?
I get the syntax error "unexpected T_CONSTANT_ENCAPSED_STRING"
<?php /* Created on: 14-9-2013 */ ?>
<html>
<head>
<script type="text/javascript" charset="utf-8">
var mldkr = Math.round(screen.availWidth/2.08);
var supro = Math.round((screen.availHeight)/6), alto=supro*4
</script>
</head>
<body>
<table>
<?php
print '
<tr height="30">
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td align="right">
<button type="button" onclick="fenEspo = window.open(urlesp,
'', 'toolbar=0, location=0, directories=0, menuBar=0,
scrollbars=1, resizable=1, height='+alto+', top='+supro+',
left='+mldkr+', width='+mldkr, true)" title="Ne gravas, ne
kalkuliĝas por la statistiko.">Kaj kion donas Gugl
Trenslejt kiel<br />traduko(j)n por Esperanto?</button>
</td>
<td align="center">
<input type="radio" name="eo" value="1" />jes
<input type="radio" name="eo" value="0" />ne
<input type="radio" name="eo" value="-1" disabled="disabled"
/><font size="-3">ne aferkoncerna</font>
</td>
</tr>
'
?>
</table>
</body>
</html>
Thank you!
What is wrong with the following code, that I produced for testing the
content of the button?
I get the syntax error "unexpected T_CONSTANT_ENCAPSED_STRING"
<?php /* Created on: 14-9-2013 */ ?>
<html>
<head>
<script type="text/javascript" charset="utf-8">
var mldkr = Math.round(screen.availWidth/2.08);
var supro = Math.round((screen.availHeight)/6), alto=supro*4
</script>
</head>
<body>
<table>
<?php
print '
<tr height="30">
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td align="right">
<button type="button" onclick="fenEspo = window.open(urlesp,
'', 'toolbar=0, location=0, directories=0, menuBar=0,
scrollbars=1, resizable=1, height='+alto+', top='+supro+',
left='+mldkr+', width='+mldkr, true)" title="Ne gravas, ne
kalkuliĝas por la statistiko.">Kaj kion donas Gugl
Trenslejt kiel<br />traduko(j)n por Esperanto?</button>
</td>
<td align="center">
<input type="radio" name="eo" value="1" />jes
<input type="radio" name="eo" value="0" />ne
<input type="radio" name="eo" value="-1" disabled="disabled"
/><font size="-3">ne aferkoncerna</font>
</td>
</tr>
'
?>
</table>
</body>
</html>
Thank you!
Friday, 13 September 2013
How can i create a note on my webpage for iphone user that there is an app?
How can i create a note on my webpage for iphone user that there is an app?
i startet to detect which platform is be used. And this already works:
// User-Agent-String auslesen
var UserAgent = navigator.userAgent.toLowerCase();
// User-Agent auf gewisse Schlüsselwörter prüfen
if (UserAgent.search(/(iphone|ipod|opera
mini|fennec|palm|blackberry|android|symbian|series60)/) > -1) {
// mobiles Endgerät
alert("YOU HAVE A SMARTPHONE");
} else {
// kein mobiles Endgerät (PC, Tablet, etc.)
alert("YOU HAVE NO SMARTPHONE");
}
but now I want to show on the iphone IF you have an iphone a full screen
page that there is an app and you should download it. and than a button
for the app and a button for "no thank you, continue to normal page".
Can someone help me? The page should be full screen and nothing else
should be visible. thank you
i startet to detect which platform is be used. And this already works:
// User-Agent-String auslesen
var UserAgent = navigator.userAgent.toLowerCase();
// User-Agent auf gewisse Schlüsselwörter prüfen
if (UserAgent.search(/(iphone|ipod|opera
mini|fennec|palm|blackberry|android|symbian|series60)/) > -1) {
// mobiles Endgerät
alert("YOU HAVE A SMARTPHONE");
} else {
// kein mobiles Endgerät (PC, Tablet, etc.)
alert("YOU HAVE NO SMARTPHONE");
}
but now I want to show on the iphone IF you have an iphone a full screen
page that there is an app and you should download it. and than a button
for the app and a button for "no thank you, continue to normal page".
Can someone help me? The page should be full screen and nothing else
should be visible. thank you
strange copy constructor behavior in inherit tree
strange copy constructor behavior in inherit tree
i have three class types: Base->Center->Child, and i want to make it
posible to construct child type from parent type, so i declared them like
this:
class Base {
public:
Base(void) {}
virtual ~Base(void) {}
Base(const Base &ref) {}
};
class Center : public virtual Base {
public:
Center(void) : Base() {}
Center(const Base &ref) : Base(ref) {}
};
class Child : public virtual Center {
public:
Child(void) : Center() {}
Child(const Base &ref) : Center(ref) {}
};
it's OK to call it like this: (calling Center and Base's copy constructor)
Base base;
Center center(base);
however, these code act unexpectedly:
Child child(base);
it would call those method step by step:
1. Child(const Base &)
2. Base()
3. Center(const Base &)
i have three class types: Base->Center->Child, and i want to make it
posible to construct child type from parent type, so i declared them like
this:
class Base {
public:
Base(void) {}
virtual ~Base(void) {}
Base(const Base &ref) {}
};
class Center : public virtual Base {
public:
Center(void) : Base() {}
Center(const Base &ref) : Base(ref) {}
};
class Child : public virtual Center {
public:
Child(void) : Center() {}
Child(const Base &ref) : Center(ref) {}
};
it's OK to call it like this: (calling Center and Base's copy constructor)
Base base;
Center center(base);
however, these code act unexpectedly:
Child child(base);
it would call those method step by step:
1. Child(const Base &)
2. Base()
3. Center(const Base &)
Using jq to parse json output of AWS CLI
Using jq to parse json output of AWS CLI
I would like to use jq (http://stedolan.github.io/jq/) to parse the json
output from aws elb describe-load-balancers and return the name and AZs
only where AvailabilityZones contains a specific value.
Here is partial redacted json representing the source output:
{
"LoadBalancerDescriptions": [
{
{
"AvailabilityZones": [
"us-east-1b",
"us-east-1c",
"us-east-1d"
],
"CanonicalHostedZoneName": "example.us-east-1.elb.amazonaws.com",
I have only been able to get this to work when specifiying the full list
of values for the AvailabilityZones key.
$ aws elb describe-load-balancers --region us-east-1 |jq
'.LoadBalancerDescriptions[] | select(.AvailabilityZones == ["us-east-1b",
"us-east-1c", "us-east-1d"]) | .CanonicalHostedZoneName,
.AvailabilityZones'
The above works, but I want to just select if it contains a value for
"us-east-1b", regardless of the other values.
I would like to use jq (http://stedolan.github.io/jq/) to parse the json
output from aws elb describe-load-balancers and return the name and AZs
only where AvailabilityZones contains a specific value.
Here is partial redacted json representing the source output:
{
"LoadBalancerDescriptions": [
{
{
"AvailabilityZones": [
"us-east-1b",
"us-east-1c",
"us-east-1d"
],
"CanonicalHostedZoneName": "example.us-east-1.elb.amazonaws.com",
I have only been able to get this to work when specifiying the full list
of values for the AvailabilityZones key.
$ aws elb describe-load-balancers --region us-east-1 |jq
'.LoadBalancerDescriptions[] | select(.AvailabilityZones == ["us-east-1b",
"us-east-1c", "us-east-1d"]) | .CanonicalHostedZoneName,
.AvailabilityZones'
The above works, but I want to just select if it contains a value for
"us-east-1b", regardless of the other values.
Java - Convert a string format to standard format
Java - Convert a string format to standard format
I am parsing the pdf file using iText and one of the pdf files is encoded
with CP1252 (at least that is what Eclipse said).
text1�text2?text3��text3?text4
In pdf, the symbol is a dash (-) and spaces. Is there anyway to convert to
a format so Java can read it?
I am parsing the pdf file using iText and one of the pdf files is encoded
with CP1252 (at least that is what Eclipse said).
text1�text2?text3��text3?text4
In pdf, the symbol is a dash (-) and spaces. Is there anyway to convert to
a format so Java can read it?
UIActionSheet is not showing separator on the last item on iOS 7 GM
UIActionSheet is not showing separator on the last item on iOS 7 GM
It could be probably a bug on iOS7. But the last button is not separated
from the previous one
As you can see from the image. This happens on both Simulator and device
using iOS7 GM. Does everyone else has the same problem?
UIActionSheet *actionSheet = [[UIActionSheet alloc]
initWithTitle:@"Title"
delegate:self
cancelButtonTitle:nil
destructiveButtonTitle:nil
otherButtonTitles:@"First", @"Second",
@"Third", @"Fourth", nil];
actionSheet.actionSheetStyle = UIBarStyleBlackOpaque;
[actionSheet showInView:self.view];
As you can see the code is quite simple. Any idea on how to fix the
problem? Or some third party library I can use instead of UIActionSheet?
Thanks, Regards
F
It could be probably a bug on iOS7. But the last button is not separated
from the previous one
As you can see from the image. This happens on both Simulator and device
using iOS7 GM. Does everyone else has the same problem?
UIActionSheet *actionSheet = [[UIActionSheet alloc]
initWithTitle:@"Title"
delegate:self
cancelButtonTitle:nil
destructiveButtonTitle:nil
otherButtonTitles:@"First", @"Second",
@"Third", @"Fourth", nil];
actionSheet.actionSheetStyle = UIBarStyleBlackOpaque;
[actionSheet showInView:self.view];
As you can see the code is quite simple. Any idea on how to fix the
problem? Or some third party library I can use instead of UIActionSheet?
Thanks, Regards
F
does same image name but from different folder affect performance in web application?
does same image name but from different folder affect performance in web
application?
i have lots of images in my we page with same name but in different folder
like
<div class="wrapper">
<div id="pictures1" class="effect_1">
<div><img src="pictures/sample/1/01/1/01.jpg" width="125"
height="188"></div>
<div><img src="pictures/sample/1/01/1/02.jpg" width="125"
height="188"></div>
<div><img src="pictures/sample/1/01/1/03.jpg" width="125"
height="188"></div>
<div><img src="pictures/sample/1/01/1/04.jpg" width="125"
height="188"></div>
<div><img src="pictures/sample/1/01/1/05.jpg" width="125"
height="188"></div>
<div><img src="pictures/sample/1/01/1/06.jpg" width="125"
height="188"></div>
<div><img src="pictures/sample/1/01/1/07.jpg" width="125"
height="188"></div>
<div><img src="pictures/sample/1/01/1/08.jpg" width="125"
height="188"></div>
<div><img src="pictures/sample/1/01/1/09.jpg" width="125"
height="188"></div>
<div><img src="pictures/sample/1/01/1/10.jpg" width="125"
height="188"></div>
<div><img src="pictures/sample/x.gif" width="125" height="188"></div>
</div>
<div id="pictures2" class="effect_2">
<div><img src="pictures/sample/1/02/1/01.jpg" width="125"
height="188"></div>
<div><img src="pictures/sample/1/02/1/02.jpg" width="125"
height="188"></div>
<div><img src="pictures/sample/1/02/1/03.jpg" width="125"
height="188"></div>
<div><img src="pictures/sample/1/02/1/04.jpg" width="125"
height="188"></div>
<div><img src="pictures/sample/1/02/1/05.jpg" width="125"
height="188"></div>
<div><img src="pictures/sample/1/02/1/06.jpg" width="125"
height="188"></div>
<div><img src="pictures/sample/1/02/1/07.jpg" width="125"
height="188"></div>
<div><img src="pictures/sample/1/02/1/08.jpg" width="125"
height="188"></div>
<div><img src="pictures/sample/1/02/1/09.jpg" width="125"
height="188"></div>
<div><img src="pictures/sample/1/02/1/10.jpg" width="125"
height="188"></div>
<div><img src="pictures/sample/x.gif" width="125" height="188"></div>
</div>
..................... up to 09/../../.jpg
</div>
there are lots of images in my page this is just for sample, when i run my
application it takes too much time to load and suddenly crash...why?
application?
i have lots of images in my we page with same name but in different folder
like
<div class="wrapper">
<div id="pictures1" class="effect_1">
<div><img src="pictures/sample/1/01/1/01.jpg" width="125"
height="188"></div>
<div><img src="pictures/sample/1/01/1/02.jpg" width="125"
height="188"></div>
<div><img src="pictures/sample/1/01/1/03.jpg" width="125"
height="188"></div>
<div><img src="pictures/sample/1/01/1/04.jpg" width="125"
height="188"></div>
<div><img src="pictures/sample/1/01/1/05.jpg" width="125"
height="188"></div>
<div><img src="pictures/sample/1/01/1/06.jpg" width="125"
height="188"></div>
<div><img src="pictures/sample/1/01/1/07.jpg" width="125"
height="188"></div>
<div><img src="pictures/sample/1/01/1/08.jpg" width="125"
height="188"></div>
<div><img src="pictures/sample/1/01/1/09.jpg" width="125"
height="188"></div>
<div><img src="pictures/sample/1/01/1/10.jpg" width="125"
height="188"></div>
<div><img src="pictures/sample/x.gif" width="125" height="188"></div>
</div>
<div id="pictures2" class="effect_2">
<div><img src="pictures/sample/1/02/1/01.jpg" width="125"
height="188"></div>
<div><img src="pictures/sample/1/02/1/02.jpg" width="125"
height="188"></div>
<div><img src="pictures/sample/1/02/1/03.jpg" width="125"
height="188"></div>
<div><img src="pictures/sample/1/02/1/04.jpg" width="125"
height="188"></div>
<div><img src="pictures/sample/1/02/1/05.jpg" width="125"
height="188"></div>
<div><img src="pictures/sample/1/02/1/06.jpg" width="125"
height="188"></div>
<div><img src="pictures/sample/1/02/1/07.jpg" width="125"
height="188"></div>
<div><img src="pictures/sample/1/02/1/08.jpg" width="125"
height="188"></div>
<div><img src="pictures/sample/1/02/1/09.jpg" width="125"
height="188"></div>
<div><img src="pictures/sample/1/02/1/10.jpg" width="125"
height="188"></div>
<div><img src="pictures/sample/x.gif" width="125" height="188"></div>
</div>
..................... up to 09/../../.jpg
</div>
there are lots of images in my page this is just for sample, when i run my
application it takes too much time to load and suddenly crash...why?
need help to custom expandableListView
need help to custom expandableListView
I am new to android, and I want to implement a ListView like the image
below. It seems expandableListView may meet my request, but what I want is
only Item 4 has children and can be expanded, 'Item 1' is just an option
user can click, and can't be expanded. I read the document of Expandable
List View, and it's not clear enough how to implement this. Can anyone
gave some suggestion on implementing this? Thank you so much
I am new to android, and I want to implement a ListView like the image
below. It seems expandableListView may meet my request, but what I want is
only Item 4 has children and can be expanded, 'Item 1' is just an option
user can click, and can't be expanded. I read the document of Expandable
List View, and it's not clear enough how to implement this. Can anyone
gave some suggestion on implementing this? Thank you so much
Thursday, 12 September 2013
Trouble Migrating Joomla Site Warning: Invalid argument supplied for foreach()
Trouble Migrating Joomla Site Warning: Invalid argument supplied for
foreach()
I am trying to migrate somebodies joomla site (with their permission of
course) to a new domain name through dreamhost. I have tried to transfer
the folder exactly as is, but I am getting the following error:
Warning: Invalid argument supplied for foreach()
This is the actual website where the error is occuring
Can somebody please help me?
foreach()
I am trying to migrate somebodies joomla site (with their permission of
course) to a new domain name through dreamhost. I have tried to transfer
the folder exactly as is, but I am getting the following error:
Warning: Invalid argument supplied for foreach()
This is the actual website where the error is occuring
Can somebody please help me?
How can I draw a cloud shape using UIBezierPath?
How can I draw a cloud shape using UIBezierPath?
I am trying to draw a cloud-like shape using UIBezierPath, and I am seeing
a line on the screen, but it isn't anything close to what I am going for.
Conceptually, I would like to start at a point and draw an arc (maybe
about 1/3 of a circle), and then when that shape is done drawing, I'd like
to draw another one right after it, in a circular motion. So that when I
am done drawing, I have a round, cloud-like creation.
Here is the code I am using to draw the UIBezierPath:
- (void)drawBezierAnimate:(BOOL)animate
{
UIBezierPath *bezierPath = [self bezierPath];
CAShapeLayer *bezier = [[CAShapeLayer alloc] init];
bezier.path = bezierPath.CGPath;
bezier.strokeColor = [UIColor blueColor].CGColor;
bezier.fillColor = [UIColor clearColor].CGColor;
bezier.lineWidth = 5.0;
bezier.strokeStart = 0.0;
bezier.strokeEnd = 1.0;
[self.view.layer addSublayer:bezier];
if (animate)
{
CABasicAnimation *animateStrokeEnd = [CABasicAnimation
animationWithKeyPath:@"strokeEnd"];
animateStrokeEnd.duration = 5.0;
animateStrokeEnd.fromValue = [NSNumber numberWithFloat:0.0f];
animateStrokeEnd.toValue = [NSNumber numberWithFloat:1.0f];
[bezier addAnimation:animateStrokeEnd forKey:@"strokeEndAnimation"];
}
}
But the real struggle comes with making the UIBezierPath match the pattern
I am looking for. Here is what I have for that:
- (UIBezierPath *)bezierPath
{
UIBezierPath *path = [UIBezierPath bezierPath];
CGPoint point = self.view.center;
[path moveToPoint:CGPointMake(0, self.view.frame.size.height / 2.0)];
for (CGFloat f = 0.0; f < 10; f++)
{
[path addArcWithCenter:path.currentPoint radius:75 startAngle:0
endAngle:DEGREES_TO_RADIANS(135) clockwise:YES];
[path addLineToPoint:point];
}
return path;
}
I thought that if I just kept adding to the currentPoint of the path that
that would update as I went and I'd be getting somewhere. But it's not
even close. Can I get a nudge in the right direction?
I am trying to draw a cloud-like shape using UIBezierPath, and I am seeing
a line on the screen, but it isn't anything close to what I am going for.
Conceptually, I would like to start at a point and draw an arc (maybe
about 1/3 of a circle), and then when that shape is done drawing, I'd like
to draw another one right after it, in a circular motion. So that when I
am done drawing, I have a round, cloud-like creation.
Here is the code I am using to draw the UIBezierPath:
- (void)drawBezierAnimate:(BOOL)animate
{
UIBezierPath *bezierPath = [self bezierPath];
CAShapeLayer *bezier = [[CAShapeLayer alloc] init];
bezier.path = bezierPath.CGPath;
bezier.strokeColor = [UIColor blueColor].CGColor;
bezier.fillColor = [UIColor clearColor].CGColor;
bezier.lineWidth = 5.0;
bezier.strokeStart = 0.0;
bezier.strokeEnd = 1.0;
[self.view.layer addSublayer:bezier];
if (animate)
{
CABasicAnimation *animateStrokeEnd = [CABasicAnimation
animationWithKeyPath:@"strokeEnd"];
animateStrokeEnd.duration = 5.0;
animateStrokeEnd.fromValue = [NSNumber numberWithFloat:0.0f];
animateStrokeEnd.toValue = [NSNumber numberWithFloat:1.0f];
[bezier addAnimation:animateStrokeEnd forKey:@"strokeEndAnimation"];
}
}
But the real struggle comes with making the UIBezierPath match the pattern
I am looking for. Here is what I have for that:
- (UIBezierPath *)bezierPath
{
UIBezierPath *path = [UIBezierPath bezierPath];
CGPoint point = self.view.center;
[path moveToPoint:CGPointMake(0, self.view.frame.size.height / 2.0)];
for (CGFloat f = 0.0; f < 10; f++)
{
[path addArcWithCenter:path.currentPoint radius:75 startAngle:0
endAngle:DEGREES_TO_RADIANS(135) clockwise:YES];
[path addLineToPoint:point];
}
return path;
}
I thought that if I just kept adding to the currentPoint of the path that
that would update as I went and I'd be getting somewhere. But it's not
even close. Can I get a nudge in the right direction?
How to change the color of svg objects imported into raphaeljs?
How to change the color of svg objects imported into raphaeljs?
I imported a .svg file into raphael and I would like to be able to change
the fill colors and stroke colors of the shapes.
my_set = my_paper.importSVG( my_svgXML ) ;
for( var i = 0 ; i < my_set.length ; i++ )
{ var lvo_element = my_set[ i ] ;
lvo_element.attr( { 'fill' : '#fafafa' } ) ;
console.log( lvo_element.attrs.fill ) ;
// correctly outputs '#fafafa'
}
... but the elements' colors are not updating. However, lvo_element.glow()
does work.
NOTE:
I used jquery.ajax to load my.svg into app
I used raphael-svg-import.js for importing it into raphael
I imported a .svg file into raphael and I would like to be able to change
the fill colors and stroke colors of the shapes.
my_set = my_paper.importSVG( my_svgXML ) ;
for( var i = 0 ; i < my_set.length ; i++ )
{ var lvo_element = my_set[ i ] ;
lvo_element.attr( { 'fill' : '#fafafa' } ) ;
console.log( lvo_element.attrs.fill ) ;
// correctly outputs '#fafafa'
}
... but the elements' colors are not updating. However, lvo_element.glow()
does work.
NOTE:
I used jquery.ajax to load my.svg into app
I used raphael-svg-import.js for importing it into raphael
Optionable pattern?
Optionable pattern?
I am trying to come up with a way to be able to make any (or at least a
group of) class have the ability to have options.
This is the generic interface that I would like to have
interface OptionableInterface
{
public function getOption($key);
public function setOption($key, $value);
public function getOptions();
public function setOptions($options, $merge);
public function removeOption($key);
}
I've thought about either implementing a concrete class with the above
interface then extending it as needed, but since PHP has no multiple
inheritance, this could be a problem.
The other way would be to use the decorator pattern. But I'm uncertain if
this is the correct usage of decorator pattern.
Any ideas? I'm stuck using PHP 5.2 for now (maybe able to change to 5.3
later in which case I can use traits).
I am trying to come up with a way to be able to make any (or at least a
group of) class have the ability to have options.
This is the generic interface that I would like to have
interface OptionableInterface
{
public function getOption($key);
public function setOption($key, $value);
public function getOptions();
public function setOptions($options, $merge);
public function removeOption($key);
}
I've thought about either implementing a concrete class with the above
interface then extending it as needed, but since PHP has no multiple
inheritance, this could be a problem.
The other way would be to use the decorator pattern. But I'm uncertain if
this is the correct usage of decorator pattern.
Any ideas? I'm stuck using PHP 5.2 for now (maybe able to change to 5.3
later in which case I can use traits).
Parsing a Nested Array (PHP)
Parsing a Nested Array (PHP)
I am trying to find an efficient way to do the following :
1) Parse an array. 2) If the element is a single value, store it/echo it.
3) If the element is an array, Parse it and store/echo all of its
elements.
An example would be :
$array = array(15,25,'Dog',[11,'Cat','Cookie15'],22)
This would be echo'd as :
15 25 Dog 11 Cat Cookie15 22
Note : The maximum number of Nested layers of Arrays = 2 (The max is an
Array within an Array, not deeper than that).
The code I have made so far is :
foreach($_POST as $key=>$value){
if(is_array($value))
{
<Not sure how to handle this condition! Need to parse the array and
echo individual elements>
}
else
{
echo "Input name : $key Value : $value ";
}
}
I am trying to find an efficient way to do the following :
1) Parse an array. 2) If the element is a single value, store it/echo it.
3) If the element is an array, Parse it and store/echo all of its
elements.
An example would be :
$array = array(15,25,'Dog',[11,'Cat','Cookie15'],22)
This would be echo'd as :
15 25 Dog 11 Cat Cookie15 22
Note : The maximum number of Nested layers of Arrays = 2 (The max is an
Array within an Array, not deeper than that).
The code I have made so far is :
foreach($_POST as $key=>$value){
if(is_array($value))
{
<Not sure how to handle this condition! Need to parse the array and
echo individual elements>
}
else
{
echo "Input name : $key Value : $value ";
}
}
ASP.NET 4.0 Deployment Issue CSS / Javascript
ASP.NET 4.0 Deployment Issue CSS / Javascript
I have created a small ASP .Net 4.5 application for a client which I have
deployed to their server.
When the application is deployed to the client server, the css is not
applied to the screens and javascript is not working either.
The clients server is a Windows Server 2008 R2 server and IIS is version 7.
Any help or advice would be greatly appreciated.
I have created a small ASP .Net 4.5 application for a client which I have
deployed to their server.
When the application is deployed to the client server, the css is not
applied to the screens and javascript is not working either.
The clients server is a Windows Server 2008 R2 server and IIS is version 7.
Any help or advice would be greatly appreciated.
Wednesday, 11 September 2013
Rule Flow In Drools
Rule Flow In Drools
I am new to drools and guvnor.
I have basic question for rule flow.
I have created 3 rules using guided editor on guvnor plugin. Now I want to
invoke the 2nd or 3rd rule based on the outcome of 1st rule.
e.g. If the patient's age is less than 18 go for 2nd rule for minor checks
otherwise invoke 3rd rule for check from senior physician.
So can this be achieved using rule flow? If yes how? Are there any example
links, documents demonstrating it? Any help very much appreciated.
Thanks
I am new to drools and guvnor.
I have basic question for rule flow.
I have created 3 rules using guided editor on guvnor plugin. Now I want to
invoke the 2nd or 3rd rule based on the outcome of 1st rule.
e.g. If the patient's age is less than 18 go for 2nd rule for minor checks
otherwise invoke 3rd rule for check from senior physician.
So can this be achieved using rule flow? If yes how? Are there any example
links, documents demonstrating it? Any help very much appreciated.
Thanks
Rails: Appending models to collection
Rails: Appending models to collection
I'm trying to conditionally build up a list of models. I.e.
@items = []
if some_condition
@items << MyModel.where(...)
end
if another_condition
@items << MyModel.where(...)
end
...
This isn't working. It will actually build up an array of the correct
objects but when I access fields and relationships of items in the array,
they are 'not found'. I tried a few other things like @items =
MyModel.none and @items = {} and .merge but none work. I cant seem to
figure this out.
What is the best way to conditionally build up a collection like this?
I'm trying to conditionally build up a list of models. I.e.
@items = []
if some_condition
@items << MyModel.where(...)
end
if another_condition
@items << MyModel.where(...)
end
...
This isn't working. It will actually build up an array of the correct
objects but when I access fields and relationships of items in the array,
they are 'not found'. I tried a few other things like @items =
MyModel.none and @items = {} and .merge but none work. I cant seem to
figure this out.
What is the best way to conditionally build up a collection like this?
Get php object values into array
Get php object values into array
Thanks for reading.
I want what is output from the initial echo $zip to be stuffed into an
array as a simple integer stack... i've tried [],{} and a variety of other
accessors... Thanks again!
I have:
$userZip = new ZipCode($userZip); $theZips = array();
foreach ($userZip->getZipsInRange(0, 10) as $miles => $zip) {
echo $zip . '
';
$theZips = $zip;
}
print_r($theZips);
// print_r($theZips) output: ZipCode Object (
[zip_code_id:ZipCode:private] => 33816 [zip_code:ZipCode:private] => 21115
[lat:ZipCode:private] => 42.48 [lon:ZipCode:private] => -83.02
[city:ZipCode:private] => CENTER Ville [county:ZipCode:private] =>
[area_code:ZipCode:private] => [time_zone:ZipCode:private] =>
[state_prefix:ZipCode:private] => VA [state_name:ZipCode:private] =>
[mysql_table] => zip_code [mysql_conn] => [mysql_row:ZipCode:private] =>
Array ( [miles] => 8.88798662376604 [zip_code_id] => 33816 [zip_code] =>
21119 [city] => City [state_prefix] => VA [lat] => 42.48 [lon] => -83.02 )
[print_name:ZipCode:private] => 48015 [location_type:ZipCode:private] =>
[miles] => 8.88798662376604 )
Thanks for reading.
I want what is output from the initial echo $zip to be stuffed into an
array as a simple integer stack... i've tried [],{} and a variety of other
accessors... Thanks again!
I have:
$userZip = new ZipCode($userZip); $theZips = array();
foreach ($userZip->getZipsInRange(0, 10) as $miles => $zip) {
echo $zip . '
';
$theZips = $zip;
}
print_r($theZips);
// print_r($theZips) output: ZipCode Object (
[zip_code_id:ZipCode:private] => 33816 [zip_code:ZipCode:private] => 21115
[lat:ZipCode:private] => 42.48 [lon:ZipCode:private] => -83.02
[city:ZipCode:private] => CENTER Ville [county:ZipCode:private] =>
[area_code:ZipCode:private] => [time_zone:ZipCode:private] =>
[state_prefix:ZipCode:private] => VA [state_name:ZipCode:private] =>
[mysql_table] => zip_code [mysql_conn] => [mysql_row:ZipCode:private] =>
Array ( [miles] => 8.88798662376604 [zip_code_id] => 33816 [zip_code] =>
21119 [city] => City [state_prefix] => VA [lat] => 42.48 [lon] => -83.02 )
[print_name:ZipCode:private] => 48015 [location_type:ZipCode:private] =>
[miles] => 8.88798662376604 )
Kruskals Algorithm using C
Kruskals Algorithm using C
I have two Kruskal algorithm programs.One which i made and another which i
took from a friend. Both the programs look almost same to me except a few
things which do not matter. hes program is givinga different ouput and
mine a different one. Though i think both of them are giving the wrong set
of edges but the right weight. My program :
#include<stdio.h>
#include<stdlib.h>
typedef struct info
{
int initial;
int final;
int weight;
}info;
void uon(int x,int y,int*p,int *r);
int findset(int x,int *p);
void sort(info *edgelist,int n);
void qksort(info *edgelist,int l,int u);
int partition(info *edgelist,int l,int u);
void makeset(int n,int *p,int *r);
int kruskal(info *edgelist,int n,int w);
int main()
{
FILE *fp;
int n,i,j,temp;
int **gmatrix,cost;
info *edgelist;
int cnt =0,a;
fp = fopen("grph.txt","r");
fscanf(fp,"%d",&n);
gmatrix=(int**)calloc(sizeof(int*),n);
for(i=0;i<n;i++)
gmatrix[i]=(int*)calloc(sizeof(int),n);
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
fscanf(fp,"%d",&temp);
gmatrix[i][j]=temp;
}
}
edgelist = (info*)calloc(sizeof(info),n*n);
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
printf("%d ",gmatrix[i][j]);
temp = gmatrix[i][j];
a=cnt;
if(temp !=0)
{
edgelist[a].initial = i;
edgelist[a].weight = temp;
edgelist[a].final = j;
cnt++;
}
}
printf("\n");
}
printf("%d \n",edgelist[0].initial);
printf("%d \n ",cnt);
cost =kruskal(edgelist,n,cnt);
printf("\nTotal Cost is %d",cost);
return 0;
}
int kruskal(info *edgelist,int n,int cnt)
{
int b,i,initial,dest,cost_cnt=0;
int *p,*r;
int cost=0;
info *krus;
p = (int*)calloc(sizeof(int),n);
r = (int*)calloc(sizeof(int),n);
makeset(n,p,r);
qksort(edgelist,0,cnt);
//sort(edgelist,w);
krus=(info*)calloc(sizeof(info),n-1);
for(i=0;i<cnt;i++)
{
//printf("INITIAL 1 : %d \n",edgelist[i].initial);
initial=findset(edgelist[i].initial,p);
// printf("INITIAL 2 : %d \n",initial);
dest=findset(edgelist[i].final,p);
if(initial!=dest)
{
b=cost_cnt;
krus[b].initial=initial;
krus[b].final=dest;
krus[b].weight=edgelist[i].weight;
cost_cnt++;
uon(initial,dest,p,r);
}
}
for(i=0;i<cost_cnt;i++)
{
printf("{%d,%d}: %d \n",krus[i].initial+1,krus[i].final+1,
krus[i].weight);
cost = cost + krus[i].weight;
}
return cost;
}
void uon(int initial,int dest,int *p,int *r)
{
int u,v;
//link(findset(x),findset(y));
printf("\n X1 : %d",initial);
u = findset(initial,p);
printf("\n X2 : %d",initial);
v = findset(dest,p);
if(r[u]>r[v])
{
p[v] = u;
}
else
{
p[u] = v;
if(r[u]==r[v])
r[v] = r[v]+1;
}
}
int findset(int x,int *p)
{
if(x!=p[x])
{
p[x]=findset(p[x],p);
}
return p[x];
}
void makeset(int n,int *p,int *r)
{
int i;
for(i=0;i<n;i++)
{
p[i] = i;
r[i] = 0;
}
}
void qksort(info *edgelist,int l,int u) {
int pq;
if(l<u)
{
pq=partition(edgelist,l,u);
qksort(edgelist,l,pq-1);
qksort(edgelist,pq+1,u);
}
}
int partition(info *edgelist,int l,int u) {
int i,j,pq;
info pv,t;
pv.initial=edgelist[l].initial;
pv.final=edgelist[l].final;
pv.weight=edgelist[l].weight;
j=l;
for(i=l+1;i<=u;i++)
{
if(edgelist[i].weight<=pv.weight)
{
j++;
t=edgelist[i];
t.initial=edgelist[i].initial;
t.final=edgelist[i].final;
t.weight=edgelist[i].weight;
edgelist[i].initial=edgelist[j].initial;
edgelist[i].final=edgelist[j].final;
edgelist[i].weight=edgelist[j].weight;
edgelist[j].initial=t.initial;
edgelist[j].final=t.final;
edgelist[j].weight=t.weight;
}
}
pq=j;
t.initial=edgelist[pq].initial;
t.final=edgelist[pq].final;
t.weight=edgelist[pq].weight;
edgelist[pq].initial=edgelist[l].initial;
edgelist[pq].final=edgelist[l].final;
edgelist[pq].weight=edgelist[l].weight;
edgelist[l].initial=t.initial;
edgelist[l].final=t.final;
edgelist[l].weight=t.weight;
return(pq);
}
Friends Program :
#include<stdio.h>
#include<stdlib.h>
struct info{
int initial;
int dest;
int weight;
};
void kruskal(struct info *,int **,int,int);
void makeset(int *,int *,int);
void quick_sort(struct info *,int,int);
int find_set(int *,int);
void union_set(int * ,int *,int,int);
int partition(struct info *,int,int);
int main(int argc,char **argv)
{
FILE *fp;
int **gmatrix;
int num,source,i,j,temp,count,a;
struct info *edgelist;
if(argc!=2)
{
printf("enter the proper argument");
return(EXIT_FAILURE);
}
fp=fopen(argv[1],"r");
fscanf(fp,"%d",&num);
printf("num=%d\n",num);
gmatrix=(int **)calloc(sizeof(int *),num);
for(i=0;i<num;i++)
gmatrix[i]=(int *)calloc(sizeof(int),num);
for(i=0;i<num;i++)
{
for(j=0;j<num;j++)
{
fscanf(fp,"%d",&temp);
*(*(gmatrix+i)+j)=temp;
}
}
edgelist=(struct info *)calloc(sizeof(struct info),num*num);
count=0;
for(i=0;i<num;i++)
{
for(j=0;j<num;j++)
{
temp=*(*(gmatrix+i)+j);
if(temp!=0)
{
a=count;
edgelist[a].initial=i;
edgelist[a].dest=j;
printf("(%d,%d)\n",edgelist[a].initial,edgelist[a].dest);
edgelist[a].weight=temp;
printf("weight=%d\t",edgelist[a].weight);
count=count+1;
printf("a=%d\n",count);
}
}
}
printf("ans=%d\t",count);
kruskal(edgelist,gmatrix,num,count);
}
void kruskal(struct info *edgelist,int **gmatrix,int num,int count)
{
int *parent;
int *rank;
int i,cost_count,b,initial,dest,cost=0;
struct info *krus;
parent = (int *)calloc(sizeof(int),num);
rank = (int *)calloc(sizeof(int),num);
makeset(parent,rank,num);
quick_sort(edgelist,0,count);
for(i=0;i<count;i++)
{
printf("sorting=%d\t",edgelist[i].weight);
}
krus=(struct info *)calloc(sizeof(struct info),num-1);
cost_count=0;
for(i=0;i<count;i++)
{
initial=find_set(parent,edgelist[i].initial);
dest=find_set(parent,edgelist[i].dest);
if(initial != dest )
{
b=cost_count;
krus[b].initial=initial;
krus[b].dest=dest;
krus[b].weight=edgelist[i].weight;
cost_count=cost_count+1;
// printf("weight=%d and
(%d,%d)\t",krus[b].weight,krus[b].initial,krus[b].dest);
union_set(parent,rank,initial,dest);
}
}
for (i=0;i<num-1;i++) {
printf("\n%d . {%d, %d}",i+1,krus[i].initial+1,krus[i].dest+1);
cost = cost + krus[i].weight;
}
printf("\ncost of minimum mst is..... %d\n\n",cost);
}
void union_set(int *parent ,int *rank,int initial,int dest)
{
int u,v;
printf("\n X1 : %d",u);
u=find_set(parent,initial);
printf("\n X2 : %d\n",u);
v=find_set(parent,dest);
if(rank[u]>rank[v])
parent[v]=u;
else
{
parent[u]=v;
if(rank[u]==rank[v])
rank[v]=rank[v]+1;
}
}
int find_set(int *parent,int x)
{
if(x!=parent[x])
parent[x] = find_set(parent,parent[x]);
return parent[x];
}
void makeset(int *parent,int *rank,int num)
{
int i;
for (i=0; i<num; i++)
{
parent[i] = i;
rank[i] = 0;
}
}
void quick_sort(struct info *edgelist,int left,int right)
{
int q;
if(left<right)
{
q=partition(edgelist,left,right);
quick_sort(edgelist,left,q-1);
quick_sort(edgelist,q+1,right);
}
}
int partition(struct info *edgelist,int left,int right)
{
struct info pivot,temp;
int i,j,k,pp;
pivot.initial=edgelist[left].initial;
pivot.dest =edgelist[left].dest;
pivot.weight =edgelist[left].weight;
j=left;
for(i=left+1;i<=right;i++)
{
if(edgelist[i].weight < pivot.weight)
{
j=j+1;
temp.initial=edgelist[i].initial;
temp.dest=edgelist[i].dest;
temp.weight=edgelist[i].weight;
edgelist[i].initial=edgelist[j].initial;
edgelist[i].dest=edgelist[j].dest;
edgelist[i].weight=edgelist[j].weight;
edgelist[j].initial=temp.initial;
edgelist[j].dest=temp.dest;
edgelist[j].weight=temp.weight;
}
}
pp=j;
temp.initial=edgelist[left].initial;
temp.dest=edgelist[left].dest;
temp.weight=edgelist[left].weight;
edgelist[left].initial=edgelist[pp].initial;
edgelist[left].dest=edgelist[pp].dest;
edgelist[left].weight=edgelist[pp].weight;
edgelist[pp].initial=temp.initial;
edgelist[pp].dest=temp.dest;
edgelist[pp].weight=temp.weight;
//printf("aaaa=%d\t\n",pp);
return pp;
}
The graph i am using
9
0 4 0 0 0 0 0 8 0
4 0 8 0 0 0 0 11 0
0 8 0 7 0 4 0 0 2
0 0 7 0 9 14 0 0 0
0 0 0 9 0 10 0 0 0
0 0 4 14 10 0 2 0 0
0 0 0 0 0 2 0 1 6
8 11 0 0 0 0 1 0 7
0 0 2 0 0 0 6 7 0
The weight is 37 but the programs arent giving the crrect set of edges
I have two Kruskal algorithm programs.One which i made and another which i
took from a friend. Both the programs look almost same to me except a few
things which do not matter. hes program is givinga different ouput and
mine a different one. Though i think both of them are giving the wrong set
of edges but the right weight. My program :
#include<stdio.h>
#include<stdlib.h>
typedef struct info
{
int initial;
int final;
int weight;
}info;
void uon(int x,int y,int*p,int *r);
int findset(int x,int *p);
void sort(info *edgelist,int n);
void qksort(info *edgelist,int l,int u);
int partition(info *edgelist,int l,int u);
void makeset(int n,int *p,int *r);
int kruskal(info *edgelist,int n,int w);
int main()
{
FILE *fp;
int n,i,j,temp;
int **gmatrix,cost;
info *edgelist;
int cnt =0,a;
fp = fopen("grph.txt","r");
fscanf(fp,"%d",&n);
gmatrix=(int**)calloc(sizeof(int*),n);
for(i=0;i<n;i++)
gmatrix[i]=(int*)calloc(sizeof(int),n);
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
fscanf(fp,"%d",&temp);
gmatrix[i][j]=temp;
}
}
edgelist = (info*)calloc(sizeof(info),n*n);
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
printf("%d ",gmatrix[i][j]);
temp = gmatrix[i][j];
a=cnt;
if(temp !=0)
{
edgelist[a].initial = i;
edgelist[a].weight = temp;
edgelist[a].final = j;
cnt++;
}
}
printf("\n");
}
printf("%d \n",edgelist[0].initial);
printf("%d \n ",cnt);
cost =kruskal(edgelist,n,cnt);
printf("\nTotal Cost is %d",cost);
return 0;
}
int kruskal(info *edgelist,int n,int cnt)
{
int b,i,initial,dest,cost_cnt=0;
int *p,*r;
int cost=0;
info *krus;
p = (int*)calloc(sizeof(int),n);
r = (int*)calloc(sizeof(int),n);
makeset(n,p,r);
qksort(edgelist,0,cnt);
//sort(edgelist,w);
krus=(info*)calloc(sizeof(info),n-1);
for(i=0;i<cnt;i++)
{
//printf("INITIAL 1 : %d \n",edgelist[i].initial);
initial=findset(edgelist[i].initial,p);
// printf("INITIAL 2 : %d \n",initial);
dest=findset(edgelist[i].final,p);
if(initial!=dest)
{
b=cost_cnt;
krus[b].initial=initial;
krus[b].final=dest;
krus[b].weight=edgelist[i].weight;
cost_cnt++;
uon(initial,dest,p,r);
}
}
for(i=0;i<cost_cnt;i++)
{
printf("{%d,%d}: %d \n",krus[i].initial+1,krus[i].final+1,
krus[i].weight);
cost = cost + krus[i].weight;
}
return cost;
}
void uon(int initial,int dest,int *p,int *r)
{
int u,v;
//link(findset(x),findset(y));
printf("\n X1 : %d",initial);
u = findset(initial,p);
printf("\n X2 : %d",initial);
v = findset(dest,p);
if(r[u]>r[v])
{
p[v] = u;
}
else
{
p[u] = v;
if(r[u]==r[v])
r[v] = r[v]+1;
}
}
int findset(int x,int *p)
{
if(x!=p[x])
{
p[x]=findset(p[x],p);
}
return p[x];
}
void makeset(int n,int *p,int *r)
{
int i;
for(i=0;i<n;i++)
{
p[i] = i;
r[i] = 0;
}
}
void qksort(info *edgelist,int l,int u) {
int pq;
if(l<u)
{
pq=partition(edgelist,l,u);
qksort(edgelist,l,pq-1);
qksort(edgelist,pq+1,u);
}
}
int partition(info *edgelist,int l,int u) {
int i,j,pq;
info pv,t;
pv.initial=edgelist[l].initial;
pv.final=edgelist[l].final;
pv.weight=edgelist[l].weight;
j=l;
for(i=l+1;i<=u;i++)
{
if(edgelist[i].weight<=pv.weight)
{
j++;
t=edgelist[i];
t.initial=edgelist[i].initial;
t.final=edgelist[i].final;
t.weight=edgelist[i].weight;
edgelist[i].initial=edgelist[j].initial;
edgelist[i].final=edgelist[j].final;
edgelist[i].weight=edgelist[j].weight;
edgelist[j].initial=t.initial;
edgelist[j].final=t.final;
edgelist[j].weight=t.weight;
}
}
pq=j;
t.initial=edgelist[pq].initial;
t.final=edgelist[pq].final;
t.weight=edgelist[pq].weight;
edgelist[pq].initial=edgelist[l].initial;
edgelist[pq].final=edgelist[l].final;
edgelist[pq].weight=edgelist[l].weight;
edgelist[l].initial=t.initial;
edgelist[l].final=t.final;
edgelist[l].weight=t.weight;
return(pq);
}
Friends Program :
#include<stdio.h>
#include<stdlib.h>
struct info{
int initial;
int dest;
int weight;
};
void kruskal(struct info *,int **,int,int);
void makeset(int *,int *,int);
void quick_sort(struct info *,int,int);
int find_set(int *,int);
void union_set(int * ,int *,int,int);
int partition(struct info *,int,int);
int main(int argc,char **argv)
{
FILE *fp;
int **gmatrix;
int num,source,i,j,temp,count,a;
struct info *edgelist;
if(argc!=2)
{
printf("enter the proper argument");
return(EXIT_FAILURE);
}
fp=fopen(argv[1],"r");
fscanf(fp,"%d",&num);
printf("num=%d\n",num);
gmatrix=(int **)calloc(sizeof(int *),num);
for(i=0;i<num;i++)
gmatrix[i]=(int *)calloc(sizeof(int),num);
for(i=0;i<num;i++)
{
for(j=0;j<num;j++)
{
fscanf(fp,"%d",&temp);
*(*(gmatrix+i)+j)=temp;
}
}
edgelist=(struct info *)calloc(sizeof(struct info),num*num);
count=0;
for(i=0;i<num;i++)
{
for(j=0;j<num;j++)
{
temp=*(*(gmatrix+i)+j);
if(temp!=0)
{
a=count;
edgelist[a].initial=i;
edgelist[a].dest=j;
printf("(%d,%d)\n",edgelist[a].initial,edgelist[a].dest);
edgelist[a].weight=temp;
printf("weight=%d\t",edgelist[a].weight);
count=count+1;
printf("a=%d\n",count);
}
}
}
printf("ans=%d\t",count);
kruskal(edgelist,gmatrix,num,count);
}
void kruskal(struct info *edgelist,int **gmatrix,int num,int count)
{
int *parent;
int *rank;
int i,cost_count,b,initial,dest,cost=0;
struct info *krus;
parent = (int *)calloc(sizeof(int),num);
rank = (int *)calloc(sizeof(int),num);
makeset(parent,rank,num);
quick_sort(edgelist,0,count);
for(i=0;i<count;i++)
{
printf("sorting=%d\t",edgelist[i].weight);
}
krus=(struct info *)calloc(sizeof(struct info),num-1);
cost_count=0;
for(i=0;i<count;i++)
{
initial=find_set(parent,edgelist[i].initial);
dest=find_set(parent,edgelist[i].dest);
if(initial != dest )
{
b=cost_count;
krus[b].initial=initial;
krus[b].dest=dest;
krus[b].weight=edgelist[i].weight;
cost_count=cost_count+1;
// printf("weight=%d and
(%d,%d)\t",krus[b].weight,krus[b].initial,krus[b].dest);
union_set(parent,rank,initial,dest);
}
}
for (i=0;i<num-1;i++) {
printf("\n%d . {%d, %d}",i+1,krus[i].initial+1,krus[i].dest+1);
cost = cost + krus[i].weight;
}
printf("\ncost of minimum mst is..... %d\n\n",cost);
}
void union_set(int *parent ,int *rank,int initial,int dest)
{
int u,v;
printf("\n X1 : %d",u);
u=find_set(parent,initial);
printf("\n X2 : %d\n",u);
v=find_set(parent,dest);
if(rank[u]>rank[v])
parent[v]=u;
else
{
parent[u]=v;
if(rank[u]==rank[v])
rank[v]=rank[v]+1;
}
}
int find_set(int *parent,int x)
{
if(x!=parent[x])
parent[x] = find_set(parent,parent[x]);
return parent[x];
}
void makeset(int *parent,int *rank,int num)
{
int i;
for (i=0; i<num; i++)
{
parent[i] = i;
rank[i] = 0;
}
}
void quick_sort(struct info *edgelist,int left,int right)
{
int q;
if(left<right)
{
q=partition(edgelist,left,right);
quick_sort(edgelist,left,q-1);
quick_sort(edgelist,q+1,right);
}
}
int partition(struct info *edgelist,int left,int right)
{
struct info pivot,temp;
int i,j,k,pp;
pivot.initial=edgelist[left].initial;
pivot.dest =edgelist[left].dest;
pivot.weight =edgelist[left].weight;
j=left;
for(i=left+1;i<=right;i++)
{
if(edgelist[i].weight < pivot.weight)
{
j=j+1;
temp.initial=edgelist[i].initial;
temp.dest=edgelist[i].dest;
temp.weight=edgelist[i].weight;
edgelist[i].initial=edgelist[j].initial;
edgelist[i].dest=edgelist[j].dest;
edgelist[i].weight=edgelist[j].weight;
edgelist[j].initial=temp.initial;
edgelist[j].dest=temp.dest;
edgelist[j].weight=temp.weight;
}
}
pp=j;
temp.initial=edgelist[left].initial;
temp.dest=edgelist[left].dest;
temp.weight=edgelist[left].weight;
edgelist[left].initial=edgelist[pp].initial;
edgelist[left].dest=edgelist[pp].dest;
edgelist[left].weight=edgelist[pp].weight;
edgelist[pp].initial=temp.initial;
edgelist[pp].dest=temp.dest;
edgelist[pp].weight=temp.weight;
//printf("aaaa=%d\t\n",pp);
return pp;
}
The graph i am using
9
0 4 0 0 0 0 0 8 0
4 0 8 0 0 0 0 11 0
0 8 0 7 0 4 0 0 2
0 0 7 0 9 14 0 0 0
0 0 0 9 0 10 0 0 0
0 0 4 14 10 0 2 0 0
0 0 0 0 0 2 0 1 6
8 11 0 0 0 0 1 0 7
0 0 2 0 0 0 6 7 0
The weight is 37 but the programs arent giving the crrect set of edges
Subscribe to:
Comments (Atom)