Friday, 27 September 2013

Issue about FileTransfer() download in Phonegap

Issue about FileTransfer() download in Phonegap


I have been develop Phonegap's App for android and iOS. And i try to
download file(.pdf) from server use FileTransfer() download, all
performing normal. But when i use fileTransfer.onprogress then it seem
download more size of file( my file 20Mb and it download 40Mb more than
2x).
fileTransfer.onprogress = function(progressEvent) {
if (progressEvent.lengthComputable) {
var percent = progressEvent.loaded/progressEvent.total;
//percent allways equal 2, than more 2x size of real file
console.log(percent);
}
};
Else FileTransfer() upload working well.
I don't known why? Can anyone help and explain for me. Thank you so much.

Bootstrap 3 - Invisible Dropdown on IE9 Bug. Fix?

Bootstrap 3 - Invisible Dropdown on IE9 Bug. Fix?

Someone pointed out a bug on the site package I've created using Bootstrap
3. ( http://getbootstrap.com/ )
Notice on my website (using Internet Explorer 9) that the dropdown menus
show shadows, but no content. ie, they are boxes holding invisible
content. (http://www.clipartillustration.com/)
I've searched and found some similar issues but they don't seem to fix the
one I'm stating.

How to remove special charachters and keep letters of any language in PHP?

How to remove special charachters and keep letters of any language in PHP?

I know this should remove any characters from string and keep only numbers
and ENGLISH letters.
$txtafter = preg_replace("/[^a-zA-Z 0-9]+/","",$txtbefore);
but I wish to remove any special characters and keep any letter of any
language like Arabic or Japanese.

mmenu and sticky nav in android

mmenu and sticky nav in android

I'm using a mmenu with a sticky header and have utilized 2 fly-out menus
each with an absolutely positioned icon on each side of the header. It
seems to work perfectly in IOS but on my old-school android, it doesn't.
When the header isn't sticky it works perfectly in Android however.
But when the header is sticky the div isn't moving like the rest of the
content to the right or left to make room for the menu fly-out.
Anyone else experience this issue? Any thoughts?

sorucetable.Select providing 2 coulms data does not work

sorucetable.Select providing 2 coulms data does not work

I created a method that takes a source data table, destination data table
, column name and value. the copies only data rows that match the value of
the column. this wroks but now I need to give 2 column names and 2 values
but It is not working following is the code I have so far.
public void SortDataByType(DataTable SourceTable, DataTable
ReturnedResult, String Custnum, string Columnname)
{
var detailedRows = SourceTable.Select(String.Format(Columnname +
"={0}", Custnum));
foreach (var detailRow in detailedRows)
{
ReturnedResult.Rows.Add(detailRow.ItemArray);
}
}
Above works fine.
below does not work.
public void SortDataByType(DataTable SourceTable, DataTable
ReturnedResult, String Custnum, String District , string
Columnname,string Columnname2)
{
var detailedRows = SourceTable.Select(String.Format(Columnname +
"={0}" , Columnname2+"{1}",Custnum,District));
foreach (var detailRow in detailedRows)
{
ReturnedResult.Rows.Add(detailRow.ItemArray);
}
}

Java read unicode with \u

Java read unicode with \u

My java program is reading unicode from text file. e.g. "\uffff".. View
from the java GUI is no problem, but when i try to print out, all wording
are overwritten, is it because of '\u', or any other way to avoid the
words overwritten?
sorry about my broken english.. thanks.

Thursday, 26 September 2013

ruby on rails application with middleman on cloud

ruby on rails application with middleman on cloud

I have a ruby on rails application which runs on middleman server. i have
deployed that application in windows azure cloud, after completing all
installation procedurw once i start the middleman server my application is
up and running in my browser but once i close the command prompt the
application stopped running. So i have tried installing apache web server
and completed the installation succesfully but if i run my server in
browser its showing this error "it works! this is the default web page for
this server. the web server software is running but no content has been
added, yet. "
i have tried a ruby application which runs on webrick server it runs
properly but this middleman server application giving that error.
please help me how to install a ruby on rails application which runs on
middleman server in cloud.

Thursday, 19 September 2013

Querying on Date in Mongo

Querying on Date in Mongo

I'm inserting a Mongo doc with the following time-stamp:
val format = new java.text.SimpleDateFormat("yyyyMMddHHmmss")
format.format(new Date()).toLong
Here's what the sectiolooks like from Mongo's shell:
"{Timestamp" : NumberLong("20130919161948")}"
Based on a few tests, it appears to me that I can simply compare 2
documents by Timestamp by simply checking > or < for the yyyyMMddHHmmss
format.
Please let me know if this time-stamp is OK for Mongo. Will I be able to
query with it?

getting id in context menu

getting id in context menu

I have seen multiple posts regarding this but after all those solutions I
stiil have this weird issue. I have implemented the following
@Override
public boolean onContextItemSelected(MenuItem item) {
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item
.getMenuInfo();
int index = info.position;
Log.i(TAG,"onContextItemSelected id:"+String.valueOf(index));
}
I still get id as 0,1,2,.. and not the actual database row id. I am
implementing list item click listener as well and here I get the correct
row id based on the row. Is there something that I am missing.

boolean equivalent to NULL in PHP

boolean equivalent to NULL in PHP

is this the right syntax to check if a value is equivalent to NULL or not
in PHP:
if($AppointmentNo==NULL)
? I have tried it but it seems that it is not working. Any suggestion for
another syntax?
Thanks

(mod) Rewriting Out of Order Parameters

(mod) Rewriting Out of Order Parameters

Is it possible to re-write parameters that are not always in the same
order in a URL?
For example, we might have a url like

/products/type/animal/id/123456
But it could also appear as:

/products/id/ab123456/type/animal
Using a mod rewrite statement like
/products[.html?]?(?:/id/([^/])?)/?(?:/type/([^/])?)/?
"products.html?id=$1&type=$2" [L, NC]
works fine for the the first example but of course fails for the second.
Is there anyway around this?

No space between buttons 'on next the line'

No space between buttons 'on next the line'

I trying to create buttons with round corner to simulate menus tabs. If
the screen is not wide enough, I want the buttons to go to the next line.
My issue is that there is no spacing between the buttons on the first line
and those on the following lines:

I am trying to replicate this issue in JSFiddle, but it does not happen
there:

My HTML is:
<div>
<span class="menuButton">Button I Button I Button I</span>
<span class="menuButton">Button II Button II Button II</span>
<span class="menuButton">Button III Button III Button III</span>
</div>
My CSS is:
.menuButton {
color: #FFFFFD;
background: #010109;
margin: 3px 0px 3px 0px;
padding: 1px 6px 0px;
border-top-left-radius: 3px;
border-top-right-radius: 3px;
font-family: 'Istok Web', sans-serif;
font-size: 14px;
white-space: nowrap;
}
Why am having this issue in my page and not JSFiddle? I have posted the
(work in progress) page here. Shrink the window to 320px wide to replicate
the issue.

Gnuplot interchanging Axes

Gnuplot interchanging Axes

How to use the Y1 axes as X axes and x2 as corresponding Y axes?
Example: X1 is time Y1 is price
This is to plot volume (X2) on every price point (Y1)

Create output file in matlab containing numeric and string cells

Create output file in matlab containing numeric and string cells

I am currently working on a project where I have to program the same tool
both in Matlab and R and compare both software options. I started in R and
now I am translating the code to Matlab but I am now stuck at the most
important part. The output file that the tool creates after doing the
analysis. Basically, my tool makes an analysis that loops n times, and
after each loop I get many variables that go into an output table. So, to
be more clear, after each loop I get variables:
A = 123
B = 456
C = 'string1'
D = 'string2'
E = 789
The values in each variable change after each loop, I just want to make
clear that the variables are both numeric and string values since this is
what causes my problem.
In R what I do after each loop is:
outp <- cbind(A,B,C,D,E)
and create a data frame containing each variable in one cell arranged
horizontally to afterwards add the result of each loop vertically in a new
data frame:
outp2 <- rbind(outp2,outp)
so in the end I get a data frame (outp2) with A,B,C,D,E columns and n rows
containing the values of each variable after each loop. So at the end of
the looping process I can use write.csv function and create an output file
of outp2 that contains both numeric and string columns.
I tried to do this in Matlab but I cannot find a function that can join
the data in the same way I am doing it in R because using brackets '[]'
only allows me to join numeric kind of variables. So basically my question
is: How can I replicate what I am doing in R in Matlab?
I hope I was clear enough, I found it a bit hard to explain.

How can I take input from card swapping machines?

How can I take input from card swapping machines?

How can I use take input from the card swapping machine ? Like the credit
card swapping machines.
I know nothing about this.

Wednesday, 18 September 2013

jsf dialog box does not show selected record in primefaces datatable

jsf dialog box does not show selected record in primefaces datatable

I want to display a datatable and once an entry is selected, its content
should be displayed in a separate dialog box. My code is like this.
<h:form id="form">
<p:growl id="msgs" showDetail="true" />
<p:dataTable id="PMDatas" var="pMData" rowIndexVar="rowIndex"
value="#
{managedBean.dataModel}" paginator="true" rows="100"
selection="#{managedBean.selectedRecord}"
selectionMode="single">
<p:ajax event="rowSelect" listener="#{managedBean.onRowSelect}"
update=":form:display :form:msgs"
oncomplete="moreviewDialog.show()"
/>
<p:ajax event="rowUnselect" listener="#{managedBean.onRowUnselect}"
update=":form:msgs"/>
<p:column headerText="#">
#{rowIndex+1}
</p:column>
<p:column headerText="Cell Name">
<h:outputText value="#{pMData.cellid}" />
</p:column>
</p:dataTable>
<p:dialog header="History Data" widgetVar="moreviewDialog"
resizable="false"
id="moreviewDlg"
showEffect="fade" hideEffect="explode" modal="true">
<h:panelGrid id="display" columns="2" cellpadding="4" style="margin:0
auto;">
<h:outputText value="CellId:" />
<h:outputText value="#{managedBean.selectedRecord.cellid}" style="font-
weight:bold"/>
</h:panelGrid>
</p:dialog>
</h:form>
my pMData class is like below.
public class PMData implements Serializable{
public PMData(String cell) {
cellid=cell;
}
private String cellid;
public void setCellid(String cellid){
this.cellid=cellid;
}
public String getCellid(){
return cellid;
}
}
and PMDataModel class is like this.
public class PMDataModel extends ListDataModel<PMData> implements
SelectableDataModel<PMData> ,Serializable{
/**
* Creates a new instance of PMDataModel
*/
public PMDataModel(){
}
@Override
public Object getRowKey(PMData object) {
return object.getCellid();
}
@Override
public PMData getRowData(String rowKey) {
List<PMData> data = (List<PMData>) getWrappedData();
for(PMData entry: data) {
if(entry.getCellid().equals(rowKey))
return entry;
}
return null;
}
public PMDataModel(List<PMData> data) {
super(data);
}
}
When I executed this selected entry is displayed in Facesmessages but
doesnot appear in dialog box.
my mangedbean class id like below.
private PMData selectedRecord;
public void setSelectedRecord(PMData selectedRecord){
this.selectedRecord=selectedRecord;
}
public PMData getSelectedRecord(){
return selectedRecord;
}
public managedBean() {
dataAll= new ArrayList<PMData>();
this.getFiles(dataAll);
dataModel = new PMDataModel(dataAll);
}
public ArrayList<PMData> getDataAll(){
return dataAll;
}
public void onRowSelect(SelectEvent event) {
System.out.println("inside onRow select Method");
FacesMessage msg = new FacesMessage("Row Selected",
((PMData)event.getObject()).getCellid());
FacesContext.getCurrentInstance().addMessage(null, msg);
}
public void onRowUnselect(UnselectEvent event) {
FacesMessage msg = new FacesMessage("Row Unselected",((PMData)
event.getObject()).getCellid());
FacesContext.getCurrentInstance().addMessage(null, msg);
}
public PMDataModel getDataModel() {
return dataModel;
}

Passing a callback to a specific function in Java

Passing a callback to a specific function in Java

I'm designing a program in Java using an MVC layout. I need the view to
initialize the buttons to run functions that the control defines. How can
my view define an actionlistener that can run a function from a given
class?

sql removing multiple records with mutltiple date values

sql removing multiple records with mutltiple date values

I have the following sample data that I need to clean the records by
specific date. For this example, lets use anything older than march 2012
will need to be removed along with other related records.
Author Book date
-------------------------------------
Smith Bk1 01/01/2012
Smith Bk2 02/01/2012
Smith Bk3 02/25/2012
Johnson Bk1 06/01/2011
Johnson Bk2 09/01/2011
Johnson Bk3 03/01/2012
Johnson Bk4 01/01/2013
Jones BK1 01/01/2001
Jones BK2 01/01/2002
Jones BK3 01/01/2009
Jones BK4 08/01/2013
Above is the data set. So if the Author has a book in the table that is
older than 03/01/2013, then All of the records need to be removed. If they
have at least one Book newer than the date specified then All records are
kept. In this scenario, the Jones records are the only ones to be kept in
the table data set.
Thanks for any help, I appreciate it.

Why is cornerRadii parameter of CGSize type in -[UIBezierPath bezierPathWithRoundedRect:byRoundingCorners:cornerRadii:]?

Why is cornerRadii parameter of CGSize type in -[UIBezierPath
bezierPathWithRoundedRect:byRoundingCorners:cornerRadii:]?

I can't figure this out... I'm playing with
-[UIBezierPath bezierPathWithRoundedRect:byRoundingCorners:cornerRadii:]
as such:
bezierPath = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(10, 10,
80, 80)
byRoundingCorners:(UIRectCornerBottomLeft)
cornerRadii:CGSizeMake(20, 20)];
And it works as expected. But if I replace cornerRadii:CGSizeMake(20, 20)
with, say, cornerRadii:CGSizeMake(20, 5) or CGSizeMake(20, 40), there's no
difference.
Why is cornerRadii CGSize and not CGFloat then? What is CGSize.height for?
Any ideas and advice will be greatly appreciated :)

