Thursday, 3 October 2013

Android Mediaplayer Won't Stop

Android Mediaplayer Won't Stop

I have the following code to play an mp3 file from the web and this is
working but when I use the stop functionality the audio does not stop. Can
anyone point me towards a resource to find out more about this or tell me
where I am going wrong? Thanks.
showAudio.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
MediaPlayer mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
if (!showAudio.getText().equals("Stop")) {
try {
String url = lblAudio.getText().toString();
if (url.length() > 2) {
mediaPlayer.setDataSource(url);
mediaPlayer.prepare();
mediaPlayer.start();
showAudio.setText("Stop");
}
} catch (Exception e) {
Toast.makeText(getBaseContext(), "Sorry, there was a
problem playing audio.", Toast.LENGTH_SHORT).show();
}
} else {
try {
mediaPlayer.stop();
mediaPlayer.release();
} catch (Exception ex) {
ex.printStackTrace();
}
showAudio.setText("Audio");
}
}
});

Wednesday, 2 October 2013

From Query resultset to a JOptionPaneDialog

From Query resultset to a JOptionPaneDialog

I have a sparql query which returns some results. I need to let the user
to choose which of these results he will use next. I have coded this with
scanner, but I want to convert it now to a joptionpanedialog so that it is
more user friendly. I assume it is achieved via
JOptionPane.showInputDialog. However I dont know how to "translate" the
resultset in the object list of the joptionpane in the right format, and
then extract the selected elements. Any ideas how could I achieve this?
Thanks in advance
Query query = QueryFactory.create(queryString);
QueryExecution qe=
QueryExecutionFactory.create(query, model);
ResultSet resultset = qe.execSelect();
ResultSet results =
ResultSetFactory.copyResults(resultset);
final ResultSet results2 =
ResultSetFactory.copyResults(results);
System.out.println( "== Available Options ==" );
ResultSetFormatter.out(System.out, results, query);
System.out.println( "== Select Option ==" );
System.out.println( "== Type 0,1,2,3.. to choose Option
==" );
Scanner input = new Scanner( System.in );
final String inputs ;
inputs = input.next();
final String[] indices = inputs.split("\\s*,\\s*");
final List<QuerySolution> selectedSolutions = new
ArrayList<QuerySolution>( indices.length ) {{
final List<QuerySolution> solutions =
ResultSetFormatter.toList( results2 );
for ( final String index : indices ) {
add( solutions.get( Integer.valueOf( index )));
}
}};
String s = selectedSolutions.toString();
Pattern p = Pattern.compile("#([^>]+)>");
Matcher m = p.matcher(s);

Query to multiple each row's cost times quantity and sum

Query to multiple each row's cost times quantity and sum

I'm having a difficult time getting this to work. I have a table that
looks like this:
quantity cost
-------- ----
5 150
2 100
and I'd like to select a single result which should be 950. When I use
group by the entire quantities gets multiplied times the entire cost

Android Viewpager in Fragment

Android Viewpager in Fragment

So I'm trying to make an Swipe Image slider in a fragment and this is what
I've Got The app crashes when I set the adapter , Not sure exactly where
the problem is.
It was working ok before I put the viewpager in a fragment
public class Slider extends Fragment {
private static final int NUM_PAGES = 5;
private TheAdapter adapter;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
View view =inflater.inflate(R.layout.activity_reader, container, false);
ViewPager pager = (ViewPager) view.findViewById(R.id.pager);
adapter = new TheAdapter(getFragmentManager());
pager.setAdapter(adapter);
return view;
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onViewCreated(view, savedInstanceState);
}
And this is the adapter class
public class TheAdapter extends FragmentStatePagerAdapter{
private static final int NUM_PAGES = 5;
LayoutInflater inflater;
public TheAdapter(android.support.v4.app.FragmentManager fm) {
super(fm);
// TODO Auto-generated constructor stub
}
@Override
public boolean isViewFromObject(View view, Object object) {
// TODO Auto-generated method stub
return view == ((ViewGroup) object);
}
@Override
public void destroyItem(ViewGroup container, int position, Object
object) {
// TODO Auto-generated method stub
((ViewPager) container).removeView((View)object);
}
public Fragment getItem(int arg0) {
// TODO Auto-generated method stub
return new Slider();
}
@Override
public void destroyItem(View container, int position, Object object) {
// TODO Auto-generated method stub
super.destroyItem(container, position, object);
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return NUM_PAGES;
}}
}

