Saturday, 31 August 2013

Update not working-NodeJs and MongoDB using MongoClient

Update not working-NodeJs and MongoDB using MongoClient

I was going through the mongodb and nodejs course on MongoDBUniversity and
one of the task involves finding the documents which has the highest
recorded temperature for any state and then add a field "month_high" to
it.I am able to find the documents for the state with the highest
temperature but am unable to update it. The code is as below.
Can someone tell me what might I be doing wrong?
var MongoClient=require('mongodb').MongoClient;
MongoClient.connect('mongodb://localhost:27017/course',function(err,db){
var cursor=db.collection("weather").find();
cursor.sort({"State":1,"Temperature":-1});
var oldState,newState;
cursor.each(function(err,doc){
if(err)throw err;
if(doc==null){
return db.close();
}
newState=doc.State;
if(newState!=oldState){
var operator={'$set':{"month_high":true}};
var query={"_id":doc._id};
console.log(doc._id+" has temp "+doc.Temperature+" "+doc.State);
db.collection("weather").update(doc,operator,function(err,updated){
console.log("hi");//---->Never Logs
if(err)throw err;
console.log(JSON.stringify(updated));
})
}
oldState=newState;
});
});

Import Excel data to Sql in Asp.Net

Import Excel data to Sql in Asp.Net

I Have imported excel data to the sql server in ASP.NET. what i got the
Problem is it upload data upto 100 row withn a minute bt after 100 of row
of excel data(even the 101) it will not upload... it gives error like
Timeout experied. The timeout Period piror to obtaning a connection from
the pool. this may occured because all the pooled connections were in use
and max pool size was reached

MS Access 2007 - Need to link command button to selected value in list box to open customer form from search results

MS Access 2007 - Need to link command button to selected value in list box
to open customer form from search results

I'm trying to create a simple form that allows the user to search for a
customer record, then either double click on the selected record from the
search results, or click a command button to open the selected record in
the customer form. I created a query linked to the "search for customer"
form that searches either last name, first name, or ID and returns the
results in a list box. That's as far as I got. Any help is much
appreciated. This is the criteria in my query:
Like "*" & [forms]![FRM_SearchMulti]![SrchText] & "*"

Unabel to retrieve variables from ajax post in codeignighter

Unabel to retrieve variables from ajax post in codeignighter

I am new to using ajax and i am having trouble with posting variable and
accessing those variables in my controllers.
Here is the Controller Code
class autocomplete extends CI_Controller {
// just returns time
function workdammit()
{
$product = $this->input->post('productName');
/* $this->load->model('product_model');
$q = 'SELECT quantity FROM products WHERE productName = "BC20BA"';
$data = $this->product_model->get_record_specific($q);
echo json_encode($data[0]->quantity);
*/
echo $product;
}
function index()
{
$this->load->view('autocomplete_view');
}
}
If i change the echo to a string inside single quotes like this 'Hello
World' it will return the hello world back to the view correctly. But it
will not do the same if I try it as it currently is. Also if i use echo
json_encode($product); it then returns false.
Here is view code with ajax.
$( document ).ready(function () {
// set an on click on the button
$('#button').click(function () {
$.ajax({
type: "POST",
url: "<?php echo site_url('autocomplete/workdammit'); ?>",
dataType: "json",
data: 'productName',
success: function(msg){
alert(msg);
}
});
});
});
</script>
</head>
<body>
<h1> Get Data from Server over Ajax </h1>
<br/>
<button id="button">
Get posted varialbe
</button>

How to implement lightweight "tag" wrapper class?

How to implement lightweight "tag" wrapper class?

I'm looking for a way to implement a universal lightweight wrapper class,
whose sole purpose is to "tag" arbitrary objects. (Hence
isinstance(wrapped_instance, WrapperClass) would return True, but in every
other respect, the enclosing "wrapper instance" would behave exactly as
the underlying "wrapped instance".)
One strategy for doing this would be to implement perfect (or
near-perfect) "pass-through delegation". IOW, each instance of the wrapper
class would store the wrapped instance (to serve as "delegate") in an
instance variable, and forward all (or rather, almost all) method calls
and instance-variable access to this delegate. (Notable exceptions to this
blanket pass-through policy would be any access to the wrapped instance
itself, and access to the __class__ property of the wrapper instance.)
Here's an attempt at doing this:
class Wrapper(object):
__slots__ = '_obj'
def __init__(self, obj):
super(Wrapper, self).__setattr__('_obj', obj)
def __getattr__(self, attr):
return getattr(self._obj, attr)
def __setattr__(self, attr, value):
return setattr(self._obj, attr, value)
At first, it seems to work. Notably, isinstance produces the desired result:
In [100]: wrapped_list = Wrapper(range(7))
In [101]: isinstance(wrapped_list, Wrapper)
Out[101]: True
But also, the standard methods of the wrapped instance seem to work:
In [102]: wrapped_list.pop()
Out[102]: 6
In [103]: wrapped_list.reverse(); wrapped_list.pop()
Out[103]: 0
All is not well, however. For example, len fails on the wrapped instance:
In [104]: len(wrapped_list)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-104-e9ec371eafc5> in <module>()
----> 1 len(wrapped_list)
TypeError: object of type 'Wrapper' has no len()
...even though pass-through seems to work fine for the __len__ method:
In [105]: wrapped_list.__len__()
Out[105]: 5
With repr the situation is, in some sense, worse, since not even
explicitly accessing the wrapper instance's __repr__ method does the right
thing:
In [106]: wrapped_list
Out[106]: <__main__.Wrapper at 0x10851a360>
In [107]: wrapped_list.__repr__()
Out[107]: '<__main__.Wrapper object at 0x10851a360>'
In [108]: wrapped_list._obj
Out[108]: [5, 4, 3, 2, 1]
Most disturbingly, basic indexing fails:
In [109]: wrapped_list[2]
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-109-424990b88e32> in <module>()
----> 1 wrapped_list[2]
TypeError: 'Wrapper' object does not support indexing
The problems shown in the example above are somewhat specific to the
example. I expect to see a different constellation of failures if I were
to test a wrapped dict() or a wrapped set(), etc.
Is there some way to achieve this effect?

How not to inherit some function in the interface in C#

How not to inherit some function in the interface in C#

I am having one interface which contains suppose 10-methods and it is
inheriting to the class say class1.My requirement is i do not want to
inherit 2-method into class1 .so how it is possible in c#.net

Create select options and get the current values for month and date

Create select options and get the current values for month and date

<select name="year"><?=options(date('Y'),1900)?></select>
<select name="month"><?php echo
date('m');?><?=options(1,12,'callback_month')?></select>
<select name="day"><?php echo date('d');?><?=options(1,31)?></select>
PHP
function options($from,$to,$callback=false)
{
$reverse=false;
if($from>$to)
{
$tmp=$from;
$from=$to;
$to=$tmp;
$reverse=true;
}
$return_string=array();
for($i=$from;$i<=$to;$i++)
{
$return_string[]='<option
value="'.$i.'">'.($callback?$callback($i):$i).'</option>';
}
if($reverse)
{
$return_string=array_reverse($return_string);
}
return join('',$return_string);
}
function callback_month($month)
{
return date('m',mktime(0,0,0,$month,1));
}
What should i make to get the current month and date in the corresponding
dropdowns as starting values, as it is the case with years (2013).

Socket send and recv manage proper disconnection

Socket send and recv manage proper disconnection

I have client-client type socket program. One client (first thread)
manages the reception from some servers and the other client (another
thread in the same process) manages to send the data received to others
servers.
When the program starts, this is the thing I do :
Creation of all the connections.
Creation of the receiving thread (poll and recv).
Creation of the sending thread (send).
When I receive data on socket x (thread 1), I have a table that knows that
those data have to be sent to socket x' (thread 2). Identically, I can
receive data from socket x' and send them to socket x.
The main problem for me is to manage the disconnection in order to remove
the unused connection from the pollfd structure :
For the moment, I manage everything in the receiving thread and I use the
return value of the recv function (if 0 then disconnection) to say if a
connection has been closed or not but it doesn't seem to be effective.
Should I use the send function to manage the disconnection as well ?
Are there any advices or better solutions ?

Friday, 30 August 2013

Python : using mod_wsgi ( environ ) : " LoL, the people on unix.stackexchange don't know i'ma troll - check out this answer i got ' [on...