Get Website Listed in Google News

Get Website Listed in Google News

I've developed a wordpress website and with the help of Yoast News SEO
plugin, I've created the News Sitemap XML. However, when I submit the
Sitemap to Google Webmasters, I get an error as below
Your Sitemap is on a site that is not in the Google News database. Google
News can only accept Sitemaps from sites that we crawl. If your site is
crawled by Google News, please check that the URL of your Sitemap agrees
with the URLs of your articles as they appear on Google News, including
any leading "www". If you would like to request inclusion of your site in
Google News, please contact the Google News support team.
It links to this page.
There are no instructions on that page to request inclusion in Google News.
I need to know where to request inclusion so that my website shows up in
Google News.

Get the current store -Ext JS

Get the current store -Ext JS

Simple question here,
I have a grid in my application that can hold one of any 3 given stores
(utlizes bindStore() function).
Is there a function to retrieve the current store? Something like:
Ext.getStore(grid.currentStore());
Cheers!

Setting binding to column in datagrid

Setting binding to column in datagrid

I have this XAML code
<WpfToolkit:DataGrid Name="_lvContacts" ItemsSource="{Binding
AccountPhonesList}"
SelectionChanged="_lvContacts_SelectedIndexChanged"
MouseDoubleClick="OnPhonesListDoubleClick"
AutoGenerateColumns="False">
<WpfToolkit:DataGrid.Columns>
<WpfToolkit:DataGridTextColumn Binding="{Binding
Path=Name}" Width="50" />
<WpfToolkit:DataGridTextColumn Binding="{Binding
Path=Office}" Width="90" />
<WpfToolkit:DataGridTextColumn Binding="{Binding
Path=Mobile}" Width="90" />
<WpfToolkit:DataGridTextColumn Binding="{Binding
Path=Home}" Width="80" />
<WpfToolkit:DataGridTextColumn Binding="{Binding
Path=Other}" Width="80" />
<WpfToolkit:DataGridTextColumn Binding="{Binding
Path=Email}" Width="55" />
</WpfToolkit:DataGrid.Columns>
</WpfToolkit:DataGrid>
And this code behind
DataGridTextColumn column = new DataGridTextColumn();
column.Binding = binding;
_lvContacts.Columns.Add(column);
My problem is that my binding property fill out all rows in created
column! How can I set binding to only one row in column?

Composite C1 console edit button available for non translated data

Composite C1 console edit button available for non translated data

We are using Composite C1 version 2.1.1 with static C# data. This data is
localizable (ILocalizedControlled) and is shown on top of the data tree
(TreeDefinitions\GlobalData.xml). Users are able to translate the data to
their selected language, but somehow it is possible to "Edit" the data
before translating it. This means that when they do it wrong (i.e. in
stead of first choosing "Translate Data" and then "Edit", choose "Edit"
directly) translated data will appear on the source language site. Which
is very annoying because the source data is lost as well. Seems that when
choosing a data item only "Translate Data" should be possible, but now
four buttons are shown (Translate Data, Edit, Add and Delete). So I would
like to be able to change this behavior, but can't seem to find where or
how to influence this.
Hope anyone can help.

How to query a restful webservice using Python

How to query a restful webservice using Python

Writing a Python script that uses Requests lib to fire off a request to a
remote webservice. Here is my code (test.py):
import logging.config
from requests import Request, Session
logging.config.fileConfig('../../resources/logging.conf')
logr = logging.getLogger('pyLog')
url = 'https://158.74.36.11:7443/hqu/hqapi1/user/get.hqu'
token01 = 'hqstatus_python'
token02 = 'ytJFRyV7g'
response_length = 351
def main():
try:
logr.info('start SO example')
s = Session()
prepped = Request('GET', url, auth=(token01, token02),
params={'name': token01}).prepare()
response = s.send(prepped, stream=True, verify=False)
logr.info('status: ' + str(response.status_code))
logr.info('elapsed: ' + str(response.elapsed))
logr.info('headers: ' + str(response.headers))
logr.info('content: ' + response.raw.read(response_length).decode())
except Exception:
logr.exception("Exception")
finally:
logr.info('stop')
if __name__ == '__main__':
main()
I get the following successful output when i run this:
INFO test - start SO example
INFO test - status: 200
INFO test - elapsed: 0:00:00.532053
INFO test - headers: CaseInsensitiveDict({'server': 'Apache-Coyote/1.1',
'set-cookie': 'JSESSIONID=8F87A69FB2B92F3ADB7F8A73E587A10C; Path=/;
Secure; HttpOnly', 'content-type': 'text/xml;charset=UTF-8',
'transfer-encoding': 'chunked', 'date': 'Wed, 18 Sep 2013 06:34:28 GMT'})
INFO test - content: <?xml version="1.0" encoding="utf-8"?>
<UserResponse><Status>Success</Status> .... </UserResponse>
INFO test - stop
As you can see, there is this weird variable 'response_length' that i need
to pass to the response object (optional argument) to be able to read the
content. This variable has to be set to a numeric value that is equal to
length of the 'content'. This obviously means that i need to know the
response-content-length before hand, which is unreasonable.
If i don't pass that variable or set it to a value greater than the
content length, I get the following error:
Traceback (most recent call last):
File "\Python33\lib\http\client.py", line 590, in _readall_chunked
chunk_left = self._read_next_chunk_size()
File "\Python33\lib\http\client.py", line 562, in _read_next_chunk_size
return int(line, 16)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xb4 in position 0:
invalid start byte
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "test.py", line 22, in main
logr.info('content: ' + response.raw.read().decode())
File
"\Python33\lib\site-packages\requests\packages\urllib3\response.py",
line 167, in read
data = self._fp.read()
File "\Python33\lib\http\client.py", line 509, in read
return self._readall_chunked()
File "\Python33\lib\http\client.py", line 594, in _readall_chunked
raise IncompleteRead(b''.join(value))
http.client.IncompleteRead: IncompleteRead(351 bytes read)
How do i make this work without this 'response_length' variable? Also, are
there any better options than 'Requests' lib?
PS: this code is an independent script, and does not run in the Django
framework.

Tuesday, 17 September 2013

adding secuity in Struts 2 spring application