Tuesday, 1 October 2013

c++ operator overloading. Function to get private value from overload

c++ operator overloading. Function to get private value from overload

I have trouble getting the "print" function in this class to get the right
total
class PRN {
private:
typedef pair < string, int > P;
int sz, // map size – no of distinct words
cnt, // counter for printing
total; // no of words
public:
// constructor
PRN ( const int& s = 1, const int& c = 0, const int& t = 0 ){
cnt= c;
total = t;
sz = s;
}
void operator ( ) ( const P& p ){
total += p.second;
cout << total;
}// overloaded operator, where P is defined as
// typedef pair < string, int > P;
void print () const{
cout <<"no of words in output list : " << total << endl;
}
};
then in my main i call
PRN p (m.size());
for_each(m.begin(),m.end(),p);
p.print();
m is a map containing some values(string, int); The operator is adding
because im printing them and I can see they are getting added but when I
called p.print() it returns zero for the "total".
Any suggestions? Thanks

Nested loops for menus (basic c++)

Nested loops for menus (basic c++)

I'm running into errors where they say that a, q, h, etc aren't declared
variables, but I'm not sure how to fix this. Here is an example of my
code.
I'm also getting an error where it doesn't recognize userinp inside the
while loop, but I'm not sure how to transfer the variable storage from
outside the while loop to inside the while loop without declaring a global
variable, which I want to avoid.
Last question: I want to be able to have any key immediately return to the
main menu after each menu item, but I'm not sure what to use for that.
Any help is greatly appreciated!
//Runs a program with a menu that the user can navigate through different
options with via text input
#include <iostream>
#include <iomanip>
#include <algorithm>
#include <ctype.h>
#include <string>
using namespace std;
int main()
{
int userinp;
cout<<"Here is the menu:" << endl;
cout<<"Help(H) addIntegers(A) subDoubles(D) Quit(Q)";
cin >> userinp;
userinp = tolower(userinp);
while userinp != q //loop while no q is input
{
if userinp == h
{
cout <<"This is the help menu. Upon returning to the main
menu, input A or a to add 2 intergers." << endl;
cout <<"Input D or d to subtract 2 doubles. Input Q or q to
quit.";
}
if userinp == a
{
int a, b, result;
cout <<"Enter two integers:";
cin << a << b;
result = a + b;
cout << "The sum of " << a << " + " << b << " = " << result;
}
}
}

Does every linear group admit a subgroup of dimension 1=?iso-8859-1?Q?=3F_=96_mathoverflow.net?=

Does every linear group admit a subgroup of dimension 1? – mathoverflow.net

Suppose that $G$ is a linear group of positive dimension, defined over
some field $k$. Is that true, that $G$ admits a (closed) one-dimensional
subgroup? I'm pretty much sure this is true in ...

The equation $f(x)= \frac{3^x+1}{2}$ for all positive integers x

The equation $f(x)= \frac{3^x+1}{2}$ for all positive integers x

The equation $f(x)= \frac{3^x+1}{2}$ for all positive integers $x$
generates a sequence such that the difference of every consecutive f(x)
forms another say g(x) such that $g(x) = 3^{x-1}$. What I did is to find
$f'(x)$ and expecting that it is equal to $3^x$, but it did not.
For example: if $x= 1,2,3,4,5$, $f(x) = 2,5,14,41,122$. I observed that $
5-2 =3; 14-5 = 3^2;41-14=3^3 ; 122-41= 3^4 $ Is this true for all? thanks

