Saturday, 31 August 2013

what is the meaning of stable in zfile_stable - CZMQ

what is the meaning of stable in zfile_stable - CZMQ

CZMQ man page for zfile explains zfile_stable as:
// Check if file is 'stable'
CZMQ_EXPORT bool zfile_stable (const char *filename);
What is the meaning of stable? when a file is said to be stable?

How does this work in javascript

How does this work in javascript

var temp = temp || {};
In the above syntax temp is created if it is not already exist otherwise
it will refer to the variable which was already created. Just I am curious
that how does this work. I think right side of expression should return
true if temp exists but it is creating an object. How does this work. Any
explanation would be helpful.

CSS extra horizontal white space

CSS extra horizontal white space

On my website there's some extra horizontal space appearing on the right
side when the window is resized and on mobile browsers. I've tried
everything I can think of and I have no idea what might be causing it. The
website is here.
Any help is appreciated, thanks!

Initializing an array of strings dynamically in C

Initializing an array of strings dynamically in C

I know I can initialize an array of strings this way:
static const char *BIN_ELEMENTS[5] = {
"0000\0", // 0
"0001\0", // 1
"0010\0", // 2
"0011\0", // 3
"0100\0", // 4
};
But I need to accomplish that in a dynamic way. Reading the characters
from a File, and inserting them into an array. Then copy that array into
an array of strings (like above).
So let's say I captured the following chars from a File, and inserted them
into an array, like these:
>char number[5];
>char *listOfNumbers[10];
>number[0]='1';
>number[1]='2';
>number[2]='3';
>number[3]='4';
>number[4]='\0';
Now I would like to copy the whole content of number, into listOfNumers[0]
// meaning that I've stored "1234" in position 0 of listOfNumers. Leaving
9 more positions to store different numbers.
So I would do something like this:
>listOfNumers[0] = number; //this actually seems to work.
But since its a huge file of numbers, I need to reuse the array number, to
extract a new number. But when I do that, the content previously stored in
listOfNumers[0] gets overwritten, eventho I updated the new position for
the new number. How can I deal with that?
Here is what I have so far:
char number[5]; //array for storing number>
int j=0; // counter
int c; //used to read char from file.
int k=0; // 2nd counter
char*listOfNumbers[10]; //array with all the extracted numbers.
FILE *infile;
infile = fopen("prueba.txt", "r");
if (infile)
{
` while ((c = getc(infile)) != EOF)`
` {`
` if(c != ' ' && c != '\n' && c != EOF)`
{`
` number[k] = c;`
` ++k;`
` }`
` else`
` {`
` number[k] = '\0';`
` listOfNumbers[j]=number;`
` printf("Element %d is: %s\n",j,listOfNumbers[j]); `
` ++j;`
` k=0;`
` }`
` }`
` fclose(infile);`
}
printf("\nElement 0 is: %s\n", decimales[0]); //fails - incorrect value
printf("Element 1 is: %s\n", decimales[1]); //fails - incorrect value
printf("Element 2 is: %s\n", decimales[2]); //fails - incorrect value

R (ggplot)- How to generate multiple plots (facets) based on data.frame with only one numeric variable and distinct categ. variables

R (ggplot)- How to generate multiple plots (facets) based on data.frame
with only one numeric variable and distinct categ. variables

starting with this kind of data:
colnames(mydata)<-c("digit","freq","bool")
1.1 1 false
1.1 2 false
1.1 20 true
1.1 3 false
1.1 7 false
1.2 8 false
1.2 25 false
1.2 10 false
1.2 60 true
1.2 28 false
1.3 7 false
1.3 0 false
1.3 56 true
1.3 12 false
1.3 7 false
1.3 4 false
1.4 3 false
1.4 87 false
1.4 25 false
1.4 56 false
1.4 167 true
2.1 46 false
2.1 25 false
2.1 75 true
2.1 20 false
2.1 12 false
2.1 15 false
... I would like to create muliple plots based on the digit field in the
data using ggplot2.
I tried
ggplot(mydata, aes(y = mydata$freq, x = seq(1, length(mydata$freq)))) +
geom_point() +
facet_wrap(~ mydata$digit)
But it won't work. Additionally, I would like to give two distinct colors
to the mydata$freq data according to the false or true $bool annotation.
So, basically something like geom_point(aes(colour=mydata$bool)) within
each subplot (facet).
How can I make it work?

Unexpected output in Java - Inheritance related

Unexpected output in Java - Inheritance related

This is my sample program.
class parent
{
void display(int i)
{
System.out.println("parent");
}
}
class child extends parent
{
void display(byte i) //Line 0
{
System.out.println("child");
return;
}
}
class impl
{
public static void main(String...args)
{
parent p = new parent();
p.display(5); //Line 1
child c = new child();
c.display(3); //Line 2
}
}
This is my output.
varun@\:~/Desktop/JavaFiles$ java impl
parent
parent
I understand Line 1 calls the display() method from the parent and outputs
"parent" which is expected.
But I don't understand why Line 2 calls the display() from the parent
instead of the child even though I am not using polymorphic initialization
(just a regular initialization of the child class is what I did).

Creating a jQuery animation in function

Creating a jQuery animation in function

I'm creating a website where users click on an icon to perform a database
function and then have the icon change, which is working fine, but I would
like to add a popup animation as well, like the one used on Deviant Art
when you favorite a photo or on Firefox when you have downloaded a file,
which moves upwards & fades out. Does anyone know how this can be done?

Add an existing project to SVN Version

Add an existing project to SVN Version

I have downloaded Tortoise SVN. I have created SVN Repository by right
clicking on an empty folder. I have an existing project and i want to add
it to the newly created SVN Repository. So that i can checkout the project
by checkout option of SVN and do the changes and can commit it.
Copy the existing project and paste it to the SVN repository folder is not
working. Because when i use checkout option in some other folder the
copied project is not coming.
Can somebody please help , how to add an existing project to the newly
created svn repository.

Friday, 30 August 2013

User Input for Variables in Bash Script

User Input for Variables in Bash Script

I'm trying to create a script that simplifies the process of creating a
new user on an iOS device. Here are the steps broken down.
# fullname="USER INPUT"
# user="USER INPUT"
# group=$user
# uid=1000
# gid=1000
# home=/var/$user
# echo "$group:*:$gid:$user" >> /private/etc/group
# echo "$user::$uid:$gid::0:0:$fullname:$home:/bin/sh" >>
/private/etc/master.passwd
# passwd $user
# mkdir $home
# chown $user:$group $home
As you can see some fields require input. How can I request input for a
variable in script?

Thursday, 29 August 2013

Is it possible to send a command from one cmd-window to another (already existing) cmd-window?

Is it possible to send a command from one cmd-window to another (already
existing) cmd-window?

Is it possible to send a command from one cmd-window to another (already
existing and opened) cmd-window?

How/Why is Maven Assembly Different the Shade Different from OneJar

How/Why is Maven Assembly Different the Shade Different from OneJar

I am working on a web service using Spring, Jax-Rs, and embedded Jetty. I
have a starter class that spins up the server, initializes the context,
all that. Thats all good.
However, the only way I have been able to compile it into a single,
executable jar is with the OnJar Maven plugin:
https://code.google.com/p/onejar-maven-plugin/
When I tried using the Maven Shade and Assembly plugins, both successfully
compiled, but then had major runtime errors, such as:
Nested exception is
org.apache.cxf.service.factory.ServiceConstructionException
at
org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:581)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1025)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:921)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:487)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:458)
at
org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:295)
at
org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223)
Given that the OneJar plugin is not hosted on Maven Central, I need access
to the plugin repository for my job, but what if thats not possible? How
do I get the Maven Assembly plugin to work. Why is it failing? Is the
assembly plugin somehow flawed in how it compiles everything together?

how to open tor browser using watir?

how to open tor browser using watir?

With my ruby code I want to open Tor Browser instead of Firefox,for this I
tried this code
path='C:\Tor Browser\App\tor.exe'
Selenium::WebDriver::Firefox.path = path
driver = Selenium::WebDriver.for :firefox
ie = Watir::Browser.new :firefox, :driver => driver
I got this error
c:/Ruby193/lib/ruby/gems/1.9.1/gems/selenium-webdriver-2.35.1/lib/selenium/webdriver/firefox/launcher.rb:79:in
`connect_until_stable': unable to obtain stable firefox connection in 60
seconds (127.0.0.1:7055) (Selenium::WebDriver::Error::WebDriverError)
from
c:/Ruby193/lib/ruby/gems/1.9.1/gems/selenium-webdriver-2.35.1/lib/selenium/webdriver/firefox/launcher.rb:37:in
`block in launch'
from
c:/Ruby193/lib/ruby/gems/1.9.1/gems/selenium-webdriver-2.35.1/lib/selenium/webdriver/firefox/socket_lock.rb:20:in
`locked'
from
c:/Ruby193/lib/ruby/gems/1.9.1/gems/selenium-webdriver-2.35.1/lib/selenium/webdriver/firefox/launcher.rb:32:in
`launch'
from
c:/Ruby193/lib/ruby/gems/1.9.1/gems/selenium-webdriver-2.35.1/lib/selenium/webdriver/firefox/bridge.rb:24:in
`initialize'
from
c:/Ruby193/lib/ruby/gems/1.9.1/gems/selenium-webdriver-2.35.1/lib/selenium/webdriver/common/driver.rb:31:in
`new'
from
c:/Ruby193/lib/ruby/gems/1.9.1/gems/selenium-webdriver-2.35.1/lib/selenium/webdriver/common/driver.rb:31:in
`for'
from
c:/Ruby193/lib/ruby/gems/1.9.1/gems/selenium-webdriver-2.35.1/lib/selenium/webdriver.rb:67:in
`for'
from C:/new_trademap/newTrademapTest.rb:28:in `<main>'
What should I have to do ? or there is any other way to do so?

