Monday, 30 September 2013

conflicts with home internet and VPN

conflicts with home internet and VPN

Sorry for my English.
I have a usb modem through which I go out to the Internet. I want to
connect via VPN to the corporative network. The connection is successful.
The corporation portal works okay, but I can't to connect to various
servers via rdp (or other services). This is my routes without vpn(on
Russian language, sorry):
This is routes with the vpn:
I think the problem is that the provider of the modem and the corporate
network(gateway address:192.168.0.1) use the same netmask. How to solve
it?
PS. When VPN is connected the Internet works okay.
PS2. I use the Kerio VPN Client.

cant download windows installer wubi

cant download windows installer wubi

I was trying to download the windows installer through the link provided
on the page for the 12.04 version, but it is giving me to download the
707MB of iso file which I already have.
Please can anyone help me on this one?
Thank you.

Waterfall with two series using Highcharts

Waterfall with two series using Highcharts

I'm trying to set two Waterfall series using Highcharts in the same chart,
I have only see one serie in this type of chart in Highcharts samples. I
have manipulate the data to be an array but still not working. Any ideas
pls.

Disabling the dates before selected date and after today date

Disabling the dates before selected date and after today date

In Reports i am showing the startDate and endDate fields to select the
particular dates using jquery ui datepicker.For the startDate and endDate
fields i am giving the today date as the default date. My requirement is
1) If the customer directly clicks in the endDate the dates before today
date and after today date should be disable.
2) If the customer selects any particular date for startdate then for
enddate the dates before to the selected date and after to the today date
should be disabled.
I am using the below code to this.
var dates = $( "#startDate,

Sunday, 29 September 2013

Taking 2d list, and writing program for column max and average

Taking 2d list, and writing program for column max and average

i have a hw assignment i just finished up but it looks pretty horrendous
knowing that theres a much simpler and efficient way to get the correct
output but i just cant seem to figure it out. Heres the objective of the
assignment. Write a program that stores the following values in a 2D list
(these will be hardcoded):
2.42 11.42 13.86 72.32
56.59 88.52 4.33 87.70
73.72 50.50 7.97 84.47
The program should determine the maximum and average of each column
Output looks like
2.42 11.42 13.86 72.32
56.59 88.52 4.33 87.70
73.72 50.50 7.97 84.47
============================
73.72 88.52 13.86 87.70 column max
44.24 50.15 8.72 81.50 column average
The printing of the 2d list was done below, my problem is calculating the
max, and averages.
data = [ [ 2.42, 11.42, 13.86, 72.32],
[ 56.59, 88.52, 4.33, 87.70],
[ 73.72, 50.50, 7.97, 84.47] ]
emptylist = []
r = 0
while r < 3:
c = 0
while c < 4 :
print "%5.2f" % data[r][c] ,
c = c + 1
r = r + 1
print
print "=" * 25
This prints the top half but the code i wrote to calculate the max and
average is bad. for max i basically comapred all indexes in columns to
each other with if, elif, statements and for the average i added the each
column indency together and averaged, then printed. IS there anyway to
calculate the bottom stuff with some sort of loop. Maybe something like
the following
for numbers in data:
r = 0 #row index
c = 0 #column index
emptylist= []
while c < 4 :
while r < 3 :
sum = data[r][c]
totalsum = totalsum + sum
avg = totalsum / float(rows)
emptylist.append(avg) #not sure if this would work?
here im just trying to
r = r + 1 #dump averages into an emptylist
to print the values
c = c + 1 #in it later?
or something like that where im not manually adding each index number to
each column and row. The max one i have no clue how to do in a loop . also
NO LIST METHODS can be used. only append and len() can be used. Any help?

Getting a child element with Selenium and Python

Getting a child element with Selenium and Python

I have this HTML:
<div id = "d029384">
<span>......</span>
</div>
and my code:
elem = browser.find_elements_by_xpath("//div[contains(@id,'d')]")
except the div isn't working for what my program is doing. I need to be
more specific. I need the span element instead. How can I get the span
element? Each div has an id that is d + numbers. I need those numbers so
that's why I used that xpath but I don't know how to make the final
WebElement point to the span and not to the div.
Anyone know?

Are Rails passwords generated with bcrypt portable?

Are Rails passwords generated with bcrypt portable?

I have an existing web application with a few thousand users which I'm
porting over to Rails. As I rewrite and refactor this app I may need to
run it on any number of different servers for development, testing, and
production purposes.
I'm using Rails' built-in has_secure_password method in my user model but
I'm concerned about the portability of password data. I will need to move
the contents of my database from machine to machine to test in different
environments and its very important that I can test the user
authentication functionality using the same set of users and passwords in
each environment.
So far its easy to find answers about how bcrypt-ruby works along with
Rails has_secure_password but after weeks of searching I haven't found a
clear answer.
If has_secure_password results in a WorkFactor + Salt + HashedPassword
concatenated and saved to the password_digest database column then can
that hash be regenerated and compared reliably if moved to any other
machine (assuming any other machine is running Rails on a Unix-like OS)?
OR To put it another way - are bcrypt-ruby passwords generated with Rails'
has_secure_password portable?
Follow up question: If the salt is always generated randomly (I've seen
the same password use different hashes so I don't think the salt is
created from the text of the password itself) then how would a Rails app
be able to reliably rehash the password on a login form submit and compare
it to what's in the database. Obviously it would have to know what the
salt is first in order to compare it. How does it do that?

Can the result of a bitwise AND operator be negative (in Java)

Can the result of a bitwise AND operator be negative (in Java)

I have the following piece of code:
int SOME_MASK = 0x0000ffff;
int value = /* some value */;
int something = SOME_MASK & value;
// WHY IS "something" guaranteed to be non-negative ?
if (something != NEGATIVE_CONSTANT) {
// do something here....
}
I keep getting the FindBugs analysis warning:
Correctness - Bad comparison of nonnegative value with negative constant
This code compares a value that is guaranteed to be non-negative with a
negative constant.
The warning pops up for the line where comparing the bitwise AND result
with the negative constant.
I am not sure why a Bitwise AND result is guaranteed to be non-negative?
is this always the case?

Saturday, 28 September 2013

StrPtr not recognized in visual basic (VS 2012)?

StrPtr not recognized in visual basic (VS 2012)?

I'm using VS 2012:
Here's my situation:
I'm writing some code in visual basic that calls a dll function that I've
written in C++ (also written using vs 2012). One of my function's
arguments takes the wchar_t* data type, so I need to format my string from
vb accordingly using StrPtr.
Here's my problem:
Visual Basic does not recognize StrPtr as a function. I get: 'StrPtr' is
not declared. It may be inaccessible due to its protection level.'
What does this mean?

Nodejs using selenium-webdriver library with phantomjs as driver, attempting to return current URL

Nodejs using selenium-webdriver library with phantomjs as driver,
attempting to return current URL

var webdriver = require('selenium-webdriver');
var driver = new webdriver.Builder().
withCapabilities(webdriver.Capabilities.phantomjs()).
build();
driver.get('http://www.duckduckgo.com');
driver.findElement(webdriver.By.id('search_form_input_homepage')).sendKeys('webdriver
books and stuff');
driver.findElement(webdriver.By.id('search_button_homepage')).click();
//this is the part I am having trouble with...
setTimeout(function() {
console.log(driver.getCurrentUrl());
}, 5000);
This all works as expected up to the setTimeout(), and for this example (I
have tried many options), I get...
{ then: [Function: then],
cancel: [Function: cancel],
isPending: [Function: isPending] }

sqlite queries return nothing! (select statement)

sqlite queries return nothing! (select statement)

I have a table in which there's a column of type BLOB. Another column is
of type 'text'. Something like:
CREATE TABLE Tbl(TXT text, BLB blob);
Now I've inserted a few records using:
INSERT INTO Tbl(TXT) VALUES("whatever");
As you can see nothing was defined for BLB. But each time that I issue a
query like:
SELECT * FROM 'Tbl' WHERE 'TXT'="whatever";
I get nothing at all without any error message or anything. My primary
guess was that the problem might have something to do with BLB being null
or undefined or something like that. Any ideas?

Dims activity except one bright view

Dims activity except one bright view

I am trying to do a guide for my app. I tries to dim the activity and
leaves one clickable bright view (like games and Android itself when its
runs first time).
But I don't know where to start to implement that.
Any idea or source-code?

Friday, 27 September 2013

Var array to list box

Var array to list box

So on my last post, C# Json - to - Array I asked how to get the two values
to a array. But I was given a var, how do I get those variables in a list
box "main_Listbox"?

Android FragmentTabHost Tabs on Bottom with Icons selection issue

Android FragmentTabHost Tabs on Bottom with Icons selection issue

I am struggling with a simple UI for two days now. I just want a tabbed
layout with tabs on bottom (can't use Tabs ActionBarSherlock due to that
reason). Also I want my tabs to be represented by icon and a text. Pretty
simple?
I managed to edit this example according to my needs. Now I have tabs on
bottom working with FragmentTabHost. After this I tried to add icons to
tabs. If I were using regular TabHost I could have done
mTabs.addTab(mTabs.newTabSpec("chapter").setIndicator("Chapter",getResources().
getDrawable(R.drawable.chapter1)), ContentFragment.class, null);
But I learnt from this post: FragmentTabHost with drawable icon that
apparently it doesn't work with the new FragmentTabHost. So, following
this post: Icon in Tab is not showing up, I implemented a custom view for
holding tab's icon and text. And it worked fine.
The problem here (as asked by comments in one of the posts as well) is
that the selection isn't there anymore. I can't see which tab is selected.
Here's the complete code:
MainActivity.java
public class MainActivity extends FragmentActivity {
private FragmentTabHost mTabHost;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.bottom_tabs);
mTabHost = (FragmentTabHost) findViewById(android.R.id.tabhost);
mTabHost.setup(this, getSupportFragmentManager(), R.id.realtabcontent);
//testing with custom view implementation to add icon
TabSpec spec = mTabHost.newTabSpec("tab" + 1);
View tabIndicator =
LayoutInflater.from(this).inflate(R.layout.tab1_icon, null, false);
TextView title = (TextView) tabIndicator.findViewById(R.id.title);
title.setText("Label 1");
ImageView icon = (ImageView) tabIndicator.findViewById(R.id.icon);
Drawable myIcon = getResources().getDrawable( R.drawable.icon1 );
icon.setImageDrawable(myIcon);
icon.setScaleType(ImageView.ScaleType.FIT_CENTER);
spec.setIndicator(tabIndicator);
mTabHost.addTab(spec,
Fragment1.class, null);
mTabHost.addTab(mTabHost.newTabSpec("contacts")
.setIndicator("Contacts"), Fragment2.class, null);
mTabHost.addTab(mTabHost.newTabSpec("custom").setIndicator("Custom"),
Fragment3.class, null);
}
}
Fragment1.java
public class Fragment1 extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
View v =
LayoutInflater.from(getActivity()).inflate(R.layout.tab1_view, null);
return v;
}
bottom_tabs.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<FrameLayout
android:id="@+id/realtabcontent"
android:layout_width="match_parent"
android:layout_height="0dip"
android:layout_weight="1" />
<android.support.v4.app.FragmentTabHost
android:id="@android:id/tabhost"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<FrameLayout
android:id="@android:id/tabcontent"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_weight="0" />
</android.support.v4.app.FragmentTabHost>
tab1_view.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FF0000"
android:orientation="vertical"
tools:context=".DeviceFragment" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tab 1!" />
tab1_icon.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="0dip"
android:layout_height="55dip"
android:layout_weight="1"
android:orientation="vertical"
android:padding="5dp"
android:weightSum="55" >
<ImageView
android:id="@+id/icon"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="30"
android:adjustViewBounds="false"
android:src="@drawable/icon1" />
<TextView
android:id="@+id/title"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="25"
android:gravity="center_horizontal" />