adding secuity in Struts 2 spring application

I am developing an application with spring 3 struts 2 and hibernate. After
login only i have to display the pages It is working fine. when i testing
i found the big mistake
that is i copy the url of the page which needs to display only to logined
user and paste it in other browser means it is dispalying the page without
login.
How would i overcome this error?

How to create an error message box for an empty text box: VB 2010 Express

How to create an error message box for an empty text box: VB 2010 Express

I am taking VB this semester, and while it is not required for this
particular assignment, I am curious how I can create a MessageBox error if
a text box is left empty.
We just covered using the Try/Catch statement, and I have successfully
created MessageBoxes for text boxes whose text is only numeric. For
example, a user must enter a name, and two numeric amounts. I am trying to
create an error if the Name text box is left empty, stop the program from
calculating the two amounts and return the insertion point to the Name
text box.
Is there an easier way to do this? The If/Then statement I currently have
does not stop the program from calculating (I am just starting out so go
easy on me):
Private Sub CalculateButton_Click(sender As System.Object, e As
System.EventArgs) Handles CalculateButton.Click
'Declare Variables
Dim SellingPrice, CostValue, Commission As Decimal
'Test to see if a name was provided the NameTextBox
If NameTextBox.Text = "" Then
MessageBox.Show("Please enter a Salesperson's name", "No entry",
MessageBoxButtons.OK, MessageBoxIcon.Error)
With NameTextBox
.Focus()
.SelectAll()
End With
End If
'Test if Numerical data was entered for SellingPriceTextBox
Try
'Convert Selling Price
SellingPrice = Decimal.Parse(SellingPriceTextBox.Text)
'Test if Numerical data was entered for CostValueTextBox
Try
'Convert Cost Value
CostValue = Decimal.Parse(CostValueTextBox.Text)
'Calculate the Commission earned
Commission = Decimal.Round(COMMISSION_RATE * (SellingPrice
- CostValue), 2)
'Format and display results
TotalCommissionLabel.Text = Commission.ToString("C")
Catch CostValueException As FormatException
'Handle a Cost Value exception
MessageBox.Show("Value must be a numeric value.", "Invalid
Input",
MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
With CostValueTextBox
.Focus()
.SelectAll()
End With
End Try
Catch SellingPriceException As FormatException
'Handle a Selling Price exception
MessageBox.Show("Price must be a numeric value.", "Invalid
Input",
MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
With SellingPriceTextBox
.Focus()
.SelectAll()
End With
End Try
End Sub

Convert String in Array JQUERY

Convert String in Array JQUERY

I have the data array return of the server :
data.arr = [[Date.UTC(2013, 9, 17),1],[Date.UTC(2013, 9,
18),5],[Date.UTC(2013, 9, 19),2],[Date.UTC(2013, 9, 20),4]]
[0] "[Date.UTC(2013, 9, 17),1]" String
[1] "[Date.UTC(2013, 9, 18),5]" String
[2] "[Date.UTC(2013, 9, 19),2]" String
[3] "[Date.UTC(2013, 9, 20),4]" String
I need to pass only value to a function that recepeit an array[i,y], i
need that stay following; i need to remove the "".
[0] [Date.UTC(2013, 9, 17),1]
[1] [Date.UTC(2013, 9, 18),5]
[2] [Date.UTC(2013, 9, 19),2]
[3] [Date.UTC(2013, 9, 20),4]
How to do it?

Setting UITextView frame to content size no longer works in Xcode 5

Setting UITextView frame to content size no longer works in Xcode 5

The code snippet below worked to resize a UITextView frame to it's content
height, before installing Xcode 5 but it doesn't work since the upgrade:
CGRect frame = _textView.frame;
frame.size.height = _textView.contentSize.height;
_textView.frame = frame;
I've searched and haven't found the fix. Any thoughts?

How Can i optimize code using collections in python?

How Can i optimize code using collections in python?

I am new to python2.6,how can i optimize the below code using collection
in python to access the item values etc.
DATA={
'item1':('name1','color1',[1,2,6]),
'item2':('name1','color1',[5,8,9])
}
Thanks hema

Create a function with 4 parameters using python 3.3

Create a function with 4 parameters using python 3.3

Create a function called student data, that takes 4 parameters, a name (a
string), age (an integer), student number (a string) and whether they are
enrolled in Management (a boolean), and returns a string containing that
information in the following format: [student number,name,age,enrolled]

Sunday, 15 September 2013

Are there any way to skip the next activity using JS

Are there any way to skip the next activity using JS

For example, I have an action like this:
Run external JS => Save file => Run External Bat
The problem is , are there any way in the JS to skip the save file acvitiy ?
What I would like to do in the JS is :
if (some condition) { //Skip the save file activity }
Is it possible or any workaround can achieve the same result? Thanks
Reference: http://www.adobe.com/devnet/acrobat/javascript.html

cannot find symbol java error

cannot find symbol java error

So I am used to writing in c++ and I just can't figure out these java
errors. I appreciate any help or advice. Here is my code:
import java.util.Scanner;
public class Grade
{
public int inputScore()
{
int testScore;
System.out.println("Welcome to the Letter Grade Converter");
System.out.println("Enter numberical grade:");
Scanner sc = new Scanner (System.in);
testScore =sc.nextInt();
return testScore;
}
public String assignLetter()
{
String grade;
if (testScore >= 88) {
grade = "A";
} else if (testScore >=80){
grade = "B";
} else if (testScore >=67){
grade = "C";
} else if (testScore >=60){
grade = "D";
} else if (testScore >= 0){
grade = "F";
}
return grade;
}
public String printResult()
{
System.out.println ("Letter grade:" + grade);
}
}
Along with my driver program:
public class GradeApp
{
public static void main (String[] args)
{
Grade studentGrade = new Grade(); // create student object
String choice="y";
while (choice.equalsIgnoreCase("y")) {
studentGrade.inputScore(); //get score from user and assign it to the
variable
studentGrade.assignLetter(); //assign a letter grade based on the
score
studentGrade.printResult(); //display the letter grade
}
}
}
Neither will compile. I can't seem to figure out why. Also I am used to
using the relational operator "::" in c++ which references the driver code
to the classes in the other code. I was wondering how to do that in java.
It keeps giving me a cannot find symbol error on the "grade" variable at
the very bottom as well as at all the testScore instances.

Php while loop not working, Strange error

Php while loop not working, Strange error

Here is my php:
<?
$i = 0;
function f() {
$i++;
echo $i;
if ($i < 3) {
return true;
}
}
while(f())
?>
I was expecting output to be 123
But I get this:
Fatal error: Maximum execution time of 30 seconds exceeded in exp.php on
line 5

How to init typeahead on new created input?

How to init typeahead on new created input?

I'm looking for a while to make it works.
This is my last try.
I have this html :
<td>
<input type="text" value="" class="typeahead" style="width: 310px"
autocomplete="off" data-provide="typeahead" />
<input type="hidden" value="" class="delivery" name="delivery[]" />
</td>
And on JS side, I have this :
$(".typeahead").on("create", function() {
$(this).typeahead({
limit : 20,
remote : {
url: '/ajax/places/?query=',
replace: function(url, encodedUrl) {
return url + encodedUrl + '&categorySon=5';
},
filter: function (result) {
var list = [];
result.aaData.map(function (item) {
list.push({
value: item.name + ' (' + item.code + ')',
id: item.id
});
});
return list;
}
}
}).bind('typeahead:selected', function (obj, datum) {
$(this).parent().parent().find("input[type='hidden']").val(datum.id);
});
});
So, when I add dynamycly an other input typeahead it doesn't works (even
on the one create on loading of the page, it works fine with basic
$(".typeahead).typeahead...)
thanks a lot for your help !

Optimizing the load of numerous images

Optimizing the load of numerous images

I have a website that displays about 30 fairly small color gif files on
the main page. When looking into optimizing the site, I ran Google's
PageSpeed Analyzer. It suggests that I create a CSS sprite for them. The
problem that I'm running into is that the main page does not show the same
30 images per user and/or per page load. Also, the images are replaced
about once a month.
I was thinking maybe a dynamic generation of a CSS sprite or a CSS sprite
that contains all possible images. I am looking for the most efficient way
of accomplishing this.So my question is, What can I do to reduce the
requests or optimize this aspect while allowing for the change described?

How to read the input and replace the character as required?

How to read the input and replace the character as required?

The code below shows a part of my program. I am trying to create an atbash
encryption for a small challenge (atbash is an encryption method; example,
I type in 'hello' and the program will output 'svool'. It reverses the
letter order. More here: http://en.wikipedia.org/wiki/Atbash)
The program works...sort-of, when i type 'abcdef' the program outputs
'zyxwvu'. However, say i wanted to type an actual word. The program won't
cycle through the array and will just output "test" (which it's NOT
supposed to do). How do I fix this?
char letter1 [] = new char []
{'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
char letter2 [] = new char []
{'z','y','x','w','v','u','t','s','r','q','p','o','n','m','l','k','j','i','h','g','f','e','d','c','b','a'};
for (int i = 0 ; i < input.length() ; i++)
{
if(i == input.length()) {
break;
}
if (input.charAt(i) == letter1[i]) {
input.setCharAt(i, letter2[i]);
System.out.println (input);
}
else if (input.charAt(i) != letter1[i]){
System.out.println ("test");
}
}

Onsite image cropping functionality with a fixed ratio with RoR, Paperclip, S3 setup

Onsite image cropping functionality with a fixed ratio with RoR,
Paperclip, S3 setup

I am looking for a way to provide a onsite image cropping functionality to
the user. However, I would only like to allow them to crop their image
with a given respect ratio. The idea is similar to the square protrait
cropper for some social website when you upload an avatar. Can anyone
suggest a solution for this? Thank you.

Using a class in a class

Using a class in a class

I'm currently receiving this error
Parse error: syntax error, unexpected T_OBJECT_OPERATOR
Please Note:
I'm new to php.
All I have basically done is merge http://phpir.com/part-of-speech-tagging
and http://tappetyclick.com/blog/2013/06/25/twitter-xml-feeds-are-back
any help would be greatly appreciated.
my overall goal is to be able to collect all twitter search results and
classify each word by its world class (part of speech)
anyway here is my code:
<?
//WORDCLASS
class PosTagger {
private $dict;
public function __construct($lexicon) {
$fh = fopen($lexicon, 'r');
while($line = fgets($fh)) {
$tags = explode(' ', $line);
$this->dict[strtolower(array_shift($tags))] = $tags;
}
fclose($fh);
}
public function tag($text) {
preg_match_all("/[\w\d\.]+/", $text, $matches);
$nouns = array('NN', 'NNS');
$return = array();
$i = 0;
foreach($matches[0] as $token) {
// default to a common noun
$return[$i] = array('token' => $token, 'tag' =>
'NN');
// remove trailing full stops
if(substr($token, -1) == '.') {
$token = preg_replace('/\.+$/', '', $token);
}
// get from dict if set
if(isset($this->dict[strtolower($token)])) {
$return[$i]['tag'] =
$this->dict[strtolower($token)][0];
}
// Converts verbs after 'the' to nouns
if($i > 0) {
if($return[$i - 1]['tag'] == 'DT' &&
in_array($return[$i]['tag'],
array('VBD',
'VBP', 'VB'))) {
$return[$i]['tag'] = 'NN';
}
}
// Convert noun to number if . appears
if($return[$i]['tag'][0] == 'N' && strpos($token,
'.') !== false) {
$return[$i]['tag'] = 'CD';
}
// Convert noun to past particile if ends with 'ed'
if($return[$i]['tag'][0] == 'N' && substr($token,
-2) == 'ed') {
$return[$i]['tag'] = 'VBN';
}
// Anything that ends 'ly' is an adverb
if(substr($token, -2) == 'ly') {
$return[$i]['tag'] = 'RB';
}
// Common noun to adjective if it ends with al
if(in_array($return[$i]['tag'], $nouns)
&& substr($token, -2) ==
'al') {
$return[$i]['tag'] = 'JJ';
}
// Noun to verb if the word before is 'would'
if($i > 0) {
if($return[$i]['tag'] == 'NN'
&&
strtolower($return[$i-1]['token'])
== 'would') {
$return[$i]['tag'] = 'VB';
}
}
// Convert noun to plural if it ends with an s
if($return[$i]['tag'] == 'NN' && substr($token,
-1) == 's') {
$return[$i]['tag'] = 'NNS';
}
// Convert common noun to gerund
if(in_array($return[$i]['tag'], $nouns)
&& substr($token, -3) == 'ing') {
$return[$i]['tag'] = 'VBG';
}
// If we get noun noun, and the second can be a
verb, convert to verb
if($i > 0) {
if(in_array($return[$i]['tag'], $nouns)
&&
in_array($return[$i-1]['tag'],
$nouns)
&&
isset($this->dict[strtolower($token)]))
{
if(in_array('VBN',
$this->dict[strtolower($token)]))
{
$return[$i]['tag'] = 'VBN';
} else if(in_array('VBZ',
$this->dict[strtolower($token)]))
{
$return[$i]['tag'] = 'VBZ';
}
}
}
$i++;
}
return $return;
}
}
?>
<?php
//TWITTER
// Include the twitter oauth library for PHP (I put it in a subdirectory
require_once("lib/twitteroauth/twitteroauth.php");
// Init
define("CONSUMER_KEY", "mykeyhere");
define("CONSUMER_SECRET", "mykeyhere");
define("OAUTH_TOKEN", "mykeyhere");
define("OAUTH_TOKEN_SECRET", "mykeyhere");
$q='search term';
// Get an authorised connection to twitter
$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, OAUTH_TOKEN,
OAUTH_TOKEN_SECRET);
$content =
$connection->get("search/tweets.json?q=".$q."&result_type=recent");
// Send the xml header
header("Content-Type: application/rss+xml; charset=ISO-8859-1");
$url = 'http://'.$_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
$xml ="";
$xml.= '<!--?xml version="1.0" encoding="ISO-8859-1"?-->'.PHP_EOL;
$xml.= '<rss version="2.0"
xmlns:atom="http://www.w3.org/2005/Atom">'.PHP_EOL;
$xml.= ' <channel>'.PHP_EOL;
$xml.= '<title>'.$q.'</title>'.PHP_EOL;
$xml.= ' <description>Search results</description>'.PHP_EOL;
$xml.= '<link>'.$url.'</link>'.PHP_EOL;
$xml.= ' <atom:link href="'.$url.'" rel="self"
type="application/rss+xml">'.PHP_EOL;
// Get the status
foreach ($content->statuses as $status) {
//wordclass
$tags = new PosTagger('lexicon.txt')->tag($status->text);
// Build the tweet url as we don't get this in the status object
$url =
'http://twitter.com/'.$status->user->screen_name.'/status/'.$status->id_str;
$date = explode(' ', $status->created_at);
$xml.= ' <item>'.PHP_EOL;
$xml.= '<title>'.$status->text.'</title>'.PHP_EOL;
$xml.= ' <description>'.$tags->text.'</description>'.PHP_EOL;
$xml.= '<link>'.$url.'</link>'.PHP_EOL;
$xml.= ' <guid ispermalink="true">'.$url.'</guid>'.PHP_EOL;
// Format the date since the twitter format doesn't work for rss
$xml.= ' <pubdate>'.$date[0].', '.$date[2].' '.$date[1].'
'.$date[5].' '.$date[3].' '.$date[4].'</pubdate>'.PHP_EOL;
// Get the attached media
/*
if ($status->entities) {
if (is_array($status->entities->media)) {
foreach ($status->entities->media as $media) {
switch ($media->type) {
//Currently only photo's supported but I suspected with vine
video will be along soon
case 'photo':
$enc_type = 'image/jpeg';
break;
}
if (!empty($enc_type)) {
// We need the file size for the media so try to get this from
the headers
$headers = get_headers($media->media_url);
$size = $headers['Content-Length'];
if (empty($size)) {
foreach ($headers as $header) {
$h = explode(':', $header);
if ($h[0] == 'Content-Length') {
$size = trim($h[1]);
break; // Found what we need, stop looping
}
}
}
if (empty($size)) {
$size = 1; //This is basically a hack to make the rss validate
}
$xml.= ' <enclosure length="'.$size.'" type="'.$enc_type.'"
url="'.$media->media_url.'">'.PHP_EOL;
}
}
}
}
$xml.= ' </enclosure></item>'.PHP_EOL;*/
$xml.= ' </item>'.PHP_EOL;
}
$xml.= ' </atom:link></channel>'.PHP_EOL;
$xml.= '</rss>'.PHP_EOL;
// Return the xml for the rss
print $xml;
?>
the above code returns the following error
Parse error: syntax error, unexpected T_OBJECT_OPERATOR in
/var/www/test/Twitter/index.php
for this line
$tags = new PosTagger('lexicon.txt')->tag($status->text);

Saturday, 14 September 2013

Multiple ObjectStateManager errors when attempting to update an Entity in Entity Framework

Multiple ObjectStateManager errors when attempting to update an Entity in
Entity Framework

This is a problem that has been cropping up for months and is proving to
be extremely frustrating.
I have an entity ... StorageContract ... which inherits from Contract;
created from a TPT (Table per Type) relationship (I am not sure if that
makes a difference). When I attempt to update an existing StorageContract
by passing an updated definition of the contract to the Update method ...
public StorageContract UpdateStorageContract(StorageContract contract)
{
Context.ObjectContext.ApplyCurrentValues("Contracts", contract);
Context.SaveChanges();
return contract;
}
... I get the error ...
"An object with a key that matches the key of the supplied object could
not be found in the ObjectStateManager"
I found the following post ... "An object with a key that matches the key
of the supplied object could not be found in the ObjectStateManager" ...
which led me to try "attaching" the contract parameter.
public StorageContract UpdateStorageContract(StorageContract contract)
{
Context.ObjectContext.AttachTo("Contracts", contract);
Context.SaveChanges();
return contract;
}
... Which results in an error that seems to be confusingly quite the
opposite of the previous error ...
"An object with the same key already exists in the ObjectStateManager. The
ObjectStateManager cannot track multiple objects with the same key"
The first error indicated that the entity could not be updated because it
could NOT be found ... where as this one seems to suggest that it cannot
be updated because it already exists(??). Anyway that led me to the
following post ... "An object with the same key already exists in the
ObjectStateManager. The ObjectStateManager cannot track multiple objects
with the same key". SO I reworked the code again based on that ...
public StorageContract UpdateStorageContract(StorageContract contract)
{
var origEntry = Context.Entry<StorageContract>(contract);
if (origEntry.State == System.Data.EntityState.Detached)
{
var set = Context.Set<StorageContract>();
StorageContract attachedEntity = set.Find(contract.Id);
if (attachedEntity != null)
{
var attachedEntry = Context.Entry(attachedEntity);
attachedEntry.CurrentValues.SetValues(contract);
}
else
{
origEntry.State = System.Data.EntityState.Modified;
}
}
Context.SaveChanges();
return contract;
}
Which results in the same error ...
"An object with the same key already exists in the ObjectStateManager. The
ObjectStateManager cannot track multiple objects with the same key"
I am chasing this down a rabbit hole that caves in at every turn! I am
desperate for help with this!!
Thanks!

Clone and insertAfter only once a time

Clone and insertAfter only once a time

HTML
<p class="field-new">content</p>
<p><a class="add-new" href="#">add new</a></p>
jQuery
$('.field-new').hide();
$('.add-new').click( function() {
$(this).parent().siblings('.field-new').clone().insertAfter('.field-new').show();
return false;
});
Can anyone help please? So one click on ".add-new" to add only one new
field ".field-new". Thanks.

Nested for loop Java text output

Nested for loop Java text output

I have been trying to write a method called printDesigns that uses nested
for loops to output this:
-----1-----
----333----
---55555---
--7777777--
-999999999-
The dashes decrease by one on each side, I know its hard to see.

Subquery returned more than 1 value.

Subquery returned more than 1 value.

I have a problem creating a query that displays results for more than one
branch. PLease see my code below. SELECT (SELECT
COUNT(FilteredAppointment.activitytypecodename) AS Expr1 FROM
FilteredBusinessUnit INNER JOIN FilteredSystemUser ON
FilteredBusinessUnit.businessunitid = FilteredSystemUser.businessunitid
INNER JOIN FilteredAppointment ON FilteredSystemUser.systemuserid =
FilteredAppointment.createdby WHERE (FilteredBusinessUnit.name IN
(@Branch))) AS Appointment, (SELECT COUNT(FilteredLead.leadid) AS Expr1
FROM FilteredBusinessUnit AS FilteredBusinessUnit_7 INNER JOIN
FilteredSystemUser AS FilteredSystemUser_7 ON
FilteredBusinessUnit_7.businessunitid =
FilteredSystemUser_7.businessunitid INNER JOIN FilteredLead ON
FilteredSystemUser_7.systemuserid = FilteredLead.createdby WHERE
(FilteredBusinessUnit_7.name IN (@Branch)) AND
(FilteredLead.new_referraltypename = 'Bank Staff')) AS
Bank_Staff_Referral, (SELECT COUNT(FilteredLead_3.leadid) AS Expr1 FROM
FilteredBusinessUnit AS FilteredBusinessUnit_6 INNER JOIN
FilteredSystemUser AS FilteredSystemUser_6 ON
FilteredBusinessUnit_6.businessunitid =
FilteredSystemUser_6.businessunitid INNER JOIN FilteredLead AS
FilteredLead_3 ON FilteredSystemUser_6.systemuserid =
FilteredLead_3.createdby WHERE (FilteredBusinessUnit_6.name IN (@Branch))
AND (FilteredLead_3.new_referraltypename = 'Existing Customer')) AS
Customer_Referral, (SELECT
COUNT(Filterednew_discoveryinterview.activityid) AS Expr1 FROM
FilteredBusinessUnit AS FilteredBusinessUnit_5 INNER JOIN
FilteredSystemUser AS FilteredSystemUser_5 ON
FilteredBusinessUnit_5.businessunitid =
FilteredSystemUser_5.businessunitid INNER JOIN
Filterednew_discoveryinterview ON FilteredSystemUser_5.systemuserid =
Filterednew_discoveryinterview.createdby WHERE
(FilteredBusinessUnit_5.name IN (@Branch))) AS Discovery_Interview,
(SELECT COUNT(FilteredLead_2.leadid) AS Expr1 FROM FilteredBusinessUnit AS
FilteredBusinessUnit_4 INNER JOIN FilteredSystemUser AS
FilteredSystemUser_4 ON FilteredBusinessUnit_4.businessunitid =
FilteredSystemUser_4.businessunitid INNER JOIN FilteredLead AS
FilteredLead_2 ON FilteredSystemUser_4.systemuserid =
FilteredLead_2.createdby WHERE (FilteredBusinessUnit_4.name IN (@Branch)))
AS Generated_Leads, (SELECT COUNT(FilteredPhoneCall.createdon) AS Expr1
FROM FilteredBusinessUnit AS FilteredBusinessUnit_3 INNER JOIN
FilteredSystemUser AS FilteredSystemUser_3 ON
FilteredBusinessUnit_3.businessunitid =
FilteredSystemUser_3.businessunitid INNER JOIN FilteredPhoneCall ON
FilteredSystemUser_3.systemuserid = FilteredPhoneCall.createdby WHERE
(FilteredBusinessUnit_3.name IN (@Branch))) AS Phonecall_Activity, (SELECT
COUNT(Filterednew_presentation.activityid) AS Expr1 FROM
FilteredBusinessUnit AS FilteredBusinessUnit_2 INNER JOIN
FilteredSystemUser AS FilteredSystemUser_2 ON
FilteredBusinessUnit_2.businessunitid =
FilteredSystemUser_2.businessunitid INNER JOIN Filterednew_presentation ON
FilteredSystemUser_2.systemuserid = Filterednew_presentation.createdby
WHERE (FilteredBusinessUnit_2.name IN (@Branch))) AS Presentations,
(SELECT COUNT(FilteredLead_1.leadid) AS Expr1 FROM FilteredBusinessUnit AS
FilteredBusinessUnit_1 INNER JOIN FilteredSystemUser AS
FilteredSystemUser_1 ON FilteredBusinessUnit_1.businessunitid =
FilteredSystemUser_1.businessunitid INNER JOIN FilteredLead AS
FilteredLead_1 ON FilteredSystemUser_1.systemuserid =
FilteredLead_1.createdby WHERE (FilteredBusinessUnit_1.name IN (@Branch))
AND (FilteredLead_1.new_referraltypename = 'Self')) AS Self_Referral,
(SELECT name FROM FilteredBusinessUnit WHERE (FilteredBusinessUnit.name IN
(@Branch ))) AS BRANCH
The code returns results for query run against a single branch but throws
error message" Subquery returned more than 1 value. This is not permitted
when the subquery follows =, !=, <, <= , >, >= or when the subquery is
used as an expression. " When I select more than one branch. My guess is
that the error occurs when the last block of select statement is run.
Please help me

Sub menu 100% width of menu

Sub menu 100% width of menu

I have a sub menu appear below my main menu. The main menu is a fixed
width, I would like the sub menu to be 100% width of the main menu. The
sub menu could contain any number of links, I would like the width of the
sub menu to change proportionately. Is this possible? Here's my code:
Fiddle
CSS
#nav a{
width: 115px;
height: 15px;
text-decoration:none;
display:block;
font-size:12px;
font-family: Arial, Verdana, Helvetica, sans-serif;
text-align:center;
color:#666666;
border: 1px solid green;
float: right;
padding: 10px 5px 5px 5px;
z-index: 2000;
}
#nav a li{
width: 115px;
height: 15px;
}
#nav:last-child {
border-right: 1px solid #999999;
}
#nav a:active, #nav a:hover, #nav a:focus {
background: #999 ;
}
#nav li {
display:block;
float:left;
}
#nav li:last-child {
border-right: 1px solid #999999;
}
#nav li ul {
display: table;
height: 30px;
position: absolute;
left: -9999px;
}
#nav li:hover ul {
left: 0;
top: 30px;
}
#nav li li {
display: table-cell;
}
#nav li li a{
text-decoration:none;
display:block;
font-size:9px;
font-family: Arial, Verdana, Helvetica, sans-serif;
text-align:center;
border-left: 1px solid #999999;
color:#666666;
z-index: 10000;
padding: 5px 5px 10px 5px;
}
HTML
<ul id="nav">
<li><a href="#">LINK1</a></li>
<li><a href="#">LINK2</a>
<ul>
<li><a href="#">LINK3 <br> MORE TEXT</a></li>
<li><a href="#">LINK4</a></li>
<li><a href="#">LINK5</a></li>
<li><a href="#">LINK6</a></li>
</ul></li>
<li><a href="#">LINK7</a></li>
<li><a href="#">LINK2</a>
<ul>
<li><a href="#">LINK3 <br> MORE TEXT</a></li>
<li><a href="#">LINK4</a></li>
<li><a href="#">LINK5</a></li>
<li><a href="#">LINK6</a></li>
<li><a href="#">LINK5</a></li>
</ul></li>
</ul>
Thanks!