Javascript: Object context overwritten?

Javascript: Object context overwritten?

I understand there is some sort of context mix up in the following
Javascript code I have.
Could someone explain my why I have this problem and how to solve the issue?
I have a class called Model which seems to work just fine. In this class
is a method called update(). This will perform an AJAX call to the backend
and parse the returned JSON. That's where things get tricky. The correct
query is sent to the backend and the correct JSON is sent back. However,
during parsing, there is some kind of collision or context issue between
both models.
I call the update function through another object called View. This View
object has a list of models (instances of Model). The view will then call
each update function of each view. This works great until the returned
data is parsed.
In the following code, everything is good until the line where there's the
comment "/!\ HERE /!\".
this.update = function(dbi) {
console.log('Updating model ' + this.name + '.');
var modelObj = this; // This is used to have a reference to 'this' Model
while in other contexts.
if (this.columns.length == 0) {
/* Let's build all the columns */
$("[id^='" + this.ref + "']").each(function() {
var colName = $(this).attr('id').split('-')[1];
if (modelObj.columns.indexOf(colName) == -1) {
modelObj.columns.push(colName);
}
});
}
/* Let's build the bindings. */
var allBindings = {};
for (placeholder in this.bindings) {
allBindings[placeholder] = this.bindings[placeholder].val();
}
$.post(path + 'inc/fetch.php', {
dbi : dbi,
table : this.table,
columns : btoa(this.columns),
limit : this.limit,
offset : this.offset,
distinct : this.distinct,
where : btoa(this.where),
bindings : btoa(JSON.stringify(allBindings))
}, function(data) {
if (!data.valid) {
$("#userError>p>span.userMessage").html(data.msg);
$("#userError").dialog({
width : 500,
buttons : {
'Dismiss' : function() {
$(this).dialog("close");
}
}
});
} else {
/* The data returned by the backend is simply JSON data with the
key-value pair. There is one key per row returned. */
var numRows = 0; // /!\ HERE /!\ Starting here, displaying the data
variable will always display the first of two objects.
for ( var rowID in data) {
if (rowID == 'valid')
continue;
numRows++;
for (column in data[rowID]) {
console.log('[' + modelObj.str() + '] setting #' + modelObj.ref +
'-' + column + ' to [' + data[rowID][column] + ']');
var el = $('#' + modelObj.ref + '-' + column);
var val = data[rowID][column];
switch (el[0].nodeName) {
case "SELECT":
el.html('<option val="' + val + "'>" + val + "</option>");
break;
case "TD":
el.text(val);
break;
case "INPUT":
el.val(val);
break;
default:
console.log('Dont know how to display "' + val + '"!');
}
}
}
if (numRows < modelObj.columns.length) {
for ( var cNo in modelObj.columns) {
var column = modelObj.columns[cNo];
console.log("col = " + column);
console.log('data');
console.log(data);
console.log('columns');
console.log(modelObj.columns);
console.log('[0] of ' + '#' + modelObj.ref)
var par = $('#' + modelObj.ref).nodeName;
var el = $('#' + modelObj.ref + '-' + column);
var val = data[0][column];
switch (par) {
case "SELECT":
el.html('<option val="' + val + "'>" + val + "</option>");
break;
case "TABLE":
var limit = $('#' + modelObj.ref + ">tr").length - 1; // The
first line (tr) is the header.
for ( var missingRow in limit) {
if (data.hasOwnProperty(missingRow) == 0 ||
data[missingRow].hasOwnProperty(column) == 0) {
console.log('[' + modelObj.str() + '] setting #' +
modelObj.ref + '-' + column + ' to [N/A]')
$('#' + modelObj.ref + '-' + column + '-' +
missingRow).text('N/A');
}
}
break;
case "INPUT":
el.val(val);
break;
default:
console.log('Dont know how to display "' + val + '"!');
}
}
}
}
}, "json");
};
Any thought is helpful. Thanks in advance.

Wednesday, 28 August 2013

Have function to show subsets of a string - now trying to adapt code to handle arrays

Have function to show subsets of a string - now trying to adapt code to
handle arrays

Some working code is on the bottom. But my poorly adapted code on the top
goes into an infinite recursion loop. What is it I do not know about
arrays?
function recSubsets(soFar, rest)
{
if (rest===[]) console.log(soFar);
else
{
recSubsets(soFar.push(rest[0])), rest.slice(1));
recSubsets(soFar, rest.slice(1));
}
}
function listSubsets(s)
{
recSubsets([],s);
}
listSubsets([4,9,3,77])
below is the working version for strings
function recSubsets(soFar, rest)
{
if (rest==="") console.log(soFar);
else
{
recSubsets(soFar+rest[0], rest.substring(1));
recSubsets(soFar, rest.substring(1));
}
}
function listSubsets(s)
{
recSubsets("",s);
}
listSubsets("cat")
gives me:
cat ca ct c at a t

Reducing Iterations During Math Factoring

Reducing Iterations During Math Factoring

I need assistance with refactoring the inner loop. I would like a more
efficient way including less iterations.
public static void main(String[] args) {
for (int i = 2; i <= 100; i++) {
System.out.print("Factors of " + i + ": ");
for (int j = 2; j < i; j++)
if ((i % j) == 0)
System.out.print(j + " ");
System.out.println();
}
}
Here is what I have attempted thus far:
int j = 2;
do{
if ((i % j) == 0) System.out.print(j + " ");
System.out.println();
j++;
} while (j < 2);
This only prints out the first factor and I cannot for the life of me
figure out how to get it to through the whole list. I know I am missing
something semantically but it is making me pull my hair out.

Binding Integer in XAML

Binding Integer in XAML

I am doing a windows phone 8 application. I show the fixture of the games
on this app.
I'am binding data and showing them on phone screen but when i try to bind
integer property, it does not showing. How can i handle that ?
Here is the code when i make request and get response from my web api
service;
protected override void OnNavigatedTo(NavigationEventArgs e)
{
const string url = "MY_WEB_API_URL";
var hWebRequest = (HttpWebRequest)WebRequest.Create(url);
hWebRequest.Method = "GET";
hWebRequest.BeginGetResponse(FixtureLoadCompleted, hWebRequest);
}
private void FixtureLoadCompleted(IAsyncResult ar)
{
var request = (HttpWebRequest)ar.AsyncState;
var response = (HttpWebResponse)request.EndGetResponse(ar);
using (var streamReader = new
StreamReader(response.GetResponseStream()))
{
_json = streamReader.ReadToEnd();
Fixturedetail =
JsonConvert.DeserializeObject<FixtureDetailApi.RootObject>(_json);
}
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
StageName.ItemsSource
=
new[]
{Fixturedetail.Dates.FirstOrDefault()};
});
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
Fixture.ItemsSource
=
Fixturedetail.Dates;
});
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
RoundName.ItemsSource
=
new[]
{
Fixturedetail.Dates.FirstOrDefault()
};
});
}
and here is how i bind it in xaml ;
<phone:LongListSelector x:Name="Fixture" Height="600" Background="White"
Margin="10,154,10,46" Grid.Row="1">
<phone:LongListSelector.ItemTemplate>
<DataTemplate>
<phone:LongListSelector ItemsSource="{Binding
Path=Matches}">
<phone:LongListSelector.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal"
Height="50">
<Border BorderBrush="Gray"
BorderThickness="0,1,1,1"
Background="#FFFFFFF7" Opacity="0.7">
<TextBlock Foreground="Black"
Text="{Binding
Path=ExtraProperties.Hour}"
Width="55" TextAlignment="Center"
VerticalAlignment="Center"
HorizontalAlignment="Center"
TextWrapping="Wrap"
FontSize="{StaticResource
PhoneFontSizeNormal}"/>
</Border>
<Border BorderBrush="Gray"
BorderThickness="0,1,1,1"
Background="#FFFFFFF7" Opacity="0.7">
<TextBlock Foreground="Black"
Text="{Binding
Path=HomeTeam.Name}" Width="160"
TextAlignment="Right"
VerticalAlignment="Center"
HorizontalAlignment="Center"
TextWrapping="Wrap"
FontSize="{StaticResource
PhoneFontSizeNormal}"
Margin="0,0,10,0"/>
</Border>
<Border BorderBrush="Gray"
BorderThickness="0,1"
Background="White" Opacity="0.7">
<TextBlock Foreground="Red"
Text="{Binding
Path=CurrentHomeTeamScore}"
Width="15" TextAlignment="Center"
VerticalAlignment="Center"
HorizontalAlignment="Center"
TextWrapping="Wrap"
FontSize="{StaticResource
PhoneFontSizeNormal}"/>
</Border>
<Border BorderBrush="Gray"
BorderThickness="0,1"
Background="White" Opacity="0.7">
<TextBlock Foreground="Red"
Text="-" TextWrapping="Wrap"
Width="10" TextAlignment="Center"
VerticalAlignment="Center"
HorizontalAlignment="Center"
FontSize="{StaticResource
PhoneFontSizeNormal}"/>
</Border>
<Border BorderBrush="Gray"
BorderThickness="0,1"
Background="White" Opacity="0.7">
<TextBlock Foreground="Red"
Text="{Binding
Path=CurrentAwayTeamScore}"
Width="15" TextAlignment="Center"
VerticalAlignment="Center"
HorizontalAlignment="Center"
TextWrapping="Wrap"
FontSize="{StaticResource
PhoneFontSizeNormal}"/>
</Border>
<Border BorderBrush="Gray"
BorderThickness="1,1,0,1"
Background="#FFFFFFF7" Opacity="0.7">
<TextBlock Foreground="Black"
Text="{Binding
Path=AwayTeam.Name}" Width="160"
TextAlignment="Left"
VerticalAlignment="Center"
HorizontalAlignment="Center"
TextWrapping="Wrap"
FontSize="{StaticResource
PhoneFontSizeNormal}"
Margin="5,0,0,0"/>
</Border>
</StackPanel>
</DataTemplate>
</phone:LongListSelector.ItemTemplate>
</phone:LongListSelector>
</DataTemplate>
</phone:LongListSelector.ItemTemplate>
</phone:LongListSelector>
As you see here, i got no problem when i try to bind
"ExtraProperties.Hour" , "HomeTeam.Name", "AwayTeam.Name",
But when i try to bind "CurrentHomeTeamScore" and "CurrentAwayTeamScore"
they are not showing on screen. I thought it can be cause of string & int
difference. Is there any way to handle this issue ?
Waiting your helps. Thank you.