Monday, 30 September 2013

please help me to prove this exercise in modern algebra

please help me to prove this exercise in modern algebra

Suppose $W$ be a free R-module with basis $X=\{x_1,...,x_n\}$ . If $\phi:
W \rightarrow W$ is an R-module endomorphism with matrix $A$ relative to
$X$ , then the determinant of the endomorphism $\phi$ is defined to be the
determinant $|A| \in R$ and is denoted $|\phi |$. How to show $|\phi |$ is
independent of the choice of $X$?
thanks in advanced..

IBM System X M4 Series Servers Oracle Linux Support

IBM System X M4 Series Servers Oracle Linux Support

Is Oracle Linux runnable/compatible with the M4 Series of the IBM System X
Servers?
In their compatibility website, most compatible machines listed are those
from Dell and HP..there are IBM system x..but all are of older models..
(This is the link of the tested configurations/compatible machines for
Oracle Linux:
http://linux.oracle.com/pls/apex/f?p=102:1:2850003747338068:pg_R_27262430945134281:NO&pg_min_row=1&pg_max_rows=20&pg_rows_fetched=20)
We currently have no machines to test the Oracle Linux if it will work...
If you guys could confirm for me if it will work on IBM System x M4 series
that would be great and appreciated :)
This is for one of our clients who would like to run Oracle Linux on one
of their machines that they will purchase from us.

Fibonacci Rabbits with life span 2.999

Fibonacci Rabbits with life span 2.999

I need the recurrence relation for Fabonacci with Life Span = 2.999
I think it will be
f(n) = 1 where n%2 = 0 & n > 2 and f(n) = 2 where n%2 = 1 $ n > 2
Thanks

Redirect after persist Symfony2 form and Doctrine

Redirect after persist Symfony2 form and Doctrine