Function arguments passed by value

Function arguments passed by value

I'm reading that in JavaScript, a common point of confusion arises because
variables of primitives are passed by value, and variables of objects are
passed by reference, while in function arguments, both primitives and
references are passed by value.
In the course of my tinkering, I've made up the following code, but am
having trouble wrapping my head around it.
> function setName2(obj) {
... obj.name="matt";
... obj = new Object();
... obj.name="obama";
... }
If I set
var person = new Object();
person.name = "michelle";
Then run
> setName2(person);
I get
> person.name;
'matt'
Which makes sense because the new object created is a pointer to a local
object, hence not affecting the property of the global 'person'.
However, what if I first set
var obj = new Object();
obj.name = "michelle";
Then run
> setName2(obj);
?
I get the same outcome. Does this mean that the compiler recognizes the
two variables of the same name (obj global and obj local) as references to
different locations within the heap, each having some different pointer
association, or is there a different explanation for this phenomenon?

Prevent title from appearing on mouseover

Prevent title from appearing on mouseover

I couldn't find anything that solved my problem in previous posts, so
here's my question:
I'm working with fancybox image gallery and when I mouse-over the
thumbnails on the main page, they're picking up the title from the first
big image in each of the the sets that pop up in the lightbox. I don't
want that to happen, I don't want anything appearing on mouse-over of the
thumbnails.
Is there anyway to keep that from happening?
Thanks,
Kirk