Html border in header with picture and text

Html border in header with picture and text

Look at my problem:
Now i have:
What i need to do:
I tryed to do with border, but nothing happends.
Here is my code:
<ul id="tabMenu">
<li class="dropdown"><div><a class="tab1"><div class="dropdown_text">ïîèñê
ïî ïðîèçâîäèòåëþ</div></a></div></li>
<li class="dropdown"><div><a class="tab2"><div class="dropdown_text">ïîèñê
ïî íàçíà÷åíèþ</div></a></div></li>
<li class="dropdown"><div id="menu_logo"></div></li>
<li class="dropdown"><div><a class="tab3"><div
class="dropdown_text">êàáèíåò</div></a></div></li>
<li class="dropdown"><div><a class="tab5"><div
class="dropdown_text">ñðàâíåíèå</div></a></div></li>
<li class="dropdown"><div>
<span id="more_search"></span><a class="tab4" href="/emarket/cart/"><div
class="dropdown_text">ïîêóïêè</div></a>
</div></li>
</ul>
Here is CSS:
ul li {
display: inline-block;
}
ul li a {
color: #ccc;
white-space: nowrap;
text-decoration: none;
padding-top: 55px;
}
ul li a div.dropdown_text {
display: inline-block;
}
div.site_info ul li a.tab1 (etc for a.tab2, a.tab3, a.tab4) {
float: left;
margin-left: 89px;
background: url(/img/new_desing/producers.png) no-repeat top center;
}
Help me please to solve this problem.

Tuesday, 27 August 2013

On submit form, return false not working

On submit form, return false not working

When I submit the form I got an alert message. When I accept the alert it
will submit the form anyway. Returning false is ignored. Onclick can not
be used. I try with var x = document.forms["form"]["fname"].value; and
still same.
<form id="f" method="post" name="form" onsubmit="return validateForm();"
action="#">
<input type="text" name="fname" id="test" />
<input type="submit" value="submit"/>
</form>
<script type="text/javascript">
function validateForm() {
var x = document.getElementById('test').value;
if (x == null || x == 0 || x == "0") {
alert("Stop");
return false;
}
}
</script>

Accessing various webservices with Javascript

Accessing various webservices with Javascript

I'm in the process of creating a crowdfunder page and want to create a
dashboard showing the current progress: http://hyve.me/crowdfunder
Here is the JavaScript I use:
<script type="text/javascript">
// Facebook Likes
$.getJSON("https://graph.facebook.com/?ids=hyve.me", function (response) {
$("#facebooklikes").text(response["hyve.me"].likes);
});
// registered Users
$.ajax({
type: 'GET',
url: 'http://www.hyve.me/usercount',
dataType: 'JSON',
success: function (response) {
$("#usercount").text = response;
}
});
// days left
jQuery(document).ready(function($) {
today = new Date();
deadline = new Date("October 31, 2013");
msPerDay = 24 * 60 * 60 * 1000 ;
timeLeft = (deadline.getTime() - today.getTime());
$("#countdown").text(Math.floor(timeLeft / msPerDay));
});
// progress bar for shares
$.getJSON("https://api-public.addthis.com/url/shares.json?url=http%3A%2F%2Fwww.hyve.me%2Fcrowdfunder%2F",
function (response) {
var mentions = response.shares;
document.getElementById("myProgressBar_Success").setAttribute('style',
"width: " + (mentions / 6).toString() + "%;");
document.getElementById("myProgressBar_Warning").setAttribute('style',
"width: " + ((600 - mentions) / 6).toString() + "%;");
});
</script>
and here is the HTML of the dashboard:
<div class="span8 offset2">
<div class="row-fluid statistics">
<div class="span4"><div class="linediv-l"><h3
id="facebooklikes">0</h3><p>FB <i
class="icon-thumbs-up"></i></p></div></div>
<div class="span4"><div class="linediv-c"><h3
id="usercount">0</h3><p>Hyve-Users</p></div></div>
<div class="span4"><div class="linediv-r"><h3
id="countdown">0</h3><p>days left</p></div></div>
</div>
</div>
<div class="row-fluid">
<div class="span10 offset1">
<div class="thermometer progress active">
<div class="bar bar-success" style="width: 50%;"
id="myProgressBar_Success"></div>
<div class="bar bar-warning" style="width: 50%;"
id="myProgressBar_Warning"></div>
</div>
</div>
</div>
Now I have a number of questions:
the number of Facebook Likes is displayed correctly in Chrome (v29) and
Firefox (v23) but not in Internet Explorer (v9) - any ideas how to make
this browser independent?
the number of registered users works only if I'm on the same domain
(hyve.me); therefore, I can test this only in production but not on
development (AWS) or staging (heroku.com) - any ideas how to fix this?
the progress bar is not updated according to data from addthis.com - why
does getJSON() work with Facebook-Graph and not with the webservices from
AddThis?
This is my first question on Stackoverflow and I have spent the last 2
days finding the answer. Maybe someone here can point me to the right
direction.
Thanks in advance!
-Christoph

Get numerical values from input fields and use them to calculate the surface area of a trapezoid

Get numerical values from input fields and use them to calculate the
surface area of a trapezoid

I am new to Javascript and I will be thankful if someone help me
understand what I am doing wrong. I am trying to calculate the surface
area of a trapezoid by obtaining values from input fields. When I press
the "Calculate S" button I get a "Nan" as an answer. This is the major
part of the HTML code:
<form method="post">
<label for="a">a</label>
<input type="text" id="a"/> <br/>
<label for="b">b</label>
<input type="text" id="b"/> <br/>
<label for="h">h</label>
<input type="text" id="h"/> <br/>
<button onclick="alert(S)">Calculate S</button>
</form>
And this is the script I am using to obtain the values and calculate the
surface:
<script type="text/javascript">
var a=parseInt(document.getElementById("a"), 10);
var b=parseInt(document.getElementById("b"), 10);
var h=parseInt(document.getElementById("h"), 10);
var S=parseInt(((a+b)/2)*h, 10);
</script>
Thanks in advance!

Partitioning ! how dose the hadoop make it? Use a hash function ? what is the default function?

Partitioning ! how dose the hadoop make it? Use a hash function ? what is
the default function?

Partitioning is the process of determining which reducer instance will
receive which intermediate keys and values. Each mapper must determine for
all of its output (key, value) pairs which reducer will receive them. It
is necessary that for any key, regardless of which mapper instance
generated it, the destination partition is the same Problem: how dose the
hadoop make it? Use a hash function ? what is the function?

How to read the PAT table of mpegts

How to read the PAT table of mpegts

I have just started looking at some work related with reading a mpeg-ts
file. This is my first project with video streaming and my first task is
to read the program names from the file.
I am currently looking at FFMpeg and FFProbe and have experience in C# and
wanted to know which tool/language I should use to do this?
Or do I need another tool or language?
I have launched TSReader and I can see the PAT section which contains the
information.

Updating UserControl (Chart) in MVVM

Updating UserControl (Chart) in MVVM

I have a chart embedded in a usercontrol
PlotControl.xaml (PlotControl.xaml.cs)
This plot control is used on a View in MVVM.
NOW! when I update the UI of PlotControl (e.g. I draw vertical and
horizontal markers on chart), these updates are not visible on View
(unless I do double click on the View or do a Minimize-Maximize window).
Is there a way the updated UI is updated automatically on View?
View code looks like:
<Grid Margin="4">
<nms:PlotControl x:Name="PlotControl" Margin="10,10"
DockPanel.Dock="Right" />
</nms:PlotControl>
Snippet from PlotControl.xaml.cs code looks like:
ChartPanel cpnl = new ChartPanel();
chart.View.Layers.Add(cpnl);
ChartMarker rightVerticalMarker = new ChartMarker(chart,
MarketType.RightVertical);
rightVerticalMarker.DataPoint = new Point(30, double.NaN);
cpnl.Children.Add(rightVerticalMarker);
cpnl.UpdateLayout();
chart.UpdateLayout();
ChartMarker is simply a line Horizontal (or Vertical) defined by enum
MarketType.

How do I determine what is using the folder?

How do I determine what is using the folder?

I just can't delete the folder under root (it says that resource/device is
busy), but lsof and fuser tell me nothing. The folder is located in the
depth of /var/www/... and I tried to delete it after I stop apache2 and
nginx.

Monday, 26 August 2013

Is the '-f' option of Linux shell sort useful?

Is the '-f' option of Linux shell sort useful?

The man specification says the meaning of '-f' is " fold lower case to
upper case characters",but isn't the lower case less than upper case? So,
if I want to sort 'a' and 'A',is it necessary to add '-f'?
Could someone can give me a example which uses '-f'?

The system is attempting to engage a module that is not available: addressing

The system is attempting to engage a module that is not available: addressing

I'm newbie in CRM dynamics, and I'm trying to connect My Java Web Service
to CRM Dynamics, but after follow this tutorial >>
http://msdn.microsoft.com/en-us/library/jj602979.aspx I'm getting this
error:
The system is attempting to engage a module that is not available: addressing
I have no idea how solve this, then if someone had this problem and was
able to help me, I'll be very greateful.
This error occours when I try to run the test code avaible at Microsoft link.

