Thursday, 3 October 2013

Padding is invalid and cannot be removed in C# licensing method

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.

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] = ???

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);
}
}
}

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;
}

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.

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!

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

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" ...

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.

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.

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?

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:

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!

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.

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;
}

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!

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

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?

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!

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