Saturday, 31 August 2013

How can I open the running application opened by my previous login?

How can I open the running application opened by my previous login?

Now I am using a remote desktop to connect to a remote linux(ubuntu)
virtual machine.Yesterday ,I opened a applicationiKomodojCand closed my
remote desktop client when I left(the virtual machine was kept
running).Today ,I reconnect to my VM and want to reuse the Komodo I opened
yesterday,What can I do?When I directly click the Komodo tag on my
desktop,I cannot open it because there is already a Komodo process
running.So I have to manually kill the process in the terminal and then
click the Komodo tag on my desktop.I think it's not a very good way
because every time I reconnect to my VM,I have to kill the Komodo process.

2D dynamic allocation in C error when incrementing the pointer

2D dynamic allocation in C error when incrementing the pointer

I wanted to allocate a string array dynamically , the program is supposed
to ask the user for characters and collect them in the first string in the
array till letter 'q' is entered then the program starts adding the
characters to the second line and so on.
When I print the characters memory location it seems like each character
takes two memory cells instead of one though I increment it only once.
Here is the source code to my program
#include <stdio.h>
void main(){
char** txt;
char* baseAddress;
txt = (char **)malloc(5*sizeof(char*));
*txt = (char *)malloc(20*sizeof(char));
baseAddress=*txt;
while(*(*txt)!='q'){
(*txt)++;
scanf("%c",(*txt));
printf("%p\r\n",(*txt));
}
*txt='\0';
printf("%p",baseAddress);
free(baseAddress);
free(txt);
}
the output is like this
>j
>0x9e12021
>0x9e12022
>s
>0x9e12023
>0x9e12024
>
I think there may be something wrong with the pointers. How do I go about
accomplishing this? and sorry for the bad english

DATETIME saving as 0000-00-00 00:00:00

DATETIME saving as 0000-00-00 00:00:00