on an web application based on Symfony2 I'm developing a page in which I
can insert a new record on my DB. The Insert operation works properly,
anyway actually after the confirmation the datas are correctly inserted
but the web application return me on the same form that I used to insert
the data. How can I redirect the page to another route, for example to the
page that show me new inserted data?
Here the action in my Controller used to create the new record:
public function newAction(Request $request)
{
$em = $this->getDoctrine()->getManager();
$form = $this->createForm(new AnagraficaType(), new
Anagrafiche() );
if ($request->isMethod('POST')) {
$form->bind($request);
if ($form->isValid()) {
$anagrafica = $form->getData();
$em->persist($anagrafica);
$em->flush();
}
}
return $this->render('AcmeMyBundle:Anagrafica:new.html.twig',
array('form' => $form->createView()));
}
Here the part of routing.yml used for the page to create the new record:
AcmeMyBundle_newAnag:
pattern: /anagrafica/new
defaults: { _controller: AcmeMyBundle:Anagrafica:new}
Here the part of routing.yml for the page that permit me to show detailed
a single record of my 'anagrafica' objects in DB:
AcmeMyBundle_showAnag:
pattern: /anagrafica/{id}
defaults: { _controller: AcmeMyBundle:Anagrafica:show }
requirements:
_method: GET
id: \d+
Here the action in my controller that manage the page to show detailed a
single record of my 'anagrafica' objects in DB:
public function showAction($id)
{
$em = $this->getDoctrine()->getEntityManager();
$anagrafica = $em->getRepository('AcmeMyBundle:Anagrafiche')->find($id);
if (!$anagrafica) {
throw $this->createNotFoundException('Unable to find anagrafica
post.');
}
return $this->render('AcmeMyBundle:Anagrafica:show.html.twig', array(
'anagrafica' => $anagrafica,
));
}
This is the view new.html.twig:
{% extends 'AcmeMyBundle::layout.html.twig' %}
{% block title %}{% endblock %}
{% block body %}
{{ form(form) }}
{% endblock %}
This is the Form Type:
<?php
namespace Acme\MyBundle\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
class AnagraficaType extends AbstractType
{
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'Acme\MyBundle\Entity\Anagrafiche',
'cascade_validation' => true,
));
}
public function buildForm(FormBuilderInterface $builder, array
$options)
{
// Create the form
$builder->add('nome', 'text', array('label' => 'Nome: ',
'required' => false));
$builder->add('cognome', 'text', array('label' => 'Cognome: ',
'required' => false));
$builder->add('data_nascita', 'date', array('label' => 'Data
nascita: ', 'required' => false));
$builder->add('luogo_nascita', 'text', array('label' => 'Luogo
Nascita: ', 'required' => false));
$builder->add('indirizzo', 'text', array('label' =>
'Indirizzo: ', 'required' => false));
$builder->add('telefono', 'text', array('label' => 'Telefono:
', 'required' => false));
$builder->add('email', 'text', array('label' => 'Email: ',
'required' => false));
$builder->add('save', 'submit');
}
public function getName()
{
return 'anagrafica';
}
}
I need to extract the id of the new persisted record, and automatically
redirect to the /anagrafica/$id route (AcmeMyBundle_showAnag) after the
confirmation of the form.
Suggestion? Thanks.

Sunday, 29 September 2013

How to embed the latest vine videos automatically?

How to embed the latest vine videos automatically?

How do I embed the latest vine videos automatically? I know you can embed
each video alone but I want to automatically embed it so that it is not so
inconvenient to have to copy and paste the code to my website everytime. I
found a website vinalwidget.com that lets you display the latest vine
video THUMBNAILS, but not videos, using an iframe code generated from that
site. Its kind of neat and convenient but like I said, it is only
thumbnails that links to a video page. If this can be achieved, then is it
possible to do it using videos instead??

wpf textbox errortemplates in a Managed Addin Framework Addin

wpf textbox errortemplates in a Managed Addin Framework Addin

I've created a textbox style to contain a validation.errortemplate for use
in a UserControl class. If the UserControl is loaded in the normal,
non-MAF way, I can see the validation rule kicking in and getting visual
feedback (thick red border, a circular bang to the right of the textbox,
and an error message-in-a-tooltip) -- everything works the way I expect it
to.
However... if I load that same UserControl in as an AddIn, I lose the
visuals. (I do see the error tooltip behaving correctly, so I know my
validation rule is firing; I just don't see the border and bang symbol.
My AddIn, by the way, is based on MSDN's example for an
'addin-which-provides-a-usercontrol.'
I know a few of the limitations of an AddIn (e.g., video won't play in an
AddIn UserControl); is this another limitation, or am I screwing up?
Thanks in advance!

Visual Studio 2012 Update 3 - initializer list & variadic templates

Visual Studio 2012 Update 3 - initializer list & variadic templates

Recently I have installed Visual Studio 2012. After the installation I
updated my IDE with update 3 to guarantee functionality of my programs on
Windows XP.
Everything is working well, but I still can not use initializer list and
variadic templates! Do I need any extra updates to get this working with
Visual Studio 2012?

Saturday, 28 September 2013

difference between mult, multu simulating in c

difference between mult, multu simulating in c

I'm writing a c program and decodes mips 32 bit instructions and simulates
their functionality minus the bitwise part. I don't know how I should be
differentiating between signed and unsigned operations here.
For instance, given registers rd and rs, i need to multiply and put the
result in in rd.
for the mult instructions, it's as simple as this:
reg[rd] = reg[rs] * reg[rt];
What should the multu instruction be? Do I need to be doing bitwise
operations on the contents of the registers first?
I also need to do:
-add, addu, -div, divu -sub, subu
Is it the same distinction in functionality for all of them?

ThrowCards in python

ThrowCards in python

Given is an ordered deck of n cards numbered 1 to n with card 1 at the top
and card n at the bottom.
The following operation is performed as long as there are at least two
cards in the deck:
Throw away the top card and move the card that is now on the top of the
deck to the bottom of the deck.
My task is to find the sequence of the last k discarded cards and the last
remaining card.
Each line of input contains two non-negative numbers
n, where n ¡Ü 5000
k, where k < n
For each input line produce two lines of output.
The sequence of k discarded cards
The last remaining card.
See the sample for the expected format.
Sample input
7 2
19 4
10 5
6 3
4000 7
Output for sample input
Last 2 cards discarded: [4, 2]
Remaining card: 6
Last 4 cards discarded: [2, 10, 18, 14]
Remaining card: 6
Last 5 cards discarded: [9, 2, 6, 10, 8]
Remaining card: 4
Last 3 cards discarded: [5, 2, 6]
Remaining card: 4
Last 7 cards discarded: [320, 1344, 2368, 3392, 832, 2880, 1856]
Remaining card: 3904
My code will keep printing out the exact answers but with None on the
following line.
I am so confused why it will print None after each output.
Here is my code:
def throw_card(n,k):
lst=[]
bst=[]
for i in range(1,n+1):
lst.append(i)
while lst[0]!=lst[1] and len(lst)>1 and n<=5000 and k<n:
bst.append(lst.pop(0))
if len(lst)==1:
break
else:
lst.append(lst[0])
lst.remove(lst[0])
print('Last',k,'cards discarded: ',bst[n-(k+1):])
print('Remaining card: ',lst.pop())
print(throw_card(7,2))
print(throw_card(19,4))
print(throw_card(10,5))
print(throw_card(6,3))
print(throw_card(4000,7))
my output:
Last 2 cards discarded: [4, 2]
Remaining card: 6
None
Last 4 cards discarded: [2, 10, 18, 14]
Remaining card: 6
None
Last 5 cards discarded: [9, 2, 6, 10, 8]
Remaining card: 4
None
Last 3 cards discarded: [5, 2, 6]
Remaining card: 4
None
Last 7 cards discarded: [320, 1344, 2368, 3392, 832, 2880, 1856]
Remaining card: 3904
None

store value in char array pointed by char pointer

store value in char array pointed by char pointer

i have a char pointer.
char *ch;
char arr[100];
now i want to store the value of the char array ch is pointing to in
another array arr. I want to store the value pointed to by ch permanently
, so that any other operation performed on ch will not modify the original
value of array. can anyone tell me how to do this?

Missing one column when using Google chart API

Missing one column when using Google chart API

I did compare my code to the example code from Google and I couldn't find
anything different. I have no idea why my chart only display 2 data
columns instead of 3. Is it because of my browser (I'm using Chrome) ? I
tried with IE and had the same problem.
Google's example code:Example
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title>Chart</title>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">google.load('visualization', '1',
{packages: ['corechart']});</script>
<script type="text/javascript">
function drawVisualization2() {
var data = google.visualization.arrayToDataTable([
['Day', 'V5161.198', 'V5161.200', 'V5161.202'],
['27/09/2013', 4.0, 9.0, 4.0],
['29/09/2013', 5.0, 8.0, 4.0]
]);
var options = {title : 'Daily usage of heaters',
vAxis: {title: "Minutes"},
hAxis: {title: "day"},
seriesType: "bars",
series: {2: {type: "line"}} // This is not the root of the problem. If I
change it to 3, the chart can be displayed normally but it will not have
the average line anymore.
};
var chart = new
google.visualization.ComboChart(document.getElementById('chart2_div'));chart.draw(data,
options);}google.setOnLoadCallback(drawVisualization2);
</script>
</head>
<body>
<div id="chart2_div" style="width: 1100px; height: 500px;"></div>
</body>
</html>
Can anyone give me an advise ?
Thank you very much.

Friday, 27 September 2013

What needs to be escaped in java regular expressions

What needs to be escaped in java regular expressions

I have the following line of code
Matcher matcher = Pattern.compile("CREATE TABLE ([^ ]*)
\\(").matcher("CREATE TABLE DeliveryPointAddress (");
And the resulting Matcher does not contain a match (or more importantly)
the table name.
What do I need to change to get a match and "DeliveryPointAddress" in
group 1.