Friday, 13 September 2013

Bootstrap: How do I make the input box and button stay on the same line?

Bootstrap: How do I make the input box and button stay on the same line?

this is my first question on Stackoverflow. I am not a CS major (Political
Economy, actually) but I would like to become proficient at programming
eventually. I'm helping with a website and learning all of these skills as
I go. I saw similar questions but did not find a helpful resolution.
You can see on the upper right of this screenshot that the search box and
button refuse to be on the same line. http://i.imgur.com/fiurnYs.png
HTML code for the search box looks like this:
<div class="col-sm-3 col-md-3 pull-right">
<form class="navbar-form" role="search">
<div class="input-group">
<input type="text" class="form-control" placeholder="Search"
name="srch-term" id="srch-term">
<div class="input-group-btn">
<button class="btn btn-default" type="submit"><i
class="icon-search"> </i></button>
</div>
</div>
</form>
</div>
CSS code looks like this:
https://raw.github.com/immenselyalive/dresswithease/master/bootstrap.css

Advantages of a VM

Advantages of a VM

The majority of languages I have come across utilise a VM, or virtual
machine. Languages such as Java (the JVM), Python, Ruby, PHP (the HHVM),
etc.
Then there are languages such as C, C++, Haskell, etc. which compile
directly to native.
My question is, what is the advantage of using a VM (outside of
OS-independence)? Isn't using a VM just creating an extra interpretation
step, by going [source code -> bytecode -> native] instead of just [source
code -> native]?
Why use a VM when you can compile directly?
EDIT
My understanding is that Python, Ruby, et al. use something akin to a VM,
if not exactly fitting under such a definition, where scripts are compiled
to an intermediate representation (for Python, e.g. .pyc files).
EDIT 2
Yep. Looked it up. Python, Ruby and PHP all use intermediate
representations, but are simply not stored in seperate files but executed
by the VM directly. See question : Java "Virtual Machine" vs. Python
"Interpreter" parlance?
" Even though Python uses a virtual machine under the covers, from a
user's perspective, one can ignore this detail most of the time. "