Python : using mod_wsgi ( environ ) : " LoL, the people on
unix.stackexchange don't know i'ma troll - check out this answer i got '
[on...

After the environ stuff in mod_wsgi
we are ready to start our search engine
and rule the world.
here's the link to unix.stackexchange question asked
http://unix.stackexchange.com/questions/88952/the-command-ls-ltu-fails-to-list-folders-files-based-on-last-accessed-time

Thursday, 29 August 2013

Need to calculate distance,height,width of a room using android camera

Need to calculate distance,height,width of a room using android camera

Sorry for my question.I have done quite a bit researched but unfortunately
after over 50 hour i am not able to get any of the working code.I want to
develop https://play.google.com/store/apps/details?id=kr.aboy.measure this
type of functionality.Not the exact one.I just need to calculate distance
between my camera and one object.also have to find the width and length of
a wall in a room.Its very important for me
If someone could help me by providing a working source code it would be
very helpful for me as well as for others.There is no proper source code
available which is working and giving output the two object distance,width
of an object and height of an object.Please Help!!!!

Style of MediaElemnt in Windows 8.1

Style of MediaElemnt in Windows 8.1

How can I change style of sample MediaElement:

For example how can I change the background.

Wednesday, 28 August 2013

Replace Text in a Div with text in another Div

Replace Text in a Div with text in another Div

<div id="replaceMe">I'm a Girl</div>
<div id="iamReplacement" style="display:none">No your are a Boy Girl</div>
the text in replaceMe should be replaced with the text in iamReplacement
i think it can be done in java script or jquery.. can some one help me on
this..
Tried (not working)
<script>
jQuery('#replaceMe').replaceWith(jQuery('#iamReplacement'));
</script>

struts2 FileUploadInterceptor fires too late to verify file size and file extension

struts2 FileUploadInterceptor fires too late to verify file size and file
extension

I can't seem to figure out how to properly use FileUploadInterceptor in
struts2. I have everything wired and it does work. I can specify the file
extensions and max file size and it indeed works. The problem is as
follows:
I specify the max file size as 100mb
When user uploads 110mb the file I can see that JakartaMultiPartRequest
class handles the file upload with the help common fileupload libraries.
This happens BEFORE the file upload interceptor.
Once the user waited for minutes and the file upload is done the file
upload interceptor fires and tells the user that the file is too big.
There is something wrong with sequence of events. I would like to looks at
content-length header and right away tell the user that the file is too
big (before uploading). I understand the header is not always there but if
it is there I would like to use it.
Other than overwriting JakartaMultiPartRequest class I don't understand
how to do this.
Thank you for your help

passing array to with jQuery

passing array to with jQuery

I'm making a custom multiselect option box and I need to pass an array of
selected values to the element
var data=[];
$(".opt > div").click(function(){
data[data.length]=$(this).attr("value");
$(".options").val(data); // putting data into custom option
});
HTML
<div class="wrapper"> <!-- own custom style -->
<select class="options"> <!-- select is hidden with CSS -->
<!-- options -->
</select>
</div>
<div class="opt"> <!-- this div is dynamically created by clicking
no class wrapper and populated the inside with select box's options with
jQuery -->
<div value="0">item 1</div>
<div value="1">item 2</div>
<div value="2">item 3</div>
</div>
Everything is going well But on click event I want to value .option class
with array 'data' and pass it via It's form on submit as request. How to
set array (data) as It's value
Like in checkbox, giving name like name="somename[]" makes the response an
array.
the above code is just a brief demonstration of What I want

Tuesday, 27 August 2013

Is there a way to tell programmatically if clicking an element will have any effect?

Is there a way to tell programmatically if clicking an element will have
any effect?

Given an element, is there any way to tell with Javascript/jQuery whether
there are any click events on that element?
I mean ANY click events. If clicking it would cause ANY code to execute, I
want to know about it.
Is this possible?
It must be, if Firebug and Chrome Dev Tools can see all the event
listeners tied to an object...

I keep geting an exception when i start my VERY simple program [on hold]

I keep geting an exception when i start my VERY simple program [on hold]

MY Exception:
Exception in thread "main" java.lang.UnsupportedClassVersionError:
app/main : Unsupported major.minor version 51.0
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClassCond(ClassLoader.java:631)
at java.lang.ClassLoader.defineClass(ClassLoader.java:615)
at
java.security.SecureClassLoader.defineClass(SecureClassLoader.java:141)
at java.net.URLClassLoader.defineClass(URLClassLoader.java:283)
at java.net.URLClassLoader.access$000(URLClassLoader.java:58)
at java.net.URLClassLoader$1.run(URLClassLoader.java:197)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
at java.lang.ClassLoader.loadClass(ClassLoader.java:247
MY Code:
package app;
import javax.swing.ImageIcon;
public class main {
public static void main(String[] args) {
System.out.println("Errors Just Keep Hapening");
}
}

PHP while(1) time based

PHP while(1) time based

I am working with GeoLocation from browser, which works great, I am
looking for a way to update the location of the browser every let say 10
minutes. I can't use Cron Job, is there a way that I can specify a while
loop in PHP that occurs every 10 min while the user has the browser open?

MongoDB C# driver fast on take(1) but slow on take(2)

MongoDB C# driver fast on take(1) but slow on take(2)

I've been playing around with the MongoDB C# driver for the first time and
I'm finding some strange results in performance. When I query a collection
with 3 million records with ordering and .Take(1) the reponse is nearly
instantanious (3ms.). But when I .Take(2) on the same query it takes up to
10 seconds. The right index is in place and it's a very simple collection
with test data.
MongoClient client = new MongoClient();
MongoServer server = client.GetServer();
var database = server.GetDatabase("db_name");
var collection = database.GetCollection<MyType>("collection_name");
var query = from c in collection.AsQueryable<MyType>()
where c.SearchString.Contains(searchString)
orderby c.SearchString
select c.SearchString;
List<string> results = query.Take(2).ToList();

Avoiding to repeat field names when using INSERT INTO ... SELECT

Avoiding to repeat field names when using INSERT INTO ... SELECT

I have a table with a very large number of fields, and the table is being
populated by a INSERT INTO ... SELECT query. Since the number of fields is
so large, I get something like this:
INSERT INTO MyTable (
column1,
colunm2,
colunm3,
...
column200)
SELECT column1,
column2,
column3,
...
column200
FROM SomeView;
The above is cumbersome and error prone to maintain, so I'd prefer if it
was possible to have some kind of "natural insert" where the field names
in the SELECT clause are mapped to the fields with the same names in the
target table.
I tried this:
INSERT INTO MyTable
SELECT column1,
column2,
column3,
...
column200
FROM SomeView;
Which is syntactically correct, but relies on matching the order of the
fields, which is even more error prone, so what to do? Am I overlooking a
much more obvious third option?
Clarification: the purpose is to make it easier to maintain the code in
the long run. We will be updating this statement many times, so I am
looking for a way to make it more readable and easy to modify.

Monday, 26 August 2013

How to check if a field in subquery in SQL?

How to check if a field in subquery in SQL?

I have to do a lot of queries with this kind of logic:
Check if a table contains a record for a patient
If it does return then 'Yes'
Else return 'No'
Now, I want to create a procedure that will do this, so I tried to create
a function that will do the above, but ended up in dynamic queries which
is not possible in functions.
Is it possible to achieve this? How can I go about this?
PS: Maybe something like:
select
(IF EXISTS(SELECT * FROM Dtl_Patient WHERE Pk = 3990 select 'Yes' else
select 'No')) as output from dtl_AllPatient;
Thanks
Thanks

django-rest-framework - trying to set required=False flag on nested 1-to-M?

django-rest-framework - trying to set required=False flag on nested 1-to-M?

I'm having some issue with django-rest-framework, and nested objects.
I have a Cart object, as well as CartItem, which links back to a Cart:
class Cart(models.Model):
customer = models.ForeignKey(Customer)
date_created = models.DateTimeField(auto_now_add=True)
date_modified = models.DateTimeField(auto_now=True)
class CartItem(models.Model):
cart = models.ForeignKey(Cart, related_name='cartitems')
product = models.ForeignKey(Product, help_text='Product in a cart')
quantity = models.PositiveIntegerField(default=1, help_text='Quantity
of this product.')
date_added = models.DateTimeField(auto_now_add=True, help_text='Date
that this product was added to the cart.')
I've created serializers for both:
class CartItemSerializer(serializers.ModelSerializer):
product = serializers.HyperlinkedRelatedField(view_name='product-detail')
class Meta:
model = CartItem
class CartSerializer(serializers.ModelSerializer):
customer =
serializers.HyperlinkedRelatedField(view_name='customer-detail')
cartitems = CartItemSerializer(required=False)
total_price = serializers.CharField(source='total_price', read_only=True)
shipping_cost = serializers.CharField(source='shipping_cost',
read_only=True)
class Meta:
model = Cart
fields = ('id', 'customer', 'date_created', 'date_modified',
'cartitems', 'total_price', 'shipping_cost')
However, whenever I try to POST to create a new cart, I get an error,
assumedly when it tries to set the non-existent CartItem:
TypeError at /api/v1/carts/
add() argument after * must be a sequence, not NoneType
However, a Cart isn't required to actually have CartItems.
Is there any way to get DRF to respect the required=False flag I get on
Cart.cartitems?
Cheers, Victor

"Copy" when using ARC

"Copy" when using ARC

I know that when using ARC and you have an NSString property, you do
@property(nonatomic, copy) just as you would MRC. But I'm wondering, after
I converted my project to ARC, I still have this in my initializer method:
_someString = [someStringParameter copy]
Is this a bug? Or even with ARC, do I still need to explicitly say "copy"
? Or should I just do:
self.someString = someStringParameter
and all will be OK? Bit confused here...

No codec available for format GIF in Ubuntu

No codec available for format GIF in Ubuntu

This is what Error i get from
8/27/2013 5:37:36 AM
Function Name : CreateCheckCodeImage
Message : No codec available for format:b96b3cb0-0728-11d3-9d7b-0000f81ef32e
This is CreateCheckCodeImage Function's Source Code
private void CreateCheckCodeImage(string checkCode)
{
if (checkCode == null || checkCode.Trim() == string.Empty)
{
return;
}
Bitmap bitmap = new
Bitmap((int)Math.Ceiling((double)checkCode.Length * 12.5), 22);
Graphics graphic = Graphics.FromImage(bitmap);
try
{
Random random = new Random();
graphic.Clear(Color.White);
for (int i = 0; i < 25; i++)
{
int num = random.Next(bitmap.Width);
int num1 = random.Next(bitmap.Width);
int num2 = random.Next(bitmap.Height);
int num3 = random.Next(bitmap.Height);
graphic.DrawLine(new Pen(Color.Silver), num, num2, num1,
num3);
Font font = new Font("Arial", 12f, FontStyle.Bold |
FontStyle.Italic);
LinearGradientBrush linearGradientBrush = new
LinearGradientBrush(new Rectangle(0, 0, bitmap.Width,
bitmap.Height), Color.Blue, Color.DarkRed, 1.2f, true);
graphic.DrawString(checkCode, font, linearGradientBrush,
2f, 2f);
for (int j = 0; j < 100; j++)
{
int num4 = random.Next(bitmap.Width);
int num5 = random.Next(bitmap.Height);
bitmap.SetPixel(num4, num5,
Color.FromArgb(random.Next()));
}
graphic.DrawRectangle(new Pen(Color.Silver), 0, 0,
bitmap.Width - 1, bitmap.Height - 1);
MemoryStream memoryStream = new MemoryStream();
bitmap.Save(memoryStream, ImageFormat.Gif);
base.Response.ClearContent();
base.Response.ContentType = "image/Gif";
base.Response.BinaryWrite(memoryStream.ToArray());
}
}
catch (Exception exception)
{
CY.WriteError(CY.GetCurrentMethod(), exception.Message);
}
finally
{
graphic.Dispose();
bitmap.Dispose();
}
}
i have found that the code problem are on the saving state.
bitmap.Save(memoryStream, ImageFormat.Gif);
base.Response.ClearContent();
base.Response.ContentType = "image/Gif";
base.Response.BinaryWrite(memoryStream.ToArray());
And i m using Ubuntu 12.04 and i have installed GDI+ and gif ext.
root@cy-VirtualBox:~/WebSite2# dpkg --get-selections | grep gif
libgif-dev install
libgif4 install
root@cy-VirtualBox:~/WebSite2# dpkg --get-selections | grep jpeg
libjpeg-turbo8 install
libjpeg8 install
root@cy-VirtualBox:~/WebSite2# dpkg --get-selections | grep gdi
printer-driver-sag-gdi install
root@cy-VirtualBox:~/WebSite2#
How to solve this problem? it is work fine in my window XP with IIS, but
not in Ubuntu and Mono.
p/s: i can sure that file is gif file. because on IIS are working fine
and this is i checking on ubuntu command with gdk-pixbuf-query-loaders
"/usr/lib/x86_64-linux-gnu/gdk-pixbuf-2.0/2.10.0/loaders/libpixbufloader-gif.so"
"gif" 4 "gdk-pixbuf" "The GIF image format" "LGPL"
"image/gif" ""
"gif" ""
"GIF8" "" 100
How to install GIF Codec in Ubuntu?

How to deal with massive retagging on a meta website=?iso-8859-1?Q?=3F_=96_meta.stackoverflow.com?=

How to deal with massive retagging on a meta website? –
meta.stackoverflow.com

I was looking through meta.codereview.SE and was flagging the questions on
which I thought the site-policy tag was relevant as it can lead to clearer
site-policy in the long run. I flagged 9 questions …

Slide Toggle After Page Resize Bugging - jQuery

Slide Toggle After Page Resize Bugging - jQuery

I have created a collapsible navigation which works fine on page load, but
on the resizing of the window it seems to get trippy and slides up and
down a number of times (can be just twice, or can go on for up to ten
times).
(function ($) {
$.fn.myfunction = function () {
$(".navi-btn").hide();
$(".navigation").show();
};
})(jQuery);
(function ($) {
$.fn.mysecondfunction = function () {
$(".navi-btn").show();
$(".navigation").hide();
$(".navi-btn").click(function () {
$(".navigation").slideToggle();
});
$("li").click(function () {
$(".navigation").slideToggle();
});
$("#width").text("too small");
};
})(jQuery);
$(document).ready(function () {
var width = $(window).width();
if (width > 400) {
$('#width').myfunction();
} else {
$('#width').mysecondfunction();
}
$(window).resize(function () {
var width = $(window).width();
if (width > 400) {
$('#width').myfunction();
} else {
$('#width').mysecondfunction();
}
});
});
Here is a "working" demo jsfiddle
I have written the script myself, so I am sure there is an easy fix, I
just don't seem to know what I have done.
I was thinking perhaps after a resize, would reloading the function be a
good workaround, and if so how can this effect be achieved?

fmt:formatDate JSTL tag and custom date sort using Datatables plugin

fmt:formatDate JSTL tag and custom date sort using Datatables plugin

Ok, so I have been scouring the internet for a few days now, and I'm still
stumped. I have a JSP that makes a database call, and displays the data in
a Datatables table. Now, when the date is passed to the page, it is in the
format of yyyy-MM-dd hh:mm:ss. Our users (U.S.) are accustomed to seeing
the MM/dd/yyyy format, so I use a fmt:formatDate JSTL tag to display it as
such. Unfortunately, for whatever reason, the JS does not like that tag,
and I'm not sure why.
Here is the javascript:
jQuery.extend( jQuery.fn.dataTableExt.oSort, {
"date-us-pre": function ( a ) {
var usDatea = a.split('/');
return (usDatea[2] + usDatea[1] + usDatea[0]) * 1;
},
"date-us-asc": function ( a, b ) {
return ((a < b) ? -1 : ((a > b) ? 1 : 0));
},
"date-us-desc": function ( a, b ) {
return ((a < b) ? 1 : ((a > b) ? -1 : 0));
}
} );
I have that in a file called jquery.datesort.js which I include on the
page. The following is the initialization that I use:
$(document).ready(function() {
$('#institution').dataTable( {
"sScrollY": "200px",
"iDisplayLength": 25,
"sPaginationType": "full_numbers",
"bScrollCollapse": true,
"aoColumns": [
null,
null,
null,
null,
null,
{ "sType": "date-us" },
null,
null
]
} )
} );
I know that this works, because I tested it against dummy data, where I
simply hard-coded the dates in the format of MM/dd/yyyy into the table.
The sort worked as expected when I did that.
Now here is the code for the table body:
<tbody>
<c:forEach items="${STAT.rows}" var="item">
<c:set value="${item.LOC_ID}" var="locationID"/>
<tr>
<td><c:out value="${item.NAME}" /></td>
<td><c:out value="${item.SUBSCRIPT}" /></td>
<td><c:out value="${item.ADDRESS}" /></td>
<td><c:out value="${item.RESULT}" /></td>
<td><c:out value="${item.STATUS}" /></td>
<td><fmt:formatDate pattern="MM/dd/yyyy"
value="${item.DATE}" /></td>
<td><c:out value="${item.TYPE}" /></td>
<td><c:out value="${item.RA}" /></td>
</tr>
</c:forEach>
</tbody>
This works fine to output the data into the format of MM/dd/yyyy, but for
some reason, my sort simply does not like it. When I click on the sort
buttons, they change image (up arrow to down arrow, and vice versa) to
reflect that a sort is being performed, but the data is not sorting on the
screen. Also, if I remove the fmt:formatDate tag and comment out the js
for the date sort, the date will render as yyyy-MM-dd hh:mm:ss, and will
sort that way without issue (as expected).
I am a bit puzzled, because it was my belief that the fmt:formatDate would
be taking place on the server side since it is JSTL. That would mean that
the client would only see the post-formatted data of MM/dd/yyyy, and when
the js does it's thing on the client side, it shouldn't be any different
than when I hard-coded the dates... but that is not happening.
Any ideas? Is there some kind of glaring issue that I'm missing?

Removing the "on/off" white rectangle from my homepage (WPtouch)

Removing the "on/off" white rectangle from my homepage (WPtouch)

I use the WPtouch plugin (here: r-bloggers.com), and some of my visitors
are getting a white rectangle on the homepage, with a "on/off" option for
the theme. The problem is that it only appears to some of the users, and
clears after a little bit.
I read online it might be a conflict with another plugin, or a theme, but
I don't wish to change any of these (they are all important for the
function of the site), instead, I'd like to remove this box completely -
is that possible?
Any other suggestions? (I have the plugin on "restricted mode" already -
that doesn't help)

CPU is at 45% and 32% is system

CPU is at 45% and 32% is system

So fresh server running 13.10 install Apache and Minecraft and have a
custom script running.
I check top, my CPU is stuck at 45% to 55% of which the system is taking
32% and I cannot find why. There is no process from root that are over
0.3% but there are 136 processes of which 125 is system processes, is this
normal? Is there an easy way to go about cleaning these up?
Thanks, Simon

Sunday, 25 August 2013

set the width and height of jquery popup large images

set the width and height of jquery popup large images

I have used a jquery popup gallery for my website where I want to set the
resizable image to some fixed height and width. I cant get the exact code
here is my code for the gallery
<script type="text/javascript" src="javascripts/top_up-min.js"></script>
<script type="text/javascript">
TopUp.addPresets({
"#images a": {
fixed: 0,
group: "images",
modal: 0,
title: "gallery"
},
"#movies": {
resizable: 0
}
});
</script>
and code for images in body part
<span id="images">
<a href="images/photos/1.jpg" toptions="overlayClose = 1">
<img src="images/thumbnails/1.jpg"/>
</a>
<a href="images/photos/1.jpg" toptions="overlayClose = 1">
<img src="images/thumbnails/1.jpg"/>
</a>
</span>

Is there a way to browse a phone's SDcard for a text file?

Is there a way to browse a phone's SDcard for a text file?

I'm making a Phonegap app that requires a text file input from the user.
I've tried using <input type="file"> but it only allows me to choose a
file from the gallery or a music file.
Is there any way for the user to browse the phone's sdcard using the
native file browsers for a text file on both iOS and Android? Or is making
my own file browser the only option available?

Add character after each word

Add character after each word

How can I implode character after each word?
I have tried the following:
$query = implode("* ", preg_split("/[\s]+/", $query));
but it always ignores one word. for example: test test will give me test*
test, test will give me test, test test test test will give me test* test*
test* test
Also tried $query = implode("*", str_split($query)); but it gives me
gibberish if query is in Cyrillic characters.

Saturday, 24 August 2013

Linux shell, get all the matches from a file

Linux shell, get all the matches from a file

I have a file like the following format:
line one
line two <% word1 %> text <% word2 %>
line three <%word3%>
I want to use linux shell tools like awk, sed etc to get all the words
quoted in <% %>
result should be like
word1
word2
word3
Thanks for help.
I forgot to mention: I am in embedded environment. grep has no -P option

Execute 2 functions in the same event

Execute 2 functions in the same event

It´s possible execute 2 functions in the same event ? , for example this :
Inside input field :
<input type="text" name="example" value="ok"
onclick="function1();function2();">
As you can see inside the event onclick i put 2 functions for execute when
the people over the field and do click , it´s possible do this and works
finally or exists other way for do this ?
Thank´s for the helps , the best regards

Ituen's want to delet my books [on hold]

Ituen's want to delet my books [on hold]

I have just lost my laptop the one that i use to sync all my books my i
book size is 2.5g an my i cloud account can support 15g I tried to backup
my iBooks it shows only 750mb that are backup When I try to sync my books
in the ituens wants to delet all my books I did not purchase any from
ituens because they don't sell books in my store what can I do my iOS
6.1.3 my ituens is the last version

Friday, 23 August 2013

Convert BMP to PNG while preserving alpha channel

Convert BMP to PNG while preserving alpha channel

I have an image stored in BMP format and would like to convert it to PNG
using imagemagick.
I looked at the pixels in a hex viewer and noticed that they are stored in
32bpp, so there is an alpha channel. The transparent pixels have RGBA
value (255, 255, 255, 0), and paint.NET is picking them up as white pixels
probably because it doesn't expect BMP's to have transparent pixels?
Anyways, the command I used is
convert -alpha on -quality 95 in.bmp out.png
However, when I opened the resulting image in Paint.NET (which usually
interprets transparent pixels properly), those transparent pixels were
still white.
Am I converting the images incorrectly? I would like the pixels with an
alpha value of 0 to appear transparent in the image editor that I commonly
use.

Regular Expression so select everything before and up to a particular text

Regular Expression so select everything before and up to a particular text

I am trying to use a regular expression to find a part of a string and
select everything up to that string. So for example if my string is
"this/is/just.some/test.txt/some/other" I want to search for .txt and when
I find it select everything before and up to .txt.

Don't include blank fields in GET request emitted by Django form

Don't include blank fields in GET request emitted by Django form

On my Django-powered site, I have a search page with several optional
fields. The search page is a Django form, and my view function is the
typical:
def search(request):
form = SearchForm(request.GET or None)
if form.is_valid():
return form.display_results(request)
return render(request, 'search.html', {'form': form})
Form.display_results() uses the fields that are provided to query the DB
and render a response. My search.html includes:
<form action="/search/" method="get">{% csrf_token %}
<!-- Render the form fields -->
<input type="submit" value="Search" />
<input type="reset" value="Reset form" />
</form>
Since most searches will have several blank fields, I'd like not to
include them in the GET request emitted by the submit button on
search.html. Current searches look something like:
http://mysite/search/?csrfmiddlewaretoken=blah&optional_field1=&optional_field2=&optional_field3=oohIWantThisOne
And I'd like them to look like:
http://mysite/search/?csrfmiddlewaretoken=blah&optional_field3=oohIWantThisOne
Of course, I have a several more fields. This would be nice to have
because it would make search URLs more easily human-parsable and sharable.

Return a reference by a class function and return a whole object in c++?

Return a reference by a class function and return a whole object in c++?

Operator overloading in class CVector:
CVector CVector::operator+ (CVector param) {
CVector temp;
temp.x = x + param.x;
temp.y = y + param.y;
return (temp);
}
and in main:
CVector a (3,1);
CVector b (1,2);
CVector c;
c = a + b;
So an object is passed by value, and then another temp object is being
created. I guess b is being passed by value, a is the one calling the +
therefore the x and y belong to a and pram.x and param.y to b. temp is
returned and the the copy assignment operator delivers temp's values to c?
But what about this:
CVector& CVector::operator= (const CVector& param)
{
x=param.x;
y=param.y;
return *this;
}
and in main:
a=b;
Again a is calling the = and b is being passed by reference as const.(in
this case does it matter if it was passed by value?) This is where i get
confused, x belonging to a is assigned param.x of be. so why isn't this
function void, since x and y can be accessed by this function. What does
return *this means, i know that this is the address of the object calling
the function, so *this would be the function itself, but if we are
returning an object we need to assign it it somewhere like the previous
c=temp after temp=a+b? And what does CVector& even mean, it doesn't look
like we are expecting an address of an object of CVector type?
In other words why isn't the function just:
void CVector::operator= (const CVector& param)
{
x=param.x;
y=param.y;
}
??
Then there is this code
#include <iostream>
using namespace std;
class Calc {
private:
int value;
public:
Calc(int value = 0) { this->value = value; }
Calc& Add(int x) { value += x; return *this; }
Calc& Sub(int x) { value -= x; return *this; }
Calc& Mult(int x) { value *= x; return *this; }
int GetValue() { return value; } };
int main() {
Calc cCalc(2);
cCalc.Add(5).Sub(3).Mult(4);
cout << cCalc.GetValue();
return 0;
}
Now if i removed the & from the functions:
Calc Add(int x) { value += x; return *this; }
Calc Sub(int x) { value -= x; return *this; }
Calc Mult(int x) { value *= x; return *this; }
and used
Calc cCalc(2)
cCalc.Add(5);
cCalc.Sub(3);
cCalc.Mult(4);
instead of the former, it would produce the same resault. So why does
Calc& returne type allow chaining.
I not only want to know how to program, since object oriented is much
writing by a pattern (this is written like this, this is needed if that)
opposed to structured programming where you have to use logic, but also to
know why is a peace of code defined as it is, and why it isn't as i
intuitively think it should be(although i only learn programming for about
a year).
Thanks!

Why has SP1 for Server 2008 R2 left 4.5 GB of files in a randomly-named directory on my C drive?

Why has SP1 for Server 2008 R2 left 4.5 GB of files in a randomly-named
directory on my C drive?

We have been having a push to get all 2k8 R2 servers up to SP1, and I've
noticed that some of them have ~4.5 GB of files left in a folder in the
root of the system root (C: drive).
This directory has a seemingly random name, eg C:\1830d38bd5fd4ccdcf. It
contains the file "spinstall.exe", and another seemingly randomly named
folder, which contains various other subfolders for different
regions/languages (eg en-us, ja-jp, es-es) and an 879 MB
windows6.1-KB976932-X64.cab file.
It appears to be the files required in order to install the service pack.
I'm pretty sure it can be deleted with no ill effect, but I'd like to
understand what it is doing there in the first place.
Usually, when installing SP1, you would see two events from "Service Pack
Installer" in the eventlog. Event ID 1 would be logged when the
installation is started, and event ID 9 would be logged upon successful
completion of the SP install. On the servers which have this directory
left behind, event ID 1 is logged, but no event ID 9. The SP appears to
have been successfully installed, according to Winver.exe, and according
to event ID 6009 which is logged on the subsequent boot (which says
'Microsoft (R) Windows (R) 6.01. 7601 Service Pack 1 Multiprocessor
Free').
I have nothing in the PendingFileRenameOperations or SetupExecute registry
keys.

Disable Skype "Click-to-Call" add-in from IE only

Disable Skype "Click-to-Call" add-in from IE only

On updating skype, "Click-to-Call" add-in is installed on windwos XP. I
disable that add-in by following criteria on this link. But, when next
time computer is started/re-started this add-in is enabled by default.
How can I disable that add-in from IE ?

Thursday, 22 August 2013

Active MQ and HttpClient

Active MQ and HttpClient

I am very new to using Apache Camel and ActiveMQ. I need to feed the
ActiveMQ JMS broker with tweets using Streaming API. the broker URL is an
HTTPURL and is configured in the camel-config XMk file as
<!-- Configure JMSConnectionFactory -->
<bean id="jmsConnectionFactory"
class="org.apache.activemq.ActiveMQConnectionFactory">
<!-- property name="brokerURL" value="vm://localhost" / -->
<property name="brokerURL" value="http://myabc:61616" />
<!-- property name="userName" value="smx"/-->
<!-- property name="password" value="smx"/-->
</bean>
<bean id="pooledConnectionFactory"
class="org.apache.activemq.pool.PooledConnectionFactory">
<property name="maxConnections" value="8" />
<property name="maximumActive" value="500" />
<property name="connectionFactory"
ref="jmsConnectionFactory" />
</bean>
<bean id="jmsConfig"
class="org.apache.camel.component.jms.JmsConfiguration">
<property name="connectionFactory"
ref="pooledConnectionFactory" />
<property name="transacted" value="false" />
<!-- property name="concurrentConsumers" value="10"/-->
</bean>
<!-- configure the Camel ActiveMQ -->
<bean id="activemq"
class="org.apache.activemq.camel.component.ActiveMQComponent">
<property name="configuration" ref="jmsConfig" />
</bean>
I have added HttpClient and HttpCore JARs to the classpath, but am still
getting this error. Could you please suggest how I can resolve this. I
will really appreciate it.
Caused by: java.lang.NoSuchMethodError:
org.apache.activemq.transport.http.HttpTransportFactory.getOption(Ljava/util/Map;Ljava
/lang/String;Ljava/lang/String;)Ljava/lang/String;
Thank you!! Christie

Starcraft 2 Building Previews

Starcraft 2 Building Previews

After watching Idra's stream, I noticed something. When he builds a
building, after picking the spot where to build, there is a preview placed
on the ground and for him it is a bright pink.

However, when I build something, my preview is a faded out version of the
building and not at all clear to see.

I'm looking for how to change my settings to be the same as his. My
current graphics settings are low graphics with Ultra textures and I've
tried with low-low and ultra-ultra but I can't seem to get the pink
previews.
Any help?
BTW .. It may not seem like a big deal and it rarely is, but I have my
hotkeys set so that the spore and spine crawler buttons are next to each
other so sometimes I build a wall of spores instead of spines which isn't
great vs ground based compositions as you can imagine.

Calculate price based on magento session variable

Calculate price based on magento session variable

I am trying to use Magento as a store for our rental business. Similar to
how price is adjusted with tier pricing, I want to show the price based on
the length of time the customer wants to rent it (the longer you rent it,
the lower the price per month is). Here is how I have tried to make it
work:
Create 'price' attributes to hold price for each 'rental tier'. My
attributes are 'price_1month, price_2months, price_3months', etc. Add to
default attribute set, and update product so that these attributes have
values. DONE
In the header, create a dropdown so customer can choose rental length.
This runs javascript that sets cookie and reloads the page. DONE
Set a magento session variable based off cookie when the page reloads. DONE:
Mage::getSingleton('core/session')->setRentalTier($_COOKIE["rentaltier"]);
In /core/mage/catalog/model/product/type/price.php I have updated
getPrice($product) with the following:
public function getPrice($product) {
$session = Mage::getSingleton('core/session', array('name' => 'frontend'));
$rentalPeriod = $session->getRentalTier();
if ($rentalTier == 1) {
$price = $product->getData('price_1month');
}
else if ($rentalTier == 2) {
$price = $product->getData('price_2month');
}
else if ($rentalTier == 3) {
$price = $product->getData('price_3month');
}
return $price;
}
DONE
So, this is working fine on the product page (changing the dropdown WILL
change the price). However, on the catalog it is still showing the system
price attribute. Also, when an item is added to the cart, it shows 0.00.
I thought that getPrice was the root of where price is calculated, but
this is Magento after all.. Anyone have any tips or another angle I can
take at this? Thank you

I want to display form data on website from what was entered

I want to display form data on website from what was entered

I have a form that when they submit it, it stores the info in the
database. But once they submit form I want them redirected to a webpage
that displays only what they entered. I do not need a page to display all
the database tables.. It will only fetch the data that they entered.
Any help would be appreciated...Thanks

Why aren't the changes reflected, I made in the GUI?

Why aren't the changes reflected, I made in the GUI?

There is a vague thing going on.
I downloaded a java project with all the libraries it uses. I set it up in
netbeans. Now if I make any change in the GUI, it doesn't get reflected.
But if I make a jar file of the project by clean and build option, and run
it through the command prompt, the changes get reflected.
I have never faced this problem before ! What could be the reason for this
? The same thing happens if use the eclipse IDE.(The changes aren't
reflected)
What happens is that, the default project always runs. The project that I
downloaded.It doesn't include my modification.

vline add remote stream for callee fail

vline add remote stream for callee fail

I am trying to use your api in a custom app with imported users.
Everything works fine (auth_token, login, call initiation) , but when the
callee should get a response and add the remotestream nothing happens. no
errors get shown in the console. I would appreciate if someone takes a
look at the code and tells me what i m missing. I tried the vline demo at
https://freeofcinema.vline.com and it worked with the same browsers and
conditions between the two computers. In my app it is a http , but i tried
it also with https, and the same problem came up. This is some simplified
code i used to test the api.
var Streams = [];
var Vsession = null;
var Vline = (function(){
var Client;
var authToken;
var service_id = 'freeofcinema';
var profile = null;
var Person;
var Calls = [];
var onMessage = function(event){
//alert('message');
var msg = event.message, sender = msg.getSender();
console.log(sender.getDisplayName() +'sais: '+ msg.getBody());
console.log(event);
}
var onMediaSession = function(event){
console.log(event);
var mediaSession = event.target;
InitSession(mediaSession);
}
function Call(mediaSession) {
mediaSession.
on('change', alert_info);
}
function alert_info(b){
console.log(b);
}
function InitSession(mediaSession){
mediaSession.on('mediaSession:addRemoteStream', function(event) {
alert('addRemoteStream');
});
mediaSession.on('mediaSession:addLocalStream', function(event) {
alert('addLocalStream');
});
mediaSession.on('mediaSession:removeLocalStream
mediaSession:removeRemoteStream', function(event) {
console.log('removedStream');
});
Calls.push(new Call(mediaSession));
}
return {
init : function(){
if(profile){
return;
}
profile = {
"displayName" : //some getusrname function...
};
$.post('vtoken.php',{//get auth token
id : Comm.Voip_user().id
},function(data){
authToken = data;
Client = vline.Client.create({
"serviceId": service_id,
"ui" : true
});
Client.on('recv:im', onMessage , this);
Client.on('add:mediaSession', onMediaSession, this);
Client.on('login', function(e) {
Vsession = e.target;
//alert('loged in');
});
Client.login(service_id, profile, authToken);
});
},
getPerson : function(id){//id of user to call
if(Vsession){
Vsession.getPerson(id).
done(function(person){
Person = person;
Vsession.startMedia(id);
});
}
}
}
}());
Thank you for your response.

Wednesday, 21 August 2013

primefaces session map attribute can not get in page

primefaces session map attribute can not get in page

I set an attribute in session map on my primefaces project. I can not get
my values in js of my Facelets page.
I upload the file in a.xhtml page and set the path values in sessionmap
and get it in a.xhtml after upload finish.
FacesContext.getCurrentInstance().getExternalContext().getSessionMap()
.put("tmpfilepath", realPath+"images"+File.separator+"tmp.jpg");
Its output is my values. Then I get the values after this step on my page
alert("#{facesContext.externalContext.sessionMap.containsKey('tmpfilepath')}");
alert("#{facesContext.externalContext.sessionMap.get('tmpfilepath')}");
Its output is false and null.

How to ban 250.000 IP ranges?

How to ban 250.000 IP ranges?

I am using iblocklist.com and I want to ban a list of IPs I made from
accessing my web server on a CentOS dedi.
I have a bash script that can parse it and add the ranges one by one to
iptables. My issues are:
It takes way too long. Anyway to speed up the processes?
Will iptables even be able to handle this kind of load?
Thanks

JSJ-decomposition of a non-hyperbolic 3-manifold

JSJ-decomposition of a non-hyperbolic 3-manifold

Suppose $M$ is a $3$-manifold. Then you can split it over spheres. This is
the "prime decomposition" and is unique. You can then split the components
of this decomposition along tori. If you leave the components which are
Seifert manifolds alone then this is called the "JSJ-decomposition" and
again is unique.
My question is this:
Can you ever split over tori if $M$ is not a hyperbolic manifold?
I am sure I read this somewhere, but I have been through, over and under
all of the things I have been reading about them and cannot find anything
which mentions this. So...help? A reference would be great, and so would a
short proof. Both would be best of all!
(Oh, and if you know what tag this should be under that would be great! I
am figuring general topology isn't quite right, but then neither is
algebraic topology nor differential topology...)

change color when i press my button

change color when i press my button

i whnt to make my button like this:
<?xml version="1.0" encoding="utf-8"?>
<!-- res/drawable/rounded_edittext.xml -->
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_focused="true"><shape android:padding="10dp"
android:shape="rectangle">
<solid android:color="#6699CC" />
<stroke android:height="10dp" android:width="2dp"
android:color="#ffffff" />
<corners android:radius="15dp" />
</shape></item>
<item><shape android:padding="10dp" android:shape="rectangle">
<solid android:color="#6699CC" />
<stroke android:height="10dp" android:width="2dp"
android:color="#780000" />
<corners android:radius="15dp" />
</shape></item>
</selector>
but i dont know how to change color when i press the button

Multiple random variable, their expected values, markov chains

Multiple random variable, their expected values, markov chains

I'm reading a paper "Modeling TCP Throughput: A Simple Model and its
Empirical Validation"
In this paper, they modeled TCP throughput using a Markov regenerative
process.
Question 1. There are three probability variables $Y_i$, $\alpha_i$,
$W_i$. Given "$Y_i = \alpha_i + W_i - 1$", they directly used that "$E[Y]
= E[\alpha] + E[W] - 1$". Is it correct? Why is this correct?
Question 2. There is "$W_i = W_{i-1} / 2 + X_i / b$", where $W_i$ is the
Markov chain. Given that, they used that "$E[W] = E[W] / 2 + E[X] / b$"
with assumption that $W_i$ and $X_i$ are independent. I don't know why
this is valid.
Please help me, thank for your help ;)

System.getProperty("user.name") returns HOSTNAME instead of currently logged username

System.getProperty("user.name") returns HOSTNAME instead of currently
logged username

Here System.getProperty("user.name"); returns hostname of windows server
2008 machine instead of currently logged in user name. Below is my code
final String user = System.getProperty("user.name");
logger.info("User Name : " + user);
its simple code. Here just i want to know that how System.getProperty
works in java and on windows server 2008? and why it is returning wrong
value in this case? I can provide more details if required.Please help me
here.

Tuesday, 20 August 2013

Vim: How to Install Airline?

Vim: How to Install Airline?

I'm just getting started with Vim. It's a fun experience, but I've found
it to be kind of overwhelming. I'm trying to get this plugin installed,
vim-airline, but I'm having a lot of trouble. The Installation section on
the Github page simply states:
copy all of the files into your ~/.vim directory
Presumably, this means download the .zip, extract it, and copy all of
those files into ~/.vim/. I did this, but Vim just starts up like normal,
and running
:help airline
just gives:
Sorry, no help for airline
I assume that this means it isn't getting installed. Also, the statusbar
remains the same. I'm new to Vim and would really like to get this
working. Thanks in advance!
EDIT: I also tried putting the files into /usr/share/vim/vim73/. No dice.

Get total amount of fruits each mammal is carring

Get total amount of fruits each mammal is carring

I am struggling with specific MySQL query based problem.
I have such result set:
Table: Report
mammal_id mammal_name fruit_name gets | total |
3 rabbit apple 4 | 5 |
3 rabbit carrot 4 | 4 |
3 rabbit cabbage 1 | 3 |
2 squirrel nuts 1 | 3 |
2 squirrel cabbage 2 | 2 |
1 chipmunk nuts 2 | 2 |
1 chipmunk apple 1 | 1 |
And I want to filter like this:
Table: Filtered
mammal_id mammal_name fruit_name has
3 rabbit apple 4
3 rabbit carrot 4
3 rabbit cabbage 1
2 squirrel nuts 1
2 squirrel cabbage 2
1 chipmunk nuts 2
1 chipmunk apple 1
The hole point is to get total amount of fruits each mammal is carring.
Now I have:
SELECT a.mammal_id, b.mammal_id, a.mammal_name, b.mammal_name,
a.fruit_name, b.fruit_name, (b.total - a.total) as has
FROM (SELECT * FROM Report (result set)) as a
INNER JOIN (SELECT * FROM Report (result set)) as b
ON a.fruit_name=b.fruit_name WHERE a.mammal_id = b.mammal_id-1
After this query, I get result like this:
Table: Result
a.mammal_id b.mammal_id a.mammal_name b.mammal_name a.fruit_name
b.fruit_name has
2 3 squirrel rabbit cabbage
cabbge 1
1 2 chipmunk squirrel nuts
nuts 1
Appreciate any guidance on this problem.

Fate of Application messages in middle of an SSL renegotiation

Fate of Application messages in middle of an SSL renegotiation

This is a question which I believe the RFC is silent about:
http://tools.ietf.org/html/rfc5246
When an SSL connection is established, and application messages being
exchanged between client and server, if at a pt of time a renegotiation is
triggered, what should happen to those application messages that are sent
while both ends are still negotiating.. ? Are they discarded ? Do they
cause renegotiation to fail ?
Thanks !

How do I get these XML values with Linq to XML ?

How do I get these XML values with Linq to XML ?

I want a query that will return a IEnumerable of string and inside that have
'as.m3' 'as.m4'
I have tried xDoc.Elements("moduleid") and xDoc.Descendents("moduleid")
with no luck
<?xml version="1.0" encoding="UTF-8">
<root>
<code>
M11088MUBWWLSRSV9LTJBH81QT
</code>
<moduleid>as.m3</moduleid>
<moduleid>as.m4</moduleid>
</root>

Trigger click event of another element in angular?

Trigger click event of another element in angular?

I have an input box and Its bound with datepicker. In my view, there is
small calendar icon besides this input box. I want to trigger click event
of an input box when user clicks on this calendar icon. I have done this
using directive which I have applied to calendar icon. But its almost like
jQuery. So is there any different way to achieve this? If my approach is
wrong then please guide me to the right direction. I am new to angular and
I have read some articles where I read that avoid use of jQuery. Thanks

What is this part of the code doing?

What is this part of the code doing?

I am new to c programming. As a part of my uni course for network
security, I have to design a SSL handshake simulation. I found a sample
code online, however i don't understand some parts of the code. Could you
please help me with following :
What does (char) 0 do ?? ( send_data is defined as char send_data[1024]; )
send_data[0] = (char) 0; //Packet Type = hello
send_data[1] = (char) 3; //Version

Monday, 19 August 2013

Question involving induction, approximation of $\frac{\pi }{2}$ and other things

Question involving induction, approximation of $\frac{\pi }{2}$ and other
things

Can you please help me do this question or give me hints to do it:

Why when I use RegularExpression as DataAnnotation is not recognizing the leading zeros?

Why when I use RegularExpression as DataAnnotation is not recognizing the
leading zeros?

pI have a field in my entity which have a RegularExpression as a
DataAnnotation:/p precode@^\$?([0-9]{6})(.[0-9]){0,1}?$ /code/pre pAnd it
always works fine, except when I use zeros before the number./p pEx./p
precode- 123456.1 Work - 012345.1 Does Not Work /code/pre pIf I do the
same validation with Regex.IsMatch it says is ok./p pHow can I force MVC
to Keep the leading zeroes when it does the validation?/p

window.print printing blank pages + IE 7 + asp.net mcv3

window.print printing blank pages + IE 7 + asp.net mcv3

I am working on a web application, it's developed using MVC3
On the top of the page I have print button which will do Window.Print()
When my page (view) has data of one page(view) it prints fine, but when my
page(view) has more more data -- more than one page it prints blank pages
followed by content.
This behavior is seen in IE7, works fine in IE8.
Any thoughts please.....

CSS Browser appearance inconsistent

CSS Browser appearance inconsistent

The way I want the CSS elements should appear works on firefox but not
chrome and IE.
Link to the screenshot comparison is below
http://postimg.org/image/3sjfgyjzh/
essentially I have four inline li which are images, when viewed in chrome
or IE the third of four falls onto a new line when there is clearly enough
space to fit all the elements.
hopefully someone can help, Thanks :)
#footer-nav {
background: #999;
/* for non-css3 browsers */
filter:
progid:DXImageTransform.Microsoft.gradient(startColorstr='#0E63AD',
endColorstr='#0E63AD');
/* for IE */
background: -webkit-gradient(linear, left top, left bottom,
from(#5FAFF5), to(#0E63AD));
/* for webkit browsers */
background: -moz-linear-gradient(bottom, #0E63AD, #5FAFF5);
/* for firefox 3.6+ */
padding-top: 0px;
padding-bottom: 14px;
margin: 0px !important;
position: absolute !important;
bottom: 20px !important;
right: 0px !important;
left: -9px !important;
}
.nav-menu li {
display:inline;
margin-left: 16px;
/*padding-left: 8px;*/
right: 0px;
}

Sunday, 18 August 2013

How to add multiple javascript by wp_register_script?

How to add multiple javascript by wp_register_script?

i have multiple javascript file. How can i add those to wordpress by
wp_register_script ? I can add single javascript file by
function wptuts_scripts_with_jquery()
{
wp_register_script( 'custom-script', get_template_directory_uri() .
'/js/custom-script.js', array( 'jquery' ) );
// For either a plugin or a theme, you can then enqueue the script:
wp_enqueue_script( 'custom-script' );
}
add_action( 'wp_enqueue_scripts', 'wptuts_scripts_with_jquery' );

GAE: File uploading failing on live

GAE: File uploading failing on live

I've created a brand new project on Google App Engine using the 1.8.2 SDK.
I'm trying to build a file uploader, locally the file uploader works fine,
after deploying it and attempting an upload, I'm getting the following
error:
POST
http://test2.website.appspot.com/_ah/upload/AMmfu6bj08dli8J-kL3D_xdt…cQ6YCoQx3NC1s4If-C2J1moqV7Lg/ALBNUaYAAAAAUhExcSNKV9D3-0TadzZaCtssmKinnP5T/
503 (Service Unavailable)
_ah/upload/AMmfu6bj08dli8J-kL3D_xdthBPw4H3jir2X86RQ3dQPlV5LukvcH9t7OP8dK147…6YCoQx3NC1s4If-C2J1moqV7Lg/ALBNUaYAAAAAUhExcSNKV9D3-0TadzZaCtssmKinnP5T/:1
I've enabled billing on both GAE and Google Cloud Storage.
The code I'm using to generate the upload url is as follow:
public static String getUploadUrl(HttpServletRequest req) {
String bucket = "website-uploads";
BlobstoreService blobstoreService =
BlobstoreServiceFactory.getBlobstoreService();
UploadOptions uploadOptions =
UploadOptions.Builder.withGoogleStorageBucketName(bucket);
return blobstoreService.createUploadUrl("/upload", uploadOptions);
}
I'm using normal servlets to handle the multipart post:
public void doPost(HttpServletRequest req, HttpServletResponse res)
throws IOException, ServletException {
if (!SH.isLoggedIn(req)){
SH.redirectPage(req, res, 200, "/login");
return;
}
BlobstoreService blobstoreService =
BlobstoreServiceFactory.getBlobstoreService();
Map<String, List<BlobKey>> blobs = blobstoreService.getUploads(req);
List<BlobKey> keys = blobs.get("file");
if (keys != null && keys.size() > 0) {
BlobKey blobKey = keys.get(0);
SH.setAttribute(req, "blobKey", blobKey.getKeyString());
} else {
SH.setAttribute(req, "uploadError", "An error occurred while
uploading ...");
}
SH.setAttribute(req, "uploadUrl", getUploadUrl(req));
SH.gotoPage(req, res, 200, JSP.pageUpload);
}
And then my form doind the submit:
<form id='uploadForm' action="${uploadUrl}" method="POST"
enctype="multipart/form-data" >
<input id="imageUploader" name="file" type="file" />
<input type="submit" name="submitBtn" value="Upload" />
</form>
Is there anything obvious that is wrong with my code or is this something
Google needs to fix? If so, how do I notify them of the problem?

Set of derivatives of a normal family of analytic functions is itself a normal family.

Set of derivatives of a normal family of analytic functions is itself a
normal family.

I'm working on a problem that is easily solvable if I can prove the
statement in the title. Here's what I've done so far:
Given $\mathscr{F}$ a normal family of analytic functions, let
$\mathscr{F}'=\{f':f\in \mathscr{F}\}$. Let $\{f_n'\}$ be a sequence in
$\mathscr{F}'$. Then the corresponding sequence $\{f_n\}$ (unique up to
constants) contains a subsequence that converges to some analytic $f$.
This implies that the subsequence of derivatives converges to $f'$, so
every sequence in $\mathscr{F}'$ has a subsequence that converges and
$\mathscr{F}'$ is normal.
Am I missing something here? It seems like a very strong statement that I
wouldn't necessarily expect to be true, but I can't think of a
counterexample either.

What is a norm that can measure average oscillatory amplitude?

What is a norm that can measure average oscillatory amplitude?

I am numerically computing the growth of an oscillatory instability in a
fluid system. Suppose for simplicity that the function $f(x)$ [defined on
a finite interval] has oscillations of different modes and different
amplitudes, but is otherwise centered about $f = 0$.
As a measure of the growth of the oscillations, I have been numerically
computing maxes and mins, and then averaging the heights. So for instance,
$$ \text{Average oscillations} = \frac{1}{N} \sum_{j=1}^N
f(x^\text{max}_i), $$
where $x^\text{max}_i$ are the locations of the $N$ maxima within the domain.
Is there an easier way to measure this notion of average oscillatory
height? Are there other norms that might work to give us a 'feel' for the
value?
What if $f(x)$ is not centered about zero? Suppose that $f(x) = x +
\cos(x)$. I'd like to say that the average heights of the oscillations are
one---assuming the oscillations are closely spaced, then I can just
compute the distance between max and min values, but again, this requires
me to code an automatic extrema-finding routine. Is there an easy norm to
apply for this case as well?
I am hoping that there might be some commonly used norms (e.g. in fields
like signal processing).

R: Ratio of the values with specific labels in the data.frame --- the filling issue

R: Ratio of the values with specific labels in the data.frame --- the
filling issue

I have a data.frame and I need to add additional column that is a ratio
between labels == 1 and labels == 2 for same cID. I have the code that can
do that but the results is the reduced form according to the number of
unique "l". But I need a full list with duplicates. Any suggestions?
Thank's in advance!
x y l cID
0.03588851 0.081635056 1 1
0.952514891 0.82677373 1 1
0.722920691 0.687278396 1 1
0.772207687 0.743329599 2 1
0.682710551 0.946685728 1 2
0.795816439 0.024320077 2 2
0.50788885 0.106910923 2 2
0.145871035 0.802771467 2 2
0.092942384 0.335054397 1 3
0.439765866 0.199329139 1 4
to reproduce
x =
c(0.03588851,0.952514891,0.722920691,0.772207687,0.682710551,0.795816439,0.50788885,0.145871035,0.092942384,0.439765866)
y =
c(0.081635056,0.82677373,0.687278396,0.743329599,0.946685728,0.024320077,0.106910923,0.802771467,0.335054397,0.199329139)
l = c(1,1,1,2,1,2,2,2,1,1)
cID = c(1,1,1,1,2,2,2,2,3,4)
dt <- data.table(x,y,l,cID)
dt[,sum(l == 1)/sum(l == 2), by = cID]
I need to obtain the ratio column that looks like this
x y l cID ratio
0.03588851 0.081635056 1 1 3
0.952514891 0.82677373 1 1 3
0.722920691 0.687278396 1 1 3
0.772207687 0.743329599 2 1 3
0.682710551 0.946685728 1 2 0.333333333
0.795816439 0.024320077 2 2 0.333333333
0.50788885 0.106910923 2 2 0.333333333
0.145871035 0.802771467 2 2 0.333333333
0.092942384 0.335054397 1 3 Inf
0.439765866 0.199329139 1 4 Inf

Mass-creating custom animations for PowerPoint presentation

Mass-creating custom animations for PowerPoint presentation

I want to create graphics/animations to represent 200 team names in a
PowerPoint presentation.
What is the best way to do this? This is the process I'm thinking of:
Type in team name
Run a processing on the text to create the animation
Simply import the picture (GIF) or movie (AVI) to the PowerPoint presentation

need help pushing with github

need help pushing with github

I finished a tutorial on how to make a to-do list with JavaScript and
html. It's in a folder that contains two files one in html and another in
JavaScript. I got into that path for that folder and did git push -u
origin master and it pushed up a rails app instead. Do I need to reset git
someone so I can have it push what I want it to?
when I did git log t his is what I got kind of confusing
C:\Users\Marshall\Project\rails_projects\todolist>git status # On branch
master # Changes not staged for commit: # (use "git add/rm ..." to update
what will be committed) # (use "git checkout -- ..." to discard changes in
working directory) # # deleted: .gitignore # deleted: Gemfile # deleted:
Gemfile.lock # deleted: README.rdoc # deleted: REDME.md # deleted:
Rakefile # deleted: app/assets/images/.keep # deleted:
app/assets/javascripts/application.js # deleted:
app/assets/javascripts/funtimes.js.coffee # deleted:
app/assets/stylesheets/application.css # deleted:
app/assets/stylesheets/funtimes.css.scss # deleted:
app/controllers/application_controller.rb # deleted:
app/controllers/concerns/.keep # deleted:
app/controllers/funtimes_controller.rb # deleted:
app/helpers/application_helper.rb # deleted:
app/helpers/funtimes_helper.rb # deleted: app/mailers/.keep # deleted:
app/models/.keep # deleted: app/models/concerns/.keep # deleted:
app/views/funtimes/index.html.erb # deleted:
app/views/layouts/application.html.erb # deleted: bin/bundle # deleted:
bin/rails # deleted: bin/rake # deleted: config.ru # deleted:
config/application.rb # deleted: config/boot.rb # deleted:
config/database.yml # deleted: config/environment.rb # deleted:
config/environments/development.rb # deleted:
config/environments/production.rb # deleted: config/environments/test.rb #
deleted: config/initializers/backtrace_silencers.rb # deleted:
config/initializers/filter_parameter_logging.rb # deleted:
config/initializers/inflections.rb # deleted:
config/initializers/mime_types.rb # deleted:
config/initializers/secret_token.rb # deleted:
config/initializers/session_store.rb # deleted:
config/initializers/wrap_parameters.rb # deleted: config/locales/en.yml #
deleted: config/routes.rb # deleted: db/seeds.rb # deleted:
lib/assets/.keep # deleted: lib/tasks/.keep # deleted: log/.keep #
deleted: public/404.html # deleted: public/422.html # deleted:
public/500.html # deleted: public/favicon.ico # deleted: public/robots.txt
# deleted: test/controllers/.keep # deleted:
test/controllers/funtimes_controller_test.rb # deleted:
test/fixtures/.keep # deleted: test/helpers/.keep # deleted:
test/helpers/funtimes_helper_test.rb # deleted: test/integration/.keep #
deleted: test/mailers/.keep # deleted: test/models/.keep # deleted:
test/test_helper.rb # deleted: vendor/assets/javascripts/.keep # deleted:
vendor/assets/stylesheets/.keep # # Untracked files: # (use "git add ..."
to include in what will be committed) # # todo.html # todo.js no changes
added to commit (use "git add" and/or "git commit -a")

Saturday, 17 August 2013

IList & other concepts for development

IList & other concepts for development

I'm a beginner to C# development.Now i'm doing C# & Entity Framework for
my project.That project is a 3-Tire Architecture Project.It's Consists of
DAL,BAL & GUI.
While i'm working on that project i realize my poor C# + Entity Framework
knowlege is not enough for those development.
Basically everytime they use IList , IEneumerable , IQueryable & So..on
and some LINQ (x=>x.IsActive==true && x.id == id ).ToList(); // i think
those are lambda expressions
And My Poor side is How to pass data between Controls to controls.(using
argument or creating object & so..on ).
So.. Experts Can you please suggest me GOOD BOOK to learn those concepts
Basic to Advance.
Please Don't Dislike this post or Vote to Close.Because your valuable
ideas helpful for all beginners to Dev world.

How to Tell Whether TSCs are Synchronized Across Cores?

How to Tell Whether TSCs are Synchronized Across Cores?

Post here states that new BIOS should synchronize all: Getting cpu cycles
using RDTSC - why does the value of RDTSC always increase?
The kernel source here
(http://lxr.linux.no/#linux+v2.6.38/arch/x86/kernel/tsc.c#L859) states
that "Intel systems are normally all synchronized" but kernel "assumes
multi socket systems are not synchronized".
Is there a way to figure whether TSCs are synchronized across cores AND CPUs?
I refer to the initial value of each TSC after startup.
Any idea?
Thanks.

Polymorphic variable in Objective-C

Polymorphic variable in Objective-C

Let's say I have a class named Parent and two derived classes called
Child1 and Child2.
@interface Parent : NSObject {
NSString *fooVariable;
-(void)foo;
}
@end
@interface Child1 : Parent {
-(void)bar1;
}
@end
@interface Child2 : Parent {
-(void)bar2;
}
@end
Now imagine I have a method called foo and in some cases I want to pass it
as a parameter an instance of Child1 and in some other cases an instance
of Child2. Depending on the class type I want to call either method bar1
or bar2.
How can I achieve this in Objective-c?
What I've tried:
I decided to use the following signature:
-(void)fooWithObject:(Parent *)instance;
So now I can do this:
Parent *instance = [[Child1 alloc] init];
//This call is supposed to lead to an invocation of bar1 inside the foo
method
[self fooWithObject:instance]
instance = [[Child2 alloc] init];
//This call is supposed to lead to an invocation of bar2 inside the foo
method
[self fooWithObject:instance]
Unfortunately, when I try to compile my code the compiler complains that
there's is no method bar1 (or bar2) declared in my Parent's interface.

Bar Notation Problem

Bar Notation Problem

everyone! I came across a problem in math that dealt with bar notation.
Does anyone know how, for instance, 1.234(with a bar notation over the 34)
is expressed as a fraction? I know already how 1.22(with a bar notation
over the 22) is expressed as 1 and 2/9. Any answer would be helpful.
Thanks!

Can PHP as slow as this?

Can PHP as slow as this?

I translated the Havlak benchmark from Robert Hundt into PHP (see
description). You can find my version on github. The algorithm tries to
find loops in a tree. I tried to stay as close as possible to the java
version. Unfortunately compared to the java version it is unbelievable
slow and i cannot see a mistake so far. Whereas the java version needs
less than a minute to run, the PHP version needs more than 8 hours on my
client. So i guess there must be a mistake. But which one?

Sketching a piecewise function online

Sketching a piecewise function online

Is there any website I can input this function into so that I can sketch
it and label any asymptotes?
$$f(x)=\begin{cases} \frac{1}{x+2} & \text{if }x<-2\\\\ |x^2-4| & \text{if
}{-2}\leq x<3\\\\ 0 & \text{if }x=3\\\\ \sqrt{x^2+16} & \text{if }x>3
\end{cases}$$

If I know the PID number of a process can I know its name?

If I know the PID number of a process can I know its name?

if I have the PID number for a process (on a UNIX machine) can I know the
name of its associated proces? What have I to do?
Tnx Andrea

Friday, 16 August 2013

Replace returns with spaces and commas with semicolons in Perl

Replace returns with spaces and commas with semicolons in Perl

This one should be relatively easy for someone who is more familiar with
Perl... I simply want to be able to be able to replace all of the line
returns (\n's) in a single string (not an entire file, just one string in
the program) with spaces and all commas in the same string with
semicolons. Here is my code that is in need of some help...
$str =~ s/"\n"/" "/g;
$str =~ s/","/";"/g;
Thank you so much in advance for helping me and other beginning Perl
programmers figure out how to manipulate strings...

Saturday, 10 August 2013

Is this the correct closed form estimation of Gamma Process mean & variance rates from data?

Is this the correct closed form estimation of Gamma Process mean &
variance rates from data?

I cannot find a single paper that details how to determine the mean and
variance rates of a Gamma Process from data; however, wikipedia has a few
closed forms, and the reason I ask is because I'm confused with the usages
of some terms and unfamiliar with their definitions & identities.
Wikipedia's Gamma Process page says
The gamma process is sometimes also parameterised in terms of the mean
($\mu$) and variance ($v$) of the increase per unit time, which is
equivalent to $\gamma=\mu^2/v$ and $\lambda=\mu/v$
and
The marginal distribution of a gamma process at time $t$, is a gamma
distribution with mean $\gamma t/\lambda$ and variance $\gamma
t/\lambda^2$.
Wikipedia's Variance Distribution page says the mean and variance is
$$E[X]=k\theta$$ $$Var[X]=k\theta^2$$
It also gives estimations for shape and scale
$$\hat\theta={1\over{kN}}\sum\limits_{i=1}^N x_i$$
$$s=ln({1\over N}\sum\limits_{i=1}^N x_i)-{1\over N}\sum\limits_{i=1}^N
ln(x_i)$$
$$k\approx{{3-s+\sqrt{(s-3)^3+24s}}\over{12s}}$$
Is it correct to that the "mean (ì) and variance (v) of the increase per
unit time" are the "mean and variance rates" of a Gamma Process? If so, is
it correct to solve for $\mu$ and $v$ by
Calculating the shape and scale parameters of the Gamma Distribution from
data then
Calculate the mean and variance of the Gamma Distribution from the shape
and scale parameters of the Gamma Distribution then
Solve for $\gamma$ and $\lambda$ by simultaneous equations from the mean
and variance of the Gamma Distribution with $t$ from data and calculate
their results, finally
Solve for mean ($\mu$) rate and variance ($v$) rate of the Gamma Process
by simultaneous equations from $\lambda$ and $\gamma$ of the Gamma
Distribution and calculate their results
?

Can not assign a specific ip under lan

Can not assign a specific ip under lan

in LAN under router there is static ips are configured,
all connections are working properly and internet also is working very
well, except a specific ip which is "192.168.2.2" which was working
properly 5 hours ago.
but now while setting this ip in "wireless adapter", the ip can not be
assigned. and after setting other ip its working, and pinging that ip eg.
"ping 192.168.2.2" it returns "Request timed out.". and i want to set
"192.168.2.2" ip to my laptop which is my reserved ip, what is the problem
i'm facing ?

Open source driver availability for main Android GPUs?

Open source driver availability for main Android GPUs?

What are the current GPUs with fully open-sourced drivers on Android?
There's been issues recently with Qualcomm's GPU in the new Nexus 7, which
makes me wonder how strict are the rules for open-sourcing all the code
for a working Android device, including the GPU drivers.

Friday, 9 August 2013

git credential.helper=cache never forgets the password?

git credential.helper=cache never forgets the password?

I want my password to be forgotten, so I have to type it again.
I have setup this:
git config credential.helper 'cache --timeout=600'
but much later on, several days, it still remembers the password and does
not ask me it again...
git version 1.7.10.4 (at Ubuntu)
did I run into a bug? (as I see similar questions but none I found that
answers this...)
EDIT: or am I missing something?
EDIT: now I know commit is local, and push is remote. BUT my commits (with
RabbitVCS Git nautilus addon) seem to be performing the push as remote
repo is being updated... When I issue push, it do asks for password... but
with the commit command it does not ask AND perform the remote update; I
checked that 4 hours ago my commit updated the remote server :(

File Transfer Between Paired Bluetooth Devices (Win8 + mobile)

File Transfer Between Paired Bluetooth Devices (Win8 + mobile)

I'm looking for native methods to transfer files between my Win 8 box and
my Android phone. Both have bluetooth capabilities and I can easily pair
the devices...but this seems utterly useless since no visible options
exist to do anything with this connection.
Pro tips?
Also, other ways I can use the bluetooth connection between my Win 8 box
and my Android might prove highly interesting.

Web.config with XDT transform to do partial replace

Web.config with XDT transform to do partial replace

I am in a situation where I just want to update a part of a the URL of a
WCF endpoint. Right now we do this by including different configs with all
the endpoints per 'variety'. This is tedious to manage. I would like to
setup a transform in the web.config to do so.
These are two examples of the files
Dev
<endpoint
address="http://servicesdev.host.com/RPUtilityServices/LogException.svc/restService"
behaviorConfiguration="restfulBehavior"
binding="webHttpBinding"
contract="Host.RP.Shared.Common.Services.Utility.Interfaces.IExceptionUtilityService"
name="LogService" />
and some more of these
Staging
<endpoint
address="http://servicessta.host.com/RPUtilityServices/LogException.svc/restService"
behaviorConfiguration="restfulBehavior"
binding="webHttpBinding"
contract="Host.RP.Shared.Common.Services.Utility.Interfaces.IExceptionUtilityService"
name="LogService" />
The difference is the servicessta versus servicesdev. Now I also have
servicesuat and a servicesqa etcera. I would like to setup a transform to
just replace the 'dev' with 'sta' etc.
But how do I do that?

Why can we use inspection for solving equation with multiple unknowns?

Why can we use inspection for solving equation with multiple unknowns?

In our algebra class, our teacher often does the following:
$a + b\sqrt{2} = 5 + 3\sqrt{2} \implies \;\text{(by inspection)}\; a=5, b
= 3 $
I asked her why we can make this statement. She was unable to provide a
satisfactory answer. So I tried proving it myself.
$a + b\sqrt{2} = x + y\sqrt{2}$. We are required to prove that $a = x$,
and $b = y$. Manipulating the equation, we get $\sqrt{2}(b - y) = x - a$,
or $\sqrt{2} = \frac{x-a}{b-y}$. Expanding this, we get $\sqrt{2} =
\frac{x}{b-y} + \frac{a}{b-y}$. I tried various other transformations, but
nothing seemed to yield a result.

Random number in java has equal probability? [on hold]

Random number in java has equal probability? [on hold]

Using Math.random(); does number generated 0.0 to less than 1.0 has equal
probability?
If possible solve this question:
In the land of Puzzlevania, Aaron, Bob, and Charlie had an argument over
which one of them was the greatest puzzler of all time. To end the
argument once and for all, they agreed on a duel to the death. Aaron was a
poor shooter and only hit his target with a probability of 1>3. Bob was a
bit better and hit his target with a probability of 1>2. Charlie was an
expert marksman and never missed. A hit means a kill and the person hit
drops out of the duel.
To compensate for the inequities in their marksmanship skills, the three
decided that they would fire in turns, starting with Aaron, followed by
Bob, and then by Charlie. The cycle would repeat until there was one man
standing, and that man would be the Greatest Puzzler of All Time. An
obvious and reasonable strategy is for each man to shoot at the most
accurate shooter still alive, on the grounds that this shooter is the
deadliest and has the best chance of hitting back.
Write a program to simulate the duel using this strategy. Your program
should use random numbers and the probabilities given in the problem to
determine whether a shooter hits the target. Create a class named Duelist
that contains the dueler's name and shooting accuracy, a Boolean
indicating whether the dueler is still alive, and a method ShootAtTarget (
Duelist target ) that sets the target to dead if the dueler hits his
target (using a random number and the shooting accuracy) and does nothing
otherwise.
Once you can simulate a single duel, add a loop to your program that
simulates 10,000 duels. Count the number of times that each contestant
wins and print the probability of winning for each contestant (e.g., for
Aaron your program might output "Aaron won 3,595>10,000 duels or 35.95%").
MY TRY:
public class DuelistDemo {
public DuelistDemo() {
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
boolean check;
int x=1;
int bobWin=0, charlieWin=0, aaronWin=0;
Duelist one=new Duelist("Charlie","1");
Duelist two= new Duelist("Bob","1/2");
Duelist three= new Duelist("Aaron","1/3");
for(int i=1;i<=10000;i++){
check=three.shootAtTarget(one);
first:
while(check){
check=two.shootAtTarget(one);
if(check){
check=one.shootAtTarget(two);
if(check){
}
else{
// System.out.println("Charlie shot Bob");
check=three.shootAtTarget(one);
if(check){
check=one.shootAtTarget(three);
// System.out.println("Charlie shot Aaron, Charlie wins");
charlieWin++;
}
else
// System.out.println("Aaron shot Charlie, Aaron wins");
aaronWin++;
}
}
else{
// System.out.println("Bob shot Charlie");
check=three.shootAtTarget(two);
if(check){
check=false;
x=0;
break first;
}
else
// System.out.println("Aaron shot Bob");
// System.out.println("Charlie shot Aaron, Charlie wins");
charlieWin++;
}
check=true;
x=0;
break;
}
for(;x==1;){
// System.out.println("Aaron shot Charlie");
x=0;
}
while(check==false){
check=two.shootAtTarget(three);
if(check){
check=three.shootAtTarget(two);
if(check){
check=false;
continue;
}
else
// System.out.println("Aaron shot Bob, Aaron wins");
aaronWin++;
}
else
// System.out.println("Bob shot Aaron, Bob wins");
bobWin++;
break;
}
}
int total=charlieWin+bobWin+aaronWin;
System.out.println("Charlie wins:"+charlieWin+" Bob wins:"+bobWin+"
Aaron wins:"+aaronWin+" Total:" +total);
}
}
public class Duelist {
String name;
String accuracy;
boolean alive=true;
public Duelist() {
}
public Duelist(String name,String accuracy){
this.name=name;
this.accuracy=accuracy;
}
private boolean Duel(){
int ran=0;
if(accuracy=="1/3"){
ran=(int)(Math.random()*3)+ 1;
// System.out.println("ran:"+ran);
}
else if(accuracy=="1/2"){
ran=(int) (Math.random()*2)+1;
// System.out.println("ran:"+ran);
}
else
return false;
if(ran==1) return false;
else return true;
}
public boolean shootAtTarget(Duelist target){
target.alive= Duel();
// System.out.println(accuracy);
return target.alive;
}
}
RESULT
Charlie wins:3317 Bob wins:4165 Aaron wins:2518 Total:10000
Question says: Aaron wins 3,595>10000. Any help!

Warning: unchecked call to compareTo(T) as a member of the raw type java.lang.Comparable

Warning: unchecked call to compareTo(T) as a member of the raw type
java.lang.Comparable

I am creating a class that implements a generic Set using a binary search
tree. I use the "compareTo" method in a couple of my methods, and I keep
getting the stated warning regardless of what I do. Any help is
appreciated!
// Allow short name access to following classes
import csc143.data_structures.*;
public class MySet<E> implements SimpleSet<E> {
// the root of the "tree" that structures the set
private BTNode root;
// the current number of elements in the set
private int numElems;
public MySet() {
root = null;
numElems = 0;
}
/**
* Add an element to the set.
*
* @param e The element to be added to the set.
* @return <tt>true</tt> If this operation updated the contents of the
set.
*/
public boolean add(E e) {
try {
root = addToSubtree(root, (Comparable) e);
return true;
} catch(DuplicateAdded exc) {
// duplicate trying to be added
return false;
}
}
// This helper method adds the element "e" to tree rooted at r. Returns
// (possibly new) tree containing "e", or throws DuplicateAdded exception
// if "e" already exists in tree.
private BTNode addToSubtree(BTNode r, Comparable elem)
throws DuplicateAdded {
if(r == null) {
return new BTNode(elem);
}
int compare = elem.compareTo(r.item);
// element already in tree
if(compare == 0) {
throw new DuplicateAdded("Element is already in set");
}
if(compare < 0) {
r.left = addToSubtree(r.left, elem);
} else { // compare > 0
r.right = addToSubtree(r.right, elem);
}
// element has been added
return r;
}
/**
* Remove all elements from this set.
*/
public void clear() {
root = null;
numElems = 0;
}
/**
* Checks for the existance of the specified value within the set.
*
* @param e The value sought.
* @return <tt>true</tt> If the value exists in the set.
*/
public boolean contains(E e) {
return subtreeContains(root, (Comparable) e);
}
// This helper method returns whether element "elem" is in
// (sub-)tree with root "r".
private boolean subtreeContains(BTNode r, Comparable elem) {
if(r == null) {
return false;
} else {
int compare = elem.compareTo(r.item);
// found element
if(compare == 0){
return true;
} else if(compare < 0) {
return subtreeContains(r.left, elem);
} else { // compare > 0
return subtreeContains(r.right, elem);
}
}
}
/**
* Check for the existance of elements in the set.
*
* @return <tt>true</tt> If there are no elements in the set.
*/
public boolean isEmpty() {
return root == null;
}
/**
* Return the number of elements in the set.
*
* @return The number of elements in the set.
*/
public int size() {
return numElems;
}
/**
* Returns a String representation of the contents of the set.
*
* @return The String representation of the set.
*/
public String toString() {
}
// this inner class creates the node that compose the binary tree structure
class BTNode<E> {
/**
* The item stored in the node.
*/
public E item;
/**
* The node to the left of "this" node.
*/
public BTNode left;
/**
* The node to the right of "this" node.
*/
public BTNode right;
/**
* Constructs the BTNode object (three parameters).
*
* @param item The item to be stored in the node.
* @param left The node to the left of "this" node.
* @param right The node to the right of "this" node.
*/
@SuppressWarnings("unchecked")
public BTNode(Object item, BTNode left, BTNode right) {
// bind to references
this.item = (E) item;
this.left = left;
this.right = right;
}
/**
* Constructs the BTNode (one parameter).
*
* @param The item to be stored in the node.
*/
public BTNode(Object item) {
// call three parameter constructor
this(item, null, null);
}
}
}