Binding RadioButton.IsChecked with Listbox.SelectedItem

Binding RadioButton.IsChecked with Listbox.SelectedItem

I don't know what i'm doing wrong. I think I might have my ViewModel
wrong, but I'm getting very frustrated because it isn't working. So far
the closest I got is that my View is clickable like a radiobutton with
about 7 other of these radiobuttons. but my listbox is not updating it's
selected property unless I click outside of my radiobutton.
Since i'm new to MVVM as a whole I may be doing this wrong. I found a
contact book example somewhere and am using that as my guide. Basically I
have a AbstractTask as my base. I have 7 child classes. I want to be able
to select one of these AbstractTasks. That's all i'm after. So in my main
window i have this.
<Window x:Class="AdvancedTaskAssigner.View.MainWindowView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:v="clr-namespace:AdvancedTaskAssigner.View"
Title="MainWindowView" Height="300" Width="300"
SizeToContent="Height">
<DockPanel>
<TextBlock Text="TextBlock" DockPanel.Dock="Top" />
<TextBlock Text="{Binding ElementName=listTasks,
Path=SelectedItem.Name}" DockPanel.Dock="Top" />
<ListBox x:Name="listTasks" ItemsSource="{Binding Tasks}"
HorizontalContentAlignment="Stretch" SelectedItem="{Binding
IsSelected}">
<ListBox.ItemTemplate>
<DataTemplate>
<v:AbstractTaskView />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</DockPanel>
</Window>
since this is a library and not a application I had to put this in the
Constructor of MainWindowView
MainWindowView.xaml.cs
public MainWindowView()
{
InitializeComponent();
var atvm = new ViewModel.MainWindowViewModel();
atvm.LoadTasks();
this.DataContext = atvm;
}
MainWindowViewModel.cs
class MainWindowViewModel
{
internal void LoadTasks()
{
var assembly =
Assembly.GetAssembly(typeof(AbstractTask)).GetTypes().Where(t =>
t.IsSubclassOf(typeof(AbstractTask)));
Type[] typelist =
GetTypesInNamespace(Assembly.GetAssembly(typeof(AbstractTask)),
typeof(AbstractTask));
foreach (Type t in typelist)
{
if(!t.IsAbstract && t.BaseType.Equals(typeof(AbstractTask)))
{
tasks.Add(new AbstractTaskViewModel(t));
}
}
}
private Type[] GetTypesInNamespace(Assembly assembly, Type baseClass)
{
return assembly.GetTypes().Where(t =>
t.IsSubclassOf(baseClass)).ToArray();
}
private ObservableCollection<AbstractTaskViewModel> tasks = new
ObservableCollection<AbstractTaskViewModel>();
public ObservableCollection<AbstractTaskViewModel> Tasks
{
get { return tasks; }
}
}
AbstractTaskViewModel.cs
public class AbstractTaskViewModel
{
public AbstractTaskViewModel(Type task)
{
if (!task.IsSubclassOf(typeof(AbstractTask)))
{
throw new NotSupportedException(string.Format("{0} is not a
subclass of AbstractTask", task.Name));
}
Task = task;
}
public string Description
{
get
{
return GetCustomAttribute(0);
}
}
public string Name
{
get
{
return GetCustomAttribute(1);
}
}
public bool IsSelected{get;set;}
private string GetCustomAttribute(int index)
{
var descriptions =
(DescriptionAttribute[])Task.GetCustomAttributes(typeof(DescriptionAttribute),
false);
if (descriptions.Length == 0)
{
return null;
}
return descriptions[index].Description;
}
protected readonly Type Task;
}
AbstractTaskView.xaml
<RadioButton
x:Class="AdvancedTaskAssigner.View.AbstractTaskView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d" d:DesignHeight="300" d:DesignWidth="300"
GroupName="AbstractTasks" Background="Transparent" IsChecked="{Binding
IsSelected, Mode=TwoWay}">
<RadioButton.Template>
<ControlTemplate TargetType="{x:Type RadioButton}">
<Grid>
<Border x:Name="MyHead" BorderBrush="Black"
BorderThickness="2" CornerRadius="5"
Background="LightGray" Margin="20,0,0,0"
HorizontalAlignment="Left" VerticalAlignment="Top"
Panel.ZIndex="2">
<TextBlock Text="{Binding Name}" Margin="5,2"
MinWidth="50" />
</Border>
<Border x:Name="Myoooo" BorderBrush="Black"
BorderThickness="2" CornerRadius="5"
Background="Transparent" Margin="0,10,0,0"
Panel.ZIndex="1">
<TextBlock Text="{Binding Description}"
Margin="5,15,5,2" />
</Border>
</Grid>
<ControlTemplate.Triggers>
<Trigger Property="IsChecked" Value="True">
<Setter TargetName="MyHead" Property="Background"
Value="LightGreen" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</RadioButton.Template>
</RadioButton>
this is what i am getting.. and it is frustrating! I want the green border
to be the selected item. not what the Listbox's Selected item is. The
bottom text box is the name of the selected item.

Select from one datasource update another

Select from one datasource update another

I am using Visual Web Developer to create a form updating my database.
Currently, I fill a gridview based on two drop down lists querying against
a view in my SQL 2008 database. This works fine, but I cannot update a
view directly, so what I need to do is update the main table that supports
the view. So here is the question(s). Can I have a select statement that
says
SELECT * FROM [vw_GridviewSource] WHERE (([Annotation Date] =
@Annotation_Date) AND ([Name] = @Name))
And have an update to another table?
Also can I somehow only allow the user to update certain fields and not
others? I have an instance where the "Annotation Number" is actually
generated by my client and should not be changed, but I do want them to be
able to update notes, business unit etc.

Documentation for oob native modules in IIS 7.x

Documentation for oob native modules in IIS 7.x

I've been working for some time at a super lean IIS 7.5 configuration for
a static file serving purposes web site. To achieve this, I've simply
stripped the designated web site for all dynamic modules, and only
specified native modules such as the StaticFileModule,
AnonymousAuthenticationModule, HttpCompressionModule etc.
This has already proved to cause a significant decline in the memory
footprint and processing overhead for the worker process, and the overall
performance is much better than the default web site.
Now, as a next step, I would like to see if I can trim down the number of
modules loaded into memory even further.
I could just remove the modules one-by-one and try to see how it affects
performance and functionality, but I would rather investigate what the
functionality the individual modules actually has/governs.
Some of the modules are pretty self-explanatory (ie.
DefaultDocumentModule, DirectoryListingModule), but some are not.
Is there anywhere I can find the documentation for the builtin native
modules?

Export django settings to my python file

Export django settings to my python file

I am trying to make logparser.py in django project which parses the data
coming from different servers.
And on running the command on terminal :
$ python logparser.py
This error is coming :
Traceback (most recent call last):
File "logparser.py", line 13, in <module>
SMTP_CONF = settings.SMTP_CONF
File
"/home/arya/.virtualenv/Devel/.virtualenvs/hu/local/lib/python2.7/site-packages/django/conf/__init__.py",
line 53, in __getattr__
self._setup(name)
File
"/home/arya/.virtualenv/Devel/.virtualenvs/hu/local/lib/python2.7/site-packages/django/conf/__init__.py",
line 48, in _setup
self._wrapped = Settings(settings_module)
File
"/home/arya/.virtualenv/Devel/.virtualenvs/hu/local/lib/python2.7/site-packages/django/conf/__init__.py",
line 134, in __init__
raise ImportError("Could not import settings '%s' (Is it on
sys.path?): %s" % (self.SETTINGS_MODULE, e))
ImportError: Could not import settings 'hma.settings' (Is it on
sys.path?): No module named hma.settings
my logparser.py contains:
import re
import os
import fnmatch
import gzip
import bz2
from collections import defaultdict
from django.core.mail import send_mail
from django.core.mail.backends import smtp
import smtplib
from email.mime.text import MIMEText
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "hma.settings")
from django.conf import settings
SMTP_CONF = settings.SMTP_CONF
def send_email(self,fromaddress,toaddresses,content,subject):
smtp_server = SMTP_CONF["SERVER"]
smtp_username = SMTP_CONF["USERNAME"]
smtp_password = SMTP_CONF["PASSWORD"]
smtp_port = SMTP_CONF["PORT"]
msg = MIMEText(content, 'html', _charset='utf-8')
msg['Subject'] ='Alert message for bad and internal server error'
msg['From'] = fromaddress
msg['To'] = toaddresses
server = smtplib.SMTP(smtp_server,smtp_port)
server.starttls()
server.login(smtp_username,smtp_password)
server.send_mail(fromaddress,toaddresses,msg.as_string())
server.quit()
return True
I know I am doing wrong something with command [python manage.py], but i
need to run like this. Any solution for this exporting django settings to
separate python file??

Sunday, 25 August 2013

GVIM : Possible to begin editing the file without having to press "i"?

GVIM : Possible to begin editing the file without having to press "i"?

I am trying to move from GEDIT to GVIM but i noticed
when i open a file i am not free to edit it

unlless i press
i
for (INSERT)
is there a way to bypass this? so the file is instantly editable ?

bind an object model to XtraReport devexpress

bind an object model to XtraReport devexpress

I need to bind a xtrareport ( devexpress ) to an object model.
Suppose that my model is :
public class ReportViewModel
{
public Header Header { get; set; }
public Body Body { get; set; }
public Footer Footer { get; set; }
}
What should I do to map this model to the report.
Thanks in advance.

Scroll Up button not showing up/not working?

Scroll Up button not showing up/not working?