Can't create google chrome driver on Mac for Geb test

Can't create google chrome driver on Mac for Geb test

I am using Geb to run a Grails function test. I want to use the Chrome
driver, I follow these instructions:
https://code.google.com/p/selenium/wiki/ChromeDriver
I install the google chrome driver at:
/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome
on my mac.
I run the test with the switch
-Dwebdriver.chrome.driver="/Applications/Google\
Chrome.app/Contents/MacOS/Google\ Chrome"
from eclipse.
When I run the test I get:
Caused by: java.lang.IllegalStateException: The driver executable does not
exist: /Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome
any ideas?

Create my own tags?

Create my own tags?

Let's say i have a like a chat or forum, and whenever someone sends/posts
a message with tags for ex: <'video> A youtube link <'/video> i want to
appear as a video when i can play it (like http://prntscr.com/1r2o4k) ...
So does anyone know a method i can do this? I can't realise how to do it
-.-
I already know how to make the video appear like that, all I need to
realise is how to make the tags method work, sth like this
<video>MyVideoLOL</video>

Swing clients, Java Server

Swing clients, Java Server

My goal ist to develop an application which is used to set up a
videoconference between two seminar rooms. I have a MySQL database
containing the room and user informations and a java server polling the
room states (=connection state of videoconference). With a desktop
application, a user should be able to log himself in (user info in db) and
start a connection between two videoconference systems by selecting the
rooms he wants to connect (room info, vid-conf info ind db).
I figure I need the following parts in order to this
A service which polls the videoconference systems
A database service providing room and user informations
A desktop client application
I played around to test how I can do this and programmed a Java server
which polls the videoconference systems and stores this info. A swing
client can open a socket to the server and ask for a room state. Reading
db information is also programmed in the client with hibernate. Now this
works but it is far from a good style and I'd like to redesign the whole
thing.
So let's say, I begin from scratch. I really am having difficulties on how
to start to come to a clean programmed result. I know the following
questions are not very specific but I hope one of you can give me
directions on how to proceed or which technology/framework to use.
First a few requirements:
The server runs on a windows machine. It currently is installed as windows
service (and does only provide the room states).
The clients have to be desktop applications, less than 20 clients are
expected to run simultaneously.
The clients are used in a university network where also the server and the
videoconference systems reside.
And a few questions:
How do I design the server? I am sure I do not have to reinvent the
wheel... The server should be capable of providing database objects and
store/provide the current state of each room.
Would you store the current room state in the database? I also need to
keep track of current connections (which room is connected to which).
Currently I store the basic room info (room name, videoconference ip and
such) in the database, the room state (ready/ occupied, sending/receiving)
is handled seperately by the server.
How to access said server with a (Swing-)Client? Currently I use hibernate
to acces the db (yes I know, not a good idea with multiple clients for the
same db) and sockets with a clear text protocoll to access the room
states.
How can I implement a chain of actions like this one: The user selects two
rooms to connect. The clients sends this request to the server. The server
sends the request to the videoconference systems, both videoconference
systems start, when started they provide a feedback, the feedback should
be made available to all clients so everyone is informed that a conference
is in progress.
I do of course not expect detailed solutions to my problem but every hint,
link, etc. in the right direction will be appreciated. Thanks.

Thursday, 12 September 2013

Installing Sinatra and JSon for ruby

Installing Sinatra and JSon for ruby

I want to install JSON and Sinatra on my Mac that does not have an
internet connection.
How can I download and install Sinatra and JSON with all their dependency
packages from another machine and then install on my Mac?

what is overriding my list-style:none

what is overriding my list-style:none

I hope someone can help me with this. Spent 2 nights reading articles
about it, and feel I have tested everything, but still something is
overriding my list-style:none
http://ny.nordvux.net/content/articleType/CategoryView/categoryId/3/Tema
If you take a look at it and can advice me I would be eternally gratefull

Generic class and new() with interfaces

Generic class and new() with interfaces

Is there a way to use a generic class passing an interface as T and still
have the new() constraint?
Class Thing<T> where T : new()
new Thing<ISomething>()
I did not want Thing to be constrained by ISomething but I guess the idea
is just to keep adding interfaces to Thing?
Thanks

Non-exact Vlookup with multiple search criteria - Microsoft Excel

Non-exact Vlookup with multiple search criteria - Microsoft Excel

I'm having a problem extracting some date from a table in Excel. The data
is in the format shown in the diagram below:
Name---------------------------First Name------------------- Surname
Billy Peter Hunt---------------Tim---------------------------Smith
Chris Paul Smith---------------Brad--------------------------Johnson
Dave Colin Jones---------------Karen-------------------------Perry
Dr James Clyde Watt------------Dave--------------------------Jones
John Phil Cross----------------Chris-------------------------Smith
Kelly Holmes-------------------Hector------------------------Baxter
Norman Bryce-West--------------Billy-------------------------Hunt
For each person listed in the First Name and Surname columns (e.g. "Tim
Smith", "Brad Johnson" etc) I want to be able to search through the Name
column, for the first cell that contains both the First Name AND Surname
of the person being searched for, and output the results into a new
column.
As there are lots of middle names, titles and double-barreled surnames in
the Name column, I can't use an exact match search. I need to search the
contents of each cell to see if they have any matching sub-strings.
I've found that I can use Vlookup with wildcards to search based on either
the First Name OR Surname columns, but I can't figure out how to use both
columns simultaneously as search criteria.
Any help with this would be much appreciated. I've been typing all sorts
into Google and making lots of frustrated grunts to no avail.

TListBox sync with TStringList

TListBox sync with TStringList

I've got a background thread sending messages to the main thread which, in
turn, adds the messages to a TListBox like a log.
Thing is, this background thread is really fast and I dont really need to
update the log that fast. I'd like to add the messages to a TStringList
and set a timer to update the TListBox every second or so.
I've tried using:
listBox1.Items := StringList1;
or
listBox1.Items.Assign(StringList1);
in the OnTimer event and it works. Thing is, it never let's the user
really scroll or click the listbox, because it refreshes every second.
I'm using Delphi XE4
Is there a more elegant way to sync the contents of the listbox with this
background StringList (or any other list if necessary)? Thank you in
advance!

Positive integer from Python hash() function

Positive integer from Python hash() function

I want to use the Python hash() function to get integer hashes from
objects. But built-in hash() can give negative values, and I want only
positive. And I want it to work sensibly on both 32-bit and 64-bit
platforms.
I.e. on 32-bit Python, hash() can return an integer in the range -2**31 to
2**31 - 1. On 64-bit systems, hash() can return an integer in the range
-2**63 to 2**63 - 1.
But I want a hash in the range 0 to 2**32-1 on 32-bit systems, and 0 to
2**64-1 on 64-bit systems.
What is the best way to convert the hash value to its equivalent positive
value within the range of the 32- or 64-bit target platform?
(Context: I'm trying to make a new random.Random style class. According to
the random.Random.seed() docs, the seed "optional argument x can be any
hashable object." So I'd like to duplicate that functionality, except that
my seed algorithm can't handle negative integer values, only positive.)

How to update user B's current location in user A's iPhone app programatically?

How to update user B's current location in user A's iPhone app
programatically?

I have a scenario where User A has to be updated about User B's current
location in my app. Currently I use Core Location Framework to retrieve
current location, Can we update only by getting values of User B's
location from server on regular interval and display on User A's Map or is
there any other possibilities?
Thanks in advance.

Wednesday, 11 September 2013

copy files using bat file

copy files using bat file

I Am trying like this
copy .\abc*.* .\Product_109\Course Library\Financial Statements-A
Preview\util\
files are kept in 'abc' folder and trying to copy to the path
(Product_109\Course Library\Financial Statements-A Preview\util),
destination path consists of spaces in between so it is not allowing me to
copy.
Please help me with this.

NSLog hebrew characters from csv file in xcode

NSLog hebrew characters from csv file in xcode

NSString *path = [[NSBundle mainBundle]
pathForResource:@"hebrewLesson1and2" ofType:@"csv"];
NSArray *rows = [NSArray arrayWithContentsOfCSVFile:path];
NSLog(@"%@", rows);
My CSV file contains hebrew characters, which I would like to see print
out to the console. Currently they get printed out like
"\U05d6\U05b8\U05e7\U05b5\U05df" instead of something like "æÈ÷Åï".
Thanks for the help.

Non-compiling code

Non-compiling code

The following code won't compile:
public class fastfood
{
public static void main(String[]args)
{
List<MenuItem> menuItems = Arrays.asList;{
new MenuItem("Big Mac",4.23);
new MenuItem("Quater Pounder",3.23);
new MenuItem("Chicken Sandwich",5.63);
};
for(MenuItem m : menuItems)
{
System.out.println(m.toString());
}
}
}

in Oracle, how can i read a large blob as a text document

in Oracle, how can i read a large blob as a text document

I have a BLOB which actually contains text from a few hundreds chars to
20K+ chars. I am given this (I know it should be a CLOB, but not my
choice). I need to be able to get the entire text document. The closest
I've come is this:
select utl_raw.cast_to_varchar2(dbms_lob.substr(blob_data,2000,1)) from
my_table where id = 'id_value'; --get up to 2000
I can't get past 2000 at a time, though I guess I can get the size (using
dbms_lob.getlength) and get 2000 at a time and put it together. Seems like
there should be a better answer. Does anyone have a better way?

What are the difference/similarities between React (app framework from Facebook) and react.js (reactive extensions for JS)?

What are the difference/similarities between React (app framework from
Facebook) and react.js (reactive extensions for JS)?

I recently learned about Facebook/Instagram's app framework for JavaScript
called "React" and wanted to look more into it. However, I found myself
getting conflicting search results, as there is another library of a
similar name. So, my question is this: Are there similarities between the
two, or could someone do a better job at naming?
React
http://facebook.github.io/react/index.html
react.js
http://www.reactjs.com/

Is there really a resource leak if I close the inner stream?

Is there really a resource leak if I close the inner stream?

I ran a dynamic code analysis tool on one of our programs and this pattern
was identified as a resource leak:
...
FileInputStream fileInputStream = new FileInputStream(file);
try {
data = someMethod(new BufferedInputStream(fileInputStream));
// Assume that someMethod(InputStream) internally reads the stream
// until BufferedInputStream.read() returns -1.
...
}
finally {
...
try {
fileInputStream.close();
} catch (IOException e) {
...
}
}
Specifically, the analysis tool marked the new BufferedInputStream(...)
call as a resource leak because it is never closed. In this pattern,
however, the underlying stream fileInputStream is closed and the
BufferedInputStream goes out of scope.
Given this situation, is this actually a resource leak?

License Commercial Gracenote

License Commercial Gracenote

How do I get a license commercial? Is there a price list?
I contacted by site with the commercial and not getting a response.

Why the standard explicate allow C-style cast to convert derived object to inaccessible base sub-object?

Why the standard explicate allow C-style cast to convert derived object to
inaccessible base sub-object?

I just get the information from this cool blog that we can cast the
derived object to inaccessible base class sub-object. On the other hand,
the static_cast cannot be used to do that.
class Base {};
class Derived: private Base {};
void main()
{
Derived d;
Base* b = (Base*)&d; // compile passed.
Base* b = static_cast<B*>(&d); // compile error.
}
Cast the object to private base sub-object will break the private keyword
mean, it make the private object accessible to caller. I assume there is
some reason why C++ standard explicit allow this, and the reason
"compliant to C language" doesn't work to me because there doesn't have
inheriate in C language even you can simulate it, which is unrelated to
this problem.
Can anyone share some thought on this?

Multiple redis instances using one shared DB file, does it work?

Multiple redis instances using one shared DB file, does it work?

To make sure redis uses multiple cores, I would like to start several
instances of redis on the same computer. Each instance will use the same
db file. I would like to know if having multiple instances sharing the
same file can cause any data corruption ?

Tuesday, 10 September 2013

c++ : dynamic number of nested for loops (without recursion)

c++ : dynamic number of nested for loops (without recursion)

I'm writing a code segment that iterates through every permutation of n
digits. So for example, if n = 3, I would want to iterate through each of
the following elements:
0, 0, 0
0, 0, 0
...
0, 1, 0
...
1, 0, 0
...
2, 3, 4
...
9, 9, 9
You get the idea. This is very easy to code using nested for loops:
for(digit1 0 to 9)
for(digit2 0 to 9)
for(digit3 0 to 9)
But I want to generalize this to n digits. If for example n = 10 I now
need 10 nested for loops.
I've thought about this and realized that the problem can be solved using
recursion (depth first search through a tree, with each node having 10
children, 0 to 10, and stopping at depth n). But I'm aiming for high
performance so I don't want to use recursion due to the overhead. What
other alternatives do I have?

Fail to inherit from QMainWindow

Fail to inherit from QMainWindow

I currently have a UI form which contains many layouts(Horizontal and
Vertical) and then the form itself has a horizontal layout the form is
currently inheriting from QDialog. Now when I try to replace QDialog with
QMainWindow. So that I could add a toolbar to it. It seems that the
QTDesigner does not like my change and when I open the form up in
QTDEsigner it says that the form still inherits from QWidget. Any
suggestion on what I might be doing wrong ? Could this be because of the
presence of multiple layouts already present on the form

Group a datafield to AdvancedDatagrid from PHP output data

Group a datafield to AdvancedDatagrid from PHP output data

I had my PHP output into XML tag format and I wanted to group the
datafield='brname' as the main tree or group in my AdvancedDatagrid.
<html>
<head></head>
<body>
<show>
<show_list>
<brname>HONDA</brname>
<dscrpn>CIVIC 2DR</dscrpn>
<cr_mdl></cr_mdl>
<cr_loc>GUAM</cr_loc>
<cr_ave>1.33</cr_ave>
</show_list>
<show_list>
<brname>HONDA</brname>
<dscrpn>FIT</dscrpn>
<cr_mdl></cr_mdl>
<cr_loc>SAIPAN</cr_loc>
<cr_ave>1.5</cr_ave>
</show_list>
</show>
</body>
</html>
I have the HTTPService to get the data from the PHP output as:
<s:HTTPService id="link" url="the php address..." method="GET"/>
I found a sample of the AdvancedDatagrid, however, the data is declared
into an Arraycollection which is not applicable to me.
http://kirill-poletaev.blogspot.com/2011/07/advanceddatagrid-in-flex-part-3.html
I tried to do the similar code and just change the DataProvider just to
test the concept if it can be applied to my desired output.
private function init():void{
var myGC:GroupingCollection2 = new GroupingCollection2();
var myG:Grouping = new Grouping();
var myGF:GroupingField = new GroupingField();
myGF.name = "dscrpn";
myG.fields = [myGF];
myGC.grouping = myG;
myGC.source = myGrid.dataProvider;
myGC.refresh();
myGrid.dataProvider = myGC;
}
<mx:AdvancedDataGrid sortExpertMode="true"
dataProvider="{link.lastResult.show.show_list}" creationComplete="init()"
id="myGrid">
<mx:columns>
<mx:AdvancedDataGridColumn dataField="brname" headerText="Brand" />
<mx:AdvancedDataGridColumn dataField="dscrpn"
headerText="Description" />
<mx:AdvancedDataGridColumn dataField="cr_mdl" headerText="Mdel"/>
<mx:AdvancedDataGridColumn dataField="cr_loc" headerText="Loc"/>
<mx:AdvancedDataGridColumn dataField="cr_ave" headerText="Average"/>
</mx:columns>
</mx:AdvancedDataGrid>
Here is the output of my code 1
Sorry I am a bit new in using AdvancedDatagrid View. Thank You.

How can I pass selected row id to a commandLink outside a primefaces datatable?

How can I pass selected row id to a commandLink outside a primefaces
datatable?

PF 3.5.11, Mojarra 2.1.20 Omnifaces 1.5 I have primefaces datatable, with
single row selection enabled. Also I have buttons outside of datable which
make some operations on selected row.
I see the following options to pass selected row (id):
use EL-Binding
event on selection with setter
Are there another options ? Link with very nice explanation if buttons are
inside datatable: How can I pass a parameter to a commandLink inside a
datatable?

Symfony 1.2 not showing files at public folder

Symfony 1.2 not showing files at public folder

I'm setting up a project made by 2 other colleagues and I'm have a problem
when putting it online.
On my local machine, everything works like a charm but online I can´t link
any file at public folder, php scripts, images etc...
Does anyone knows if there's anything at symfony config's that can make
this behavior?
Thanks

Can I pass arguments to a base constructor from a derived class's default constructor?

Can I pass arguments to a base constructor from a derived class's default
constructor?

Suppose I have an abstract base class Deck:
public abstract class Deck
{
public List<Card> cards;
public Deck(string[] values, string[] suits)
{...}
...
}
and a derived class EuchreDeck:
public class EuchreDeck : Deck
{
string[] values = new string[] { "9", "10", "J", "Q", "K", "A" };
string[] suits = new string[] { "clubs", "spades", "hearts", "diamonds" };
public EuchreDeck() : base(values, suits) // Error.
{}
...
}
I want the ability to instantiate EuchreDeck and have the two string
arrays passed to the base class, i.e. var gameDeck = new EuchreDeck();.
Currently I'm getting the error: "An object reference is required for the
non-static field, method, or property EuchreDeck.values."
Is this possible, or will calling the derived default constructor always
call the base default constructor?

Good Coding Practice with Databases: One connection / query vs one connection / all queries

Good Coding Practice with Databases: One connection / query vs one
connection / all queries

So I am finding myself struggling which is the best practice. This is my
first time coding C# and first time coding anything in like a decade. Back
when I worked as a php / sql programmer, we usually frowned on the idea of
opening a new connection for every query, but the more I research this
question on google today, specifically with C# and sqlite, the more it
seems many recommend doing the polar opposite.
So, I was hoping the put this question out for some of you guys, who have
obviously been doing this a lot more than eye. Here is the general setup
of my database class:
class DatabaseController
{
static private SQLiteConnection _sqlconn;
static private string _uri;
public static SQLiteConnection Sqlconn
{
get { return DatabaseController._sqlconn; }
set { DatabaseController._sqlconn = value; }
}
public static string Uri
{
get { return DatabaseController._uri; }
set { DatabaseController._uri = value; }
}
}
The second class, which is the main Database class, which deals with
actually running queries and such. The reason I have the
DatabaseController class is because I can store the open connection handle
to the static member _sqlconn and so the connection is only ever opened
once, and Database objects simply use the same handle, even though the
program can and will create many Database objects.
But again, is this actually necessary? Should I simply be opening a new
connection within the main Database class, every time an object is
created? There was another site and thread I found that apparently, what
the .NET Framework does is even though you maintains a connection pool for
you, so even though you might be opening and disposing of several
connections, they aren't truly closed. Is this truly so, and does that
apply to both desktop and windows 8 apps?

Split multiple data cells per row in single data cell per row - jQuery

Split multiple data cells per row in single data cell per row - jQuery

I have a table with multiple data cells per row, like this:
<table>
<tbody>
<tr>
<td>content 1</td>
<td>content 2</td>
<td>content 3</td>
</tr>
<tr>
<td colspan="2">content 4</td>
<td>content 5</td>
</tr>
<tr>
<td colspan="3">content 6</td>
</tr>
</tbody>
</table>
How can I split all elements in independent rows using jQuery. To be be
more specific the result will have to be like this
<table>
<tbody>
<tr>
<td>content 1</td>
</tr>
<tr>
<td>content 2</td>
</tr>
<tr>
<td>content 3</td>
</tr>
<tr>
<td>content 4</td>
</tr>
<tr>
<td>content 5</td>
</tr>
<tr>
<td>content 6</td>
</tr>
</tbody>
</table>

Monday, 9 September 2013

how can I use regex and format string argument?

how can I use regex and format string argument?

I want to modify my original code in order to get sentences from database,
and changed each of them depends on the condition. How can I do that?
Inside my database I have 3 sequences that needs to be change...
CREATE SEQUENCE "MY_SEQUENCE" MINVALUE -8 MAXVALUE 999 INCREMENT BY 1
START WITH 250 CACHE 50 NOORDER NOCYCLE;
CREATE SEQUENCE "_SEQUENCE" MINVALUE 151 MAXVALUE 500 INCREMENT BY 4 START
WITH 160 CACHE 30 NOORDER NOCYCLE;
CREATE SEQUENCE "MY_TEST" MINVALUE 1 MAXVALUE 888 INCREMENT BY 9 START
WITH 1 CACHE 20 NOORDER NOCYCLE;
Result should be like below
CREATE SEQUENCE "MY_SEQUENCE" MINVALUE -8 MAXVALUE 999 INCREMENT BY 1
START WITH 999 CACHE 50 NOORDER NOCYCLE;
CREATE SEQUENCE "_SEQUENCE" MINVALUE 151 MAXVALUE 500 INCREMENT BY 4 START
WITH 151 CACHE 30 NOORDER NOCYCLE;
CREATE SEQUENCE "MY_TEST" MINVALUE 1 MAXVALUE 888 INCREMENT BY 9 START
WITH 1 CACHE 20 NOORDER NOCYCLE;
Conditions for changing the sentence
if MINVALUE has plus value inside the sentence than make start with value
same as MINVALUE...
if MINVALUE has minus value inside the sentence than make start with value
same as MAXVALUE
My Code:
//Inside my list there are sequence names to call each sequence from
database using DDL command.
private static List<string> LIST = new List<string>();
string sentence = "";
string formatprototype = "";
string output = "";
foreach (string Items in LIST)
{
using (OracleConnection conn1 =
MyConnection.GetSourceConnection(src.SrcDB, src.SrcID,
src.SrcPassword))
{
conn1.Open();
using (OracleCommand crtCommand = new
OracleCommand(@"SELECT REGEXP_REPLACE ( REPLACE (
dbms_metadata.get_ddl ('SEQUENCE', '" + Items + @"'),
'""" + src.SrcID + @""".'),'^\s+', NULL, 1, 0, 'm')
FROM dual", conn1)) //THIS COMMAND BRING EACH
SEQUENCES LIKE THIS: CREATE SEQUENCE "MY_SEQUENCE"
MINVALUE -8 MAXVALUE 999 INCREMENT BY 1 START WITH 250
CACHE 50 NOORDER NOCYCLE;
{
sentence = crtCommand.ExecuteScalar().ToString();
string pattern = @".*[
]+?[\""]{1}(?<String>[a-zA-Z0-9_]*)[\""]{1}[
]+?MINVALUE[ ]*(?<MinValue>[-?\d]*)[ ]*MAXVALUE[
]*(?<MaxValue>[\d]*)[ ]+?[INCREMENT]*[ ]+?[BY]*[
]+?(?<IncrementBy>[\d]*)[ ]+?[START]*[ ]+?[WITH]*[
]+?(?<StartWith>[\d]*)[ ]+?[CACHE]*[
]+?(?<Cache>[\d]*)\s+?";
Regex regex = new Regex(pattern);
Match match = regex.Match(sentence);
Group @string = match.Groups[1];
Group minvalue = match.Groups[2];
Group maxvalue = match.Groups[3];
Group incrementby = match.Groups[4];
Group startswith = match.Groups[5];
Group cache = match.Groups[6];
formatprototype = @"CREATE SEQUENCE ""{0}""
MINVALUE {1} MAXVALUE {2} INCREMENT BY {3} START
WITH {4} CACHE {5} NOORDER NOCYCLE";
if (minvalue.Value.StartsWith("-"))
{
output = string.Format(formatprototype,
@string, minvalue, maxvalue, incrementby,
maxvalue, cache);
}
else if (!minvalue.Value.StartsWith("-"))
{
output = string.Format(formatprototype,
@string, minvalue, maxvalue, incrementby,
minvalue, cache);
}
MessageBox.Show(output);
}
}
}
Errors on my code:
Getting the sentences without values like this one: CREATE SEQUENCE ""
MINVALUE MAXVALUE INCREMENT BY START WITH CACHE NOORDER NOCYCLE;

error with img selector

error with img selector

here is my HTML code
<!DOCTYPE html>
<html>
<head>
<title>Result</title>
<link type="text/css" rel="stylesheet" href="stylesheet.css"/>
</head>
<body>
<h1>testing css</h1>
<p>this text shows the paragrpah going under css</p>
<img src = "http://images.wikia.com/glee/images/1/1d/ImaFes.jpg" />
</body>
</html>
and here is my CSS code
h1 {
font-family: Verdana, sans-serif , serif;
color:#576D94;
}
p {
font-size:18px;
color: #4A4943;
font-family: Garamond, serif;
}
img {
height=100px;
width=300px;
border=1px solid #4682b4;
}
the error i found is with img selector. the editor shows an empty rule on
img selector line. hope i didn't do anything wrong with img selector.
sorry if any grammatical errors

Backbone google map suggestions on implementing markers

Backbone google map suggestions on implementing markers

Hello stackoverflow community,
I am trying to get may hands dirty with google maps and backbone together.
All is going very well with both. I just have one slight issue I am
slightly stumped on. I have a backbone view for my map, which looks like
this:
var MapWidget = Backbone.View.extend({
el: '.map-widget',
model: new Model,
center: function (e) {
},
addMarker: function () {
},
render: function() {
this.map = new google.maps.Map(this.el, this.model.attributes);
this.bindings();
console.log('Map Widget Rendered');
return this;
},
initialize: function() {
console.log('Map Widget initialized');
}
});
here is the model:
var MapWidget = Backbone.Model.extend({
defaults: {
zoom: 8,
center: new google.maps.LatLng(39.23036, -94.48182),
mapTypeId: google.maps.MapTypeId.ROADMAP,
disableDefaultUI: true
},
initialize: function(){
}
});
As you can see all the maps options are pulled from the maps model. What i
am struggled to figure out(or organize) is, if I start to add markers to
my map should the markers be stored in the same map model or should the
markers have their own collection? If i should have a collection of
markers, would it make more sense then to have a markerLoader view that
added the markers to the map from its own marker collection?
I hope all that make sense, just looking for some advice from some
seasoned backbone guys or anyone looking to add there two cents.let me
know if i need to explain more. Thank you stackoverflow community

Django fails to find R when loading RPy2 under virtualenv

Django fails to find R when loading RPy2 under virtualenv

This is kind of confusing, apologies in advance. I am configuring a new
(temporary) internal production web server with the following specs:
OSX 10.8.4 (Mountain Lion), Apache 2.2.25, PostgreSQL 9.2, Python 2.7.5,
Django 1.5.2, R 3.0.1, RPy2 2.3.7, virtualenv 1.10.4, virtualenvwrapper
4.1.1, mod_wsgi 3.4
This was set up on a new machine using Homebrew and pip. I removed
original, Apple-installed versions of Apache and Postgres before doing the
installs. Both Apache and mod_wsgi work. mod_wsgi is installed to run as
daemon process.
Virtual hosts is configured in Apache to access django via mod_wsgi and
the wsgi.py file contains the following lines:
import os,sys,site
site.addsitedir('/Users/kaiju/.virtualenvs/nauru_dev/lib/python2.7/site-packages')
# Activate the virtual environment
# Taken from
http://thecodeship.com/deployment/deploy-django-apache-virtualenv-and-mod_wsgi/
activate_env =
os.path.expanduser('/Users/kaiju/.virtualenvs/nauru_dev/bin/activate_this.py')
execfile(activate_env,dict(__file__=activate_env))
All python packages (including django and RPy2) have been installed using
the virtual environment's python site-packages.
R was installed using Homebrew and works fine from the command line or
from python interpreter when invoked within the virtual env (most of the
time, more later).
homebrew.mxcl.httpd.plist has been added to /Library/LaunchDaemons instead
of ~/Library/LaunchAgents so that it would automatically start when the
machine is rebooted. homebrew.mxcl.postgres.plist has been added to
~/Library/LaunchAgents (probably should also move it to
/Library/LaunchDaemons).
So here is the problem. When everything was installed, it worked together
fine. To verify everything was cool, I restarted the machine and tested
the django application. Apache is running, as is django, but now I get the
following error:
RuntimeError at /admin/
R_HOME not defined, and no R command in the PATH.
Request Method: GET
Request URL: http://nauru.xoma.com/admin/
Django Version: 1.5.2
Exception Type: RuntimeError
Exception Value: R_HOME not defined, and no R command in the PATH.
Exception Location:
/Users/kaiju/.virtualenvs/nauru_dev/lib/python2.7/site-packages/rpy2/rinterface/__init__.py
in <module>, line 48
Python Executable: /usr/local/opt/python/bin/python2.7
Python Version: 2.7.5
Python Path: ['usr/local/var/django/code/ri',
'/usr/local/var/django/code',
'/usr/local/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/setuptools-0.9.8-py2.7.egg',
'/usr/local/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pip-1.4-py2.7.egg',
'/usr/local/Frameworks/Python.framework/Versions/2.7/lib/python27.zip',
'/usr/local/Frameworks/Python.framework/Versions/2.7/lib/python2.7',
'/usr/local/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-darwin',
'/usr/local/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac',
'/usr/local/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac/lib-scriptpackages',
'/usr/local/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk',
'/usr/local/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-old',
'/usr/local/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload',
'/usr/local/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages',
'/Library/Python/2.7/site-packages',
'/Users/kaiju/.virtualenvs/nauru_dev/lib/python2.7/site-packages',
'/Users/kaiju/.virtualenvs/nauru_dev/lib/python2.7/site-packages/PIL']
But if I open a terminal window and type
sudo apachectl stop
sudo apachectl start
When the server comes back, everything works. This does not happen if I
use sudo apachectl restart, in that case the error remains. What is going
on? Too many moving parts for me.