How deploy maven3 artifact to remote server using scp

How deploy maven3 artifact to remote server using scp



Hello everyone
I want to have my own maven repository for artifacts created by myself but
I have a problem trying to make a deploy of maven 3 artifact to a custom
server. To explain this better I'm going to give some information:
I'm using Maven 3
I'm using Eclipse Keppler
I'm using Jenkins
The remote server is running Ubuntu Server 11.04
Jenkins is running on the Ubuntu server
My local machine is running Windows XP
My first attempt was with my machine. I run Maven in Eclipse to make the
deploy, and everything works fine. I add the following to my projects pom
<build>
...
<extensions>
<extension>
<groupId>org.apache.maven.wagon</groupId>
<artifactId>wagon-ssh-external</artifactId>
<version>1.0-beta-6</version>
</extension>
</extensions>
...
</build>
...
<distributionManagement>
<repository>
<id>my server id</id>
<name>my repository name</name>
<url>scpexe://my server//path/to/my/repository</url>
</repository>
</distributionManagement>
And in my settings.xml I add
<servers>
<server>
<id>my server id</id>
<username>server username</username>
<password>server password</password>
<configuration>
<sshExecutable>plink</sshExecutable>
<scpExecutable>pscp</scpExecutable>
</configuration>
</server>
</servers>
So in my local machine it works, but I need to get this work using
Jenkins. I modified the Jenkins settings.xml, because it runs on Linux, so
doesn't need sshExecutable. The Jenkins settings.xml looks like
<servers>
<server>
<id>my server id</id>
<username>server username</username>
<password>server password</password>
</server>
</servers>
Then I modified the pom.xml to execute just scp and not scpexe
<distributionManagement>
<repository>
<id>my server id</id>
<name>my repository name</name>
<url>scp://my server//path/to/my/repository</url>
</repository>
</distributionManagement>
But according to this page
https://cwiki.apache.org/confluence/display/MAVEN/Maven+3.x+Compatibility+Notes
maven 3 does not support scp. I run it any way and I got the following
error message from Jenkins log
mavenExecutionResult exceptions not empty
message : Failed to execute goal
org.apache.maven.plugins:maven-deploy-plugin:2.7:deploy (default-deploy)
on project myproject: Failed to deploy artifacts/metadata: No connector
available to access repository my_repository (scp://my
server//path/to/my/repository) of type default using the available
factories WagonRepositoryConnectorFactory
cause : Failed to deploy artifacts/metadata: No connector available to
access repository my_repository (scp://my server//path/to/my/repository)
of type default using the available factories
WagonRepositoryConnectorFactory
Stack trace :
If I use scpexe instead of scp I got another error message
mavenExecutionResult exceptions not empty
message : Failed to execute goal
org.apache.maven.plugins:maven-deploy-plugin:2.7:deploy (default-deploy)
on project pruebanueva: Failed to deploy artifacts: Could not transfer
artifact {$groupId}:{$artifactId}:{$package}:{$version} from/to
my_repository (scpexe://my server//path/to/my/repository): Error executing
command for transfer
cause : Failed to deploy artifacts: Could not transfer artifact
{$groupId}:{$artifactId}:{$package}:{$version} from/to my_repository
(scpexe://my server//path/to/my/repository): Error executing command for
transfer
Stack trace :
The only way I could make deploy, was doing it in two steps
Configuring Jenkins to make just the install goal
Running the following command from command line
mvn deploy:deploy-file -DgroupId=$groupId -DartifactId=$artifactId
-Dversion=$version -Dpackaging=jar -Dfile=path/to/file.jar -Durl=scp://my
server//path/to/my/repository -DrepositoryId=my repository id
I tried many things, including writing that command into Jenkins goal, but
everytime I use the scp command in Jenkins the build fails.
Any idea of how to solve this issue will be appreciated, thanks in advance

Download HTML source of webpage not getting the right data

Download HTML source of webpage not getting the right data

I'm trying to download the HTML source of a website
(http://thefuckingweather.com) to a String value for later manipulation.
The code I have listed below works for every other website I've tried, but
for some reason when I run it with the website listed above, I get the
following result:
The page you requested was removed.
The problem is that I can access that exact URL via the browser and that
is clearly not what's being displayed.. Any ideas? Here's my code:
public void getHtml(final String website) throws ClientProtocolException,
IOException
{
Thread thread = new Thread(new Runnable(){
@Override
public void run() {
try {
HttpClient httpclient = new DefaultHttpClient(); // Create
HTTP Client
HttpGet httpget = new HttpGet(website); // Set the action
you want to do
HttpResponse response = httpclient.execute(httpget); //
Executeit
HttpEntity entity = response.getEntity();
InputStream is = entity.getContent(); // Create an
InputStream with the response
BufferedReader reader = new BufferedReader(new
InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) // Read line by
line
sb.append(line + "\n");
String resString = sb.toString(); // Result is here
is.close(); // Close the stream
SettingsActivity.stringReturn=resString;
} catch (Exception e) {
e.printStackTrace();
}
}
});
thread.start();
}
And in OnCreate() I call:
try {
getHtml("http://thefuckingweather.com");
while(stringReturn.equals("")){
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

Resizing/Cropping a view or a particular area by the points as shown in image in arc shape but not straight line cropping

Resizing/Cropping a view or a particular area by the points as shown in
image in arc shape but not straight line cropping

I am working on a Makeup app like coloring lips, eyes for static and
dynamic images from camera. Attached is the image exactly what i needed
like setting some points and dragging as user wishes for coloring tat
particular area. You can look over "Modiface-Makeup" app for reference. If
anyone having idea on tat, please comment...

Durandal nested view composition

Durandal nested view composition

We are trying to build SPA Application using Durandal JS as a concept, we
have layout where there is top navigation panel and main container where
SPA content is loaded. in one of out views, we have left side panel with
navigation which should only change right panel of the same view. I know
that thee is child rout inside Durandal 2.0, but I am not able to achieve
what my goal is. clicking on top panel should change main container (there
are tow tabs on top) but on the second tab, where there is extra sub
navigation on the left side of loaded view I can not figure out how to
make Durandal to only change right panel of same view. I am not asking for
code not for concrete implementation, but for concept or theoretical
guidelines on how to achieve this.
I even tried using Areas inside durandal 2.0 but that seems to be
different from what I want to get as a result.

Accented characters are not indexed in Sphinx

Accented characters are not indexed in Sphinx

I have problems with searching words that contains accented characters. I
use Sphinx 2.1.1, Linux, MsSQL 2005 via odbc (freetds).
Here is my sphinx.conf:
source parentSource
{
type = odbc
...
}
index parentIndex
{
morphology = stem_en
charset_type = utf-8
charset_table = 0..9, a..z, A..Z->a..z, ... (mapping taken from
http://sphinxsearch.com/wiki/doku.php?id=charset_tables for common, A-Z)
...
}
After changing config, I've reindexed all indexes and restarted searchd.
When I search for "Muller" - I get results that contain only "Muller".
When I search for "Müller" - I also get only "Muller" results. But there
are also "Müller" records in db, that not indexed properly. Mapping for ü
(U+00FC->u) present in config. I mean after I've added accented characters
to charset_table, it (accented characters) is converted when I search, but
not when content is indexed, as I understand.
When I run indexer with --buildstops option, I found next record in output
file: "mller". And yes, when I search for "mller" - I get "Müller" results
(but no "Muller" of course).
What I need to do for search by "Muller/Müller" give results for both
"Muller" and "Müller"?
PS: collation used for column (and for wohle database) is
SQL_LATIN1_GENERAL_CP1_CI_AS. I change column type from varchar to
nvarchar, but it doesn't help. "Müller" records displaued properly on the
site (without ???) and when I run indexer with --dump-rows.

Thursday, 26 September 2013

Remove Trailing Zeros from a Double Value

Remove Trailing Zeros from a Double Value

I have encountered a problem in a solution that I am trying to achieve,
namely I need to be able to remove trailing zeros from a double value.
For instance, if I were creating two objects that represent a formula, it
would be appropriate to say that the two formulas (2.0 + 7) and (2.000 +
7) are equivalent. That is, (2.0 + 7) == (2.00000 + 7). However, I'm not
sure the best way to approach this is. I'm thinking regular expressions,
but I'm not certain that I can get the outcome I am looking for.
It seems that there would be an issue with resolution in this case. As an
example, the two formulas 2.0 + 7 and 2.000000001 + 7 aren't the same, but
they are extremely close. So my question is, could a regular expression
account for this? Likewise, would a regular expression be the best
approach?

Wednesday, 25 September 2013

Wrong assembly version brought with dependency

Wrong assembly version brought with dependency

I have an assembly_A that depends on *some_framework* v2.1 from NuGet.
Then I have some assembly_B that depends on assembly_A, but when I compile
the solution, it's the version 2.0 - not 2.1 of *some_framework* that is
brought with assembly_B.
My guess is that the build has chosen v2.0 because that's the version in
my GAC, but I need v2.1... No other dependency uses *some_framework*.
Obvious bypass would be to make assembly_B depend on *some_framework* v2.1
through NuGet, but that's not very elegant!
Any thoughts?
Thanks

Thursday, 19 September 2013

Views stacking over each other?

Views stacking over each other?

I'm currently using the ECSlidingViewControllersample and I'm having a
small bug while opening the same view I'm currently in.
For Example if I'm inside GudjonDaneil and I open the "drawer" and hit
GudjonDaniel again the viewDidLoad method calls twice, If I open it again
it calls the viewDidLoad 3 times in a row. It seems like the views are
stacking above each other. I need someway of killing the class(view) once
I open the view again.
Here's what happens once you click on the -UItableView
NSLog(@"Channel 1 Loading");
tableViewCellLoading = true;
[self.slidingViewController anchorTopViewOffScreenTo:ECRight
animations:nil onComplete:^{
CGRect frame =
self.slidingViewController.topViewController.view.frame;
self.slidingViewController.topViewController =
[self.storyboard
instantiateViewControllerWithIdentifier:@"firstChannel"];
self.slidingViewController.topViewController.view.frame = frame;
[self.slidingViewController resetTopView];
[tableView deselectRowAtIndexPath:indexPath animated:YES]; }];
How the drawer application looks like
http://gyazo.com/f811283fadbad5b50ee4d594b6798f18

Setting Redis To Go Up On Heroku

Setting Redis To Go Up On Heroku

On the Redis To Go page for my Heroku app it says: Unable to connect to
instance
I have checked the environment variables via the Terminal and I see that
the Redis To Go EV is the same there as described by the Redis To Go page
on Heroku.
Does anyone have any experience on getting Redis To Go for Python apps on
Heroku to work?
By the way I am on the free Heroku section, and Redis To Go Nano section,
if that makes any difference in setting it up.
Thanks in advance.

Comparison of two strings in C++

Comparison of two strings in C++

When I attempt to compare two strings in C++ (one read in from a file, the
other assigned a value), I get an incorrect output:
ifstream pgmFile;
pgmFile.open(fileName);
string temp;
string comp = "P5";
for(int i = 0; i < 2; i++)
{
pgmFile >> noskipws >> temp;
cout << temp;
}
if(temp == comp)
{}
else
cout << "File does not contain 'P5'. Please provide the correct type
of file." << endl;
In theory this SHOULD return "true" that these two strings are correct.
The output for temp = "P5", so I don't understand why it hits my else case
every single time. Any help is much appreciated thanks!

Comment on a closed issue or open a new issue?

Comment on a closed issue or open a new issue?

If I want to re-open discussion of a closed issue on a github repository
because the original discussion did not address a particular detail of the
named issue; should I open a new issue or just comment on the closed
issue?
It does not appear that as a third party to the original thread that I am
capable of officially re-opening the issue...

Changing UILabel font

Changing UILabel font

Say I have three UILabels.
I create a font and assign that font to all three labels.
Now I edit this font's type/size etc and expect the fonts of those labels
to change too, which does not happen. I basically need to apply a single
font to multiple labels and I know this can be done with an outlet
collection but i'd just like some help in understanding the flaw in my
logic here so here's my code...
self.labelFont = [UIFont fontWithName:@"System" size:12];
self.label1.font = self.labelFont;
self.label2.font = self.labelFont;
self.label3.font = self.labelFont;
self.labelFont = [UIFont fontWithName:@"Courier" size:30];
Thank

Access Android "Google Settings" app programmatically

Access Android "Google Settings" app programmatically

Is there a way to programmatically check if Remotely locate this device
and Allow remote lock and factory reset settings are enabled?
I believe it is from com.google.android.gms.common.settings Activity.
Unfortunately I couldn't find any information about accessing their
settings here - http://developer.android.com/reference/gms-packages.html

Wednesday, 18 September 2013

Why we use maven in our project

Why we use maven in our project

Why we use maven in spring projects? I searched it in internet but cant
understand what is its usage. I cant understand 'dependancy' and POM.
Please help

Segmentation fault when printing out arrays

Segmentation fault when printing out arrays

this is part of the program i am working on, it is copying the file opened
and then put it into an array (file1). However, I am getting a
segmentation when i try to print out the content of the file1. I had tried
to set the MAX_MAC_ADD to 50 and BIG_NUM to 30000 such that it is big
enough to sustain the file from fgets()
char file1[MAX_MAC_ADD][BIG_NUM];
int num_MAC = 0;
char *Programe_Name;
int saperate_fields1(char line[])
{
int i = 0;
int f = 0;
while(line[i] != '\0' && line[i] != '\n')
{
int c = 0;
while(line[i] != '\t' && line[i] != '\0' && line[i] != '\n')
{
file1[f][c] = line[i];
++c;
++i;
}
file1[f][c] = '\0';
++f;
if(f == (MAX_MAC_ADD-1))
{
break;
}
++i;
}
return f,i;
}
void read_file1(char filename[])
{
//OPEN FOR READING
FILE *fp = fopen(filename,"r");
if(fp == NULL)
{
printf("%s: cannot open '%s'\n", Programe_Name, filename);
exit(EXIT_FAILURE);
}
char line[BUFSIZ];
while(fgets(line, sizeof line, fp) != NULL)
{
saperate_fields1(line); //SAPERATE INTO FIELDS
num_MAC = num_MAC + 1;
printf("%d times\n", num_MAC);
}
fclose(fp);
printf("line is:\n%s\n", line); //TO CHECK WHERE DO THE PROGRAM STOP READING
printf("file1 is:\n%s\n", file1);
}

Nodejs, keep socket io connection alive in MongoStore

Nodejs, keep socket io connection alive in MongoStore

In a nodejs-express app, in the server.js file I set the socket-io
connection. It works fine doing something like this
var server = require('http').createServer(app)
var io = require('socket.io').listen(server);
io.sockets.on('connection', function (socket) {
// how can I save globally this 'socket'?
});
I would like to save this 'socket' globally in the server.js file and so,
be able to use it everywhere in the project. Like this:
app.get('/on', function(req, res){
socket.on('test', function (data) {
console.log(data);
});
});
app.get('/emit', function(req, res){
socket.emit('test', "ciao");
});
I red there is a way to do it saving the 'socket' connection in session.
My sessions settings:
app.configure(function(){
// ....
app.use(express.cookieParser(SITE_SECRET));
app.use(express.session({
secret :
,store : new MongoStore({
mongoose_connection : mongoose.connection
,db: mongoose.connections[0].db
})
,cookie: { maxAge: new Date(Date.now() + (1000*60*60*24*30*12)) }
}));
...
});
What is a good way to do it?

regular expression replacement of numbers

regular expression replacement of numbers

Using regular expression how do I replace 1,186.55 with 1186.55?
My search string is
\b[1-9],[0-9][0-9][0-9].[0-9][0-9]
which works fine. I just can't seem to get the replacement part to work.

Ordering of transparent ParticleSystem with BufferGeometry in Threejs

Ordering of transparent ParticleSystem with BufferGeometry in Threejs

Related to this question : Z-buffer issue with BufferGeometry in
ParticleSystem
The given solution does not work for me, I made my own shader for
rendering as I added custom attributes for size and UV. Everythinf works
fine with the buffer geometry except the particle ordering for
transparency.
If Activated > squared texture are partly hiding the other particles.
If Deactivated (depthTest : false) > particles looks fine but are not
ordered.
Thanks for your answer, the subject has been raised several times but
nothing worked for me yet.
particleMaterial = new THREE.ShaderMaterial({
fragmentShader :
document.getElementById("sectorPointFragment").textContent,
vertexShader :
document.getElementById("sectorPointVertex").textContent,
uniforms : uniforms,
attributes : attributes,
transparent : true,
alphaTest : 0.5
});
_this.particles = new THREE.ParticleSystem(geometry,
particleMaterial);
_this.particles.sortParticles = true;

calculate the sum of two columns kategory

calculate the sum of two columns kategory

I Have 2 tables :
1. Table Master(Vehicle,Vehicle_Color) :
Vehicle Vehicle_Color
---------------------------
Car Black
Car Yellow
Car White
Car Orange
motorcyle Black
motorcyle Yellow
motorcyle White
motorcyle Orange
2. Table Data(Name,Vehicle,Vehicle_Color) :
Name Vehicle Vehicle_Color
-----------------------------------
Ony motorcycle white
Galih motorcycle white
Zening motorcycle black
Lia motorcycle yellow
Tika motorcycle yellow
Fredy car black
Kenzy car white
Arka car white
Nugraha car white
I want to select vehicle , vehicle_color and count the number of vehicles
and the color
query select vehicle,vehicle_color,(.....) as number from Master left join
data on .... result like this
Vehicle Vehicle_Color Number
--------------------------------------
Car Black 1
Car Yellow 0
Car White 3
Car Orange 0
motorcyle Black 1
motorcyle Yellow 2
motorcyle White 2
motorcyle Orange 0
is there any suggestion, to create query? Tq..

Jboss 7.1 EJB3 with Apache FTPClient

Jboss 7.1 EJB3 with Apache FTPClient

I have deployed EJB3 with Apache FTPClient File upload in Jboss 7 its
working fine,
But the same code is not working in Jboss 7.1, I am not getting exception
from application, but its hanging while enter into FTP Part. Finally
getting following error in Jboss console.
[com.arjuna.ats.arjuna] (Transaction Reaper) ARJUNA012117:
TransactionReaper::check timeout for TX
0:ffff0a00000a:19692d93:52396a3c:6c in state RUN
13:06:34,848 WARN [com.arjuna.ats.arjuna] (Transaction Reaper Worker 0)
ARJUNA012095: Abort of action id 0:ffff0a00000a:19692d93:52396a3c:6c
invoked while multiple threads active within it.
13:06:34,848 WARN [com.arjuna.ats.arjuna] (Transaction Reaper Worker 0)
ARJUNA012108: CheckedAction::check - atomic action
0:ffff0a00000a:19692d93:52396a3c:6c aborting with 1 threads active!
13:06:34,878 WARN [com.arjuna.ats.arjuna] (Transaction Reaper Worker 0)
ARJUNA012121: TransactionReaper::doCancellations worker Thread[Transaction
Reaper Worker 0,5,main] successfully canceled TX
0:ffff0a00000a:19692d93:52396a3c:6c
How we can do FtpClient in Jboss 7.1 EJB3, please share your ideas.
Application Flow ------>Stateless Session Bean ----------> DAO class
--------->FTPClient.
Thanks and Regards
J Babu
babuj03@gmail.com

How to open a document located at remote server from web root of another server in PHP?

How to open a document located at remote server from web root of another
server in PHP?

cdsapplication is folder name inside htdocs.
localhost/cdsapplication/itemslist.php?showmaster=Product_list&PARENT_ID=2
This PHP page contains a link like this
<a href="\\srv01\CDS\ITEMS\ITEMLIST.xls" target="_blank">document</a>
ITEMLIST.xls document is available at srv01 server(srv01 and localhost are
two different servers). When I click on document link the url becomes like
this
http://localhost/cdsapplication/\\srv01\CDS\ITEMS\ITEMLIST.xls
But requirement is, when user clicks document link the url should be
\\srv01\CDS\ITEMS\ITEMLIST.xls
I mean open remote server document location from web root of another php
server.

Tuesday, 17 September 2013

Clickevent on a firefox plugin/addon

Clickevent on a firefox plugin/addon

I want to check the functionality of an add-on through automation, I am
not able to click on an add-on bar . Is there any way to do that ?

How to check the error messge of failed job in Redis queue?

How to check the error messge of failed job in Redis queue?

I want to get the information showing why my jobs in redis queue failed.
Does anybody has a method other than the one in (Inspect and retry resque
jobs via redis-cli)?

How display public google calendar in android app?

How display public google calendar in android app?

Is there some library that permits to display a public google calendar in
android app?

mongoid has_many belongs_to controller test not passing

mongoid has_many belongs_to controller test not passing

I'm having trouble getting my controller to set a has_many/belongs_to
association. I'm using mongodb with mongoid and I am totally new to it, so
perhaps I'm missing something related to that? I normally have no problem
getting this to work with relational databases.
Models:
class User
include Mongoid::Document
include Mongoid::Timestamps::Created
include Mongoid::Timestamps::Created
field :team_id
belongs_to :team, inverse_of: :user
end
class Team
include Mongoid::Document
include Mongoid::Timestamps::Created
include Mongoid::Timestamps::Created
field :name
field :slug
field :description
embeds_one :leader, class_name: 'User'
field :holiday_days_per_year, type: Integer
field :hours_per_day, type: Integer
field :organisation_id, type: Integer
has_many :users, inverse_of: :team
def users=(user_ids)
self.users.clear
user_ids.each do |id|
self.users << User.find(id)
end
end
end
controller:
class TeamsController < ApplicationController
def create
@team = Team.new(team_params)
if @team.save
render json: @team, status: :created, location: @team
else
render json: @team.errors, status: :unprocessable_entity
end
end
private
def team_params
params.permit(:name, :holiday_days_per_year, :hours_per_day, :leader,
:users => [])
end
end
This test always fails because team.users is empty.
require 'spec_helper'
describe TeamsController do
let(:user) { create :user }
let(:valid_attributes){ { "name" => "MyString", "hours_per_day" => 5,
"holiday_days_per_year" => 2, "users" => [user.id]} }
let(:valid_session) { {} }
describe "GET index" do
it "assigns all teams as @teams" do
team = Team.create! valid_attributes
get :index, {}, valid_session
assigns(:teams).should eq([team])
end
end
end
However this model spec passes fine:
require 'spec_helper'
describe Team do
let(:team){ Team.create name: 'my cool team', holiday_days_per_year: 1,
hours_per_day: 1 }
let(:user){ create :user }
it "can assign users" do
team.users = [user.id]
expect(team.users).to eq [user]
end
end

how to horizontally align 3 subviews of a UIView with NSLayoutConstraint visual format

how to horizontally align 3 subviews of a UIView with NSLayoutConstraint
visual format

I have the following setup:
A UIView with size (40,40)
3 subviews of this view, each with frames (0,0,40,40)
Now I'd like for this setup to have the following constraint hold at all
times:
H:|-10-[v1]-10-[v2]-10-[v3]-10-|
Which implies the following desired behavior throughout the lifecycle of
the superview:
Immediately after setting the constraints, the views should autolayout as
shown above.
Since the superview itself is only (40,40), it should automatically resize
to make the layout possible.
From there onwards, changing the width of any of the subviews should
layout the views again so that they still stick to the layout format.
My approach so far is like so:
- (id)init
{
self = [super initWithFrame:CGRectMake(0, 0, 40, 40)];
if (self) {
self.autoresizingMask = UIViewAutoresizingFlexibleWidth |
UIViewAutoresizingFlexibleHeight;
self.v1 = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 40, 40)];
self.v2 = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 40, 40)];
self.v3 = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 40, 40)];
[self addSubview:self.v1];
[self addSubview:self.v2];
[self addSubview:self.v3];
NSDictionary *views = @{@"v1" : self.v1, @"v2" : self.v2, @"v3" :
self.v3};
[self addConstraints:[NSLayoutConstraint
constraintsWithVisualFormat:@"H:|-10-[v1]-10-[v2]-10-[v3]-10-|"
options:0 metrics:@{@"10":@10} views:views]];
[self layoutIfNeeded];
}
}
but I get the conflicting constraints message:
(
"<NSLayoutConstraint:0xed9f040 H:|-(10)-[UIView:0xed9ad30] (Names:
'|':MyView:0xed9a040 )>",
"<NSLayoutConstraint:0xed9f270
H:[UIView:0xed9ad30]-(10)-[UIView:0xed9c370]>",
"<NSAutoresizingMaskLayoutConstraint:0xeda3770 h=&&& v=-&-
UIView:0xed9c370.midX == 0.5*MyView:0xed9a040.width>",
"<NSAutoresizingMaskLayoutConstraint:0xeda37a0 h=&&& v=-&-
UIView:0xed9c370.width == MyView:0xed9a040.width>"
)
Will attempt to recover by breaking constraint
<NSLayoutConstraint:0xed9f270 H:[UIView:0xed9ad30]-(10)-[UIView:0xed9c370]>
My guess is that it has to do with the superview not being able to resize.
But I'm overall somewhat confused about it. Does anyone know what am I
doing wrong?

Sunday, 15 September 2013

how to convert bytes to binary in C language

how to convert bytes to binary in C language

I need to convert bytes into binary, I have a couple of functions which
will output the byte representation of a file. Does anybody know how to do
this effeciently? I know of several code extensive methods but I'm curious
to see the ideas people here come up with.
I have this function which create a byte dump file:
void bindump(char *infile, char *outfile, int line_length, int size) {
FILE *in, *out;
int c;
int i, j;
char patterns[256][9];
for (i = 0; i < 256; i++) {
for (j = 0; j < 8; j++) {
patterns[i][j] = ((i>>(7-j))&1)+'0';
}
patterns[i][8] = '\0';
}
if (line_length % 8 != 0)
errx(1, "Line length %d is not a multiple of 8\n", line_length);
line_length /= 8;
if ((in = fopen(infile, "r")) == NULL)
err(1, "could not open %s for reading", infile);
if ((out = fopen(outfile, "w")) == NULL)
err(1, "could not open %s for writing", outfile);
i = 0;
while (1) {
c = fgetc(in);
if (feof(in)) break;
if (ferror(in))
err(1, "error reading from %s", infile);
if (fputs(patterns[c], out) == EOF)
err(1, "error writing to %s", outfile);
if ((++i) % line_length == 0) {
if (fputc('\n', out) == EOF)
err(1, "error writing to %s", outfile);
}
}
if (i % line_length != 0) {
if (fputc('\n', out) == EOF)
err(1, "error writing to %s", outfile);
warn("file length not multiple of line length (%d bits)", line_length*8);
}
if (size != 0) {
int remaining = size-i/line_length;
if (remaining < 0)
errx(1, "too long file, length is %d\n", i/line_length);
if (remaining > 0) {
for (i = 0; i < remaining; i++) {
for (j = 0; j < line_length; j++)
fputs("00000000", out);
fputc('\n', out);
}
}
}
fclose(in);
fclose(out);
}
which is tested by function main:
int main(int argc, char **argv)
{
int size;
if (argc < 4) {
fprintf(stderr,
"usage: %s INFILE OUTFILE LINE-LENGTH [SIZE]\n"
"Writes each bit from INFILE as ASCII '1' or '0' in OUTFILE,\n"
"with a newline after every LINE-LENGTH bits.\n",
argv[0]);
return 1;
}
size = (argc == 4) ? 0 : atoi(argv[4]);
bindump(argv[1], argv[2], atoi(argv[3]), size);
}
You need these header files to run this:
#include <stdio.h>
#include <err.h>
#include <stdlib.h>
To compile this program you need gcc and the input file, output file,
length of line, and size must be entered at the command line:
gcc main.c
./a [inputfile.txt] [outputfile.txt] [line length] [size]

Python--Finding Parent Keys for a specific value in a nested dictionary

Python--Finding Parent Keys for a specific value in a nested dictionary

I am struggling to process a nested dictionary, and return the nested
Parent Keys, for a specific Value, when the Value may exist more than once
in the nested dictionary. For example:
example_dict = { 'key1' : 'value1', 'key2' : 'value2', 'key3' : { 'key3a':
'value3a' }, 'key4' : { 'key4a': { 'key4aa': 'value4aa', 'key4ab':
'value4ab', 'key4ac': 'value1'}, 'key4b': 'value4b'} }
You will notice that 'value1' appears twice in the above dictionary, and I
would like to create a function that returns either a single list, or a
series of lists, that identify the different Parent Keys, which in this
case would be 'key1' and ('key4', 'key4a', key4ac).
This type of problem was dealt with elsewhere on this site, when the Value
one was looking for only appeared once, and was readily handled by the
following recursive function:
def find_key(d,key): for k,v in d.items(): if isinstance(v,dict): p =
find_key(v,key) if p: return [k] + p elif v == key: return [k]
print find_key(example_dict,'value4ac').
If you run the above code on the dictionary, I only get one answer for the
parent keys. Any help would be much appreciated, Thanks!

Determine the asymptotic complexity

Determine the asymptotic complexity

If I'm given two functions and asked to find asymptotic complexity for
both, what does that mean? Is it O() or Big Theta? For example f1(n)=a^n
and f2(n)=n^3+n^2
Should I say that f1 is O(a^n) and f2 is O(n^3) or should I use big-theta?

Anonymous Types in C#

Anonymous Types in C#

// x is compiled as an int
var x = 10;
// y is compiled as a string
var y = "Hello";
// z is compiled as int[]
var z = new[] { 0, 1, 2 };
but
// ano is compiled as an anonymous type
var ano = new { x1 = 10, y1 = "Hello" };
ano object's properties created are read-only . I want to figure it out
why those properties are read only. suggestions appreciated ?

How to instantiate Main Window Form Correctly?

How to instantiate Main Window Form Correctly?

I'm trying to make instance of the Main Form1 but I don't know clearly
where/how to do it.
in Main Program entry point there is Application.Run(new
ProgramTalking()); do I replace it with Form1 MyMainForm = new Form1();
MyMainForm.Show(); ?
I'm kinda lost in how to correctly instantiate and where to do it. For
example I can instantiate my second Form2 and store it in memory but first
Form1 just runs and I cant have any access to it from Form2 despite
setting fields and properties to public. However I can effortlessly access
Form2 from my From1. Thank you for any help.

Execute PHP script in same page

Execute PHP script in same page

I'm having a very annoying issue and I have no idea what I'm doing wrong.
It has (again) something to do with loading in a page into a DIV.
I have made a form which can be used to update information into a
database. This form and PHP code is in one file and is being loaded in one
DIV. When I visit the page which is loaded into the DIV itself, everything
is working fine and the database is being updates as it should.
Though, when the page is loaded into the page. When I press submit nothing
happens. What I want to happen is that the echo, which is either
"Success!" or "Error!" is being displayed in the same DIV as the page is
loaded into. This is my code, I hope someone can help! some variables are
in Dutch, excuse me for that.
if(isset($_POST['submit'])) {
include "database.php";
session_start();
$id = $_POST['id'];
$titel = $_POST['titel'];
$text = $_POST['text'];
$categorie = $_POST['categorie'];
$auteur = $_SESSION['sess_loginnaam'];
$laatst_aangepast = date("Y-m-d H:i:s");
$sql="UPDATE paginas SET id='$id', titel='$titel',
text='$text', categorie='$categorie',
auteur='$auteur',
laatst_aangepast='$laatst_aangepast' WHERE id='$id'";
$result=mysql_query($sql);
if($result){
echo "Success!";
?>
<META HTTP-EQUIV="refresh" content="2;URL=index.php">
<?php }
else {
echo "Mislukt!";
}
}
else {
include "database.php";
$id = $_GET['id'];
$sql="SELECT * FROM paginas WHERE id='$id'";
$result=mysql_query($sql);
$rows=mysql_fetch_array($result);
<form name="form1" method="post" action="">
ID:
<input name="id" type="text" id="id" value="<? echo
$rows['ID']; ?>" size="2"></div> Titel:
<input name="titel" type="text" id="titel" value="<?
echo $rows['titel']; ?>" size="50%"> Categorie:
<select name="categorie"><option
value="Paginas">Pagina's</option>
</select>
Tekst:
<textarea name="text" type="text" id="text" rows="31"
cols="79"><? echo $rows['text']; ?
></textarea>
<button type="submit" name="submit">Edit!</button>
</form>
And here is the code I use to load this page into the DIV:
$("#edit").on('click',function(){
$('#content').load($(this).attr('href'));
});
So how can I manage to display the echo into the same DIV? :)

Concatenate two PCRE regex, one with unicode characters

Concatenate two PCRE regex, one with unicode characters

I want to write a regex for phone numbers. The first pattern uses english
numbers and the second uses persian numbers. How do concatenate these
patterns using |?
$pattern1 = '/^(\d{4})?\s?[1-9]{1}[0-9]{6}$/';
$pattern2 =
'/^([\x{0660}-\x{0669}]{4})?\s?[\x{0661}-\x{0669}]{1}[\x{0660}-\x{0669}]{6}$/u';
This doesn't work:
if (preg_match("($pattern1)|($pattern2)", $phone_number))...
And prints this warning:
Warning: preg_match(): Unknown modifier '|'
I'm also not sure whether the /u delimiter should be placed at the end of
second pattern and each subpattern(pattern1 and pattern2) should have
their delimiters OR whole concatenated pattarn should have only one
delimiter(e.g/pattern1|pattern2/u)

Saturday, 14 September 2013

Any Settings for the update the android app

Any Settings for the update the android app

I have upload a application few days back, Now I want to update the
application. Is there any settings I need to set in the application, users
which have application on their device, once i upload the updated version
then how they will receive the "Update Available".
Please help me. I never did this.

Is my Java program efficent and does it look clean and clear?

Is my Java program efficent and does it look clean and clear?

I made a java program that asks for a word, then a screen width, then
whether you want it to go fast or slow. Then it outputs that word and
bounces it across the screen. Is this code efficent for what it does? Is
there a better way to do it (without a pre-defined method/class)? And does
it look proffesional and easy to read?
/*
This program was designed for use with command prompt on an ASCII
character set. Output is run through CMD.
This was designed for CMD with only an 80 ASCII character width.
str1 is the string containing the spaces.
str2 is the string containing the input word.
*/
import java.util.Scanner;
class Wave6 {
//Causes the output to lag for a set amount.
public static void xwait(long L) {
for(long c=0; c<L; c++);
}
//Asks for a string to "bounce" across the screen.
public static String input_string(char chr, String str2)
throws java.io.IOException {
do {
System.out.print("\n"
+ "What word do you what to input? \n"
+ "Must be less than 81 characters: ");
/*
Reads a list of characters and
inputs it into a string (to allow
for spaces and other non-letter chars).
*/
do {
chr = (char) System.in.read();
if(chr != '\n') str2 += chr;
} while(chr != '\n');
//Checks if the string is in the acceptable range.
} while((str2.length() < 1) | (str2.length() > 80));
return str2;
}
//Asks for a screen width (this is arbitrary).
public static int input_width(int width, String str2){
Scanner input = new Scanner(System.in);
do {
System.out.print("\n"
+ "What is the width of the screen? \n"
+ "Must be less than 81, and more than " +
str2.length() + " characters: ");
width = input.nextInt();
} while((width <= str2.length() ) | (width >= 81));
return width;
}
//Asks if the user wants the program to run
//at full speed, or slower.
public static long input_speed(char ch, char ign, long L)
throws java.io.IOException {
do {
System.out.print("\n
+ "Do you want it slow or fast? \n"
+ "S or F: ");
ch = (char) System.in.read();
//Gets rid of unwanted chars in
//the char buffer.
do {
ign = (char) System.in.read();
} while(ign != '\n');
//checks if ch == F or S
} while( !(ch == ('F')) ^ (ch == ('S')) );
//Returns a large or small number
//to slow down the program, or not.
L = 0;
if(ch == 'S')
L = 25550000L;
else if(ch == 'F')
L = 0;
return L;
}
public static void main(String args[])
throws java.io.IOException {
String str1 = "", str2 = "";
int width = 0, i;
char ch = '\0', chr = '\0', ign = '\0';
long L = 0L;
str2 = input_string(chr, str2);
width = input_width(width, str2);
L = input_speed(ch, ign, L);
/*
Part of the program that actually makes the word
bounce around.
*/
for(;;) {
for(;;) { //Right bound
/*
If the two strings added length is equal to the
Input width +1, do not output a character return.
This is the end of the right bound, break out
of the infinite loop.
Based on the code, between the conversion from
right bound to left bound, str1 has to equal width.
Otherwise the word only goes to the width -1 space.
So str1 + str2 must equal width +1
*/
if( width + 1 == (str1.length() + str2.length()) ) {
System.out.print(str1 + str2);
xwait(L);
break;
}
else {
System.out.println(str1 + str2);
xwait(L);
}
//If the two strings are not equal to width +1
//add one space to str1
if(width + 1 != ( str1.length() + str2.length()) )
str1 += " ";
}
for(;;) { //Left bound
/*
Right bound handles the code when str1 and str2
are equal to width +1, so left bound doesn't have to.
Similarly Right bound handles the output for when
str1 equals 0, but left bound makes it equal to 0.
*/
if( width + 1 != (str1.length() + str2.length()) ) {
System.out.println(str1 + str2);
xwait(L);
}
//Take a space off of str1.
str1 = str1.substring(0, str1.lastIndexOf(" "));
if(str1.length() == 0)
break;
}
}
}
}
Also, I use n++, and i have my tab set to two ASCII character widths, so
when I copied and pasted all of it was set to four spaces, is there an
easy way to copy it without having to go back and delete all of the tabs
and replace them with spaces, it takes forever. (this isn't important to
me, but it is a hassle when trying to ask questions about code on here)
Is there a way to convert a char with a number stored in it to an int? I
used the scanner nextInt but it failes when you type in a letter. But if i
could find a way (using the System.in.read()) I could make a do {} while
command to provide a check method for it.
This happened when I did this in Basic on my Ti 84, but what if I had made
an output_leftBound() and output_rightBound() method, used main to call
rightBound(), then had rightBound() and leftBound() call eachother? would
that be efficient or would it cause the memory to build up. On the
calculator, if you goto out of loops, the calculator builds up memory
because it reserved it to look for an END command to signal the end of a
loop, but it never finds one.
Note that I am an uneducated, beginner programmer, and I have only gotten
to page 201/600 in the book Java A Beginner's Guide (Fifth edition) And
sorry for the long post. by Herbert Schildt

Mysql Match Against & Like search

Mysql Match Against & Like search

SELECT * FROM `db`
WHERE MATCH (city) AGAINST ('south ban' IN BOOLEAN MODE)
SELECT * FROM 'db'
WHERE city LIKE '%south ban%'
I have 2 queries, one is use Match against, the other is LIKE,
When I try to search 'south bank'
Match wont return if user type south ban but Like will return the result
How can I improve Match against search?

Add class to accordion heading using angualr ui bootstrap?

Add class to accordion heading using angualr ui bootstrap?

I want use ng-class to conditionally add a class to the accordion-heading,
but it appears that not even setting a class explicitly on the element
gets preserved. I have this:
<div accordion close-others="true">
<div ng-repeat="currItem in items" accordion-group>
<div accordion-heading class="myClass">My Heading {{$index}}</div>
<div class="accordion-inner myClass">asdf asdf asdf</div>
</div>
</div>
And the fiddle: http://jsfiddle.net/Zmhx5/1/
When I inspect the accordion heading element, the class myClass is nowhere
to be found. Is there some reason I can't add classes to the accordion
heading?

change the base href in javascript:openwindow

change the base href in javascript:openwindow

I have link like that in content i get from remore site with file get content
javascript:openwindow("http://www.remotesite.com/index1.php?option=com_lsh&view=lsh&event_id=170119&tid=414745&channel=0&tmpl=component&layout=popup","730","770")
i want to change http://www.remotesite. com to mysite. com.

is String Manipulation considered as Encryption when submitting to Appstore

is String Manipulation considered as Encryption when submitting to Appstore

I need a way to protect the database bundled with the App. I do not want
to use standard encryption algorithms. Reason being the red tape needed to
get the app approved. Just simple string manipulation is fine for me. The
goal being to have a bar to throttle any casual data thieves and to not
have to carry the burden of red tape associated with standard encryption
algorithms. But the question is, will this be considered as encryption or
cryptography as per Apple's policies ?

how to create service groups in wso2 DSS server

how to create service groups in wso2 DSS server

I need to create a several services . I found we can create one query
service easily. how to create service groups in WSO2 DSS server?

Google ads in android app

Google ads in android app

I am working with adding Google ads in android apps... my code is as follows
adView = new AdView(this, AdSize.SMART_BANNER, "xxxxxxxxxx");
LinearLayout layout = (LinearLayout)findViewById(R.id.mainlayout);
layout.addView(adView);
AdRequest ads=new AdRequest();
ads.addTestDevice(AdRequest.TEST_EMULATOR);
adView.loadAd(ads);
all is working fine on emulator but doesn't show ads on my device please
suggest me what i'm doing wrong here

Friday, 13 September 2013

I'm getting a different value from what I expect when accessing to an object's property

I'm getting a different value from what I expect when accessing to an
object's property

I'm having a trouble with getting access to an object's property.
I'm able to get access to an object's property, but I get a different
value from what I expect.
This is the code I'm working on right now.
alertHeading.on('blur', function(){
var inputtedVal = $(this).val();
var key = alertMode.val();
chrome.runtime.getBackgroundPage(function(backgroundPage) {
var background = backgroundPage.background;
var alertObject = background.getStorage(key);
alertObject.heading="aaa";
alertObject.heading[0]="zero";
alertObject.heading[1]="one";
(1)This works fine.
console.log(alertObject); //outputs Object {heading: "aaa"}
(2)These don't work as I expect.
console.log(alertObject.heading[0]); // outputs a. I'm expecting
"zero".
console.log(alertObject.heading[1]); // outputs a. I'm expecting "one".
});
})
How am I able to get access the value I set in the line where I write "to
"alertObject.heading[0]"?
Please help me out to solve this problem. Thanks!

why is select much slower with left join+where

why is select much slower with left join+where

I am attempting to optimize a MySQL query that is taking a long time to
process. Imagine we have two tables, a users table and a purchases table.
Both tables have ~20,000 rows in them.
mysql> select NOW(),u.id from users u left join purchases p on p.user_id =
u.id where p.website_id = 1234 order by u.total_paid desc limit 10;
+---------------------+-------+
| NOW() | id |
+---------------------+-------+
*snip*
+---------------------+-------+
10 rows in set (0.06 sec)
Not super fast but pretty snappy. If I change nothing other than change
u.id to u.* it will slow down dramatically:
mysql> select NOW(),u.* from users u left join purchases p on p.user_id =
u.id where p.website_id = 1234 order by u.total_paid desc limit 10;
+---------------------+-------+
*snip*
+---------------------+-------+
10 rows in set (0.37 sec)
Before you say "Well, you should never use select *" consider that it
slowly creeps up to that length of time the more fields you add, i.e.
naming half of the fields to select will cause the query execute in ~0.20
seconds and no field on the users table is larger than a varchar(255).
However, if I take the ids from my relatively snappy query and I simply:
mysql> select * from users where id in (*snip*);
+---------------------+-------+
*snip*
+---------------------+-------+
10 rows in set (0.01 sec)
So my two queries: select u.id plus select u.* where id in is faster than
what I assume is a similar query. What the heck?

Dart, extending a class that has a mixin editor warnings?

Dart, extending a class that has a mixin editor warnings?

I have:
class Button extends Control with Tooltip{
//stuff
}
and:
class SimpleContextMenuButton extends Button{ //error on 'Button' -
classes can only extend other classes
//stuff
}
why is Dart Editor complaining about extending from Button?

DELETE IN with explode()

DELETE IN with explode()

Good afternoon,
I have a form that submits an array of transaction IDs to
$_POST['transid'] so those transaction records can be deleted. I typically
use mysqli_real_escape_string to help prevent attacks, but I am not sure
how to go about it with an array. The following is my query:
$query = 'DELETE FROM TRANSACTIONS WHERE (transid) IN
("'.implode('","',$_POST[transid]).'")'
...which gives me something like this:
$query = 'DELETE FROM TRANSACTIONS WHERE (transid) IN
("123","124","138","145")'
This seems to be asking for trouble. How can I protect myself from
disaster (malicious or otherwise)? Is there an efficient way to sanitize
the array? Or should I go about this another way?
Any thoughts or guidance would be appreciated.

Create an application that can contain other applications in iOS

Create an application that can contain other applications in iOS

I would like to know if it is possible to create an application in iOS,
downloadable from the Apple Store that works as a "Container" for other
apps downloaded from the Apple Store like the "Apple NewsStand" app.
Thanks
Sergio

Thursday, 12 September 2013

Repaint in AchartEngine

Repaint in AchartEngine

I am new to android. I am using AChartEngine to plot the frequency
spectrum from Accelerometer.
I understand that repaint(), refreshes the plot. I have an issue here.
When I do repaint, whole view i.e X-Axis, Y-Axis and The plot is getting
repainted. I am looking for a function or a command which only refreshes
the plot.
Also, When I repaint, it looks like the screen is flickering. I would like
to make the repaint operation smooth.
Please help.
Thanks Vivek

Python:Let Python int overflow like C int

Python:Let Python int overflow like C int

In Python, when a int bigger than 2**31, then it will turn to a long:
a = 2147483647 a + 1 = 2147483648
b = -2147483648 b - 1 = -2147483649
but I need the Python int overflow like the int in C:
a = 2147483647 a + 1 = -2147483648
b = -2147483648 b - 1 = 2147483647
Is it possible? thanks in advance!

Does Django 1.5 come with a default logout view?

Does Django 1.5 come with a default logout view?

Django seems to come with a prebuilt login view implementation:
url(r'^accounts/login/$', 'django.contrib.auth.views.login'),
which populates a template, by default located at registration/login.html.
Is there a symmetric implementation of logout? Can I write something like
url(r'^accounts/logout/$', 'django.contrib.auth.views.logout'),
and implement a template at registration/logout.html?

Do JUnit test suites support custom annotations?

Do JUnit test suites support custom annotations?

In JUnit, you can create test suites like so:
public class SecurityTest1 {
@Test
public void testSecurity1() {
// ...
}
}
public class LoadTest1 {
@Test
public void testLoad1() {
// ...
}
}
public class SecurityTest2 {
@Test
public void testSecurity2() {
// ...
}
}
@RunWith(Suite.class)
@SuiteClasses({SecurityTest1.class, SecurityTest2.class})
public class SecurityTestSuite {}
But this seems rather cumbersome. It would be so nice to define a simple
class-level annotation:
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface SecurityTest {}
And then define your suite like so:
@SecurityTest
public class SecurityTest1 {
@Test
public void testSecurity1() {
// ...
}
}
public class LoadTest1 {
@Test
public void testLoad1() {
// ...
}
}
@SecurityTest
public class SecurityTest2 {
@Test
public void testSecurity2() {
// ...
}
}
@RunWith(Suite.class)
@SuiteClasses({SecurityTest.class})
public class SecurityTestSuite {}
Is this possible? If so how? Note: not interested in switching to TestNG
or any other test framework if JUnit does not support this...thanks in
advance!

php sending email with the name in MX records and not with the hostname

php sending email with the name in MX records and not with the hostname

i just setup a mail server in the same server as my web server, in order
to send emails and not getting thrown in the Spam, i've configured a TXT
record for my SPF info and of course an MX record, the problem is when i
send an email it still classified as spam, and when i showed the original
message i found this :
Gmail : smtp.mail=root@nsxxxx.ovh.net
Hotmail : smtp.mailfrom=root@nsxxxx.ovh.net
i'de lik to now how can i send it with the name in my MX record, and how
to avoid spaming

Prevent video from pre-loading on website

Prevent video from pre-loading on website

I have the following code for a video on my website. I have the AutoPlay
turned off in order to prevent playback as soon as I open the website. The
problem is that the video still loads automatically and this hurts the
bandwidth of some visitors. What can I do to prevent the video from
loading until the user decides to play it?
<object width="530" height="405" scale="to fit" hspace="10" border="5">
<param name="VideoTitle" value="/urlpath/movie.m4v" />
<param name="AutoStart" value="False" />
<param name="ShowControls" value="True" />
<param name="ShowStatusBar" value="True" />
<param name="ShowDiplay" value="True" />
<param name="AutoRewind" value="True" />
<embed width="530" height="405" scale="tofit" hspace="0" filename=
"/urlpath/movie.m4v"
autostart="False" showcontrols="True" showstatusbar="True"
showdiplay="True"
autorewind="True" border="1" src="/urlpath/movie.m4v"></embed>
</object>
Thanks in advance.

Appending paragraphs to an image attribute in order? (1st to 1st, 2nd to 2nd ... nth to nth) JQUERY

Appending paragraphs to an image attribute in order? (1st to 1st, 2nd to
2nd ... nth to nth) JQUERY

I have made a division of paragraphs with information in each. I also have
a division of images.
My goal is to use jquery to append the text in each paragraph to an
attribute in each image called 'data-description'.
So the first paragraph put in the 'data-description' attribute for the
first image, and the second paragraph put in the 'data-description'
attribute for the second image, etc...
For instance this code will do it just for the first:
$('#galleria :first-child').attr('data-description', $('#descriptions
:first-child').text());
..given that the #galleria div contains the images, and the #descriptions
div contains the text.
I've attempted to use a variable which increases each time, or classes
which apply to each in sequence, or arrays, but I've had no joy.
I hope this explanation makes some sense!
I'd appreciate any thoughts, thanks.

Find the path of JSON for a key value

Find the path of JSON for a key value

jSon = {
"id":"node1",
"name":"Languages",
"rel":"",
"children":1,
"step":1,
"path":1,
"nodes":[
{
"id":"node2",
"name":"Java",
"rel":"Pure Object Oriented Prog",
"children":1,
"step":2,
"path":2,
"nodes":[
{
"id":"node3",
"name":"C#",
"rel":"Framework",
"children":0,
"step":3,
"path":3,
"nodes":[]
},{
"id":"node4",
"name":"C++",
"rel":"OOPS",
"children":0,
"step":3,
"path":4,
"nodes":[]
}]
}]
};
For above structure, how do I get path of id(key) = node3(value)
(i.e) jSon.nodes[0].nodes[1].id
So that i could able push new Object (i.e) jSon.nodes[0].nodes.push(newjSon);
Or is there any other way to add new object in particular position for
this structure... Please suggest some javascript code.. No jQuery

Wednesday, 11 September 2013

Time Series analysis with R, how to deal with daily data

Time Series analysis with R, how to deal with daily data

This might be a easy and dump question for some of you, but really
appreciate your help.
I try to convert a daily dataset to ts, but how do you deal with leap
year? so what value should I set the freq equal to?
ts(data,start=c(2010,1,1),frequency=365)?

Alternitive to constructor?

Alternitive to constructor?

I want to set the location of a form using:
this.Location = new Point(2908, 953);
in the constructor. The constructor seems to ignore it. I want it to go to
the location only once during the whole execution of the program and have
it do it right when the program starts.
What should I do?

C++ looping error

C++ looping error

well here is my code what I want it to do is ask the user if they want to
play. Then I want it to output options for the user to input then it
performs random numbers by dice by the number of sides the user inputted.
Then I want it to ask if they want to play again y restarts the program no
exits wit Thank you for playing".
The issue i am having is the first cycle of the program works as it should
but instead of it asking if you want to play again it is blank and if you
hit a number for the dice it will output how many sides the first dice had
no matter what is inputted.
#include <iostream>
#include <ctime>
using namespace std;
int throwDie(int Sides, int &throwResult)
{
throwResult = 1 + rand() % (Sides - 1 + 1);
return throwResult;
}
int main()
{
int dieTot = 0,
throwNumber = 0,
numberSides = 0,
throwResult = 0;
int die1 =4;
int die2 =6;
int die3 =8;
int die4 =10;
int die5 =12;
int die6 =20;
char rollAgain;
srand(unsigned(time(0) ));
START:
cout << "Do you want Play? ";
cin >> rollAgain;
cout << "How many sides? " << endl;
cout << "1 - 4 sided die\n";
cout << "2 - 6 sided die\n";
cout << "3 - 8 sided die\n";
cout << "4 - 10 sided die\n";
cout << "5 - 12 sided die\n";
cout << "6 - 20 sided die\n";
int choice;
cout << "Enter choice: ";
cin >> choice;
switch( choice )
{
case 1:
do
{
cout << "You have choosen a 4 sided die? " << endl;
int numberSides = die1;
cout << numberSides << "-sided die rolled for a value of " <<
throwDie(numberSides, throwResult) << "!" << endl;
dieTot = dieTot + throwResult;
throwNumber++;
cin >> numberSides;
} while (choice != numberSides );
goto START;
break;
case 2:
do
{
cout << "You have choosen a 6 sided die? " << endl;
int numberSides = die2;
cout << numberSides << "-sided die rolled for a value of " <<
throwDie(numberSides, throwResult) << "!" << endl;
dieTot = dieTot + throwResult;
throwNumber++;
cin >> numberSides;
cout << endl << "Total for " << throwNumber << " throws = " << dieTot
<< endl;
} while (choice != numberSides );
break;
case 3:
do
{
cout << "You have choosen a 8 sided die? " << endl;
int numberSides = die3;
cout << numberSides << "-sided die rolled for a value of " <<
throwDie(numberSides, throwResult) << "!" << endl;
dieTot = dieTot + throwResult;
throwNumber++;
cin >> numberSides;
cout << endl << "Total for " << throwNumber << " throws = " << dieTot
<< endl;
} while (choice != numberSides );
break;
case 4:
do
{
cout << "You have choosen a 10 sided die? " << endl;
int numberSides = die4;
cout << numberSides << "-sided die rolled for a value of " <<
throwDie(numberSides, throwResult) << "!" << endl;
dieTot = dieTot + throwResult;
throwNumber++;
cin >> numberSides;
cout << endl << "Total for " << throwNumber << " throws = " << dieTot
<< endl;
} while (choice != numberSides );
break;
case 5:
do
{
cout << "You have choosen a 12 sided die? " << endl;
int numberSides = die5;
cout << numberSides << "-sided die rolled for a value of " <<
throwDie(numberSides, throwResult) << "!" << endl;
dieTot = dieTot + throwResult;
throwNumber++;
cin >> numberSides;
cout << endl << "Total for " << throwNumber << " throws = " << dieTot
<< endl;
} while (choice != numberSides );
break;
case 6:
do
{
cout << "You have choosen a 20 sided die? " << endl;
int numberSides = die6;
cout << numberSides << "-sided die rolled for a value of " <<
throwDie(numberSides, throwResult) << "!" << endl;
dieTot = dieTot + throwResult;
throwNumber++;
cin >> numberSides;
cout << endl << "Total for " << throwNumber << " throws = " << dieTot
<< endl;
}
while (choice != numberSides );
break;
default:
cout << "Not a proper entry.\n";
break;
cout << endl << "Total for " << throwNumber << " throws = " << dieTot <<
endl;
return 0;
}}

Display an image on a Windows.Form from a SQL Database in VB 6

Display an image on a Windows.Form from a SQL Database in VB 6

I have some headshots in an ID Card database that I want to display in a
program I am writing in VB 2008. The following code is based off of a
support article from Microsoft, it can be found here and is specifically
from step '11'.
aiuQuery.CommandText = "select a.ImageData From Images a, Cardholders
b WHERE b.UserText6 = '" & _
empID & "' And a.CardholderID = b.CardholderID"
aiuReader = aiuQuery.ExecuteReader
If aiuReader.Read Then
Dim bytBLOBData(aiuReader.GetBytes(1, 0, Nothing, 0,
Integer.MaxValue) - 1) As Byte
aiuReader.GetBytes(1, 0, bytBLOBData, 0, bytBLOBData.Length)
Dim stmBLOBData As New MemoryStream(bytBLOBData)
pbHeadShot.Image = Image.FromStream(stmBLOBData)
End If
aiuReader.Close()
The first line inside the 'If' block (Dim bytBLOBData...) generates an
error claiming "Index was outside the bounds of the array."
The SQL is correct as tested outside of the program.
Any suggestions on what the cause of this error could be? A better way to
go about this?

Maven is over 100%! [downloading no-stop]

Maven is over 100%! [downloading no-stop]

I've imported a new project from our svn repo and maven started
downloading all the dependencies.
And keep downloading...
What should I do? Kill it or just wait? Is this "normal"?

Can I build semi-advanced reports using only MySQL queries?

Can I build semi-advanced reports using only MySQL queries?

I have a MySQL table whose structure and data looks something like this:
name | date | type | value
-----+------------+-------+------
foo | 2013-01-01 | blue | 4
foo | 2013-01-02 | green | 1
foo | 2013-01-01 | blue | 9
foo | 2013-01-02 | green | 5
bar | 2013-01-01 | blue | 10
bar | 2013-01-02 | green | 4
bar | 2013-01-01 | blue | 6
bar | 2013-01-02 | green | 2
meow | 2013-01-01 | blue | 5
meow | 2013-01-02 | green | 6
meow | 2013-01-01 | blue | 4
meow | 2013-01-02 | green | 4
I'm trying to construct a query that will produce this output:
name | blue | green
-----+------+------
foo | 13 | 6
bar | 16 | 6
meow | 9 | 10
The name column is maintained. The blue and green columns of the output
are generated based on the values of the type table column. The values of
those two columns are the accumulated value of the value table column for
all dates. I hope that made sense.
This is a bit out of my league when it comes to MySQL so I have no idea
where to start. Is this possible using MySQL, and if so, how? For
instance, how does one create output columns based on the values of a
single table column?

Proper syntax for "CASE WHEN ... THEN ... DELETE ... END" in SQLite triggers?

Proper syntax for "CASE WHEN ... THEN ... DELETE ... END" in SQLite triggers?

I'm trying to figure out how to put a delete statement inside a
conditional in an SQLite trigger.
I've come up with this code:
CREATE TRIGGER mytrigger
BEFORE INSERT ON mytable
BEGIN
SELECT CASE WHEN
1 == 1
THEN
DELETE FROM mytable
END;
END;
But it fails with:
Error: near "DELETE": syntax error
If I replace DELETE FROM mytable with RAISE(FAIL, "mytrigger was
activated"), it compiles fine.

Getting list out of python list of list

Getting list out of python list of list

I am using python list of list as follows,
List L = [ ['a',4] ['b',2] ,['c',13]]
I want to generate new List for all the number which are the position
second in each set of the list
New List L* = [ 4, 2, 13]
Is there any shortcut in python to get above L* list

Which one runs faster, ArrayList or LinkedList? [duplicate]

Which one runs faster, ArrayList or LinkedList? [duplicate]

This question already has an answer here:
When to use LinkedList<> over ArrayList<>? 24 answers
Performance differences between ArrayList and LinkedList 6 answers
List li = new LinkedList();
for (int i = 0; i < 100; i++) {
li.add(i);
}
long start1 = System.nanoTime();
li.get(57);
long end1 = System.nanoTime();
long diff1 = end1-start1;
System.out.println("Time taken by LinkedList = "+diff1);
List al = new ArrayList();
for (int i = 0; i < 100; i++) {
al.add(i);
}
long start2 = System.nanoTime();
al.get(57);
long end2 = System.nanoTime();
long diff2 = end2-start2;
System.out.println("Time taken ArrayList = "+diff2);
System.out.println((diff1<diff2)?"LinkedList runs faster":"ArrayList
runs faster");
}
What ever operations i perform on both the Lists, when i print out the
time taken, it is always ArrayList that runs faster. Can somebody explain
which performs better in terms of time taken? Also let me know if there is
something wrong in the code. Thanks!

Tuesday, 10 September 2013

Audio Comparison using Micorosft speech recognition engine

Audio Comparison using Micorosft speech recognition engine

I have an application in which user can speak and a word and he will be
given the percentage accuracy of the word he spoke. i.e how much clearly
the engine recognized the word.
This all works fine ,but i have a dilemma that what words needed to be
added to the dictionary which i will give to the recognition engine as
dictionary.
If i give words starting with "p" for case pen then words like pendant
,pent etc all will be added to the dictionary.In that case i am not
getting the recognized word as "pen".
Instead i always get other words like "pendant" etc
But if i only add limited words to dictionary like "pe","pen" then for the
same recorded file i got the recognized words as "Pen" only.
Means it clearly depends on the words which we give to the dictionary.
I have conveyed the same to my client.But what they want is that they can
speak wrong words also for a given input words ,so at that time they need
not want to get the accuracy and also get the recognized text.
I have done what i could have done for the issue.But my client needs
something apart from universe.
Do any experts have solution for this here? Any help will be appreciated.
Thanks

How to get "isDirty" flag in Epf (Ember Persistence Foundation) to reset after flush or refresh?

How to get "isDirty" flag in Epf (Ember Persistence Foundation) to reset
after flush or refresh?

I'm using Epf in a new project, and have set up my model as so:
Etst.Persona = Ep.Model.extend
name: Ep.attr 'string'
age: Ep.attr 'number'
favorite_food: Ep.attr 'string'
isClean: ( ->
! @get("isDirty")
).property("name", "age", "favorite_food")
I need the "isClean" rather than straight "isDirty" to make a disabled
button show up only when the model is dirty.
I find that when I change any field through an Ember.TextField it changes
perfectly.
However, I find that after I do either a call to flush() or refresh(), the
model in memory does NOT have its "isDirty" flag cleared, even though it's
been successfully saved or reloaded.
Thanks!

CollectionProxy returns nil when creating a new object

CollectionProxy returns nil when creating a new object

I have a model with a has_many relationship that's built through nested
forms:
class User < ActiveRecord::Base
has_many :properties
accepts_nested_attributes_for :properties, allow_destroy: true
def billing_address
debugger
properties.find_by(billing_address: true)
end
end
Overall, the relationship and nested form works. However, if I call the
method billing_address during creation, then it returns nil, even if there
is a nested property with billing_address set to true. I experimented with
this in debugger, and it seems that calling properties.find_by or
properties.where during creation always results in nil, even if the
parameters match a real object.
When I type properties into debugger, I get results like this, which
clearly show that there is a property with billing_address set to true:
#<ActiveRecord::Associations::CollectionProxy [#<User::Property id: nil,
address: "1111 E 1st", city: "Austin", state: "TX", zip_code: "11111",
phone_number: "11111111111", user_id: nil, primary: true, billing_address:
true, created_at: nil, updated_at: nil>]>
So why can't I find it with a query such as
properties.find_by(billing_address: true)? Is there another approach to
getting at this data?

Discarding transport error while using nodejs + socketio

Discarding transport error while using nodejs + socketio

I am building an android chat application. I am using nodejs at server end
and trying to implement android client for socketIO. First the client
echoes "hello" to the server and the server echoes it back to the client.
This works fine. Now there is a Button, which when pressed echoes the text
in the EditText to the server. Server is supposed to echo the text back to
the client. However, as soon as text is echoed to the server, I get
Discarding transport error at server end and nothing is echoed back.
Client is unable to echo anything further. What is wrong with the codes ?
Server
var http = require('http'),fs = require('fs');
var app = http.createServer(function (req, res) {
res.end();
}).listen(8000,
'127.0.0.1');
var io = require('socket.io').listen(app);
io.sockets.on('connection', function(socket) {
socket.on('echo', function(data) {
socket.emit('echoback', data);
});
});
Client
package com.jack.pri;
import java.net.MalformedURLException;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import io.socket.*;
public class MainActivity extends Activity {
private SocketIO socket;
private TextView tview;
private Button btn;
private EditText tt;
private String k;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tview=(TextView) findViewById(R.id.tv);
tt = (EditText) findViewById(R.id.et);
btn = (Button) findViewById(R.id.button1);
//socket = null;
try {
socket = new SocketIO("http://10.0.2.2:8000");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
socket.connect(new IOCallback() {
@Override
public void on(String event, IOAcknowledge ack, Object... args) {
if ("echoback".equals(event) && args.length > 0) {
tview.setText(""+args[0]);
Log.e("received",""+args[0]);
}
}
@Override
public void onMessage(JSONObject json, IOAcknowledge ack) {}
@Override
public void onMessage(String data, IOAcknowledge ack) {}
@Override
public void onError(SocketIOException socketIOException) {
socketIOException.printStackTrace();}
@Override
public void onDisconnect() {}
@Override
public void onConnect() {}
});
///
socket.emit("echo", "hello");
btn.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
k=tt.getText().toString();
socket.emit("echo", k);
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
Errorlog at server end
debug - client authorized
info - handshake authorized kaHbMG-lFmuFtvkFGY2W
debug - setting request GET /socket.io/1/websocket/kaHbMG-lFmuFtvkFGY2W
debug - set heartbeat interval for client kaHbMG-lFmuFtvkFGY2W
debug - client authorized for
debug - websocket writing 1::
debug - websocket writing 5:::{"name":"echoback","args":["hello"]}
debug - emitting heartbeat for client kaHbMG-lFmuFtvkFGY2W
debug - websocket writing 2::
debug - set heartbeat timeout for client kaHbMG-lFmuFtvkFGY2W
debug - got heartbeat packet
debug - cleared heartbeat timeout for client kaHbMG-lFmuFtvkFGY2W
debug - set heartbeat interval for client kaHbMG-lFmuFtvkFGY2W
debug - websocket writing 5:::{"name":"echoback","args":["this is textbox
input text"]}
info - transport end (undefined)
debug - set close timeout for client kaHbMG-lFmuFtvkFGY2W
debug - cleared close timeout for client kaHbMG-lFmuFtvkFGY2W
debug - cleared heartbeat interval for client kaHbMG-lFmuFtvkFGY2W
debug - discarding transport