This is my sql code ive ran this same code a good amount of times and
never had any issues with it but today or some reason it is.
mysqli_query($con,"INSERT INTO 'u_visits' ('ip_adress','dates') VALUES
('$ip',now()) ON
DUPLICATE KEY UPDATE visits = visits + 1");
mysqli_close($con);
Everything works fine except my dates row gets added as 0000-00-00 00:00:00
thanks in advance for the help.

Tab bar icons pixelated and cut off

Tab bar icons pixelated and cut off

I am trying to set my UITabbar icons via interface builder. Here is what I
am seeing:

Two problems here:
Why is the bottom cut off? The dimensions of these 3 images in order is
64x42, 44x44, 46x46.
Why are they pixelated/blurry?
I am following the guidelines for tab bar icons listed here:
https://developer.apple.com/library/ios/documentation/userexperience/conceptual/mobilehig/IconsImages/IconsImages.html
I am not using the image, image@2x naming scheme. I am just setting these
in IB. This app will be only released to devices with retina displays in
any case. The screenshot is from an iPhone 5.

How to frame two for loops in list comprehension python

How to frame two for loops in list comprehension python

I have two lists as below
tags = [u'man', u'you', u'are', u'awesome']
entries = [[u'man', u'thats'],[ u'right',u'awesome']]
result = []
for tag in tags:
for entry in entries:
if tag in entry:
result.append(entry)
How to do the above logic using list comprehension in a single line, and
that should be ultimate and very fast ?

Integrating facebook with my website in 3 different ways

Integrating facebook with my website in 3 different ways

I would like to integrate my website to facebook in three different ways.
My goals are :
A facebook like button for my facebook page in my website.
A facebook like button for my domain url in my menubar.
A facebook like button for the specific content inside my website.
example:`domain.com/content1.html'
All I have are the following two blocks of code.
<div id="fb-root"></div>
<script>(function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_US/all.js#xfbml=1";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));</script>
and
<div class="fb-like" data-href="URL here" data-width="450"
data-show-faces="true" data-send="true"></div>
Questions:
Do I need an app ID or anything to proceed.
Is it possible to accomplish all three of my codes with the above two
blocks of HTML 5 code. If yes, what will the differences be between them.

Vimgolf Top X explaination

Vimgolf Top X explaination

Challenge: http://vimgolf.com/challenges/51cf1fae5e439e0002000001
Best solution:
S]*daw{@.UP@.JZZ
Now the question is how does the solution work? Just picking up Vim and
now just getting into the more advanced commands.

how to Video capture of the computer on the network?

how to Video capture of the computer on the network?

We have a network in our office.
And i want to get video capture of another computer's screen
from my computer.
Do you know any software for this.
Thank you.

Friday, 30 August 2013

In Ruby, do i require within a class or outside?

In Ruby, do i require within a class or outside?

If i want to make a class :
class Foo
#methods here
end
that requires lets say FileUtils
do i do
require 'fileutils'
class Foo
#methods here
end
or
class Foo
require 'fileutils'
#methods here
end

Thursday, 29 August 2013

How to add custom Managers to Taggit models django

How to add custom Managers to Taggit models django

I have a django app and trying to use django-taggit in it
Actually django-taggit had two models in its API at taggit/models as below
class Tag(TagBase):
class Meta:
verbose_name = _("Tag")
verbose_name_plural = _("Tags")
class TaggedItem(GenericTaggedItemBase, TaggedItemBase):
class Meta:
verbose_name = _("Tagged Item")
verbose_name_plural = _("Tagged Items")
But i had written by custom managers to use for both classes(Tag,
TaggedItem) something like as below
from django.db import models
class TagManager(models.Manager):
def update_tags(self, obj, tag_names):
"""
Update tags associated with an object.
"""
ctype = ContentType.objects.get_for_model(obj)
...........
...........
class TaggedItemManager(models.Manager):
"""
Something works here
"""
def get_by_model(self, queryset_or_model, tags):
........
......
return something
so now i need to update the default/original class with my custom managers
like below
class Tag(TagBase):
objects = TagManager()
class Meta:
verbose_name = _("Tag")
verbose_name_plural = _("Tags")
class TaggedItem(GenericTaggedItemBase, TaggedItemBase):
objects = TaggedItemManager()
class Meta:
verbose_name = _("Tagged Item")
verbose_name_plural = _("Tagged Items")
so how to override the objects attributes of the above classes from my
file.py, we can do this by inheriting the Tag, TaggedItem classes or is
there any other way ?
so that i can use by custom manager methods something like
Tag.objects.update_tags, TaggedItem.objects.get_by_model

Force Disposal of an Inaccessible Static Object

Force Disposal of an Inaccessible Static Object

Is there a way to force an object to be disposed along with any objects
(including static) which it references when that object is in a library /
you do not have access to the source? The library is .Net code - but the
dispose method on the presented object does not completely clean up the
object (presumably because some singleton's persisted in the background /
not available to my code).
The reason I ask is to solve a problem working with the Dynamics AX .Net
Business Connector (BC) [see Dynamics AX 2009 Business Connector Logon.
Essentially this is a connection object, only the class stores information
about the first instance's parameters in some variable which persists for
the process lifetime; thus preventing the use of other instances of the
object from accepting parameters different to those given to the first
instance.
I'm hoping to run some method which will make it look like the process has
ended from the point of view of the BC (but not from the rest of my code
running in the same process), or to call some dispose/finalize method
which is also able to clean up the static information accessible only
internally by the BC.

Wednesday, 28 August 2013

How to write verilog hdl code which passes test bench easily.

How to write verilog hdl code which passes test bench easily.

How to write a code in verilog which passes test bench easily? Is there
any tool which generates verilog code for a particular test bench?

Text file with column to odbc database

Text file with column to odbc database

I daily get logs in text file format. After I run notepad++ macro to clean
the file(junk lines and empty/blank lines)/
I imported it in access table and from there I exported to odbc database
some how I don't know.
After making the odbc access connection I use access odbc connection to do
my sql query and create a needed report.
Is there a way I can automate this process? to update access database from
daily text log I get?
Thanks

JSONPath query returns same-named keys from nested objects when I only want the parent object

JSONPath query returns same-named keys from nested objects when I only
want the parent object

I'm currently working with Pentaho Kettle for some ETL jobs, and I need to
integrate a JSON feed, which means I need to use JSONPath to grab data.
For the most part, it's working well, except some of the JSON data is
nested objects with the same field name in both parent and child.
Example JSON:
[
{
"Key": "5e59d536-2e3c-487c-bff1-efd0a706532f",
"Product": {
"Name": "Some Product",
"LastUpdated": "2013-08-23T12:10:25.454",
},
"Reviewer": {
"Email": "blah@foo.com",
"LastUpdated": "2013-08-23T12:10:25.454",
},
"LastUpdated": "2013-08-23T12:10:25.407",
},
{
"Key": "f3ae6a4b-1a20-4a9a-9a8e-2de5949c4493",
"Product": {
"Name": "Some Product",
"LastUpdated": "2013-08-23T12:10:51.896",
},
"Reviewer": {
"Email": "blah@foo.com",
"LastUpdated": "2013-08-23T12:10:51.896",
},
"LastUpdated": "2013-08-23T12:10:51.896",
},
{
"Key": "de01c358-6c74-473c-8cd4-a44cf50132df",
"Product": {
"Name": "Some Product",
"LastUpdated": "2013-08-26T10:30:13.617",
},
"Reviewer": {
"Email": "blah@foo.com",
"LastUpdated": "2013-08-26T10:30:13.617",
},
"LastUpdated": "2013-08-26T10:30:13.601",
},
},
{
"Key": "af04e48a-3ce8-4227-a00a-14483ca75058",
"Product": {
"Name": "Some Product",
"LastUpdated": "2013-08-26T10:31:20.573",
},
"Reviewer": {
"Email": "blah@foo.com",
"LastUpdated": "2013-08-26T10:31:20.573",
},
"LastUpdated": "2013-08-26T10:31:20.573",
},
{
"Key": "d1a787bb-37d2-4ea9-84fd-5a3d454b9127",
"Product": {
"Name": "Some Product",
"LastUpdated": "2013-08-27T11:59:56.777",
},
"Reviewer": {
"Email": "blah@foo.com",
"LastUpdated": "2013-08-27T11:59:56.777",
},
"LastUpdated": "2013-08-27T11:59:56.73",
},
{
"Key": "d8646319-af27-464f-bd50-d61e035800c6",
"Product": {
"Name": "Some Product",
"LastUpdated": "2013-08-27T19:43:06.928",
},
"Reviewer": {
"Email": "blah@foo.com",
"LastUpdated": "2013-08-27T19:43:06.928",
},
"LastUpdated": "2013-08-27T19:43:06.866",
},
]
As you can see, the parent object, and its child objects "Product" and
"Reviewer" all have "LastUpdated" fields. I'm trying to get the parent
object's "LastUpdated" only, but using:
$..LastUpdated
returns, in order, the parent LastUpdated, Product LastUpdated, then
Reviewer LastUpdated.
RESULTS:
[
"2013-08-23T12:10:25.407",
"2013-08-23T12:10:25.454",
"2013-08-23T12:10:25.454",
"2013-08-23T12:10:51.896",
"2013-08-23T12:10:51.896",
"2013-08-23T12:10:51.896",
"2013-08-26T10:30:13.601",
"2013-08-26T10:30:13.617",
"2013-08-26T10:30:13.617",
"2013-08-26T10:31:20.573",
"2013-08-26T10:31:20.573",
"2013-08-26T10:31:20.573",
"2013-08-27T11:59:56.73",
"2013-08-27T11:59:56.777",
"2013-08-27T11:59:56.777",
"2013-08-27T19:43:06.866",
"2013-08-27T19:43:06.928",
"2013-08-27T19:43:06.928"
]
EXPECTED RESULTS:
[
"2013-08-23T12:10:25.407",
"2013-08-23T12:10:51.896",
"2013-08-26T10:30:13.601",
"2013-08-26T10:31:20.573",
"2013-08-27T11:59:56.73",
"2013-08-27T19:43:06.866",
]
Is there a query I can use to only get the parent objects' LastUpdated
fields?

VS .Net reference issue

VS .Net reference issue

Can anyone explain why this code line works perfectly fine in a method in
another class, but yet in the class I am working on VS says its reference
is missing? Both have the Import statement for System.Web.Security
Dim newUser As MembershipUser = Membership.GetUser(username)

Getting links of google search results

Getting links of google search results

How can I search on google and then get the links of results? And please
give me sample of source code. Thank you so much!

Tuesday, 27 August 2013

Read AS400 Spooled File with All pages - JAVA (JT400)

Read AS400 Spooled File with All pages - JAVA (JT400)

I'm Trying to read AS400 Spooled file in JAVA. I read it using this code.
but problem is it's retrieve only one page details of that Spooled file.
But i want to read and get all pages details. Any one know how to do it ?
Thanks in Advance!
CODE :
try {
jTextArea1.setText(null);
DefaultTableModel DTM =(DefaultTableModel) jTable1.getModel();
int SR = jTable1.getSelectedRow();
String SPLFNAME = (String) DTM.getValueAt(SR, 0);
String SPLFNUMBERT = (String) DTM.getValueAt(SR, 1);
String JOBNAME = (String) DTM.getValueAt(SR, 3);
String JOBUSER = (String) DTM.getValueAt(SR, 4);
String JOBFNUMBER = (String) DTM.getValueAt(SR, 5);
int SPLNO = Integer.parseInt(SPLFNUMBERT);
AS400 sys = new AS400();
SpooledFile sf = new SpooledFile( sys, // AS400
SPLFNAME, // splf name
SPLNO, // splf number
JOBNAME, // job name
JOBUSER, // job user
JOBFNUMBER ); // job number
PrintParameterList printParms = new PrintParameterList();
printParms.setParameter(PrintObject.ATTR_WORKSTATION_CUST_OBJECT,
"/QSYS.LIB/QWPDEFAULT.WSCST");
printParms.setParameter(PrintObject.ATTR_MFGTYPE,
"*WSCST");
// Create a page input stream from the spooled file
PrintObjectPageInputStream is =
sf.getPageInputStream(printParms);
BufferedReader d = new BufferedReader(new
InputStreamReader(is));
String data ="";
while((data = d.readLine() )!=null)
{
System.out.println (data);
jTextArea1.setText(jTextArea1.getText()+"\n"+data);
}
} catch (Exception e) {
System.out.println(e);
}

Allow the same project to be opened and built with Android Studio OR IntelliJ IDEA

Allow the same project to be opened and built with Android Studio OR
IntelliJ IDEA

I develop an SDK, and would like to be able to check in module files for
both IntelliJ IDEA and Android Studio. I've devised the following
solution, with one missing piece:
Create module files ending in -intellij-idea for the main project, and
each module.
Create build.gradle files, and use the "sourceset" directive to use the
old style src and res directory structure.
The problem is that the project information is always stored in a
directory called ".idea". Before, I could have two IPR files, such as
my-project-android-studio.ipr and my-project-intellij-idea.ipr. I could
then open one in Android Studio, and the other in Intellij IDEA, but the
actual source would remain the same.
How can I accomplish this? If there is a way to force Android Studio to
generate IPR files instead of the ridiculous .idea directory, that would
be optimal.

JS file works fine on IE but not on other browsers

JS file works fine on IE but not on other browsers

The function below gets results in ie but not on the other browsers. Any
suggestion?
....
function show_packet(str, company)
{
var cam=document.getElementById("company");
if (window.XMLHttpRequest)
{
var xmlhttp=new XMLHttpRequest();
}
else
{
var xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("packet_1").innerHTML=xmlhttp.responseText;
document.getElementById("icon_1").innerHTML="";
}
}
xmlhttp.open("GET","show_packet.php?car_moto="+encodeURIComponent(str,true)+"&cam="+encodeURIComponent(cam.value,true));
xmlhttp.send();
}
....

Add Handler for ButtonBase.Click AttachedEvent

Add Handler for ButtonBase.Click AttachedEvent

I Have a ComboBoxItem which i attempt to register to a Click event :
var cbItem =
(ComboBoxItem)cb.ItemContainerGenerator.ContainerFromItem(currentItem);
cbItem.AddHandler(ButtonBase.ClickEvent, new
RoutedEventHandler(cb.ItemClicked),true);
The Handler :
public void ItemClicked(object sender, RoutedEventArgs e)
{
var cbItem = (ComboBoxItem)sender;
............
}
This does not seem to have any effect when Clicking the Item .
1) How can i check what Handlers the ComboBoxItem references ? 2) In
general is there any thing wrong with the way i registered to that event ?
thanks .

Changing java doubles to floats in eclipse

Changing java doubles to floats in eclipse

Do you know any way to easily change every double to float in a source
file in eclipse (java)? I.e. how do I change
double a = 123.45
to
float a = 123.45f
I figured out the renaming double to float bit (whoa!), but how to add the
f's without having to go through it manually?

PayPal - Payment Summery doesn't show items set by SetPaymentOptions

PayPal - Payment Summery doesn't show items set by SetPaymentOptions

I'm working with Adaptive Payments using PayPal SDK for .Net. I'm trying
to use SetPaymentOptions method to set the items I wish to display in the
Payment Summary section, however, when I redirect the site to the sandbox
approval page using the pay key I received from the Pay method, the
payment summary only shows one row that says "faciliator account's Test
Store" and the total amount.
The response returns a success code, plus I see that other parameters,
such as BuisnessName (in DisplayOptions) are showing up on the page.
Following is the code I'm trying to execute (the parameters are replaced
by real values that map to actual accounts, urls, amounts, etc.). Can
anybody tell me what I'm doing wrong?
Thanks!
AdaptivePaymentsService service = new AdaptivePaymentsService();
RequestEnvelope envelopeRequest = new RequestEnvelope();
envelopeRequest.errorLanguage = "en_US";
List<Receiver> listReceiver = new List<Receiver>();
Receiver receive = new Receiver((decimal)300.15);
receive.email = "receiver@mail.com";
listReceiver.Add(receive);
ReceiverList listOfReceivers = new ReceiverList(listReceiver);
PayRequest reqPay = new PayRequest(envelopeRequest, "CREATE", "url",
"USD", listOfReceivers, "url");
reqPay.sender = new SenderIdentifier();
reqPay.sender.email = "sender@mail.com";
PayResponse responsePay = service.Pay(reqPay);
if (responsePay != null &&
responsePay.responseEnvelope.ack.ToString().Trim().ToUpper().Equals("SUCCESS"))
{
SetPaymentOptionsRequest payOptionsReq = new
SetPaymentOptionsRequest();
payOptionsReq.displayOptions = new DisplayOptions()
{
businessName = "My business name"
};
payOptionsReq.payKey = responsePay.payKey;
payOptionsReq.requestEnvelope = envelopeRequest;
payOptionsReq.receiverOptions = new List<ReceiverOptions>()
{
new ReceiverOptions()
{
receiver = new ReceiverIdentifier()
{
email = "receiver@mail.com"
},
description = "invoice test",
invoiceData = new InvoiceData()
{
item = new List<InvoiceItem>()
{
new InvoiceItem()
{
identifier = "1",
itemCount = 2,
itemPrice = (decimal)100.0,
name = "test",
price = (decimal)150.0
},
new InvoiceItem()
{
identifier = "2",
itemCount = 1,
itemPrice = (decimal)100.0,
name = "test2",
price = (decimal)150.15
}
},
totalShipping = 0,
totalTax = 0
}
}
};
SetPaymentOptionsResponse r =
service.SetPaymentOptions(payOptionsReq);
// ....
}

Put a DIV over another with CSS only

Put a DIV over another with CSS only

I'm trying to put a div over another with just CSS because will have a PC
and mobile style.
For example i have a container with 3 divs inside (style att just for this
example):
<div>
<div style='float:left;'>div #1</div>
<div style='float:left;'>div #2</div>
<div style='float:right;'>div #3</div>
</div>
will show as
-----------------------
--div #1--div#2--div3--
-----------------------
but in mobile will show as
-----------------------
--div #1---------------
--div #2---------------
---------------div #3--
So i plan to use something different for mobile as:
-----------------------
--div #1-------div #3--
---------div #2--------
with resolutions from 320px to 1024px:
@media only screen
and (min-device-width : 320px)
and (max-device-width : 1024px) {
/* HERE MY CSS */
}
So, Is this possible?. Thanks in advance for your help/suggestions.

Monday, 26 August 2013

What's the difference between dic[key] and [dic objectforkey:key]?

What's the difference between dic[key] and [dic objectforkey:key]?

What's the difference between dic[key] and [dic objectforkey:key]?
I'm so confuse about it . And which function is the best way in
objective-c development.

CGContext line width

CGContext line width

I'm trying to draw a simple line, the problem is that it is coming out not
as 1 pixel in width but 2. The docs state that user space units will
translate to a pixel, if I read it correctly.
The code is as simple as it gets, yet my line is always 2 pixels wide.
//Get the CGContext from this view
CGContextRef context = UIGraphicsGetCurrentContext();
//Set the stroke (pen) color
CGContextSetStrokeColorWithColor(context, [UIColor blueColor].CGColor);
//Set the width of the pen mark
CGContextSetLineWidth(context, 1);
for (int i = 1; i <= sections - 1; i++)
{
UIBezierPath *path = [UIBezierPath bezierPath];
[path moveToPoint:CGPointMake(0.0, i * kSectionHeight)];
CGContextMoveToPoint(context, 0.0, i * kSectionHeight); //Start point
CGContextAddLineToPoint(context, self.frame.size.width, i *
kSectionHeight);
}
CGContextStrokePath(context);

How to read mouse events when mousing over an embed VLC video object?

How to read mouse events when mousing over an embed VLC video object?

In my C#, .Net MVC4 application given the following HTML:
<div id="centerContent">
Some Text...
<embed id="plugin" type="application/x-vlc-plugin"
pluginspage="http://www.videolan.org"version="VideoLAN.VLCPlugin.2"
width="100%"
height="100%" id="vlc" loop="yes"autoplay="yes"
target="http://10.1.2.201:8000/"></embed>
</div>
I created wrote some JS code to output events like double left/right
click, and coordinates within the container. However, after installing the
VLC plugin, no events are available when the mouse is inside the player.
Makes sense.
Is there a way to return mouse events from within that container without
using WPF/Silverlight?
I have been looking at the LibVLC video controls, where you can get the
mouse coordinates from within a player:
LIBVLC_API int libvlc_video_get_cursor (
libvlc_media_player_t * p_mi,
unsigned num,
int * px,
int * py
)
However this option looks like rewriting the codec code (??). Using
libvlc_video_set_mouse_input to handle mouse events.
I'd like the simplest way to simply capture these events over the video
player. Setting the z-index of the embed object had no effect.
Would there be a ffmpeg option - on-the fly conversion to a different
format where I can still capture mouse events?
Is it possible to wrap the player in another JS-accessible object or some
MVC extension?
Thanks.

How to build whitelist dns

How to build whitelist dns

I need to build a whitelist dns.
I am half way there ... I am using authoritative powerdns and entering
only the whitelisted domains in the "records" database table.
I have two problems:
a) I can whitelist specific subdomains, but I can't figure out the format
for whitelisting a complete domain. I can whitelist "images.google.com"
but "google.com" is still blocked. I tried entering "*.google.com" but
that didn't work.
b) Requests for domains which are not on the whitelist come back as "page
cannot be displayed" ... I'd like to throw up a block page so how would I
redirect or default all unresolved requests to a specific page on the same
server, or even a different server? The nxdomain script might do it but I
can't find documentation anywhere on how to implement.
Thanks in advance.

Correctly Performing Calculations SQL

Correctly Performing Calculations SQL

I have a table called #rtn1 with four columns: dt, indx_nm, cusip_id, and
lrtn and another table called #rtn3 with four columns: dt, ticker,
cusip_id, and lrtn. I have bunch of different indx_nm and ticker each with
a bunch of different lrtn for different dates. I have a query written that
looks like:
insert into [CORP\Eng].etf_to_indx_cor (ticker, cusip_id, indx_nm,
cor , dt_pnts)
select b.ticker, b.cusip_id, a.indx_nm,
(AVG(a.lrtn*b.lrtn) - AVG(a.lrtn)*AVG(b.lrtn))/
STDEVP(a.lrtn)/STDEVP(b.lrtn),
COUNT(*)
from #rtn1 a, #rtn3 b
where a.cusip_id < b.cusip_id and a.dt = b.dt
group by b.cusip_id, b.ticker, a.indx_nm
having STDEVP(a.lrtn) > 0 and STDEVP(b.lrtn) > 0
order by 1,2
This is supposed to take each lrtn for the corresponding indx_nm from
#rtn1 and perform (AVG(a.lrtn*b.lrtn) - AVG(a.lrtn)*AVG(b.lrtn))/
STDEVP(a.lrtn)/STDEVP(b.lrtn) against each lrtn for the corresponding
cusip_id. Since the dates only random from todays date and exactly one
year from now, there should be a maximum of around 250 dt_pnts (only
business days). However, some of my results have 1000+ dt_pnts, meaning
that the calculation was run way too many times. How can I fix this?

#rtn1 looks like
dt ticker cusip_id lrtn
2013-08-14 ABQI 33736Q104 -0.0117821120522711
2013-08-13 ABQI 33736Q104 -0.00173822840021087
2013-08-14 ACNACTR 18385P101 -0.00183689770083951
2013-08-13 ACNACTR 18385P101 -0.00132366141379037
2013-08-12 ACNACTR 18385P101 0.018715153518994
and #rtn3 looks like
dt ticker cusip_id lrtn
2013-08-14 CEW 97717W133 0
2013-08-13 CEW 97717W133 -0.010598181
2013-08-14 EDV 921910709 0.015324696
2013-08-13 EDV 921910709 -0.013134064
both with a lot more indx_nm/ticker values and dates and lrtn

Copy values from one field to another within a subset

Copy values from one field to another within a subset

I'm trying to create a query but I'm stuck.
Context On my website users have different fields on their profile. One of
these fields is a checkbox for the newsletter. Now we are going to make a
second newsletter. Every user that is subscribed to the newsletter will be
automatically subscribed to the second and have the option to unsubscribe.
The user that are not subscribed for the original newsletter should not
receive the second newsletter either.
Table The fields are stored in a table "Profile_field". This table has 3
columns
fid => field Id (this can be profile name, address, newsletter, ...)
uid => user Id
value
So for every user I need to copy the value of field1 to field2
The query so far
UPDATE profile_values AS copy
SET value =
(SELECT value
FROM ( Select Value
FROM profile_values as original
WHERE fid = 12
) AS temp
)
WHERE fid=37
;
Now this gives me the error:
ERROR 1242 (21000): Subquery returns more than 1 row
I understand why I have this. It's because in my subquery I don't take
into account that a field returns multiple results because of the
different users. In other words I don't take the user into account.
So I tried something like
FROM ( Select Value
FROM profile_values as original
WHERE fid = 12
) AS temp
WHERE uid=copy.uid
But that doesn't work either.
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual
that corresponds to your MySQL server version for the right syntax to use
near '"temp" WHERE uid=copy.uid )where fid=37' at line 1
So how can I take the user into account in my query?
Warm regards
Stephan Celis

MATLAB: Using 'syms', getting error "Undefined function 'sym' "

MATLAB: Using 'syms', getting error "Undefined function 'sym' "

I'm trying to do some simple symbolic math in MATLAB and I'm getting the
error "Undefined function 'syms' for variable type 'char' ". I am
following a tutorial and doing exactly what they're doing, and then I get
this error! This is what I'm putting into MATLAB
syms a b c x
f = sym('a*x^2 + b*x + c');
Then it throws the error. Help is much appreciated, thanks!

Sunday, 25 August 2013

MySQL select only the newest records older than 2 days (timestamp)

MySQL select only the newest records older than 2 days (timestamp)

I have a people table, a units table, and a wellness table (described
below). Basically at my work we have to check up on people, and if they
haven't been seen for two days we go looking for them... What I'd like is
to be able to select all records from the wellness table that are older
than two days, but only the NEWEST ones (as there will probably be
multiple entries per person per day, which is how I want it because with
the wellness.username field you can tell who saw who, and when).
People
+------------+-------------+------+-----+-------------------+----------------+
| Field | Type | Null | Key | Default | Extra
|
+------------+-------------+------+-----+-------------------+----------------+
| id | int(11) | NO | PRI | NULL |
auto_increment |
| fname | varchar(32) | NO | | NULL |
|
| lname | varchar(32) | NO | | NULL |
|
| dob | date | NO | | 0000-00-00 |
|
| license_no | varchar(24) | NO | | NULL |
|
| date_added | timestamp | NO | | CURRENT_TIMESTAMP |
|
| status | varchar(8) | NO | | Allow |
|
+------------+-------------+------+-----+-------------------+----------------+
Units
+----------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+----------+-------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| number | varchar(3) | NO | | NULL | |
| resident | int(11) | NO | MUL | NULL | |
| type | varchar(16) | NO | | NULL | |
+----------+-------------+------+-----+---------+----------------+
+--------------+-------------+------+-----+-------------------+----------------+
| Field | Type | Null | Key | Default | Extra
|
+--------------+-------------+------+-----+-------------------+----------------+
| wellness_id | int(11) | NO | PRI | NULL |
auto_increment |
| people_id | int(11) | NO | | NULL |
|
| time_checked | timestamp | NO | | CURRENT_TIMESTAMP |
|
| check_type | varchar(1) | NO | | NULL |
|
| username | varchar(16) | NO | | jmd9qs |
|
+--------------+-------------+------+-----+-------------------+----------------+
The units table is ugly, I know, but it will be changed soon; as it
stands, resident references people.id.
Here's my Minimum Working Example, which only gives me one result even
though there are multiple people in wellness that have a time_checked row
older than 2 days. The one result I do get is more like 4-1/2 days old....
select w.wellness_id, p.id, p.lname, p.fname, u.number, u.type,
w.time_checked, w.check_type, w.username
from people p
left join units u on p.id = u.resident
right join wellness w on p.id = w.people_id
WHERE w.time_checked <= DATE_ADD(CURDATE(), INTERVAL -2 DAY)
order by w.time_checked asc;
I'm trying to get the newest records that are older than two days, but
only 1 per people that are in the wellness table.
Sorry for my rather rambling question, hope it's clear enough!

Using a Servlet doPost method

Using a Servlet doPost method

Im new to Java and trying out some financial analysis java file I'm using
for my studies. I got it to work when I created a main method within the
bean itself. However when I try to pass the values needed through a jsp
form and using a servlet doPost method to do the calculations by
instantiating the methods from the bean nothing happens I get a
NullPointerException. Im assuming the BlackScholes.java works as a bean
should and that the issue is within the code presented. Help here would be
greatly appreciated.
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException,IOException {
String action = request.getParameter("action");
if (action != null) {
try {
String spotPrice = request.getParameter("sprice");
String strikePrice = request.getParameter("strike");
String interestRate = request.getParameter("rate");
String timeTo = request.getParameter("time");
String vol = request.getParameter("volatility");
double sprice = Double.parseDouble(spotPrice);
double strike = Double.parseDouble(strikePrice);
double rate = Double.parseDouble(interestRate);
double time = Double.parseDouble(timeTo);
double volatility = Double.parseDouble(vol);
double carryrate = rate;
request.setAttribute("sprice", sprice);
request.setAttribute("strike", strike);
request.setAttribute("rate", rate);
request.setAttribute("time", time);
request.setAttribute("volatility", volatility);
BlackScholes BS = new BlackScholes(carryrate);
BS.bscholEprice(sprice, strike, volatility, time, rate);
double currentpriceC = BS.getCalle();
request.setAttribute("validation1", currentpriceC);
} catch (NullPointerException e) {
return;
}
} else {
request.getRequestDispatcher("/index.jsp").forward(request,
response);
}
}
}
The jsp file used to creat the form data:
<form action="${pageContext.request.contextPath}/OptionsController"
method="post">
<input type="hidden" name="action" value="docalculate" />
Spot Price: <input type="text" name="sprice" /> <br />
<p />
Strike Price: <input type="text" name="strike" /> <br />
<p />
Risk Free Rate: <input type="text" name="rate" /> <br />
<p />
Months To Expire: <input type="text" name="time" /> <br />
<p />
Volatility: <input type="text" name="volatility" /> <br />
<p />
<input type="submit" value="Submit" /><br />
<p />
One call options costs: <input type="text" name="validation1"
readonly="readonly"
value="<%if (request.getAttribute("validation1") != null) {
out.print(request.getAttribute("validation1"));
}%>">
</form>

Ubuntu 12.10 Black Screen Installation

Ubuntu 12.10 Black Screen Installation

I am new to ubuntu. I am trying to install Ubuntu 12.10 on my hp with:
Intel i3 CPU, AMD 5000 Radeon HD Grahics I am getting a black screen after
the Ubuntu's installation. I already tried the nomodeset option and the
noapic option but no luck. What can I do to bypass this problem? Thanks
All!

Android GCM message successfully sent but not received

Android GCM message successfully sent but not received

I'm trying to use the GCM service to send push notifications to my devices.
I've followed the Android Hive tutorial (which is now deprecated like many
other questions and answers about this) for the server-side functions,
which look to work as expected since I can get this kind of outputs :
{"multicast_id":9131068334342174816,"success":1,"failure":0,"canonical_ids":0,"results":[{"message_id":"0:1377441098827443%1d84a26ff9fd7ecd"}]}
But according to some answers, receiving this response just means that the
message has been accepted by GCM servers for sending, but not that it has
been sent. So, as expected, my BroadcastReceiver doesn't receive anything.
Here's my BroadcastReceiver code :
public class GcmBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Log.i("gcm_debug", "PushReceiver onReceive called");
Bundle extras = intent.getExtras();
GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(context);
String msgType = gcm.getMessageType(intent);
if(!extras.isEmpty()){
if(GoogleCloudMessaging.MESSAGE_TYPE_SEND_ERROR.equals(msgType)){
Log.i("gcm_debug", "Message send error");
}else
if(GoogleCloudMessaging.MESSAGE_TYPE_DELETED.equals(msgType)){
Log.i("gcm_debug", "Message deleted");
}else
if(GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE.equals(msgType)){
Log.i("gcm_debug", "Message received : " +
extras.toString());
}
}
setResultCode(Activity.RESULT_OK);
}
}
And my AndroidManifest :
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission
android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"
/>
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<permission android:name="<MYAPP>.permission.C2D_MESSAGE"
android:protectionLevel="signature" />
<uses-permission android:name="<MYAPP>.permission.C2D_MESSAGE" />
<!-- Require OpenGL ES2 for GMap -->
<uses-feature android:glEsVersion="0x00020000"
android:required="true" />
<!-- Because this app is using the GCM library to send messages, the min
SDK cannot be lower
than 8 -->
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="18" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/LovRTheme" >
<receiver
android:name=".GcmBroadcastReceiver"
android:permission="com.google.android.gcm.c2dm.permission.SEND" >
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<!-- <action
android:name="com.google.android.c2dm.intent.REGISTRATION" />
-->
<category android:name="<MYAPP>" />
</intent-filter>
</receiver>
<service android:name=".GcmIntentService" />
And the server-side code :
$url = "https://android.googleapis.com/gcm/send";
$fields = array(
'registration_ids' => array($dstRegId),
'delay_while_idle' => true,
'data' => array("message" => $message));
$headers = array(
'Authorization: key=' . $google_api_key,
'Content-Type: application/json');
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
$result = curl_exec($ch);
if($result === FALSE){
die("Curl failed");
}
curl_close($ch);
echo $result;
I'm coding from home, so I assume that GCM would not have problems getting
in and out of the network since GCM uses a kind of reverse-shell
connection. Anyway, i don't receive any of the log output i'm expecting.

Saturday, 24 August 2013

how to import json file in mongodb?

how to import json file in mongodb?

i am new to mongodb database . i a creating an application in which data
store as a json file. what i want to do is import that data into mongodb
and then display it on command prompt. i already tried following commands
but error is displaying Failure parsing josn near: } my command is:
mongoimport -d mydb -c mydb --type json --file glossary.json --headerlinei
put json file in c:\mongodb\bin\glossary.json thanx i advace.
{
"glossary": {
"title": "example glossary",
"GlossDiv": {
"title": "S",
"GlossList": {
"GlossEntry": {
"ID": "SGML",
"SortAs": "SGML",
"GlossTerm": "Standard Generalized Markup Language",
"Acronym": "SGML",
"Abbrev": "ISO 8879:1986",
"GlossDef": {
"para": "A meta-markup language, used to create markup
languages such as DocBook.",
"GlossSeeAlso": ["GML", "XML"]
},
"GlossSee": "markup"
}
}
}
}
}

Best Practice: AWS ftp with file processing

Best Practice: AWS ftp with file processing

I'm looking for some direction on an AWS architictural decision. My goal
is to allow users to ftp a file to an EC2 instance and then run some
analysis on the file. My focus is to build this in as much a
service-oriented way as possible.. and in the future scale it out for
multiple clients where each would have there own ftp server and processing
queue with no co-mingling of data.
Currently I have a dev EC2 instance with vsftpd installed and a node.js
process running Chokidar that is continuously watching for new files to be
dropped. When that file drops I'd like for another server or group of
servers to be notified to get the file and process it.
Should the ftp server move the file to S3 and then use SQS to let the pool
of processing servers know that it's ready for processing? Should I use
SQS and then have the pool of servers ssh into the ftp instance (or other
approach) to get the file rather than use S3 as a intermediary? Are there
better approaches?
Any guidance is very much appreciated. Feel free to school me on any
alternate ideas that might save money at high file volume.
Thank you for the help.

Buffered Image Junit error

Buffered Image Junit error

I get the following error when I try to load a buffered image in a junit
test.
Default constructor cannot handle exception type IOException thrown by
implicit super constructor. Must define an explicit constructor
The code this affects is:
BufferedImage testFrame = ImageIO.read(new
File("C:/Users/Darren/testPicture.png"));
I have tried surrounding it with try and catch. I get an error stating
incorrect syntax when I use try catch.
I have no errors when using buffered image in my main program.
Any help would be great.

Can some programs really access more than 4GB of RAM on a 32-bit system?

Can some programs really access more than 4GB of RAM on a 32-bit system?

I've seen some programs (especially RAM-drive software) that purport to
being able to access the "unavailable RAM" on 32-bit systems. That is,
even though Windows cannot see or access some of the 4GB that is installed
on a 32-bit system, these programs claim that they can.
On my 32-bit system with 4GB, Windows sees only 3.20GB, but so does the
BIOS. It is not a matter of using PAE or the /3G switch, because it's not
a Windows limitation, it is a motherboard limitation. If the chipset and
memory controller can't access beyond that, then I don't see how Windows
or any software can either, even if they access the hardware directly.
I know that using PAE requires using either a Server or 64-bit edition of
Windows (though I don't see how even these versions of Windows can access
what the BIOS cannot). However these programs say nothing about that and
imply (or outright say) that they work for normal users with consumer
versions of Windows.
I've tried a couple of these programs (specifically RAM-drives), but was
not able to have it access the upper memory. Does anybody know if there is
any truth to these programs' claims? Has anybody actually seen it work?
And if so, how exactly do they pull it off?
(I'm not asking about generic programs accessing more than 4GB, I'm asking
specifically about programs that claim they can, particularly in regard to
the RAM amount reported by the BIOS.)

Implementing a web scraper in c#

Implementing a web scraper in c#

I'm developing a web scraper, but I need to persist cookies between
requests much like I can do in PHP using curl. However, it seems that if I
try to use a CookieContainer object in C#, it doesn't grab all of the
cookies from the response and send them to the next request.
Here's my C# class:
public class Scraper
{
public string Username { get; set; }
public string Password { get; set; }
public string UserAgent { get; set; }
public string ContentType { get; set; }
public CookieCollection Cookies { get; set; }
public CookieContainer Container { get; set; }
public Scraper()
{
UserAgent = "Mozilla/5.0 (Windows NT 6.2; WOW64; rv:18.0)
Gecko/20100101 Firefox/18.0";
ContentType = "application/x-www-form-urlencoded";
Cookies = new CookieCollection();
Container = new CookieContainer();
}
public string Load(string uri, string postData = "",
NetworkCredential creds = null, int timeout = 60000, string host =
"", string referer = "", string requestedwith = "")
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
request.CookieContainer = Container;
request.CookieContainer.Add(Cookies);
request.UserAgent = UserAgent;
request.AllowWriteStreamBuffering = true;
request.ProtocolVersion = HttpVersion.Version11;
request.AllowAutoRedirect = true;
request.ContentType = ContentType;
request.PreAuthenticate = true;
if (requestedwith.Length > 0)
request.Headers["X-Requested-With"] = requestedwith;
if (host.Length > 0)
request.Host = host;
if (referer.Length > 0)
request.Referer = referer;
if (timeout > 0)
request.Timeout = timeout;
if (creds != null)
request.Credentials = creds;
if (postData.Length > 0)
{
request.Method = "POST";
ASCIIEncoding encoding = new ASCIIEncoding();
byte[] data = encoding.GetBytes(postData);
request.ContentLength = data.Length;
Stream newStream = request.GetRequestStream(); //open
connection
newStream.Write(data, 0, data.Length); // Send the data.
newStream.Close();
}
else
request.Method = "GET";
HttpWebResponse response =
(HttpWebResponse)request.GetResponse();
Cookies = response.Cookies;
StringBuilder page;
using (StreamReader sr = new
StreamReader(response.GetResponseStream()))
{
page = new StringBuilder(sr.ReadToEnd());
page = page.Replace("\r\n", ""); // strip all new lines
and tabs
page = page.Replace("\r", ""); // strip all new lines and
tabs
page = page.Replace("\n", ""); // strip all new lines and
tabs
page = page.Replace("\t", ""); // strip all new lines and
tabs
}
string str = page.ToString();
str = Regex.Replace(str, @">\s+<", "><");
return str;
}
}
Here's my PHP code for loading and maintaining cookies in a cookie jar:
private function load($url = 'http://www.google.com/', $postData =
array(), $headers = FALSE)
{
$useragent = "User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1;
" . $this->locale . "; rv:1.9.2.10) Gecko/20100914 BRI/1
Firefox/3.6.10 ( .NET CLR 3.5.30729)";
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($curl, CURLOPT_HEADER, FALSE);
if($headers) curl_setopt($curl, CURLOPT_HTTPHEADER,
array('X-Requested-With: XMLHttpRequest'));
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($curl, CURLOPT_ENCODING, 'UTF-8');
curl_setopt($curl, CURLOPT_USERAGENT, $useragent);
curl_setopt($curl, CURLOPT_POST, !empty($postData));
if(!empty($postData)) curl_setopt($curl, CURLOPT_POSTFIELDS,
$postData);
curl_setopt($curl, CURLOPT_COOKIEFILE, $this->cookieFile);
curl_setopt($curl, CURLOPT_COOKIEJAR, $this->cookieFile);
$page = curl_exec ($curl);
$page = str_replace(array("\r\n", "\r", "\n", "\t"), "", $page);
// strip all new lines and tabs
$page = preg_replace('~>\s+<~', '><', $page);// strip all
whitespace between tags
curl_close ($curl);
return $page;
}
How do I successfully maintain cookies between requests?

Ipswich vs Leeds Live Stream

Ipswich vs Leeds Live Stream

Watch Live Streaming Link
Ipswich vs Leeds Live StreamIpswich vs Leeds Live StreamIpswich vs Leeds
Live StreamIpswich vs Leeds Live StreamIpswich vs Leeds Live StreamIpswich
vs Leeds Live StreamIpswich vs Leeds Live StreamIpswich vs Leeds Live
StreamIpswich vs Leeds Live StreamIpswich vs Leeds Live StreamIpswich vs
Leeds Live StreamIpswich vs Leeds Live StreamIpswich vs Leeds Live
StreamIpswich vs Leeds Live StreamIpswich vs Leeds Live StreamIpswich vs
Leeds Live StreamIpswich vs Leeds Live StreamIpswich vs Leeds Live
StreamIpswich vs Leeds Live StreamIpswich vs Leeds Live StreamIpswich vs
Leeds Live StreamIpswich vs Leeds Live StreamIpswich vs Leeds Live
StreamIpswich vs Leeds Live StreamIpswich vs Leeds Live StreamIpswich vs
Leeds Live StreamIpswich vs Leeds Live StreamIpswich vs Leeds Live
StreamIpswich vs Leeds Live StreamIpswich vs Leeds Live StreamIpswich vs
Leeds Live StreamIpswich vs Leeds Live StreamIpswich vs Leeds Live
StreamIpswich vs Leeds Live StreamIpswich vs Leeds Live StreamIpswich vs
Leeds Live StreamIpswich vs Leeds Live StreamIpswich vs Leeds Live
StreamIpswich vs Leeds Live StreamIpswich vs Leeds Live StreamIpswich vs
Leeds Live StreamIpswich vs Leeds Live Stream
Watch Live Streaming Link

Parsing json array with sub objects

Parsing json array with sub objects

I want to parse this jason into java code for an android app:
{
"name":"London",
"coord":{"lon":-0.12574,"lat":51.50853},
"country":"GB",
"cnt":6,
"list":[{
"dt":1377345600,
"temp":{
"min":290.42,
"max":294.3,
"weather":[{
"id":501,
"main":"Rain",
"icon":"10d"}],
{
"dt":1377432000,
"temp":{
"min":289.81,
"max":296.92,
"weather":[{
"id":800,
"main":"Clear",
"icon":"01d"}],}
How can i do this? i know how to parse single object arrays, but how do
subobjects work?

How to make a Hybrid Application in Android

How to make a Hybrid Application in Android

Can someone please describe me what a hybrid application is, and what it
takes to make one for Android ? (with an example if you can)
thanks

Friday, 23 August 2013

Open web browser control multiple times by using background worker, using list with Thread in C#

Open web browser control multiple times by using background worker, using
list with Thread in C#

I want to do in my project that user select a text file which have some
number of website address. when all the website address from the text file
bounded with listview control, then there is a button for browsing this
links into web browser control which I have created at another form. all
this work done by BACKGROUND WORKER control at 1st Form. I calling the
backgroundWorker1.RunWorkerAsync(_WebList); where WebList is List which
contains all the links address which is showing at Listview in the 1st
Form. Now at the DoWorkEventArgs event of the backgroundworker1 I am
browsing all the links but I am getting error. private void
backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) { List _WebList
= new List(); _WebList = (List)e.Argument; Thread t = new Thread(() => {
for (int i = 0; i < _WebList.Count; i++) { BrowserIntegration obj = new
BrowserIntegration(_WebList[i].ToString()); obj.Show(); if
(!ShowBrowserchck.Checked) { obj.Hide(); } } }); t.ApartmentState =
ApartmentState.STA; t.Start(); t.Join(); } Error: Here I can't cancel the
Async function and all the form are open too much fast and then disposed
if I am doing another coding with DoWorkEventArgs event of
backgroundworker then I got other error. private void
backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) { List _WebList
= new List(); _WebList = (List)e.Argument; for (int i = 0; i <
_WebList.Count; i++) { BrowserIntegration obj = new
BrowserIntegration(_WebList[i].ToString()); obj.Show(); if
(!ShowBrowserchck.Checked) { obj.Hide(); } } } Here I got error with web
browser control : ActiveX control '8856f961-340a-11d0-a96b-00c04fd705a2'
cannot be instantiated because the current thread is not in a
single-threaded apartment. anyone can please help me regarding this
topic.....

Matching everything after series of hyphens

Matching everything after series of hyphens

I'm trying to capture all the remaining text in a file after three hyphens
at the start of a line (---).
Example:
Anything above this first set of hyphens should not be captured.
---
This is content. It should be captured.
Any sets of three hyphens beyond this point should be ignored.
Everything after the first set of three hyphens should be captured. The
closest I've gotten is using this regex [^(---)]+$ which works slightly.
It will capture everything after the hyphens, but if the user places any
hyphens after that point it instead then captures after the last hyphen
the user placed.
I am using this in combination with python to capture text.
If anyone can help me sort out this regex problem I'd appreciate it.

How to choose a random number in objective c

How to choose a random number in objective c

How to choose a random number from 4 numbers in objective c and assign it
to an int?
int monsterPos = (arc4random() %(40,120,200,280));
i dont think thats correct but i need x to be assigned a number randomly
from those 4

Button action to navigate another URL link in sapui5

Button action to navigate another URL link in sapui5

I have a button code is given below.
new sap.ui.commons.Button("myButton2",{text:"Next",press:function(){
},style: sap.ui.commons.ButtonStyle.Emph })
when i press Next button it should navigate to new page
Can any one help me on this....
Thankyou

ASP.NET, MVC, DOJO: RequestError: Unable to load undefined status: 404

ASP.NET, MVC, DOJO: RequestError: Unable to load undefined status: 404

I have tried to call ASP.NET MVC Action method from .ASPX page using Dojo.
but it is showing the following error..
RequestError: Unable to load undefined status: 404
My code is like below:
function SearchUser() {
var userName = document.getElementById("txtUserName").value;
var firstName = document.getElementById("txtFirstName").value;
var lastName = document.getElementById("txtLastName").value;
var applicationName =
document.getElementById("txtApplicationName").value;
var roleName = document.getElementById("txtRoleName").value;
var locationType = document.getElementById("txtLocationType").value;
var location = document.getElementById("txtLocation").value;
var userType = document.getElementById("txtUserType").value;
var isAdmin = document.getElementById("chkAdmin").checked;
var searchUserParameters = { "pageIndex": "1", "pageSize": "100",
"userName": ""+ userName +"", "firstName":""+ firstName +"",
"lastName":""+ lastName +"", "userType":""+ userType +"",
"appName":""+ applicationName +"", "roleName":""+ roleName +"",
"LocationType":""+ locationType +"", "location":""+ location +"",
"isAdmin":""+ isAdmin +"" };
var xhrArgs = {
postData: dojo.toJson(searchUserParameters),
handleAs: "text",
headers: { "Content-Type": "application/json", "Accept":
"application/json" },
load: function (data) {
document.getElementById("svsOutput").innerHTML = data;
},
error: function (error) {
alert("Error occured:" + error);
}
}
var deferred = dojo.xhrPost(xhrArgs);
return false;
}
Can anybody suggest me what is the problem?

Thursday, 22 August 2013

Why website http://cobertura.sourceforge.net/ cannot be accessed right here at Shanghai China?

Why website http://cobertura.sourceforge.net/ cannot be accessed right
here at Shanghai China?

I start using Cobertura to coverage our Junit test cases, but I alway get
problem when I try to access http://cobertura.sourceforge.net/ to obtain
the Cobertura tool, it cannot be accessed. I don't know what caused it,
whether this website is expired or our government prohibited this website.
No matter what caused this, can somebody tell me where I can gain the
Prohibited tool and related reference document?
Thanks.

weblogic datasource ora-04068

weblogic datasource ora-04068

I've done a lot of research and haven't been able to find a definite
answer on this. Basically the issue I have is the behavior I'm seeing with
weblogic jdbc datasources when we compile oracle packages.
Now the vast majority of time, I can do a hot compile of an oracle
package. On the first time after compiling and executing a stored
procedure, I'll see the
ora-04068 error: existing state of package has been discarded
error. That is expected behavior which refreshes the datasource and
everything works as it should after that first attempt. Periodically
though, when packages are compiled which have nested dependencies.
For instance: java code running in weblogic depends on package A. Package
A depends on Package B. Package B is compiled.
Now I know Oracle automatically compiles on first attempts to execute
invalid packages. But we have to many times manually compile the oracle
packages because of other clients that can't execute the invalid code,
thus Oracle never recompiles the package. This will frequently put the
datasource into a state where it permanently returns the ORA-04068 error.
The only way to fix this is to bounce the managed weblogic server. Trying
to manually stop the datasource or remove target and retarget the
datasource doesn't work.
Has anybody figured out a way to reliably do hot deploys of oracle code
and compile it manually while not having weblogic datasources going into
these recoverable states that require complete bounces of the managed
servers?
Some info: This is oracle 11g and weblogic 10.3.3.

Inhertance and Object Creation

Inhertance and Object Creation

This is my first question here and I hope I am up to standards of
Stackoverflow. Well, here it is.
Base Class:
public class Inheritance {
int i;
Inheritance() {
System.out.println("I am in base class" + i);
}
}
Derived Class:
public class TestInheritance extends Inheritance {
TestInheritance() {
System.out.println("I am in derived class");
}
public static void main(String[] args) {
TestInheritance obj = new TestInheritance();
}
}
This is what I have in mind regarding what is going on above.
when I create an object of the derived class by default super() is called
and the constructor of the base class is called and it initializes the
variable i. Now, my question is does the constructor in this case only
initializes the variable i and doesn't create a concrete object of class.
From what I have read so far there is only one object created i.e of the
derived class which has i variable in it. But from the time the
constructor of base class is called and the point in time where
constructor of the derived class is called how(where) is i stored in
memory. And what would be case in which base class is an abstract one. I
would really appreciate if I can know what happens in memory at different
points of time.
If I have said something which is fundamentally incorrect please let me
know. I really want to know how this thing works.

IIS 7.5 ARR URL Rewrite rule removed, yet still running

IIS 7.5 ARR URL Rewrite rule removed, yet still running

I was playing around with IIS's Application Request Routing plugin, using
the URL Rewrite tool to (obviously) rewrite some URL's. I set up a server
farm and had the rules route to that. As I was working on it, I noticed
one option that kept changing, the "Use URL Rewrite" checkbox in the
server farm Routing Rules section. Also it kept adding the default "Route
everything to this server farm" rule, no matter how many times I kept
removing it. Eventually I was able to get the rules set to what I think is
right. As I went to test though, it seemed to be using one of my older
rules that hadn't worked. I played around some more, but could not get
that to change, it would ALWAYS redirect using that same rule that I had
deleted 10 minutes ago.
I tried removing every rule I had in every site (including rules in the
server farm and local machine section) to reset it to normal, however it
still redirected. I uninstalled the Application Request Routing, restarted
the computer and checked again, however it still redirected. I uninstalled
IIS entirely, restarted the computer and checked again, however it STILL
redirects! There isn't even a web server to accept the request, yet it
manages to rewrite the URL?!?
It's like there's a ghost rule that just won't go away. I tried looking
through the IIS & ARR file structure, however I couldn't find anything
that looked like it was holding the rule set. Though the file structure
seems to be the Windows folder for the most part, so I might be looking in
the wrong place. I'm not really sure what else to do at this point, has
anyone encountered this issue before, or have any ideas of what to do?
Thanks in advance,
Doug

Using Google api to get State/Country suggestions for city

Using Google api to get State/Country suggestions for city

I have a list of North American cities that are inconsistently paired with
provinces and countries. Example:
Calgary AB Canada
CALGARY Alberta - CA
Calgary Canada
I would like to format each city so it follows a consistent pattern. So
that it includes City State/Province and Country. Like:
Calgary Alberta Canada
I've tried using Google's Places API to get suggestions for possible
formating but all I've been able to achieve is a sort of validation that
indicates if such a city exists. I was wondering if someone who has worked
extensively with Google API's can guide me on how I can get
City/Province-State/Country suggestions ( possibly in JSON format) from a
city input.
var input = "City Name";
var service = new google.maps.places.AutocompleteService();
service.getQueryPredictions({ input: input }, callback});
I tried looking into geocoding but that seems to bring back lat/log
information.

How to parse the below xml string using linq to sql?

How to parse the below xml string using linq to sql?

pXML: /p precodelt;shift_detailsgt; lt;shift_timegt;10:00 to
10:30lt;/shift_timegt; lt;countgt;0lt;/countgt; lt;shift_timegt;10:30 to
11:00lt;/shift_timegt; lt;countgt;0lt;/countgt; lt;shift_timegt;11:00 to
11:30lt;/shift_timegt; lt;countgt;0lt;/countgt; lt;shift_timegt;11:30 to
12:00lt;/shift_timegt; lt;countgt;0lt;/countgt; lt;shift_timegt;12:00 to
12:30lt;/shift_timegt; lt;countgt;0lt;/countgt; lt;/shift_detailsgt;
/code/pre pCode:/p precode var slots = from c in
xmlResponse.Descendants(shift_details) select new TimeSlots { time =
(string)c.Element(shift_time), count = (string)c.Element(count), };
customerCollection = new ObservableCollectionlt;TimeSlotsgt;(slots);
return customerCollection; /code/pre pThe above code return only one slot
item as output .but my xml contains too many records.How to read all
records in above xml?/p

Autofac manual injection in ASP .NET Web API application with per request lifetime scope

Autofac manual injection in ASP .NET Web API application with per request
lifetime scope

I am developing ASP .NET Web API application and I need to use autofac
manual injection in custom class (not web api controller) with per request
lifetime scope. I have been searching for solutions for several days, and
have found only the suggestion to use HttpRequestMessage in web api
controller here
In web api controller:
var dependencyScope = actionContext.Request.GetDependencyScope();
var lifetimeScope = dependencyScope.GetRequestLifetimeScope();
var serviceObject = new AutofacWebApiDependencyResolver(lifetimeScope
).GetService(typeof(IMyService)) as IMyService;
But I, as far as I know, I cannot retrieve HttpRequestMessage object
(actionContext.Request) in custom class. I know this is some odd approach
and I should consider using constructor injection, but I am trying to add
autofac to already existing big project and not to break everything for
this step (this will definitely be refactored later). Could you please
help me with this issue.
Thanks for all responses!

Wednesday, 21 August 2013

Need to install mysql in php webserver to access remote server mysql database?

Need to install mysql in php webserver to access remote server mysql
database?

I'm trying to setup an separate debian webserver using php-fpm and nginx
to access remote mysql server. So far after I go through several setup
from this reference
http://www.cyberciti.biz/tips/how-do-i-enable-remote-access-to-mysql-database-server.html
After finish, it works when I remote it from outside using command line
mysql -uxxx -p -hxxxxx
Then when I try it on my web server using fuelphp to access the database,
it give me error:
Fuel\Core\Database_Exception [ 2002 ]: Can't connect to local MySQL server
through socket '/var/run/mysqld/mysqld.sock' (2)
It seems try to find socket locally to connect to the remote mysql. On the
installation of php, I already include apt-get php5-mysql and others
except mysql server.
My question: is it possible to setup webserver without have to install
mysql in the local machine in order to access mysql on remote? I want to
optimize the webserver by separating it from the database. Thanks

Bootstrap Modal bindinghandler not working with the backdrop

Bootstrap Modal bindinghandler not working with the backdrop

I'm trying to disable the backdrop from closing the modal when clicked
with the following:
ko.bindingHandlers.showModal = {
init: function (element, valueAccessor) {
},
update: function (element, valueAccessor) {
var value = valueAccessor();
if (ko.utils.unwrapObservable(value)) {
$(element).modal({ backdrop: 'static', keyboard: true });
// this is to focus input field inside dialog
$("input", element).focus();
}
else {
$(element).modal('hide');
}
}
};
However clicking on the backdrop still closes the modal, and in fact
breaks the "show" button. What am I doing wrong?
Fiddle: http://jsfiddle.net/PTSkR/175/

CSS 100% height layout. Fluid header, footer and content. In IE10 and firefox

CSS 100% height layout. Fluid header, footer and content. In IE10 and firefox

This works for Chrome: http://jsfiddle.net/EtNgv/ I want to make it work
in IE and Firefox.
Answers to other similar questions said that it is not possible - but did
not mention that it was possible in Chrome - so I am hoping that someone
could tweak what I have here to make it work in FireFox and IE10.
Desired outcome:
A container div that takes up 100% height - but no more. Which wraps
header and footer divs whose heights are determined by their content. The
footer div is always flush with the bottom of the page. A middle div which
stretches between the header and footer. If its content overflows it
should scroll.
Image: http://i.stack.imgur.com/e7ddc.png
Current implementation:
CSS:
html,
body {
height:100%;
margin:0;
}
#container {
display:table;
height:100%;
width:100%;
}
#header,
#footer {
display:table-row;
background-color:#FC0;
height:2px;
}
#middle {
display:table-row;
overflow:hidden;
position:relative;
}
#content {
height:100%;
overflow-y:scroll;
}
HTML:
<div id="container">
<div id="header">header<br/>header line 2<br/></div>
<div id="middle">
<div id="content">Burrow under covers...</div>
</div>
<div id="footer">footer</div>
</div>
This works in Chrome, but in IE and Firefox if the content is larger than
the middle div the container becomes larger than 100% high and the page
obtains a scroll bar.

Distort pattern like contoured fabric

Distort pattern like contoured fabric

Can anyone think of a way in SVG to distort a pattern as though it is a
piece of fabric with folds and wrinkles?
For instance, if I have a striped beach towel that is laying over an
uneven beach, the stripes will not run in straight lines, but will wave
and fold and generally distort as they cross the contours of the beach.
I know there are various transformations that can be applied in SVG, but
is there any kind of transformation that can apply this sort of
distortion?

Using Active Directory to login using a local user

Using Active Directory to login using a local user

I am using the standard Simple Membership model for login via forms in my
application. I would like to provide the possibility to login via AD as an
alternative.
When logging in via AD, the process should be as follows:
Check that AD authenticates the user, but do not use the information for
the principal.
Check if any local user exists with the provided Active Directory username
(I have a property on my UserProfile model named ActiveDirectoryID).
If it exists, perform a local login using the local username for this
UserProfile.
The problem: I cannot retrieve the local password, so in order to login
locally after AD authentication, I need to be able to force the login
without the password.
I've considered the following strategies:
Create an extension method for Websecurity to allow
Websecurity.Login(string username)
Somehow set the logged in user manually, without implicating Websecurity.
Is this doable / feasible? Is it possible for the framework to create the
necessary auth cookie without the plaintext password? And how would I do
this?

Does accessing UI controls inside ComDataPacket.OnPacket needs synchronization?

Does accessing UI controls inside ComDataPacket.OnPacket needs
synchronization?

I have a ComPort1 and a ComDataPacket1 on my form and
ComDataPacket1.ComPort:= ComPort1;. I see that there is a properties
SyncMethod and I guess that TComPort creating a thread when
ComPort1.Connected:=true;.
Recently I realized that every UI access from OnExecute event of Indy
IdTCPServer component needs to be Synchronized with MainThread so is it
true for TComPort? How to do this(Indy has a class to doing this)?
I am reading data from com port like this(data is sent as packet so
ComDataPacket1 is very useful):
procedure TForm2.ComDataPacket1Packet(Sender: TObject; const Str: string);
begin
Label1.caption:= str;
end;
I am working on a project and sometimes I got famous "Your application has
stopped working" message box(When my program is closed). I am suspecting
this error is because of that.

How can I force browsers to check for a new version despite a caching directive max-age 30 days?

How can I force browsers to check for a new version despite a caching
directive max-age 30 days?

I had the following declaration in my website's root:
I think this tells browsers not to look for new versions of any file
unless it's older than 30 days - is that correct?
This was not my intention and I've since modified the instruction, but
while some browsers are now updating despite the old instruction, some are
not. Is there a way to force browsers to look for a new version with
immediate effect?
Thanks.

Tuesday, 20 August 2013

keyboard malfunction for hp mini

keyboard malfunction for hp mini

my keys are not working properly. they(hotkeys,enter,backspace) will only
work if i hold down the control key.keys that only work properly without
the aid of control key are f3,t and y. i tried using an external keyboard
but i still have the same issue. sometimes the control key holds down
itself even without pressing it.functions like f2 and f9 will only work if
i press ctrl+alt+fn. as of now i am using on screen keyboard to type this
message. this happened before. after three weeks the keys worked
properly.after quite sometime the same problem happened again. i already
tried reformatting my unit but the problem still exist.

How to find the path of the service/agent/daemon listed in launchctl list?

How to find the path of the service/agent/daemon listed in launchctl list?

If I execute launchctl list I get the results:
...
- 0 com.apple.screensharing.agent
- 0 com.apple.ScreenReaderUIServer
- 0 com.apple.scopedbookmarksagent.xpc
- 0 com.apple.safaridavclient
... etc
are all these and other processes running now, will be running at some time?

How do you do math in a mako template?

How do you do math in a mako template?

Assuming I have two variables "one" and "two" where they equal 1 and 2
respectively. How can I divide them in a mako template if possible? I want
something like:
${"{0:.2f}".format(one/two)}
The result I want to output in the template is: 0.50
I am using python 2.x.

Project still tries to load symbols from removed reference? (Ninject.NameScope extension)

Project still tries to load symbols from removed reference?
(Ninject.NameScope extension)

I've got a weird issue that seems to be slowing down my project. I (at one
point) installed the Ninject NamedScope extension into my project, but
later found out I didn't need it and removed it. However, when I run the
project at the bottom of visual studio it tells me loading symbols for
Ninject.Extensions.NamedScope, and then it tries to look for them quickly
in various places which seems to be make my site pretty slow.
I've searched my entire solution for any references to NamedScope,
nothing. I've checked my packages.config, nothing. I've checked the
references, not there. I've even checked the .dlls in the bin folder, not
there either.
So why is it trying to load symbols from something I removed and how can I
get it to stop? It's noticeably slowed down my page load times.

How do you keep track of what stage you are at in a program?

How do you keep track of what stage you are at in a program?

Like many, I'm developing a couple of applications on my own (not at the
same time) to eventually sell. But I also have websites to run, college
work and a social life etc., so often I can forgot what stage I am in
programming, especially after holidays abroad.
Are there any techniques that I can use to help me keep track of everything?

I want to create a script so that everytime i dont want to type su and password

I want to create a script so that everytime i dont want to type su and
password

I want to create a script so that everytime i dont want to type su and
password for logging into root.

Search space data

Search space data

I was wondering if anyone knew of a source which provides 2D model search
spaces to test a GA against. I believe i read a while ago that there are a
bunch of standard search spaces which are typically used when evaluating
these type of algorithms.
If not, is it just a case of randomly generating this data yourself each
time?

Monday, 19 August 2013

Google Wallet - SSL / https handled completely by Google?

Google Wallet - SSL / https handled completely by Google?

For Google Wallet, I'm wondering if a SSL certificate for https needs to
be setup on the serverside, or if all https access is done on Google's
servers?
In the wallet tutorial, I notice that all https addresses are from google -
https://developers.google.com/commerce/wallet/digital/docs/tutorial

Maps Android V2: java.lang.noclassdeffounderror: com.google.android.gms.R$styleable

Maps Android V2: java.lang.noclassdeffounderror:
com.google.android.gms.R$styleable

As many I get the following error: java.lang.noclassdeffounderror:
com.google.android.gms.R$styleable when trying to implement Maps for
Android V2.
Somehow I must be missing what I exactly am doing wrong, since it's not
working. What I tried first is to copy the google-play-services.lib into
the lib folder, but I saw somewhere I shouldn't do this.
Then I tried to import addon-google_apis-google-8 as a project, but the
project gives the error The import com.google cannot be resolved.
I'm following the Vogella Tutorial:
Activity:
SupportMapFragment fm = (SupportMapFragment)
getSupportFragmentManager().findFragmentById(R.id.map);
map = fm.getMap();
//map = ((MapFragment)
getFragmentManager().findFragmentById(R.id.map)).getMap();
Marker hamburg = map.addMarker(new
MarkerOptions().position(HAMBURG)
.title("Hamburg"));
Marker kiel = map.addMarker(new MarkerOptions()
.position(KIEL)
.title("Kiel")
.snippet("Kiel is cool")
.icon(BitmapDescriptorFactory
.fromResource(R.drawable.btn_logo)));
// Move the camera instantly to hamburg with a zoom of 15.
map.moveCamera(CameraUpdateFactory.newLatLngZoom(HAMBURG,
15));
// Zoom in, animating the camera.
map.animateCamera(CameraUpdateFactory.zoomTo(10), 2000,
null);
Manifest:
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<permission
android:name="com.testmap.test.permission.MAPS_RECEIVE"
android:protectionLevel="signature" />
<uses-permission
android:name="com.testmap.test.permission.MAPS_RECEIVE" />
<uses-permission
android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission
android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"
/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission
android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.WRITE_SETTINGS" />
uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-feature
android:glEsVersion="0x00020000"
android:required="true" />
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="a_real_api_key" />
</application>
I retrieved a_real_api_key by entering the SHA1 retrieved by installing
the keytool plugin.. http://keytool.sourceforge.net/update
fingerprint;com.testmap.test in the google console.
And xml:
<fragment
android:id="@+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="com.google.android.gms.maps.SupportMapFragment" />
I have the feeling I need to import the google-play-services library, can
somebody tell me step by step how to do this in Eclipse, I've followed
many answers, but I seem to do something wrong every time.

Display message in Knocout.js

Display message in Knocout.js

I have button called Fact. I want it to display message "true" when
someone clicks it. My HTML looks like this:
<div id="option">
<button data-bind="click: displayMessage">Fact</button>
<div data-bind="if: displayMessage">You are right.</div>
My Javascript is this:
ko.applyBindings({
displayMessage: ko.observable(false)
});
However, this is not working. Can someone please help.

EncryptedDataBagItem.load produces 'cannot convert nil into String'

EncryptedDataBagItem.load produces 'cannot convert nil into String'

I'm following the method described in this post for creating a DNS record
for a new server as Chef provisions it. I've created an encrypted data bag
item for my AWS credentials:
$ knife data bag show passwords aws --secret-file
.chef/encryted_data_bag_secret
aws_access_key: <my_access_key>
aws_secret_key: <my_secret_key>
id: aws
However, when I run the chef client, this line...
aws_creds = Chef::EncryptedDataBagItem.load('passwords', 'aws')
produces this error:
TypeError: can't convert nil into String
I've tried searching for the error, but while I can see evidence that
other people have encountered this, it's not clear what their problem was
or how it was resolved. What's going on here, and how can I fix it?

jqGrid TableDnD issue

jqGrid TableDnD issue

I created a table using jqGrid Plugin for jQuery and relying on following
demo, I want to drag and drop the rows of my table. Demo:
http://trirand.com/blog/jqgrid/jqgrid.html (New in version 3.3 -> Row Drag
and Drop)
When I try to drag a row, I get the error "TypeError: e is null" in
firebug. I searched for a solution to this problem but I didn't find
anything in this case... Moreover I tried to use the same version of
jQuery and jQueryUI as shown in the example above, but it doesn't fix the
problem. The new release of jQuery TableDnD (version 0.7) was not helpful,
too Any idea to fix this problem?
My code:
<script type="text/javascript" src="js/jquery-1.9.1.js"></script>
<script type="text/javascript" src="js/jqueryUI-1.10.3.js"></script>
<script type="text/javascript" src="js/jquery.ui.datepicker-de.js"></script>
<script type="text/javascript"
src="js/jqGrid/i18n/grid.locale-de.js"></script>
<script type="text/javascript" src="js/jqGrid/jqGrid-4.5.2.js"></script>
<script type="text/javascript" src="js/plugins/jqTableDnD-0.5.js"></script>
<link type="text/css" rel="stylesheet"
href="css/cupertino/jquery-ui-1.10.3.css"/>
<link type="text/css" rel="stylesheet" href="css/ui.jqgrid.css" />
<link type="text/css" rel="stylesheet" href="css/ui.multiselect.css" />
<table id="grid"></table>
<div id="navi"></div>
<script type="text/javascript">
$(document).ready(function() {
$("#grid").tableDnD({scrollAmount:0});
$("#grid").jqGrid({
colNames:["Artnr", "Bezeichnung", "Angebot (Position)",
"Enddatum Startseite", "Eigener Bestand", "Versandlager
Bestand"],
colModel:[
{name:"artnr", index:"artnr", align:"center", width:75,
sortable:false, formatter:formatPic},
{name:"benennung", index:"benennung", width:400,
sortable:false, formatter:formatLink }
...
],
datatype: "json",
editurl: "edit.php",
height: "auto",
mtype: "POST",
pager: "#navi",
rowNum: 20,
sortname: "angebot",
sortorder: "asc",
url: "load.php",
viewrecords: true,
gridComplete: function() {
$("#_empty","#grid").addClass("nodrag nodrop");
$("#grid").tableDnDUpdate();
}
}).navGrid ('#navi',
{view:false,edit:false,add:false,del:true,search:false}, {}, {},
{}, {}, {} )
});
function formatPic(cellVal, options, rowObject) {
return "<htmltag title=\""+ cellVal +"\" class=\"tooltip\">"+
cellVal +"</htmltag>";
}
function formatLink(cellVal, options, rowObject) {
return "<a href=\"../details.php?art=" + rowObject[0] + "\"
target=\"_blank\">"+ cellVal +"</a>";
}
</script>
Thanks in advance!

Sunday, 18 August 2013

Adding new element to page with PHP

Adding new element to page with PHP

I'm setting up a registration page, and I'm adding checks right now for
forms that are left empty.
Here's the HTML I have for the username form:
<label>Username</label>
<div class="form-group">
<input name="username" maxlength="25" class="span-default" type="text"
placeholder="Choose a username">
</div>
And the PHP I have:
$username = $_POST['username'];
if(empty($username)) {
// todo
}
What I need for the "todo" portion of the PHP to do is to add a new line
under the input form in the HTML, like this:
<label>Username</label>
<div class="form-group">
<input name="username" maxlength="25" class="span-default" type="text"
placeholder="Choose a username">
<div class="form-warning">This username is already taken!</div>
</div>
How can I do this?

How is kerning encoded on embedded Adobe Type 1 fonts in PDF files?

How is kerning encoded on embedded Adobe Type 1 fonts in PDF files?

Adobe PDF reference talks about /Widths array and /FontFile stream, but
Adobe Type 1 font programs (.pfb or .pfa files) don't include font
metrics; they are included in font metric files (.afm or .pfm files) but
these are not embedded in PDF file.
PDF can just encode char width metrics or it can encode kerning pair too?
How?

SBT Broken Pipe

SBT Broken Pipe

I've been avoiding using SBT since the support in intellij for maven has
always been far superior, plus I don't see much advantage in SBT; but I
figure why fight the masses.
So one of my open source projects I've converted over to SBT. Now when I
run tests (approx 1000 test cases), I get OOMs. Ok so I've tried
fork in Test := true
javaOptions in Test ++= Seq("-Xmx2048m", "-XX:MaxPermSize")
Ok so my OOMs go away but now I get
sbt.ForkMain$Run$RunAborted: java.net.SocketException: Broken pipe
at sbt.ForkMain$Run.write(ForkMain.java:114)
at sbt.ForkMain$Run$1.info(ForkMain.java:132)
Seems to be in different places each time.
These tests all pass if I'm building via maven (scala test maven plugin).
Help me Obi-wan or SBT lovers.

How to use @RequestBody with a JSONP request?

How to use @RequestBody with a JSONP request?

I am trying to perform an ajax request using the jsonp data type due to
cross domain issues in a clustered environment.
I can make jsonp requests to methods mapped with no @RequestBody
parameters, but when I do try to implement a RequestMapping with a
@RequestBody parameter I get a 415 Unsupported Media Type error.
Usually when I get this problem it is due to some property not mapping
correctly between the json object posted and the Java object it is mapped
to in Spring. But the only discrepency I can find is that using jsonp it
adds a parm named callback and one with the name of an underscore "_"
So I added the tag @JsonIgnoreProperties(ignoreUnknown = true) to my Java
object and figured that should solve that, however it is still throwing
this error.
Is there anything else I need to do?
$.ajax({
url : 'http://blah/blah.html',
data : { abc : '123' }, (I also tried to JSON.stringify the object but
no difference)
dataType : 'jsonp',
success : function(response) {
alert('ok '+JSON.stringify(response));
},
fail : function(response) {
alert('error'+JSON.stringify(response));
}
});
The Spring controller is:
@RequestMapping({ "blah/blah" })
@ResponseBody
public ReturnObject getBlahBlah (@RequestBody MyObject obj) throws
Exception {
}
The parameter object is:
@JsonIgnoreProperties(ignoreUnknown = true)
public class MyObject {
private String abc;
// getter and setter for abc auto generated by MyEclipse
}
I have a breakpoint on the Controller method which is never hit.