I am developing a one page website. So far, I successfully implemented
'vertical smooth scroll' function (for my HOME, ABOUT, GALLERY...
navigation links) and it works just fine.
Now, I wanted to add another jquery to the same website - a small 'scroll
up' button which is supposed to show up at the bottom right corner for
easier navigation. The thing is that it never shows up???
Here is what I have done so far:
HTML:
<a class="scrollup" href="#">Scroll</a>
CSS:
.scrollup {
height: 38px;
width: 38px;
opacity: 1.0;
position:fixed;
bottom: 35px;
right: 35px;
background: url(images/top.png) no-repeat;
}
JQUERY (I opened scrollup.js document and added this code inside):
// scroll-to-top button show and hide
jQuery(document).ready(function(){
jQuery(window).scroll(function(){
if (jQuery(this).scrollTop() > 100) {
jQuery('.scrollup').fadeIn();
} else {
jQuery('.scrollup').fadeOut();
}
});
// scroll-to-top animate
jQuery('.scrollup').click(function(){
jQuery("html, body").animate({ scrollTop: 0 }, 600);
return false;
});
});
I also added these scripts into my HTML header:
<script type='text/javascript'
src='http://code.jquery.com/jquery-1.9.1.min.js'></script>
<script
src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.9.1/jquery-ui.min.js"></script>
<link rel='stylesheet' type='text/css'
href='http://code.jquery.com/ui/1.9.1/themes/base/jquery-ui.css'/>
<script type='text/javascript' src='verticalsmoothscrolling.js'></script>
<script type='text/javascript' src='scrollup.js'></script>
Still, my vertical smooth scroll is working fine, but 'scrollup' button
never shows up??? Does the order of the scripts at the bottom of this
question matters? Or it is something else? Hope you guys can help me to
solve this. Thankssss :)

Chrome extension as an API

Chrome extension as an API

I want to build a smart home system with voice commands, that should be
able to respond to you.
After playing with Windows SAPI for speech-to-text, I've found it to be
extremely bad, and have settled on the new HTML5 Speech API, which is
supported by Chrome.
Unfortunately Chrome doesn't also support text-to-speech, except for
extensions. That's why I want to know if extensions can expose JavaScript
functions that can be called from a website.
So basically what I want is to call a JS function from my site, that would
call an internal extension function (that I will build), which would call
the Chrome TTS function. Is something like this possible?

Multiple activities competing one intent

Multiple activities competing one intent

I got an interview question.....
How to specify which Activity to be launched from an implicit intent, when
there are multiple activities competing to execute the intent, without
requiring user intervention.
My answer to this question is to use proper intent-filter within every
activity, but it just sounds wrong..
Thanks in advance!

Saturday, 24 August 2013

Unexpected ifstream behavior?

Unexpected ifstream behavior?

I am trying to load GLSL vertex/fragment shader sources into const char*
array to be used with OpenGL. The function I am using to do that is
const char* loadSource(const char* path)
{
string line;
stringstream output;
ifstream source(path);
if(source.is_open())
{
while(source.good())
{
getline(source, line);
output << line << endl;
}
source.close();
}
return output.str().c_str();
}
The source input works fine on first call. However if I call for the
second source, the first source gets "corrupted" (both calls are inside
scope of a single function):
const char* vs_source = loadSource("vertex.vert"); // vs_source loads fine
const char* fs_source = loadSource("fragment.frag"); // fs_source loads
fine. vs_source is terminated sooner than after previous call.
Note: I tried to code vs_source directly into *.cpp file and both shaders
compiled. This points out to the fact that I must be doing something silly
in the loadSource function.
Question: What causes such weird behaviour of the text input?

How to make wifi (rt3090) work on ubuntu raring?

How to make wifi (rt3090) work on ubuntu raring?

As I can see, one can solve this problem on earlier versions of ubuntu.
But there is no packages for raring in ppa:markus-tisoft/rt3090 and it
doesn't compile from sources. Also, there is no rt2860sta.ko and
rt3090sta.ko in ubuntu repositories other than for lucid. Have they
discontinued support for this device? I can probably use old kernel, but
I'd like to find a better solution if any.

Logic: $\text{Mod } \Sigma$, the class of all models of $\Sigma$ and $\text{Th Mod }\Sigma$, how do these relate?

Logic: $\text{Mod } \Sigma$, the class of all models of $\Sigma$ and
$\text{Th Mod }\Sigma$, how do these relate?

While reviewing a question I had asked earlier here: Proving and
understanding the Fixed point lemma (Diagonal Lemma) in Logic - used in
proof of Godel's incompleteness theorem
I have the following:
"$\text{Mod } \Sigma$ is the class of all models of $ \Sigma$. $\text{Th
Mod } \Sigma$ is the set of all sentences which are true in all models of
$\Sigma$. This however is just the set of all sentences logically implied
by $\Sigma$. We call this set the set of consequences of $\Sigma$ or
$\text{Cn }\Sigma$. Thus we have that $\text{Cn }\Sigma = \{\sigma \mid
\Sigma \models \sigma \} = \text{Th Mod } \Sigma$."
Letting $\Sigma$ denote a set of axioms. Since $\text{Th Mod } \Sigma$ is
the set of all sentences which are true in all models of $\Sigma$ then
this seems to imply that there are sentances which may not be true in all
$\text{Th Mod } \Sigma$. So in other words $\text{Th Mod } \Sigma$ is
derivable from $\Sigma$ i.e. we can build some sentence in $\text{Th Mod }
\Sigma$ from axioms in $\Sigma$. I however am trying to understand better:
$\text{Th Mod } \Sigma$ is implied from $\Sigma$. This would mean that
$\Sigma \Rightarrow \text{Th Mod } \Sigma$. Now this is always true (is a
Tautology) as the only case which would be false would be that something
derived from a set of axioms (or just a set of axioms?) in $\Sigma$
implying $\text{Th Mod } \Sigma$ would be false as all statements in
$\text{Th Mod } \Sigma$ are true by definition. I am thinking this
explains their relationship, but could use some confirmation and maybe
some more insight.
Thanks,
Brian

Regex help needed for multiline content

Regex help needed for multiline content

I need to parse the data from the following multiline content but my regex
is not working
<a href="#" class="a-qzic">
Manipur <!-- <img
src="http://testsite.com/unsanswerit.php?iaodifu=1" /> -->
</a>
Please help me anyone to write better regex for this in vb.net

$\sec^2\theta+\csc^2\theta=\sec^2\theta\csc^2\theta$

$\sec^2\theta+\csc^2\theta=\sec^2\theta\csc^2\theta$

I was playing around with trigonometric functions when I stumbled across
this $$\sec^2\theta+\csc^2\theta=\sec^2\theta\csc^2\theta$$ Immediately I
checked it to see if it was flawed so I devised a proof $$\begin{align}
\sec^2\theta+\csc^2\theta&=\sec^2\theta\csc^2\theta\\
\frac1{\cos^2\theta}+\frac1{\sin^2\theta}&=\frac1{\cos^2\theta\sin^2\theta}\\
\frac{\cos^2\theta+\sin^2\theta}{\cos^2\theta\sin^2\theta}&=\frac1{\cos^2\theta\sin^2\theta}\\
\frac1{\cos^2\theta\sin^2\theta}&=\frac1{\cos^2\theta\sin^2\theta}\blacksquare\\
\end{align}$$ I checked over my proof many times and I couldn't find a
mistake, so I assume that my claim must be true.
So my questions are:
Is there a deeper explanation into why adding the squares is the same as
multiplying?
Is this just a property of these trigonometric functions or do similar
relationships occur with other trigonometric functions?
And finally as an additional curiosity what does this translate into
geometrically?

android studio for mac doesn't show setting menu

android studio for mac doesn't show setting menu

Before today,there is a lot of menu that I can click,but now is gone.
http://i.stack.imgur.com/otBss.png
But eclipse on my Mac is still work fine like
this:http://i.stack.imgur.com/Eqsi7.png
I cannot figure what's going on.And my Android Studio Version is 0.2.0
build 130.737825

Friday, 23 August 2013

how to delete Facebook profile picture on blackberry bold3

how to delete Facebook profile picture on blackberry bold3

I can't delete my old profile pictures that appears repeatedly because
when I hit the option botton I see no delete option neither do I see an
option to remove. Am using blackberry bold. Anyone with an idea?

strange leading "f" when print out a char

strange leading "f" when print out a char

Hi guys, I wrote the following code:
union endian {
char a;
int b;
} test;
char c;
test.b = 0xaabbccdd;
c = (char)test.a;
printf("0x%x\n", c);
printf("0x%x\n", test.b);
printf("0x%x\n", test.a);
printf("0x%x\n", (char)test.a);
But the output is:
0xffffffdd
0xaabbccdd
0xffffffdd
0xffffffdd
I want to know why there is some leading 0xffffff before the char variable.

Func parameter in LINQ expression

Func parameter in LINQ expression

i have problem with Func delegate in LINQ expression. This is the
problmatic part of the method:
public static ActionResult XXX<T>(IRepository<T> repository,
Func<T, int> keyExtractor, int id = 0)
{
if (id == 0) return ...
T item = repository.Items.Where(x => keyExtractor(x) == id).
FirstOrDefault();
if (item == null) return ...
try {
repository.DeleteItem(item);
return ...
} catch (Exception e) {
return ...
}
}
But when i run the method, i get error like type of node is not in LINQ
entities supported. I tried also version with predikate but i had no luck
at all.
Any ideas how to fix it?

Prevent web page refresh

Prevent web page refresh

There's a periodic page refresh on this page
(http://sosconso.blog.lemonde.fr/2013/07/24/mes-vacances-ne-se-passent-pas-comme-prevu/),
I was wondering how it worked and how to prevent it (using greasemonkey
for example).
I'm just a user of the site, so all I can do is play with my browser
options, or use greasemonkey to alter the javascript.
The page doesn't appear to use the meta refresh tag so I'm a bit puzzled.

SQL first occurance of a string

SQL first occurance of a string

I have a query which returns results like
Jim 456
Joe 567
Joe 789
Jane 456
What I want to do is have 456 only appear once and take the first name
(Jim). Query looks like
select p.id_id as num_id,
p.FIRST_NAME || ' ' || p.LAST_NAME as Name_
from DWH.V_TABLE p
where p.id_id>100
The reasons for this is I need each to have only one owner, not two

Automatic file versioning on Linux

Automatic file versioning on Linux

I want to do the following: when a file is changed then the old file
should be backed up to another location with different name on Linux. E.g.
whenever example.text is changed, at each change, new files should be
created like this: example1.text, example2.text ...

How to add Menu under file menu in Quick books 2012 with vb.net

How to add Menu under file menu in Quick books 2012 with vb.net

I have a problem with Quick Books menu Subscription in Quick Books 2012 $
2013 , it is working in 2010 and below versions. Is there any changes
needed for QB 2012 $ 13 . Present i'm using file versions are :
Interop.QBXMLRP2 ----------- > 12.0.0.29
Interop.QBSDKEVENTLib---------->1.0.0.0
Interop.QBFC1----->12.0.0.29
COMEventHandler----->1.0.0.0
Please help me how can i resolve this one ..please...

Thursday, 22 August 2013

How is it guaranteed that an API is bugfree?

How is it guaranteed that an API is bugfree?

We all use APIs to make writing our own code simpler by using other
people's already-written functions. But we all make mistakes. How is it
that APIs are always perfect? We all test our work before putting it out
for others to use so what makes API code perfect?

On the proof that the inverse value set of a regular value is a submanifold

On the proof that the inverse value set of a regular value is a submanifold

I have a doubt on the proof of the following, well-known theorem:
Let $f:M^m\rightarrow N^n$ ($m\geq n$) be a $C$ map, $r\geq 1$.If $y\in
f(M)$ is a regular value, then $f^{-1}(y)$ is a $C$ submanifold of $M$
The proof for this uses the Local Form of Submersions, that is, $f$ can be
representated, in open sets A and B around $x\in f^{-1}(y)$ and $y$,
respectively, as $$
\tilde{f}:V\underset{open}\subset\mathbb{R}^n\times\mathbb{R}^{m-n}\cong
\mathbb{R}^m\longrightarrow W\underset{open}\subset \mathbb{R}^n $$ such
that $\tilde{f}(x,y)= x$ in adequate open sets $V$ and $W$, where $y\in B$
corresponds to $0\in W$. The set $f^{-1}(y)\cap A$ is the diffeomorphic
(by the local chart) to $\tilde{f}^{-1}(0)\cap V=\{(x,y)\in V:x=0\}$
Then, if
$\pi:\mathbb{R}^n\times\mathbb{R}^{m-n}\rightarrow\mathbb{R}^{m-n}$ is the
projection $\pi(x,y)=y$, then $\left(\pi\vert_{\tilde{f}^{-1}(0)\cap V},
\tilde{f}^{-1}(0)\cap V\right)$ is a local chart for
$\tilde{f}^{-1}(0)\cap V$, which is open in $\tilde{f}^{-1}(0)$ since $V$
is open.
Using the local character of submanifolds and its invariance under
diffeomorphisms, and noting that $\tilde{f}^{-1}(0)\cap V$ is an
isomorphism, we have that $f^{-1}(y)\cap A$ is a submanifold of $M$.
Is this correct?

Reading From A Website

Reading From A Website

I am a high school student who is interested in programming. I have been
working on a project to get the homework from my school's website however
I cannot seem to understand how! I first thought of using OCR programs to
read the text from the website however that proved too difficult. Then I
tried reading the webpage's content however that just gave me the source
code and the content I was looking for is not present there. Now, using
Chrome's Inspector Tool, I am able to see the Network traffic going on. I
can even get a preview of what is sent as a response from the server! That
response is what I am looking for however I do not know how to go about
getting that response! I am hoping that there is a way to read the
response of a server. I also trust that this community would not exploit
the website I provide. I am hoping to gain much experience from writing
this program. Thanks to all who can help!
Website I am trying to read from:
http://www.westonmath.org/courses/371/home/14-371-gabrinerd-A12

What's wrong with my MySQL update code?

What's wrong with my MySQL update code?

I updated my code today from this:
$queue = "UPDATE hurlumhei SET barn = $barn, voksenuke = $voksenuke,
voksenhelg = $voksenhelg";
to this
$queue = "UPDATE hurlumhei
SET barn = $barn,
voksenuke = $voksenuke,
voksenhelg = $voksenhelg,
klippekort = $klippekort,
klippekortmega = $klippekortmega,
parkering = $parkering,
Kakao = $kakao,
Te = $te,
Kaffe = $kaffe,
Solbærtoddy = $solbærtoddy,
Powerrade = $powerrade,
Brus_stor = $brus_stor,
Brus_medium = $brus_medium,
Brus_liten = $brus_liten,
Bonaqua = $bonaqua,
Iste = $iste,
Sjokolademelk = $sjokolademelk,
Juice = $juice,
Friskus = $friskus,
Slush = $slush,
Pai = $pai,
Calzone = $calzone,
Lasagne = $lasagne,
Buffalo_burger = $buffalo_burger,
Bakt_potet = $bakt_potet,
Pizza = $pizza,
Panini = $panini,
Toast = $toast,
Inngang_pølse1 = $inngang_pølse1,
Inngang_pølse2 = $inngang_pølse2,
Inngang_calzone = $inngang_calzone,
Frukttallerken = $frukttallerken,
Kake = $kake,
Muffins = $muffins,
Popcorn = $popcorn,
Baconchips = $baconchips,
Potetgull = $potetgull,
Baguette_reker = $baguette_reker,
Baguette_kyllingbryst = $baguette_kyllingbryst,
Baguette_ostskinke = $baguette_ostskinke,
Salat_reker = $salat_reker,
Salat_kyllingbryst = $salat_kyllingbryst,
Salat_ostskinke = $salat_ostskinke";
Can anyone help me find the error ? For the record the columns in the
database has capital first letters on the new ones, so that's not the
error. Welcome to any suggestions, thanks

If Username & Password Are Correct, Start Session

If Username & Password Are Correct, Start Session

I am working on a basic login system that allows registration / sign in
storing users in a MySQL database. I have it so people can register, it
stores the username and a hashed password in the DB. When someone logs in,
it shows a success message or an error message depending on if the
username and password matched up.
My problem lies in the login function. I need to create the user session
and redirect them to the logged-in only section of the site, instead of
displaying the success message that is currently there. I'm unsure of how
to do that...
Here is my code:
Login / Register Functions
function login($username, $password) {
$userpass = sha1($password);
$result = mysqli_query($con, "SELECT * FROM members WHERE
username='$username' AND password='$userpass'");
while($row = mysqli_fetch_array($result)) {
$success = true;
}
if($success == true) {
echo 'Success!';
} else {
echo '<div class="alert alert-danger">Oops! It looks like your
username and/or password are incorrect. Please try again.</div>';
}
} // END LOGIN FUNCTION
function register($username, $password) {
$userpass = sha1($password);
// Check if Username Exists
$result = mysqli_query($con,"SELECT * FROM members WHERE
username='$username'");
while($row = mysqli_fetch_array($result)) {
$userexist = 1;
}
if($userexist > 0) {
echo '<div class="alert alert-danger">Sorry, it looks like that
username is already taken.</div>';
} else {
$newmember = "INSERT INTO members SET username='$username',
password='$userpass'";
if(mysqli_query($con,$newmember)) {
echo '<div class="alert alert-success">Congrats! You can now
log in using your username and password</div>';
}
}
}

Rookie cannot upload txt file with php

Rookie cannot upload txt file with php

I am using the following php file,
<?php
if ($_FILES["file"]["error"] > 0)
{
echo "Error: " . $_FILES["file"]["error"] . "<br>";
}
else
{
echo "Upload: " . $_FILES["file"]["name"] . "<br>";
echo "Type: " . $_FILES["file"]["type"] . "<br>";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
echo "Stored in: " . $_FILES["file"]["tmp_name"];
}
$uploaddir = '/var/www/setup/upload';
$uploadfile = $uploaddir . basename($_FILES['file']['name']);
echo '<pre>';
if (move_uploaded_file($_FILES['file']['tmp_name'], $uploadfile)) {
echo "File is valid, and was successfully uploaded.\n";
} else {
echo "Possible file upload attack!\n";
}
echo 'Here is some more debugging info:';
print_r($_FILES);
print "</pre>";
?>
So, I cannot upload file. I would appreciate any hint , Thanks in advance :-)

Wednesday, 21 August 2013

dynamic / responsive / liquid layout css

dynamic / responsive / liquid layout css

I was wondering if there is an alternative to writing css rather than with
css tables to make liquid / dynamic layouts. vinyll really helped me
here... simple 3 Column responsive layout
and that is exactly how I need the columns to work, but when I use css
tables, it seems I cannot position things inside with margin and padding
(I probably could with left and right but relative positing breaks the
document flow so I don't want to do that)...heres and example
http://jsfiddle.net/u5nR2/4/
.container{
width:100%;
height:100%;
display: table;
}
div > div {
display: table-cell;
}
.three div{margin-top:100px}/*why doesnt this move?*/

ios - stop scroll when reach to expected object

ios - stop scroll when reach to expected object

The image https://www.dropbox.com/s/e7b189mzl168efk/scrollview.png is my
scrollview and 4views. What I want is when I pulldown the scrollview it
display the views base on the offset. And I want to stop the scroll when
it reach to end view. Currently it still continue to scroll.
its like
if(scrollView.contentOffset.y == -155)
then scroll will not continue to scroll but i can still scroll back to the
bottom to highlight the view3 or until view1. Please refer on the image.
example code is very helpful.

Solid State Drive suddenly stopped working

Solid State Drive suddenly stopped working

I had SSD in my desktop and I had Windows 7 installed in it. Week age
computer asked to restart to install the updates and I did. After that
computer didn't boot. Finally I found that my SSD is not working. I tried
to plug it to different computers and no luck. It even doesn't have any
kind of ledthat indicates it is working. It still has warranty, but it has
data that I don't want anyone else see it. Is there way to format it?
Help appreciated!

Shortest distance between two lines

Shortest distance between two lines

Suppose L1 and L2 be the two lines in 3D, suppose P1 and P2 be two points
on L1, L2 resp. such that distance(P2-P1) is shortest distance between L1
and L2. Does vector (P2-P1) need to be perpendicular to both L1 and L2? If
so, then why? Is it true for 2D space also?

Twig: adding twig extension debug from config file

Twig: adding twig extension debug from config file

According to TWIG documentation, in order to use the dumb function I
should first add the extension debug like so:
$twig = new Twig_Environment($loader, array(
'debug' => true,
// ...
));
$twig->addExtension(new Twig_Extension_Debug());
But how do I do that from config.yml ? I use symfony2.

WCF service returning HTML instead of response

WCF service returning HTML instead of response

I created a WCF service which connects some websites. But when I try to
consume it, I get this error. What can cause it? Funny thing is, I
duplicated WCF service from another working one so I'm confused.
The content type text/html; charset=utf-8 of the response message does not
match the content type of the binding (text/xml; charset=utf-8). If using
a custom encoder, be sure that the IsContentTypeSupported method is
implemented properly. The first 1024 bytes of the response were: '
<!DOCTYPE html>
<html>
<head>
<title>Runtime Error</title>
<meta name="viewport" content="width=device-width" />
...

Google Chart: java.lang.NoClassDefFoundError: com/google/gwt/core/client/JavaScriptObject

Google Chart: java.lang.NoClassDefFoundError:
com/google/gwt/core/client/JavaScriptObject

I try using Google Chart to display the trendlines, based on some datas
generated from the .java files. My basic idea is to create a DataTable in
java file, and then I pass this DataTable to web pages by JSF. Here are
part of my codes:
public void resolveEvolution() {
this.evolution = new ArrayList<Long>();
this.evolutionTime = new ArrayList<String>();
Calendar first = Calendar.getInstance();
first.setTime(this.start);
first.set(Calendar.DAY_OF_MONTH, 1);
Calendar last = Calendar.getInstance();
last.setTime(this.end);
int i = 0;
this.dt = DataTable.create();
dt.addColumn(ColumnType.NUMBER, "Time");
dt.addColumn(ColumnType.NUMBER, "Utilisation");
dt.addRow();
while (first.before(last)) {
Calendar endMonth = Calendar.getInstance();
endMonth.setTime(first.getTime());
endMonth.add(Calendar.MONTH, 1);
endMonth.add(Calendar.DAY_OF_MONTH, -1);
this.evolution
.add(actionQueries.countByComponent(this.selectedComponent,
first.getTime(), endMonth.getTime()));
this.evolutionTime.add(first.get(Calendar.MONTH) + "/"
+ first.get(Calendar.YEAR));
dt.addRow();
dt.setValue(i, 0, i);
dt.setValue(i, 1,
actionQueries.countByComponent(this.selectedComponent,
first.getTime(), endMonth.getTime()));
i++;
first.add(Calendar.MONTH, 1);
}
}
public DataTable getDt() {
System.out.println(this.dt);
return this.dt;
}
And in my .xhtml file it's like this:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core">
<head>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();
data = "#{globalComponentsManager.dt}";
var options = {
title: 'Test',
trendlines: { 0: {} }
};
var chart = new
google.visualization.ScatterChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="chart_div" style="width: 900px; height: 500px;"></div>
</body>
</html>
However, when I execute this application in Tomcat, it tells me:
GRAVE: Exception lors de l'envoi de l'évènement contexte initialisé
(context initialized) à l'instance de classe d'écoute (listener)
org.apache.myfaces.webapp.StartupServletContextListener
java.lang.NoClassDefFoundError: com/google/gwt/core/client/JavaScriptObject
What's the problem? Thanks in adavance.

Tuesday, 20 August 2013

Infinitely many sets in $\bigcup_{k=j}^\infty E_k$ for $j = \infty$?

Infinitely many sets in $\bigcup_{k=j}^\infty E_k$ for $j = \infty$?

If $\{E_k\}_{k=1}^\infty$ is a sequence of sets, we define $$\limsup E_k =
\bigcap_{j=1}^\infty\left(\bigcup_{k=j}^\infty E_k\right).$$
So here's what I don't understand: I see $\limsup E_k$ as \begin{align*}
\limsup E_k & = \bigcap_{j=1}^\infty\left(\bigcup_{k=j}^\infty
E_k\right)\\ &= \bigcap_{j=1}^\infty(E_j \cup E_{j+1} \cup \cdots \cup
E_\infty)\\ &= (E_1 \cup E_2 \cup \cdots \cup E_\infty) \cap (E_2 \cup E_3
\cup \cdots \cup E_\infty) \cap E_\infty\\ & = E_\infty. \end{align*}
But them I am confused by the statement:
$\limsup E_k$ consists of those points in $\mathbb{R}^n$ which belong to
infinitely many $E_k$.
So how should I understand $E_\infty$? Is it infinitely many $E_k$s? So
for $j = \infty$, we still get infinitely many sets in
$\bigcup_{k=j}^\infty E_k$?

Taking These Tables and Associating Their Appropriate Teams Together

Taking These Tables and Associating Their Appropriate Teams Together

I was recently assisted with getting the scores from a yahoo NHL page that
would print out the teams and their aforementioned scores in a respective
manner. Here is my code:
from bs4 import BeautifulSoup
from urllib.request import urlopen
url = urlopen("http://sports.yahoo.com/nhl/scoreboard?d=2013-01-19")
content = url.read()
soup = BeautifulSoup(content)
def yahooscores():
results = {}
for table in soup.find_all('table', class_='scores'):
for row in table.find_all('tr'):
scores = []
name = None
for cell in row.find_all('td', class_='yspscores'):
link = cell.find('a')
if link:
name = link.text
elif cell.text.isdigit():
scores.append(cell.text)
if name is not None:
results[name] = scores
for name, scores in results.items():
print ('%s: %s' % (name, ', '.join(scores)) + '.')
yahooscores()
Now, first of all: I am associating this stuff in a function because I am
going to have to change the url constantly to get all the values of every
day of the January month.
The issue here is that while I can print the scores and team text fine, I
am trying to accomplish this:
Ottawa: 1, 1, 2.
Winnipeg: 1, 0, 0.
Pittsburgh: 2, 0, 1
Philadelphia: 0, 1, 0.
See, my code doesn't do that. I was in the process of trying to get that
to happen, but what is complicating the process is that the tables are all
under the same class of "scores" and seemingly, I can't find anything
different amongst them.
In a nutshell, associate teams correctly with each other and have a space
in-between for organization.

How to get rid of erroneously drag-n-dropped folder shortcut in Finder toolbar?

How to get rid of erroneously drag-n-dropped folder shortcut in Finder
toolbar?

I erroneously drag-n-dropped a folder shortcut in my Finder toolbar. I
tried dragging it off and right clicking, to no avail. How do I remove it?

the server is a J2EE web service and MySQL is the database server, client and J2EE server are in different time zones

the server is a J2EE web service and MySQL is the database server, client
and J2EE server are in different time zones

We are working on a client – server environment where the client is a J2SE
app, the server is a J2EE web service and MySQL is the database server,
client and J2EE server are in different time zones and java is performing
an automatic time zone conversion in client side but we want the client to
work in the same time zone as the server with no conversions. Any ideas on
how we can do this?

What does Zest (Eclipse) mean?

What does Zest (Eclipse) mean?

I am wondering what Zest (part of the GEF in Eclipse) means? Is it an
abbreviation for something else or do they just use the english word
"zest" for their stuff? I can't find any information about the background
of the name. But it would be nice, if someone knows it, because i am
writing a paper about Zest.
Thanks in advance!

Sending html mail displays correctly on some applications but not on others?

Sending html mail displays correctly on some applications but not on others?

I am sending emails via a C# application. The following characters
displays correctly on some email applications but on others, I get a weird
replacement (See attached image). How can I go about making these
characters always display correctly?
The character set : ( ) & * % $ # @ ! ~ ; _ = + / - ?
The Message : 18cm – 22cm Wide; Fat O
The result :
No matter which one of the characters gets used, The result is always the
same as the attached image.

Will fillInStackTrace() is more cheaper when use in log4j?

Will fillInStackTrace() is more cheaper when use in log4j?

I'm using log4j in my application, just curious to know if I'm passing in
an Exception object into logger, as in (1), will this consume more
resource than if I pass in e.fillInStackTrace(), as in (2)? In other
words, will (2) is more cheaper than (1)? Below is my sample code on
log4j.
private static Logger logger = Logger.getLogger(...);
try {
...
}
catch( Exception e ) {
logger.error("blah blah blah", e); // (1)
logger.error("blah blah blah", e.fillInStackTrace()); // (2)
}
I am a bit confuse here, please help clarify?

Monday, 19 August 2013

Show the float value in formatted String two digits after decimal in iphone

Show the float value in formatted String two digits after decimal in iphone

I have a float number in which i insert comma after thousands value it
works fine
NSNumberFormatter *formatter = [NSNumberFormatter new];
[formatter setNumberStyle:NSNumberFormatterDecimalStyle]; // this line
is important!
NSString *formatted = [formatter stringFromNumber:[NSNumber
numberWithFloat:appDelegate.C_WND_ClinInf_Average_Default]];
but it shows 1,947 but i want it to show 1,947.00 any idea how to formate
like this.
Thanks

Hide default Android Soft-input in EditText doesn't works

Hide default Android Soft-input in EditText doesn't works

I have try to hide the default soft-input keyboard with
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
but when I click the EditText the keyboard appears again
I have tried also
input.setImeOptions(EditorInfo.IME_FLAG_NO_EXTRACT_UI);
and
android:imeOptions="flagNoExtractUi"
with no result, the keyboard appears always when I click the EditText.
If I set inputType null, the keybard doesn't appear but the editText
became unusable since I cannot select or move the cursor anymore nor
copy-paste anything
Any solution?

System event key codes not working on thunderbolt display

System event key codes not working on thunderbolt display

my applescript works when i am just using my MBPretina however if i have
my thunderbolt display turned in the script does not work
Here is the script which works perfectly on just the laptop
######## turn screen bright
repeat 25 times
tell application "System Events"
key code 113
end tell
end repeat
Terminal will display this if i am running on the thunderbolt
^[[28~^[[28~^{{... etc
does any one know the key code system events for thunderbolt or where i
may find them?
Thanks in advance

Booting from ISO in Xen Paravirtualized Environment

Booting from ISO in Xen Paravirtualized Environment

Specifically, Citrix XenServer 5.6.
I can map the an ISO from a Storage Repository with no issues and mount it
inside the OS but I can't boot from the DVD drive without converting it to
HVM, which causes problems because the ISO I'm trying to boot from is a
"Bare Metal" restore so it's a tad bit sensitive to whether it boots into
paravirt or HVM mode (for example, former uses paravirt drivers for
primary HDD at /dev/xvda whereas the latter puts primary HDD at /dev/sda).
I've looked online and the only thing I've been able to find are
instructions on how to boot from ISO by converting to HVM (which works for
the boot, but undercuts the reason for the boot in the first place).
I've looked around without much luck on how to configure Citrix's PyGrub
to boot from ISO. No joy on that, and the only PyGrub examples I've found
don't look like they're going to play well with Citrix and are far too
manual for that to be our SOP in case of disaster recovery.

PF autocomplete showing wrong label when validation fails

PF autocomplete showing wrong label when validation fails

I'm having a weird behaviour with primefaces' autocomplete.
The component works perfectly fine when I submit a form without validation
errors, or with errors on other form fields. However, if validation fails
on the autocomplete, the label is replaced by the item @Id field.
I suspect something is wrong with the converter I'm using. What the
converter does, basically, is get the entity's @Id value and insert the
actual entity in the component's attribute map with the @Id value as its
key.
Here is my xhtml:
<p:autoComplete
id="autoComp"
value="#{action.timeTable}"
completeMethod="#{action.timeTables}"
var="tt"
itemLabel="#{tt.description}"
itemValue="#{tt}"
dropdown="true"
minQueryLength="3"
forceSelection="true"
converter="entityConverter"
size="30"
required="true"
maxResults="10">
<f:validator validatorId="customValidator" />
</p:autoComplete>
And here is my converter code:
@FacesConverter("entityConverter")
public class EntityConverter implements Converter {
@Override
public Object getAsObject(FacesContext ctx, UIComponent component, String
value) {
if (value != null) {
return component.getAttributes().get(value);
}
return null;
}
@Override
public String getAsString(FacesContext ctx, UIComponent component, Object
obj) {
if (obj instanceof String) {
return obj.toString();
}
if (obj != null) {
String id;
try {
id = this.getId(getClazz(ctx, component), obj);
} catch (NoSuchFieldException | IllegalAccessException e) {
throw new ConverterException("msg");
}
id = id.trim();
component.getAttributes().put(id, getClazz(ctx,
component).cast(obj));
return id;
}
return null;
}
private Class<?> getClazz(FacesContext facesContext, UIComponent component) {
//get entity's class
}
private String getId(Class<?> clazz, Object obj) throws
NoSuchFieldException, IllegalAccessException {
// get entity's ID value
}
}

Sunday, 18 August 2013

Generics and ArrayList Help please

Generics and ArrayList Help please

How can i access the methods in the Students class. when i print myList it
uses the toString in the students class, i'm not sure how to access the
other methods. can someone help? is that even possible? help please.
ps i already have the try and catch in my program, i just didn't post here
to make the code shorter
public class DatabaseAccess <T> {
public T[] database;
public ArrayList<T>myList = new ArrayList<T>();
public ArrayList<T> testlist = new ArrayList<T>();
public void userInterface(){
int count = 1;
for (T i : myList){
System.out.println(count++ + ": " + i);
}
}
public void readDatabase(){
try {
ObjectInputStream in = new ObjectInputStream(new
FileInputStream("grocery.bin"));
database = (T[]) in.readObject();
for (int i = 0; i < database.length; i++){
myList.add(database[i]);
}
myList.add((T) "\n");
myList.add((T) "\tStudents:");
ObjectInputStream in1 = new ObjectInputStream(new
FileInputStream("students.bin"));
database = (T[]) in1.readObject();
for (int i = 0; i < database.length; i++){
myList.add(database[i]);
}
}
}
public class Student implements Serializable, Comparable{
private String name, id, address;
private double gpa;
public Student(String name, String id, double gpa){
this.name = name;
this.id = id;
this.gpa = gpa;
}
public int compareTo(Object object){
Student student = (Student ) object;
if(this.gpa < student.getGpa())
return -1;
else
if(this.gpa > student.getGpa())
return 1;
else
return 0;
}
public String getName(){ return name;}
public String getId(){ return id;}
public double getGpa(){ return gpa;}
public String toString(){ return (String.format("%16s%10.4s%8s",
name, id, gpa));}
}

Java - Using the output of one method in the statement body of another method is not producing the expected result

Java - Using the output of one method in the statement body of another
method is not producing the expected result

I have 2 classes, LotSelection and LotGen, in a package called
lotterynumberselector. LotSelection has 2 methods: LotPool() and
WinningSequence(). LotPool() is meant to return an ArrayList of 50
integers from 0 to 49 and scramble it. WinningSequence() is meant to
create a 6-element array containing the first 6 integers from the
ArrayList generated in LotPool().
This is the code for LotSelection.
package lotterynumberselector;
import java.util.ArrayList;
import java.util.Collections;
public class LotSelection {
ArrayList<Integer> LotPool() {
ArrayList<Integer> sequencedraw = new ArrayList<Integer>();
for(int i = 0; i < 49; i++) {
sequencedraw.add(i);
}
Collections.shuffle(sequencedraw);
return sequencedraw;
}
int[] WinningSequence() {
int[] WinningSequence = new int[6];
int j = 0;
while (j < 6) {
WinningSequence[j] = LotPool().get(j);
j++;
}
return WinningSequence;
}
}
The purpose of LotGen is to test if the outputs created by LotSelection
were doing their expected tasks. However, the output from
WinningSequence() didn't match the first six numbers created from
LotPool() and I'm wondering why. I'm not sure if it's because the code in
LotGen or LotSelection is creating an unexpected result. I suspect it's
because LotPool() is producing one 50-element ArrayList and
WinningSequence() is creating ANOTHER LotPool() so it's making it's array
from a DIFFERENT 50-element ArrayList, but I'm not sure.
Here is the code for LotGen:
package lotterynumberselector;
import java.util.ArrayList;
import java.util.Arrays;
public class LotGen {
public static void main(String [] args) {
LotSelection a = new LotSelection();
ArrayList<Integer> LotPool = new ArrayList<Integer>();
LotPool = a.LotPool();
System.out.println(LotPool);
int[] WinSeq = new int[6];
WinSeq = a.WinningSequence();
System.out.println(Arrays.toString(WinSeq));
}
}

How to get a certain array element's key?

How to get a certain array element's key?

I'm pretty new to java, and I'm trying to create a simple method that
sorts inputted numbers, either ascending or descending. However, there's a
problem that I can't put in repeated values. Is there a way to get the key
of a certain item of an array??
My code:
import java.io.Console;
public class TestSort {
public static void main(String args[]) {
Console c = System.console();
if (c == null) {
System.err.println("No console.");
System.exit(1);
}
System.out.println("TESTSORT.java");
System.out.println("-------------");
System.out.println("Type in a set of numbers here:");
String in = c.readLine();
System.out.println("(A)scending or (D)escending");
String ad = c.readLine();
boolean d = false;
if(ad.equals("a")) d = false;
else if(ad.equals("d")) d = true;
else {
System.out.println("Invalid Input.");
System.exit(1);
}
String[] in2 = in.split(" ");
int[] x = new int[in2.length];
int count1 = 0;
for(String val : in2)
x[count1++] = Integer.parseInt(val);
int[] a = new int[x.length];
int count = 0;
for(int y : x) {
for(int z : x) {
// if index of y equals index of z continue
if(z < y) count++;
}
a[count] = y;
count = 0;
}
if(d) {
int[] arr3 = new int[a.length];
int length = a.length;
for(int b : a) arr3[--length] = b;
for(int b : arr3) System.out.println(b);
} else
for(int b : a)
System.out.println(b);
}
}
This program just counts up the number of other numbers smaller than
itself, but not including itself. However, it doesn't differentiate itself
from other numbers with the same value.
Help would be appreciated.
Thanks.

How to type "^" in Texmaker?

How to type "^" in Texmaker?

I am using Texmaker for making documents in Latex. However for some reason
I am not able to type the symbol "^". I am able to type other symbols
which require your to hold SHIFT + , such as !, @, #, $, %, & and *, using
the numbers 1 to 5 and 7 to 9. However when I try to do the same with 6,
which should produce a ^, I get nothing.
My temporary solution is to type it in another program (often a web
browser) and copy out of it. But I would expect that you would be able to
type it in Texmaker itself.
Do other people have the same issue, or does anyone know how to resolve this?