Saturday, 31 August 2013

Difficulty with try and catch statements?

Difficulty with try and catch statements?

How in the world do I set a try and catch to stop the user from inputting
more than one decimal. Is it a try and catch? Or what exactly do i want to
do here? Very new to windows form applications....
Also somewthing to note... when I click the calculations the numbers
dissapear.. it doesn't continuously stay there. I thought that was odd.
Would anyone know why? For example if I hit 6 + 6 it shows "6" and then
another "6" and then 12, not a display of 6 + 6 = 12. I dont understand
that either
public partial class Form1 : Form
{
string c;
double num1;
double num2;
public Form1()
{
InitializeComponent();
}
private void button11_Click(object sender, EventArgs e)
{
textBox1.AppendText("0");
}
private void button1_Click(object sender, EventArgs e)
{
textBox1.AppendText("1");
}
private void button2_Click(object sender, EventArgs e)
{
textBox1.AppendText("2");
}
private void button5_Click(object sender, EventArgs e)
{
textBox1.AppendText("3");
}
private void button6_Click(object sender, EventArgs e)
{
textBox1.AppendText("4");
}
private void button7_Click(object sender, EventArgs e)
{
textBox1.AppendText("5");
}
private void button8_Click(object sender, EventArgs e)
{
textBox1.AppendText("6");
}
private void button15_Click(object sender, EventArgs e)
{
textBox1.AppendText("7");
}
private void button16_Click(object sender, EventArgs e)
{
textBox1.AppendText("8");
}
private void button17_Click(object sender, EventArgs e)
{
textBox1.AppendText("9");
}
private void button9_Click(object sender, EventArgs e)
{
textBox1.Clear();
}
private void button10_Click(object sender, EventArgs e)
{
textBox1.AppendText(".");
}
private void button3_Click(object sender, EventArgs e)
{
c = "+";
num1 = double.Parse(textBox1.Text);
textBox1.Text = string.Empty;
}
private void button12_Click(object sender, EventArgs e)
{
c = "-";
num1 = double.Parse(textBox1.Text);
textBox1.Text = string.Empty;
}
private void button13_Click(object sender, EventArgs e)
{
c = "*";
num1 = double.Parse(textBox1.Text);
textBox1.Text = string.Empty;
}
private void button14_Click(object sender, EventArgs e)
{
c = "/";
num1 = double.Parse(textBox1.Text);
textBox1.Text = string.Empty;
}
private void button4_Click(object sender, EventArgs e)
{
num2 = double.Parse(textBox1.Text);
double result;
if (c == "+")
{
result = num1 + num2;
textBox1.Text = result.ToString();
}
else if (c == "-")
{
result = num1 - num2;
textBox1.Text = result.ToString();
}
else if (c == "*")
{
result = num1 * num2;
textBox1.Text = result.ToString();
}
else if (c == "/")
{
result = num1 / num2;
textBox1.Text = result.ToString();
}
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void Form1_Load(object sender, EventArgs e)
{
}
}
}

How to understand "((size_t) &((TYPE *)0)->MEMBER)"?

How to understand "((size_t) &((TYPE *)0)->MEMBER)"?

the codes in linux-2.6.16/include/linux/stddef.h is:
#undef offsetof
#ifdef __compiler_offsetof
#define offsetof(TYPE,MEMBER) __compiler_offsetof(TYPE,MEMBER)
#else
#define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER)

Structural-type casting does not work with String?

Structural-type casting does not work with String?

Given these definitions:
type HasMkString = { def mkString(sep:String):String }
val name = "John"
val names = List("Peter", "Gabriel")
And given these facts:
name.mkString("-") // => "J-o-h-n"
name.isInstanceOf[HasMkString] // => true
names.isInstanceOf[HasMkString] // => true
While this works:
names.asInstanceOf[HasMkString].mkString("-")
// => Peter-Gabriel
This does not work:
name.asInstanceOf[HasMkString].mkString(", ")
java.lang.NoSuchMethodException: java.lang.String.mkString(java.lang.String)
at java.lang.Class.getMethod(Class.java:1624)
at .reflMethod$Method1(<console>:10)
at .<init>(<console>:10)
at .<clinit>(<console>:10)
at .<init>(<console>:7)
at .<clinit>(<console>)
at $print(<console>)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
Why is that? Is it because String is a Java class? Can I work around this
problem? Is this a bug/shortcoming in the Scala implementation?

Adding text to paragraph moves neighbor elements down

Adding text to paragraph moves neighbor elements down

When ever I add text that differs in size to one of my paragraph tags the
neighbor elements get pushed down and I can't figure out why.
Codepen: http://cdpn.io/bqJec

Creating multiple android publisher accounts

Creating multiple android publisher accounts

I am android apps publisher. I want to create separate accounts for
different category of applications e.g. ABCAndroidApps.com (for publishing
utilities) and XYZGames.com (for publishing games).
Will Google ban my accounts as I will create two different gmail accounts
for the same.
Can I use same credit/debit card for creating both the accounts.
Should I link both these accounts to one of the two admob accounts. Is it
OK for a person to keep two separate admob accounts.
I am asking this question to know if Google will ban my accounts in any
particular case. Anyone having practical experience with this scenario,
having already done this?

PHP - Generating several forms, but the forms only ever output the same thing for each form

PHP - Generating several forms, but the forms only ever output the same
thing for each form

Ok so I basically have generated a list of links that use forms to send a
variable to PHP that would allow me to load different things on the next
page from each link. However, each link seems to only request the same
data from the database each time
Here is the first page:

Friday, 30 August 2013

How to have a progress bar in jQuery.get()

How to have a progress bar in jQuery.get()

is it possible to have a progress bar measuring the jQuery.get() progress?

Wednesday, 28 August 2013

MySQL C++ Connector strange compile warning

MySQL C++ Connector strange compile warning

I have an application that uses the MySQL C++ Connector, version 1.1.3.
Everything works fine, but the compiler has been throwing an odd warning
that I can't seem to make go away:
sqlstring.h(38): warning C4251: 'sql::SQLString::realStr' : class
'std::basic_string<_Elem,_Traits,_Ax>' needs to have dll-interface to be
used by clients
of class 'sql::SQLString'
with
[
_Elem=char,
_Traits=std::char_traits<char>,
_Ax=std::allocator<char>
]
As I said, everything works fine, this warning is just bugging me. It
shows up in a lot of places in the Connector library. What is it and how
can I fix it?

PHP variable scoping

PHP variable scoping

I'm having some trouble with variable scoping in PHP. Here's the structure
of my code--
<?php
$loader = new ELLoad();
$sessionid = '';
$method = $_REQUEST['m'];
if (strcasecmp($method, "getfile") == 0) {
global $loader;
$loader->load($file['text']);
global $sessionid;
$sessionid = $loader->getSessionId();
}
if (strcasecmp($method, "extract") == 0) {
$extractor = new ELExtract();
global $sessionid;
$extractor->extract($sessionid); //$session id for some reason is
still ' ' here
}
The sequence of the requests from the client is always load followed by
extract. Can anyone tell me why my $sessionid variable may not be getting
updated right?

Modification in one MultiValueMap affecting another

Modification in one MultiValueMap affecting another

I have two MultiValueMap in my class
Those are MapA and MapB. Two maps are equal. I have iterate Using MapA and
Did some changes in MapB. But it is affecting the MapA. MapA is also
changing. Why it happens.

What is type system in C#? [on hold]

What is type system in C#? [on hold]

I was reading an article about "weakly typed" and "strongly typed". this
is a little part of that article: a more-strongly-typed language is one
that has some restriction in its type system that a more-weakly-typed
language it is being compared to lacks. I was wondering what's type
system?

How to get single index on multiple bar in a bar graph in android using acharengine

How to get single index on multiple bar in a bar graph in android using
acharengine

I am using achartengine for plotting bar graph in android. My requirement
is to get a list of customers onclick of bar in bar graph but i am having
three bars on the label of x-axis.When i click the bars ,i am getting
three different indexes instead of one on that label.I am using series
selection api suggested bay Dan. Thanks for any help in advance.

Tuesday, 27 August 2013

Handlebars.js template not transitioning properly with Ember.js

Handlebars.js template not transitioning properly with Ember.js

I am hoping that someone can help me out with this because it is driving
me to shout things at strangers.
*NOTE: I do have a JS Bin for this, but it is not completely operational
with FIXTURE data at the moment.
I am currently building a small web application leveraging ember.js and
handlebars.js - nothing crazy, just rendering a list of blog posts within
a handlebars template called 'blogs'. When the user clicks on the header,
it loads a blog detail template called 'blog'. This works fine - 'blogs'
is hidden and 'blog' is now rendered. As you can see from the first 2
screenshots, the posts are loaded, then blog details are shown.


Where things awry is when i attempt to click a link within template 'blog'
that takes me back to template 'blogs'. Instead of hiding template 'blog'
and showing template 'blogs' again, template 'blog stays in place with
template 'blogs' showing under template 'blog', as shown in this
screenshot:

Template 'blog' will then be displayed indefinitely regardless of what
links I click unless I refresh the browser.
Here is a little bit of code you may find useful:
GY.Router.map(function () {
this.route('blogs', { path: '/' });
this.route('blogs', { path: '/blog' });
this.route('blog', { path: '/blog/:blog_number' });
this.route('albums', { path: '/albums' });
});
I wanted the unique identifier for the blog post to be something other
than an integer like '#/blog/2', so I decided to use my model's
blog_number property, leaving me with something like this: '#/blog/eTWQFxc
To do this, I leveraged my blog route's serialize function:
GY.BlogsRoute = Ember.Route.extend({
model: function(){
return GY.BlogPost.find();
}
});
GY.BlogRoute = Ember.Route.extend({
serialize: function (model) {
return { blog_number: model.BlogNumber };
}
});
Here is the BlogPost model I defined - note that I reopen the class and
make a $.get call because I could not make a get work with Ember Data:
GY.BlogPost = DS.Model.extend({
Id: DS.attr('string'),
BlogNumber: DS.attr('string'),
Title: DS.attr('string'),
Description: DS.attr('string'),
Body: DS.attr('string'),
Comments: DS.hasMany('GY.Comment')
}).reopenClass({
find: function () {
var self = this;
var records = [];
$.get('/blog', function (data) {
if (data.BlogPosts) {
var posts = data.BlogPosts;
//load our model
posts.forEach(function (p) {
records.addObject(GY.BlogPost.createRecord(p))
}, this);
}
});
return records;
}
});

How to capture a specific value in Shell from a captured output variable?

How to capture a specific value in Shell from a captured output variable?

I wanted to find the highest value of "id" from the below output and then
get the associated "version" from it. Here is the response captured in a
variable. Greatly appreciate your help!
{"app_versions":[{"version":"16125","shortversion":"4.4.0","title":"App
1","timestamp":1377277516,"appsize":46110031,"mandatory":false,"minimum_os_version":"6.0","device_family":"iPhone/iPod","id":22,"app_id":25196,"download_url":"https://rink.hockeyapp.net/apps/b5dc72777668ca5716aa6aec8237058f/app_versions/22","status":2,"tags":["alpha"]},{"version":"16126","shortversion":"4.4.0","title":"App
1","timestamp":1377177516,"appsize":46330031,"mandatory":false,"minimum_os_version":"6.0","device_family":"iPhone/iPod","id":20,"app_id":25190,"download_url":"https://rink.hockeyapp.net/apps/b5dc72777668ca5716aa6aec8237058f/app_versions/20","status":2,"tags":["alpha"]}

Shortcode to display custom field of custom post type works only in some post types

Shortcode to display custom field of custom post type works only in some
post types

I created a shortcode to pull custom fields from a custom post type called
"room", by the post slug. The shortcode works fine within a different
custom post type, but doesn't return anything when used in the same custom
post type (room), or in normal posts/pages.
Interestingly, the fields for "title" and "link" display fine for all post
types. So, I believe the problem must be with my get_post_meta line.
If anyone could help me, I'd really appreciate it.
// Add shortcode for getting specific custom field from custom post type
add_shortcode('room-info', 'room_info_func');
function room_info_func($atts) {
extract(shortcode_atts(array(
'name' => null, 'field' => null,
), $atts));
$excerpt_post_name = $name;
$excerpt_field = $field;
// Get post ID from post slug
$args=array(
'name' => $excerpt_post_name,
'post_type' => 'room',
'post_status' => 'publish',
'showposts' => 1,
'caller_get_posts'=> 1
);
$my_posts = get_posts($args);
$excerpt_out = null; // Return empty if there's no post by that slug
if( $my_posts ) {
$id=$my_posts[0]->ID;
// Get custom field from post ID
$excerpt_out = get_post_meta($id, 'wpcf-'.$excerpt_field, $single=true);
}
switch ($field) {
case 'link': return $res=get_post_permalink($id); break;
case 'title': return $res=get_the_title($id); break;
case 'image-url': return
$res=wp_get_attachment_url(get_post_thumbnail_id($id)); break;
default: return $res="$excerpt_out"; break;
}
}

How to remove null character from file content in java

How to remove null character from file content in java

I receive an XML file from a client. I've another file containing Base-64
encoded data which I embed in one of the elements in XML file. After doing
all this merging, I need to return the content of file either as string or
a DOM object, returning as InputStream will not work.
But the resulting merged file has null character at the end which is
causing issues when file is processed as XML. How can I get rid of it.

Unicode characters in nginx fastcgi links

Unicode characters in nginx fastcgi links

I have a django project hosted over nginx with fastcgi. Django has some
urls that user cyrillic characters. But when I try to open page with such
link, django tells that it doesn't have such model, because the link got
escaped and is taken to django as "%D0%BA%D0%BD%D0%B8%D0%B3%D0%B8". On
apache the same project works fine. What option do I need to tell nginx
not to escape links like that?

Fetching rows in array using SELECT * FROM table WHERE IN

Fetching rows in array using SELECT * FROM table WHERE IN

Hi I am trying to fetch data from a particular coloumn from all rows.
Eg Situation: DB Data: id, fbid, name
$sql = 'SELECT id FROM table WHERE table.fbid IN (1234,5678,4321)';
$sql_run = mysql_query($sql);
$sql_fetch = mysql_fetch_assoc($sql_run);
print_r($sql_fetch);
This returns the data when I test it using Sequel PRO or PHPmyAdmin. But
when I print the array it only displays one value.
Can you help me with a solution or tell me where I'm going wrong?

How to get this hover effect with just CSS

How to get this hover effect with just CSS



I've already got the circle part. I set a background color of black on the
div. and for the text, I set a:hover as the color shown. I just can't
figure out how do I set a:hover for the div as well just for that amount
of circumference.
Here's my code:
HTML:
<a class="cirlink" href="http://www.somesite.com">
<div class="circle">
<h2 class="textcolor">click<br> here</h2>
</div>
</a>
CSS:
.circle
{
border-radius: 125px;
width:250px;
height:250px;
background-color:black;
margin:auto;
text-align:center;
}
.textcolor:hover
{
transition:1s;
color:#FF4800;
}
Also, is there any way to change the background image of a div on hover?

Monday, 26 August 2013

Java - How to create "anonymous" class on the fly

Java - How to create "anonymous" class on the fly

I can do this:
new Object(){
public void hi(){}
}.hi();
how do i (or can i) do this:
IDontWorkForSomeReasonThread t = new IDontWorkForSomeReasonThread extends
Thread(){
public void NoNoYouCantCallMe(String s){}
};
t.NoNoYouCantCallMe("some useful data that i will need later, but don't
want to save this anonymous class");

SSO with V1 API in desktop app supported?

SSO with V1 API in desktop app supported?

Should SSO work in a Windows Box desktop app that still uses the V1 API
and is using the IE-based WebBrowser control hosted in a dialog box to
allow the user to log into his/hers Box account?
The user is able to successfully login to Box this way; however, the
subsequent "get_auth_token" API fails.
Does this app requires upgrading to the Box V2 API for this to work? If
this is supposed to work, could you provide a suggestion how to best setup
a test/development environment to troubleshoot this issue?
Thanks Peter

Regular Expression for decimal numbers (at max 3 decimal numbers with comma)

Regular Expression for decimal numbers (at max 3 decimal numbers with comma)

how can I write a regular expression that validates an input textbox that
should contain only decimal values that can have at max 3 decimals, but
also none, and a comma as separated characted. For example, these values
are valid:
1,234
1,23
1,2
1
These are not valid:
1,2345 (too many decimal numbers)
A (a letter is not a number)
(a space or string empty)
1.234 (used a dot instead of a comma)
Thank for every help.
Luis

Why does the visual of this directive not line up with the value

Why does the visual of this directive not line up with the value

http://plnkr.co/edit/VAE43y5cagCF8jq5AlaY?p=preview
Within the directive, I'm using scope.$apply(). However, if you click too
quickly it changes the value but not the visual affect. This problem seems
to be related to timing. If I load the page and let it sit for 2 seconds
the first click changes the value. However, if I try to click it too
quickly, it'll change the value without changing the visuals.
Can anyone explain this? I'm thinking it might be mid-digest cycle or
something like that, but can't say for sure and I'm not sure what to do
about it...
//toggle the state when clicked
el.bind('click', function () {
scope.$apply(function () {
var getter=$parse(attrs.ngModel);
var setter=getter.assign;
setter(scope,!getter(scope));
//scope[attrs.ngModel] = !scope[attrs.ngModel];
if (el.hasClass('on')) {
off();
} else {
on();
}
});
});

nicEditor some items not working to display

nicEditor some items not working to display

I'm using NicEdit with image upload option.
I'd tested my site on localhost and everything works well. But as I've
uploaded it to the server it doesn't work.
I found the reason is that, it is adding \ to every ". And the tags I'm
getting looks like:
<img src=\"http://someurl.com/image.jpg\">
How could I tackle with this problem?

how to get the html text length without set it to a textfield?

how to get the html text length without set it to a textfield?

in actionscript ,i didn't find a direct way to get the actually string's
length of a html text.here's how i get things work
var myText:String = "<p>This is <b>some</b> content to <i>render</i> as
<u>HTML</u> text.</p>";
myTextBox.htmlText = myText;
trace(myTextBox.length);
deal with large content of html text would be a performance problem.
is there a way i can get the length while i don't have to pass it to a
text device?

Deprecated java classes in stdlib.jar

Deprecated java classes in stdlib.jar

guys!
I'm facing a problem with deprecated classes in a set of Libs for the
Programming in Java tutorial. Currantly, I'm trying to run ThreeSum.java
and getting NoClassDefFoundError in cmd (Windows). The problem is that
readInts(args[0]) class is deprecated. My programming skills are not good
enouph to fix it by myself. I would really appreciate your help.

Sunday, 25 August 2013

How to select all empty p tag using jQuery?

How to select all empty p tag using jQuery?

How can I select all the empty tag using jQuery.
I want to select
<p></p>
<p style="display: block"></p>
<p> </p>
<p> </p>
<p>&nbsp;</p>
and not
<p>0</p>
<p>Test</p>

[ Polls & Surveys ] Open Question : I personally think Miley looks great with short hair,do you?

[ Polls & Surveys ] Open Question : I personally think Miley looks great
with short hair,do you?

Few women can wear their hair short

mv multiple files from one directory to another directory by renaming them in UNIX

mv multiple files from one directory to another directory by renaming them
in UNIX

i have files in a directory with *.xml.inuse i want to move all of them to
destination directory by renaming to *.xml Tried with the below code but
didn't work
cd sourcedirectory/
for file in *xml.inuse
do
mv "${file}" ../destinationdirectory/"${file}.xml"
as it created destination files as *.xml.inuse.xml

Node.js async consistency

Node.js async consistency

I have the following code :
server.use(function(req, res, next) {
users_db.set(req.user, function(err) { // async call to mongodb
if (err) {
console.error(err);
}
});
}
return next();
});
server.get('/', function(req, res) {
req.user.active = true; // this is a new field in user object
res.send(req.user);
}
});
So, As you see, when users_db.set() is called, req.user doesn't have the
active=true field. It is being inserted only in the server.get() function.
Is it possible that user.active = true is registered in the db
nevertheless because of the asynchronous nature of the call ?

What is BlueZ and How to use it?

What is BlueZ and How to use it?

I have to write a code for Bluetooth Serial port in C. I'm using Ubuntu
and when I was searching I found something called BlueZ. I have no idea
about it and I don't know how to use it. I'm looking for some explanation
about BlueZ and a working example for Bluetooth in C.
In addition to that I have written a code for Bluetooth Serial
communication in Android but it keeps waiting for data though I can see
the sending side has done. Does anyone know what the problem is???
Thanks.

getting exception when i use Acquire method to scan

getting exception when i use Acquire method to scan

I am getting the folowing exception after I call the Acquire method (with
flag TwainUserInterfaceFlags.Show) .that is the error " problem caused the
program to stop working correctly" . please help me

Saturday, 24 August 2013

!! Watch !! New York Giants vs New York Jets Live Stream

!! Watch !! New York Giants vs New York Jets Live Stream

Today live the most exciting NFL Regular Season Match between New York
Giants vs New York Jets.You have come to the right place. Watch New York
Giants vs New York Jets live stream sop cast video online.You can watch
the NFL Regular Season Match on your
PC,Mac,Laptop,iPhone,iPod,iPad,Smartphone and other devices Hd quality
picture 100% satisfaction guarantee. Also, you can watch Highlights,
preview, review and live score.Okay New York Giants vs New York Jets fans,
don't late to watch live online only on here
New York Giants vs New York Jets Live Here
http://sportshdtv.dimitapapers.com/2013/08/25/watch-new-york-giants-vs-new-york-jets-live-stream/
http://sportshdtv.dimitapapers.com/2013/08/25/watch-new-york-giants-vs-new-york-jets-live-stream/
Match Schedules Competition: National Football League (NFL) Regular Season
2013 Week 3 Competitor:New York Giants vs New York Jets Venue:Sports
Authority Field at Mile High Date: SATURDAY AUGUST 24,2013
New York Giants vs New York Jets Live stream Online NFL, New York Jets vs
New York Giants live, New York Jets vs New York Giants live stream, New
York Jets vs New York Giants live pc tv, New York Jets vs New York Giants
live online NFL, New York Jets vs New York Giants live streaming, New York
Jets vs New York Giants live CBC tv, New York Jets vs New York Giants
streaming free, New York Jets vs New York Giants stream online, New York
Jets vs New York Giants free live broadcast, New York Jets vs New York
Giants live coverage, New York Jets vs New York Giants live boxing online,
New York Jets vs New York Giants boxing live stream online, New York Jets
vs New York Giants live NFL preseason tv.

"The calling thread cannot access this object because a different thread owns it" how i can resolve it

"The calling thread cannot access this object because a different thread
owns it" how i can resolve it

i m not understanding the logic of dispatcher in my code and my code is
when i click the button after 5 sec a message box should accour but its
giving me exception mentioed above
//this code is of my button click
private void button1_Click(object sender, RoutedEventArgs e)
{
dt[0] = DateTime.Now;
Thread th = new Thread(time);
//textBox2.Dispatcher.Invoke(( new Action=>textBox2.Text=.ToString));
th.Start();
//Thread thr = new Thread(time);
//thr.Start();
}
//this function is
private void time()
{
TimeSpan time_diference=new TimeSpan();
time_diference=DateTime.Now - dt[0];
while (true)
{
MessageBox.Show(time_diference.TotalSeconds.ToString() + "
textbox2 " + textBox1.Text.ToString());
if (time_diference.TotalSeconds.ToString() == textBox2.Text)
{
FBC.Post("/me/feed", new { message = textBox1.Text });
MessageBox.Show("posted");
break;
}
}
}

Find next word in a string

Find next word in a string

I have a text: ...N'eziokwu, &#7885; magh&#7883; ihe kpatara ha jiri ruo
oge &#7885; na-enwegh&#7883; onye nwere ike ikwuz&#7883; uche ya, oge
&#7909;m&#7909; nk&#7883;ta anya na-acha &#7885;k&#7909; juru ebe niile,
ya na oge &#7883; ga-an&#7885;r&#7885; na-ele nd&#7883; otu g&#7883; ebe a
d&#7885;sara ozu ha n'ihi mmehie nd&#7883; na-amacha akpata oyi
n'ah&#7909; ha kwup&#7909;tara...
Want to tag NCC to "otu" each time it is found after "nd&#7883;" in the
entire text. The program only prints out the text for me. Have below
codes:
#-*- coding: utf-8 *-*
import sys, codecs, re
def words(filin):
for line in filin:
for word in line.split():
yield word
igtag = []
with codecs.open(sys.argv[1], 'rb', encoding = 'utf-8') as fii:
word = words(fii)
for w in word:
if w == 'nd&#7883;'.decode('utf-8') and w[w.index(w) + 1] ==
'otu':
igtag.append(w[w.index(w) + 1] +'\NCC')
else:
igtag.append(w)
for line in igtag:
print u"".join(line).encode('utf-8')

MySQL Comparasion of two databases and tables and get results

MySQL Comparasion of two databases and tables and get results

I Have Two Databases (DTB1 and DTB2). I would like to show only results
from DTB1 that is not equal in DTB2.I know which field i need to compare
and that is Field MOUSES.
Example:
DTB1 DTB2
CLICKS 0 1
MOUSES 1 1
HOUSES 2 1
CARS 3 1
Result the output result is CLICKS, HOUSES and CARS (because MOUSES have
both equal values).
i try this...but my sql cpu is 94% when i try this query:
SELECT a.mouses FROM $database.$table a WHERE NOT EXISTS (SELECT b.mouses
FROM $database2.$table2 b WHERE b.mouses=a.mouses);
Any Help Welcome.

How to install PIL (or any module really) to the raspberry pi?

How to install PIL (or any module really) to the raspberry pi?

I want to install PIL and python-numpy at the least. I want to turn an
image into an array but really can't seem to find info on installing/using
modules to raspberry pi. Could somebody just explain?

how read *.csv file in string array

how read *.csv file in string array

try to realize reading csv file with some structured data (this file used
for my programm reminder - data in file structured with next way: date ,
name, time from, time till, description). Currently i want to read all
data from file and put it in some string array, where each element - 1
line from file. what was done
write some code, that create stream for reading and opening file. But
currently i can only read one line. or all file in one line. How to know,
how many lines in file exist? or how to read all lines in file in array,
where eaach element - one line from file.
Code
FileStream fs = new FileStream(FilePath, FileMode.Open,
FileAccess.Read, FileShare.None);
StreamReader sr = new StreamReader(fs);
string lines = sr.ReadLine();
//temp veiw result
viewTextBox.Text = lines; //read only one first line in file
sr.Close();
or try to read all lines
string []line = File.ReadAllLines(FilePath); //read all lines in File
//temp check
for (int i=0; i<line.Length;i++){
viewTextBox.Text += line[i]; // in this case all data stored
in one lines
}
i need this array with data, because next action - search some data in
this array and show it in form.

Valid HTML5 tag and attribute

Valid HTML5 tag and attribute

I would like to know if this code is allowed?
<article intro> .... </article>
I would like to use this if this is valid as attribute/elements of HTML5.

Friday, 23 August 2013

Set font-size in pixels from em units during resizing of page?

Set font-size in pixels from em units during resizing of page?

Ok, have been looking through code on how to get pixel values from em
units, but the code I've seen is this:
var eleInpx = $(".element").css("font-size");
However, this doesn't help me, since there is a font-size already applied
to the element in em units, and since the font-size changes during
resizing of the browser window (because it is in em units), I need to set
the wrapper element in pixels according to the font-size in pixels.
Mainly, because I need to use pixels in the wrapper element, not em units
for the effect that I am using with CSS Triangles, and em units do not
properly scale well when coding in CSS Triangles. Therefore I am stuck
with pixels for this. However, I need this wrapper element to resize, in
height (in pixels), according to the font-size (which is in em units) of
the element within it, as the browser window resizes.
Here's a bit of HTML to give you an example of what I mean exactly:
<div style="position: absolute; top: 50%;">
<div class="name_container">
<div class="sub_head">
<h1 class="h1_candidates">
<span class="sidestar-left">&#9733;</span> Ceyl Prinster
<span class="sidestar-right">&#9733;</span>
</h1>
<div class="sub_head_text">President &amp;
CEO&nbsp;&nbsp;&bull;&nbsp;&nbsp;Colorado Enterprise
Fund&nbsp;&nbsp;&bull;&nbsp;&nbsp;Denver, CO</div>
</div>
</div>
</div>
CSS looks like this:
div.name_container {
text-align: center;
margin: 0 auto;
}
.sub_head {
display: inline-block;
padding: 0 1em .3em;
position: relative;
margin: 0 auto;
top: -50px;
text-align: center;
background-color: #212D3B;
font-family: "MissionGothic-Regular", "Mission Gothic Regular
Regular", "mission_gothicregular";
font-size: 1.6em;
color: #f2efe9;
-moz-border-radius: .5em;
-webkit-border-radius: .5em;
-khtml-border-radius: .5em;
border-radius: .5em;
text-transform: uppercase;
}
.sub_head_text {
text-align: center;
text-transform: uppercase;
font-size: .8em;
margin: -0.5em;
padding-bottom: .5em;
position: relative;
white-space: nowrap;
}
.h1_candidates {
white-space: nowrap;
top: -20px;
}
h1 {
font-family: "MissionGothic-Regular", "Mission Gothic Regular
Regular", "mission_gothicregular";
font-size: 1em;
margin: 0 -2.1em;
background:#BF2C24;
display: inline-block;
color: #f2efe9;
position: relative;
height: 40px;
line-height: 40px;
text-transform: uppercase;
}
h1:before { /* this will create white triangle on the left side */
position: absolute;
content: "";
top: 0px;
left: -20px;
height: 0px;
width: 0px;
border-top: 20px solid #BF2C24;
border-left: 20px solid transparent;
border-bottom: 20px solid #BF2C24;
margin-left: 0;
}
h1:after { /* this will create white triangle on the right side */
position: absolute;
content: "";
top: 0px;
left: auto;
right: 20px;
height: 0px;
width: 0px;
border-top: 20px solid #BF2C24;
border-right: 20px solid transparent;
border-bottom: 20px solid #BF2C24;
margin-right: -40px;
}
h1 span.sidestar-left, h1 span.sidestar-right {
position: relative;
font-size: .6em;
top: -4px;
padding: 0 10px;
}
Ok, so I tried to create a jsFiddle of this here:
http://jsfiddle.net/5f9wA/4/ (full page result here:
http://jsfiddle.net/5f9wA/4/embedded/result/ )
However, in the jsfiddle, it doesn't show the problem I am experiencing
with the actual webpage for some odd reason. Probably because jsfiddle.net
wraps the code output in such a way that it doesn't resize the content at
all.
You will see the problem when you look at the actual webpage here:
http://opportunityfinance.net/Test/newest_conference-2013/meetcandidates.html
What is supposed to happen is the Name of person in the red ribbon and
blue background, just under that, will RESIZE the font-size accordingly to
the browsers width and/or height (as you resize your browser window).
However, during the resize of this, since the height of the red ribbon is
set to 40px via the h1 property, it causes the font-size to exceed the
height in bigger browser dimensions. How to control this? The height on
the h1 is set in order to properly set the CSS Triangles to half of the
height (so 20 pixels to be exact). If I set the height to em units, it
will completely ruin the ribbon effect.
So, not entirely sure how to tackle this issue, other than using jQuery to
resize the h1 and the div.sub_head_text element to a pixel value,
according to the font-size within the h1 element so that the elements
height is resized accordingly when the page gets resized.
Hopefully this makes sense to you all here. How can this be done during a
resize?
And yes, I'm aware that you can bind anything to the resize event in jQuery:
$(window).bind("resize", function(){ ... }).trigger("resize");
But I can't very well calculate the css font-size em unit value, since
this will always be 1.6em, I need to calculate the actual size of the font
as it grows and shrinks... How?

ssh server closes connection when client using NAT but work perfectly when client on same network

ssh server closes connection when client using NAT but work perfectly when
client on same network

Server: RH (though I am not sure which version) Client: Linux Mint 15
I'm trying to ssh from a machine behind a router to a server on the
network to which the router is connected. I'm using public key
authentication. I get this error:
debug1: Next authentication method: publickey debug1: Offering DSA public
key: /home/XXXXX/.ssh/id_dsa Connection closed by XXX.XXX.XXX.XXX
If I connect the client to the same network the router and server are
attached, then everything seems to work fine.
Does SSHD contact the client and could the router be blocking this
transaction? The logs are not providing a lot of information, and I do not
have admin permission for the server, so I cannot look at all the
configuration the way it is set up.

Saving a graph with ggsave after using ggplot_build and ggplot_gtable

Saving a graph with ggsave after using ggplot_build and ggplot_gtable

I am modifying a graph built with ggplot by altering the data produced by
ggplot_build (for a reason similar to R ggplot empty factor level). As far
as I understand the help I found on this topic, I should be able to save
the result by applying ggplot_gtable and arrangeGrob before calling ggsave
on the results (Saving grid.arrange() plot to file).
However I obtain an error "plot should be a ggplot2 plot", also with this
simple reproductible example:
require('ggplot2')
require('gridExtra')
df <- data.frame(f1=factor(rbinom(100, 1, 0.45), label=c("m","w")),
f2=factor(rbinom(100, 1, 0.45), label=c("young","old")),
boxthis=rnorm(100))
g <- ggplot(aes(y = boxthis, x = f2, fill = f1), data = df) + geom_boxplot()
dd <- ggplot_build(g)
# Printing the graph works:
print(arrangeGrob(ggplot_gtable(dd)))
# Saving the graph doesn't:
ggsave('test.png',arrangeGrob(ggplot_gtable(dd)))
Can anybody explain why this does not work ? Is there a way to use ggsave
after modifying the data by using ggplot_build() ?
(My version of the packages are gridExtra_0.9.1 and ggplot2_0.9.3.1)

Setting base class object to derived class object

Setting base class object to derived class object

I have four classes. Person, NaturalPerson (Inherits from Person),
GroupFamilyMember(Inherits from NaturalPerson), QuotationHolder(Inherits
from GroupFamilyMember).
They all share the same ID.
My problem is the following one:
There is a method that returns an existing NaturalPerson(stored in DB)
object based on a document number. Then, I have to create a
QuotationHolder, and I want that QuotationHolder object to contain the
retrieved NaturalPerson object.
The issue, is that I can´t cast the object like this (I know the reason):
QuotationHolder quotationHolder = (QuotationHolder) naturalPerson;
I tried creating a new QuotationHolder object and setting its values with
the naturalPerson´s object values using reflection.
But as I lose the reference to the retrieved object, when I want to save
in cascade, NHibernate gives me the following exception:
a different object with the same identifier value was already associated
with the session
I guess that its trying to save the object as a new one.
Just to consider:
The IDs are set using the HILO Algorithm. The mappings cannot be changed,
neither the classes.

plugin-container high CPU usage

plugin-container high CPU usage

I use debian(unstable) and gnome3 desktop.When I use iceweasel(firefox)
,the CPU usage of plugin-container will be very high .Sometimes more than
50% and browser will not work.In addition my friend who use
dibain(unstable) and kde desktop doesn't have this problem. Who can help
me solve this? Thank you

Thursday, 22 August 2013

Textarea moving up when scrolling in BootStrap

Textarea moving up when scrolling in BootStrap

I have an problem in my application that i have developed in bootstrap.The
problem is that i have a modal whose body max-height is setted. It
contains a textarea,now when the tap on the textarea it gains the
focus(correct till now) but when i scroll to down the text area which is
in modal-body shown above the modal-header, it shows some type of
duplicacy of textarea. But as soon as i stop the scrolling everything gone
perfect again.
<div id="textPanel" class="modal fade">
<div class="modal-dialog">
<div class="modal-content" style="padding-bottom: 5px">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"
aria-hidden="true">&times;</button>
<h4 class="modal-title">Add/Edit Text</h4>
</div>
<div class="modal-body" style="overflow-x: auto">
<div class="row">
<div class="col-12">
<div id="textPreviewPanel" class="outer"
style="height: 60px;margin-bottom:
5px;margin-top: -15px">
<div class="inner" style="height: 100%">
<img id="textPreview" style="height:
100%;text-align: center"/>
</div>
</div>
</div>
<div class="col-12">
**<textarea id="addTextInput"
ng-model="addEditTextModel" placeholder="Enter your
text here"
rows="3"
class="form-control" style="resize:
none"></textarea>**
</div>

Audio Recode during sleep - Android

Audio Recode during sleep - Android

I am making some app using AudioRecord class in Android. Someone might
have already asked the same question.. But, I appreciate any insight.
I am recording "voice" like the following:
recorder.startRecording();
Thread.sleep(10000);
recorder.read(buffer, 0, bufferSize);
recorder.stop();
"recorder" is an instance of "AudioRecord" class.
I can get data with this code, but, I am not sure if the data collected by
this way is reliable.
My intention of this code is to stop the program & record voice for 10
seconds.
So, the question is if this approach can get the correct voice data?
Thank you,

Microsoft Exchange Management console, Initilization Failed

Microsoft Exchange Management console, Initilization Failed

Upon starting Exchange Management Console I am presented with the error
[###################] Connecting to remote server failed with the
following error message : The WinRM client
sent a request to an HTTP server and got a response saying the requested
HTTP URL was not available. This is usually re
turned by a HTTP server that does not support the WS-Management protocol.
For more information, see the about_Remote_Tr
oubleshooting Help topic.
+ CategoryInfo : OpenError:
(System.Manageme....RemoteRunspace:RemoteRunspace) >[],
PSRemotingTransportExc
eption
+ FullyQualifiedErrorId : PSSessionOpenFailed
After spending some time googling most problems were resolved by
correcting the bindings on port 80. I did this following these
instructions here (Microsoft Support).
I've run out of ideas of how to fix this problem and would appreciate if
someone could shed some light or point me in a good direction. Thank you

CSS Animations - How to make it stay there after animation?

CSS Animations - How to make it stay there after animation?

I got CSS Animations working on a logo. I make the image slide down from
top to bottom, just once. How do I make the image stay where it went to
after the animation stops?

Sub page using ng-include and refearing main pages $scope objects

Sub page using ng-include and refearing main pages $scope objects

I have had problems with variables defined in $scope of Main page and then
refering them in sub pages that are included in Main page using ng-include
syntax.
Many times those $scope variables are empty especially in first load.
Is this because of some kind of synchronizing problem and how to avoid it?
I like to use sub pages but what is the Best Practice to include them in
Main page so that there would not be problems with $scope variable?
Thanks a lot,
Michael

Returning back to an HTML page

Returning back to an HTML page

I have two html files called home.html and options.html. In the
options.html, after I clicked the submit button, I am now in the cgi-bin
directory of my webserver. What should be the format of my anchor tag so I
can go back to the home.html page?
This is the code:
<a href='localhost/cgi-bin'>GO BACK</a>
The error I encounter is:
The requested URL /cgi-bin/localhost/home.html was not found on this server.

Problems when listening with two QUdpSockets

Problems when listening with two QUdpSockets

I am trying to use QUdpSockets in my application, but I have a problem I
don't understand at all. I am working with pyQt4 but I think it will be
the same problem in C++.
I create a QDialog with an attribute QUdpSocket and It works well I bind
this socket and I can listen messages.Here the code wich is the same of
the documentation of Qt :
http://harmattan-dev.nokia.com/docs/library/html/qt4/qudpsocket.html
self.udpSocket.bind(QHostAddress("125.10.20.30"),2000)
QObject.connect.(self.udpSocket,SIGNAL("readyRead()"),self.readPendingDatagrams)
But when I create a second QDialog which will listen of an other port
'2001' while the first QDialog is still listening on port '2000' for
example :
When I send messages to this port 2001 the first QDialog stop listening on
port 2000 and all the messages send to port 2000 are redirect on port 2001
I tried all the BindMode possible proponed by the documentation but
nothing changed.
Do you have any ideas ?
Thank you very much

Wednesday, 21 August 2013

Reading json input in php

Reading json input in php

'php://input' is working properly in localhost. But in server it returns
empty. Input( request ) to my site is a json, so $_POST didn't work. is
there is any solution for it?
class Webservice_Controller extends CI_Controller {
public $json_input_data;
public function __construct(){
parent::__construct();
$this->json_input_data =
json_decode(file_get_contents('php://input'),TRUE);
}
public function cus_input($label){
if(isset($this->json_input_data[$label])) return
$this->json_input_data[$label];
else return NULL;
}
}

Google Feed Api bug in ie8?

Google Feed Api bug in ie8?

Google Feed does not get loaded in ie8 at the very first time. Here's the
code (exactly from
https://developers.google.com/feed/v1/devguide#hiworld):
<html>
<head>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("feeds", "1");
function initialize() {
var feed = new
google.feeds.Feed("http://fastpshb.appspot.com/feed/1/fastpshb");
feed.load(function(result) {
if (!result.error) {
var container = document.getElementById("feed");
for (var i = 0; i < result.feed.entries.length; i++) {
var entry = result.feed.entries[i];
var div = document.createElement("div");
div.appendChild(document.createTextNode(entry.title));
container.appendChild(div);
}
}
});
}
google.setOnLoadCallback(initialize);
</script>
</head>
<body>
<div id="feed"></div>
</body>
</html>
And if you refresh the page, then it works fine, but if you clear the
cache (plus restart the browser, is freaking ie, so...) it will happen
again, all the time.
Try to print out the json object of google.feed via
for(var key in google.feeds){
console.log(key);
}
gets only 3 keys: Version, JSHash, LoadArgs
Tried calling new google.feeds.Feed() in a timeout, if google.feeds.Feed
is undefined, but it didn't work as well, as it kept staying as undefined.
Anyone has any other idea or workaround? Thanks.

Clarification of definition of category

Clarification of definition of category

Need the set of objects and the set of morphisms be disjoint? If not, can
the morphisms be a subset of the objects?

jquery code for checkbox in MVC

jquery code for checkbox in MVC

jquery function: It is returning true always in alert(isChecked) even when
unchecked.
$('.accrualCheckbox').click(function () {
var isChecked = $(this).attr('checked') ? true : false;
alert($(this).attr('checked'));
alert(isChecked);
if ($(this).prop('checked', 'checked')) {
var parentDiv = $(this).parents('.searchLine');
$(parentDiv).css('border', '1px solid red');
//Checkbox
$(parentDiv).find("input[type=text]").each(function () {
$(this).val('B');
$(this).prop('disabled', true);
});
}
});
});
i have kept check box in div ,
<div class="accrualCheckbox">
@Html.CheckBox("chkSalesAndMarketing")
</div>

How to add a comments box in android app

How to add a comments box in android app

I have recently started working on an app which allows users to read news
articles from a website and I would like to allow users to directly
comment about the articles on facebook.
I would like to add a comments box below the article where users can write
a comment and place it on their wall with the link to the article. This
comment box should also load all comments other users have previously
placed on facebook for the same article.
I am following the how to guide from Facebook developers which teaches me
how to login with facebook, but I am a bit overwhelmed and not quite sure
which guide/tutorial/part of the SDK I should use to add a comments box.
So I was hoping someone who has experience with comment boxes on Android
could help me out and tell me what I should be using. I don't need an
in-depth description or tutorial, I just need to know what I should be
using and where I can find some information about it.
Thanks in advance!

How to give regular expression for Regex.ismatch function?

How to give regular expression for Regex.ismatch function?

I am trying to write a regular expression for accepting a Number of length
upto 14 and if they keep the decimal point then it should accept only 2
numbers after the decimal point.
I have tried it from this link below :
http://stackoverflow.com/a/9967694/861995
But, the same Regex.IsMatch function is not accepting the normal regex
expression's starting with ^ and ending with $.
Please help me on this i am new to regular expressions

Fill in form with append and bind

Fill in form with append and bind

Currently I'm working on a project that has 1 register form. In this form
it is allowed to add multiple members in 1 go. The first member is
required, the others aren't. To add more members I use 'append' from
jQuery that adds the form for the second and third member perfectly.
Now, I want to add a piece of code that fills in my streetname and city
automatically when I fill in the postalcode.
I use jquery with json to fill in some form fields for me. I use this
piece of code:
$('input[name=postcode_1]').change(function(){
//100420//
b_postcode = $('input[name=postcode_1]').val();
$.getJSON('/inc/getPostcodeInfo.php', {postcode:b_postcode},
function(data) {
$('input[name=adres_1]').val('');
$('input[name=plaats_1]').val('');
$.each(data, function(index, array) {
// alert(array['straat']);
$('input[name=adres_1]').val(array['straat']);
$('input[name=plaats_1]').val(array['woonplaats']);
})
});
});
This works perfectly for 1 member but when I add the second and third
member it doesn't work. I read that I'd need to use the function 'bind'
which is what I used for the second and third member like so:
html.bind('change', '[name=postcode_'+ count +']', function(){
b_postcode = $('input[name=postcode_'+ count +']').val();
$.getJSON('/inc/getPostcodeInfo.php', {postcode:b_postcode},
function(data) {
$('input[name=adres_'+ count +']').val('');
$('input[name=plaats_'+ count +']').val('');
$.each(data, function(index, array) {
// alert(array['straat']);
$('input[name=adres_'+ count +']').val(array['straat']);
$('input[name=plaats_'+ count
+']').val(array['woonplaats']);
})
});
});
(Whenever a new member is added count becomes count++)
This seems to only work for the last member added. How can I make this
work so I can automatically fill in the streetname and city for all
members?
Information members:
Member 1 - postalcode: 1111 AA
Member 2 - portalcode: 2222 BB
Member 3 - postalcode: 3333 CC

Tuesday, 20 August 2013

How to close Parent Window from RadTab child page?

How to close Parent Window from RadTab child page?

there are several tabstrip in my aspx page, when use click on the tab, it
will redirect to another aspx.
example:
Parent.aspx
RabTab1 (page1.aspx)
RabTab2 (page2.aspx)
how can i close the whole window (parent.aspx) when user already click
RadTab2 and enter into (page2.aspx) ?
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Position Details</title>
<script type="text/javascript">
function UpdateRefresh() {
if (window.opener)
window.opener.UpdateRefresh();
}
</script>
</head>
<body>
<form id="form1" runat="server">
<telerik:RadScriptManager ID="RadScriptManager1" runat="server">
</telerik:RadScriptManager>
<telerik:RadSplitter ID="RadSplitter1" runat="server" Width="100%"
Height="100%" Orientation="Horizontal">
<telerik:RadPane ID="rpTitle" runat="server" BackColor="#003399"
Height="27px" MinHeight="27" MaxHeight="27" Width="100%"
Scrolling=None>
<asp:Table ID="Table1" runat="server" Width="100%" Height="100%">
<asp:TableRow>
<asp:TableCell Width="33%">
<asp:Label ID="lblPositionCode" runat="server" Text=""
ForeColor="White" Font-Size="12pt"
Font-Bold="true"></asp:Label>
</asp:TableCell>
<asp:TableCell Width="33%" HorizontalAlign="Center">
<asp:Label ID="lblPositionName" runat="server" Text=""
ForeColor="White" Font-Size="12pt"
Font-Bold="true"></asp:Label></asp:TableCell>
<asp:TableCell Width="34%" HorizontalAlign="Right">
<asp:Label ID="lblDepartment" runat="server" Text=""
ForeColor="#FFCC00" Font-Size="12pt"
Font-Bold="true"></asp:Label>
</asp:TableCell>
</asp:TableRow>
</asp:Table>
</telerik:RadPane>
<telerik:RadPane ID="rpTab" runat="server" Height="26px"
MinHeight="26" MaxHeight="26" Width="100%">
<telerik:RadTabStrip ID="rtMenu" runat="server" Skin="Outlook"
SelectedIndex="0">
<Tabs>
<telerik:RadTab Text="History" Value="History"
Selected="True" Width="100px"></telerik:RadTab>
<telerik:RadTab Text="Details" Value="Details"
Width="100px"></telerik:RadTab>
<telerik:RadTab Text="Compliance" Value="Compliance"
Width="100px"></telerik:RadTab>
<telerik:RadTab Text="Competency" Value="Competency"
Width="100px"></telerik:RadTab>
<telerik:RadTab Text="Procedure" Value="Procedure"
Width="100px"></telerik:RadTab>
<telerik:RadTab Text="Succession" Value="Succession"
Width="100px"></telerik:RadTab>
</Tabs>
</telerik:RadTabStrip>
</telerik:RadPane>
<telerik:RadPane ID="rpContent" runat="server">
</telerik:RadPane>
</telerik:RadSplitter>
</form>
</body>
</html>
Code behind:
Protected Sub rtMenu_TabClick(ByVal sender As Object, ByVal e As
Telerik.Web.UI.RadTabStripEventArgs) Handles rtMenu.TabClick
If e.Tab.Value = "History" Then
rpContent.ContentUrl = "PositionHistory.aspx?PosID=" &
Request("PosID")
ElseIf e.Tab.Value = "Details" Then
rpContent.ContentUrl = "PositionInfo.aspx?PosID=" & Request("PosID")
ElseIf e.Tab.Value = "Succession" Then
rpContent.ContentUrl = "SuccessionPlanning.aspx?PosID=" &
Request("PosID")
ElseIf e.Tab.Value = "Compliance" Then
rpContent.ContentUrl = "Compliance.aspx?PosID=" & Request("PosID")
ElseIf e.Tab.Value = "Competency" Then
rpContent.ContentUrl = "Competency.aspx?PosID=" & Request("PosID")
ElseIf e.Tab.Value = "Procedure" Then
rpContent.ContentUrl = "Procedure.aspx?PosID=" & Request("PosID")
End If
End Sub
i had tried to add the following function in child page code behind, but
none of them work
'auto close browser
Response.Write("<script type='text/javascript'> " & "window.opener =
'Self';" & "window.open('','_parent','');" & "window.close(); " &
"</script>")
Me.ClientScript.RegisterClientScriptBlock(Me.[GetType](), "Close",
"window.close()", True)
Page.ClientScript.RegisterOnSubmitStatement(GetType(Page), "closePage",
"window.onunload = CloseWindow();")
Response.Write("<script type='text/javascript'> " & "window.opener =
'Self';" & "window.open('','_parent','');" & "window.close(); " &
"</script>")
Page.ClientScriptManager.RegisterClientScriptBlock(Me.[GetType](),
"RedirectScript", "window.parent.location = '../Images/Logo_Done.jpg'",
True)
Page.ClientScript.RegisterStartupScript([GetType](), "Load", "<script
type='text/javascript'>window.parent.location.href =
'../Images/Logo_Done.jpg'; </script>")

JQuery delegate command does not seem to be working

JQuery delegate command does not seem to be working

I have a fieldset that contains a bunch of input elements and which is
initially collapsed when displayed to the user. I would like to attach an
event handler on the a drop down list that is contained in the fieldset
but I seem to be having trouble accomplishing this. I am using jQuery 1.5
and this is the code that I am using:
// Add a change listener to the specified select box.
$(document).delegate("select[name='type_config[format]']", 'change',
function() {
var selectedValue =
$("select[name='type_config[format]']").find(":selected").val();
console.log("the value you selected: " + selectedValue);
});
I thought using delegate would accomplish this as drop down is not
initially visible. However when I change the selection in the drop down
list nothing happens. I know the selector is correct as I tested it out in
the console when the drop down is visible. Any ideas what I am doing wrong
(or what I may be overlooking)?
Thanks.

Save the data and using it after restarting the app Android

Save the data and using it after restarting the app Android

I'm creating a simple app where the user can change the seekbar value.
make the default value as 0 and setMax as 5. Every time the app is closed
and started back, seekbar value is set to 0. How can I use and set the
previous seekbar value which was set before closing the app.
Here's my Activity class >
public class MainActivity extends Activity {
SeekBar s;
TextView v;
public int n;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
s=(SeekBar)findViewById(R.id.seekBar1);
v=(TextView)findViewById(R.id.textView1);
next=(Button)findViewById(R.id.button1);
s.setProgress(n);
v.setText(n+" ");
s.setOnSeekBarChangeListener(new OnSeekBarChangeListener(){
@Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
// TODO Auto-generated method stub
n = progress;
v.setText(n+" ");
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
v.setText(n+" ");
}
});
}
}
I Tried using onSaveInstanceState and onRestoreInstanceState but failed to
restore back to the previous state. Please Help
Thanks in Advance.

Display deflation percentage of tar command (like zip command)

Display deflation percentage of tar command (like zip command)

This question may sound wierd but I would like to know if there is a
possibilty to display the deflation percentage of the files processed in
the tar command.
I use this command tar -cjvf "$BACKUP_PATH/Complete Backup $date.tar.bz2"
$MINECRAFT_PATH to create a backup of a minecraft game server. And this is
displaying all the files it is processing. This looks almost like the zip
command. The differnece here is that once the zip command is finished it
displays how much the file got deflated. I wonder if this is possible with
the tar command.

Failed to impersonate domain user via C#

Failed to impersonate domain user via C#

I am trying to impersonate remote admin user so that i can perform
modifications on the files present on remote Linux machine. But i get
error message as Access to the path is denied. However this thing manually
i am able to do via putty using command :
sudo -S -u wtsnqa rm /path-to-file/
Any help is worth appreciable.
My code :
SessionOptions sessionOptions = new SessionOptions
{
Protocol = Protocol.Sftp,
HostName = "sj1slm612",
UserName = "userid",
Password = "password",
SshHostKeyFingerprint = "ssh-rsa 2048
fa:e9:58:24:1b:41:a3:15:63:0d:c0:72:41:5d:51:7a"
};
using (Session session = new Session())
{
// Connect
session.Open(sessionOptions);
// Performing removing files from remote server via
impersonation.......
AppDomain.CurrentDomain.SetPrincipalPolicy(System.Security.Principal.PrincipalPolicy.WindowsPrincipal);
using (WindowsIdentity Authorized_user = new
WindowsIdentity("wtsnqa"))
{
using (WindowsImpersonationContext context =
Authorized_user.Impersonate())
{
File.Delete(@"\\sj1slm612\apps\instances\express_13000\configuration\standalone-full.xml");
File.Delete(@"\\sj1slm612\apps\instances\query_13100\configuration\standalone-full.xml");
File.Delete(@"\\sj1slm612\apps\instances\wppapi_13200\configuration\standalone-full.xml");
File.Delete(@"\\sj1slm612\apps\instances\wppgui_13300\configuration\standalone-full.xml");
Console.WriteLine("All config files removed from
sj1slm612");
Console.ReadLine();
context.Undo();
}

How to use putting validation message underneath a control using backbone validation

How to use putting validation message underneath a control using backbone
validation

I am using backbone.validation.js
I am able to implement this as shown in the demo here

So, I am able to show the error messages next to the field. I want to be
able to show these message underneath the controls.
I checked the HTML generated for these messages, it reads
<span class="help-inline error-message">
Please provide your first name
</span>
I tried doing through CSS, it could do it but it gets a little messy.
Wanted to know if there is already a provision for this which I may have
missed.
Please advice.

Monday, 19 August 2013

Missing Argument 2 for encrypt()

Missing Argument 2 for encrypt()

I had to rebuild my nginx server. Installed the same way I have every
time. Now all of a sudden one of my scripts wont authenticate people and I
get this message
2013/08/19 21:14:26 [error] 2392#0: *1667 FastCGI sent in stderr: "PHP
message: PHP Warning: Missing argument 2 for encrypt(), called in
*DIRECTORY_LOCATION*.php on line 139 and defined in
*DIRECTORY_LOCATION*.php on line 27" while reading response header from
upstream, client: *IP_ADDRESS*, server: *SERVER_NAME*, request: "GET
*DIRECTORY_LOCATION*.php HTTP/1.1", upstream:
"fastcgi://unix:/var/run/php5-fpm.sock:", host: "*SERVER_NAME*"
I understand this might be too general and I am sorry for that. I am just
not sure where to even begin or end to resolve this.

WaTcH Pittsburgh Steelers vs Washington Redskins Live Stream Preseason NFL Football TV

WaTcH Pittsburgh Steelers vs Washington Redskins Live Stream Preseason NFL
Football TV

Enjoy The 2013 NFL Preseason Week 2 ®Are you looking for 2013 NFL Game
Pittsburgh Steelers vs Washington Redskins match online live streaming of
NFL(National Football League) 2013 From United States Then you have come
to right place. You can watch all the match of NFL 2012 here in HD quality
video. Not only the NFL 2012 match but you can Watch Live ALL USA Football
Matches online for one year by only one time subscription.Direct-TV
Channels !.
Pittsburgh Steelers vs Washington Redskins Live Here
http://striming-nfl.blogspot.com/2013/08/watch-pittsburgh-steelers-vs-washington.html
http://striming-nfl.blogspot.com/2013/08/watch-pittsburgh-steelers-vs-washington.html
Match Schedule ~~!! Preseason Week 2 Football League 2013 Team Name :
Pittsburgh Steelers vs Washington Redskins Live Date: Monday ,August 19th,
2013 Time: 8:00 PM ET, Preseason Live/Repeat:Live
Watch Pittsburgh Steelers vs Washington Redskins 2013 NFL Regular Season
Divisional live streaming online NFL Games on your PC, Get live stream
Pittsburgh Steelers vs Washington Redskins video Sopcast and Highlights.
NFL Football streamers must watch this match. Pittsburgh Steelers vs
Washington Redskins 2013 NFL Regular Season Divisional exciting NFL match
streaming live online. Get instant access Here to watch Pittsburgh
Steelers vs Washington Redskins live broadcast Online HD TV. Hello man
Don't mistake to start watching live streaming of this NFL Regular Season
2013 game will broadcast the following TV channel :CBS,FOX,NBC,ESPN live
stream Online TV on PC today of NFL TV.

How do I create a C++ project in Visual Studio with a bunch of source files?

How do I create a C++ project in Visual Studio with a bunch of source files?

I have around 10 files, including a main and I want to compile that into a
project in Visual Studio so I can run it. How do I do this? I'm running
Visual Studio 2012

13.04 Mouse Pointer Shadow

13.04 Mouse Pointer Shadow

Suddenly my mouse pointer had a shadow, and is very difficult to use. It
happens with any mouse, whether USB or my Dell Bluetooth Mouse.
Can someone suggest a way to get it back to the default? I can't think of
anything that would have changed. Thanks.

Sunday, 18 August 2013

why is headless qwebpage throwing sigsegv?

why is headless qwebpage throwing sigsegv?

so, I need to parse some javascript against one html page (kinda a
scripting for my app), but QWebPage throws SIGSEGV when I try to
initialize it. It console application. Relevat parts of my code:
QT += core sql network xml webkit
QT -= gui
QMAKE_CXXFLAGS += -std=c++11
LIBS += -lqca
TARGET = jarvisd
CONFIG += console
CONFIG -= app_bundle
TEMPLATE = app
QWebPage * p = new QWebPage();
p->mainFrame()->load(QUrl(url));
It crashes on the first line. From documentation for QWebPage, from "Using
QWebPage in a Widget-less Environment" part, it seems this should be
possible. But there is not error, just sigsegv :/
Thanks for your help.

Accessing phone data when locked out

Accessing phone data when locked out

I am using a BLU Quattro HD 5.7 phone, running ICS, and I have locked
myself out due to my own stupidity. It doesn't have a wifi connection or a
data connection at the moment because I do not have a data plan and I
haven't connected to any wifi networks in my area. I see that the only way
for me to recover from this is to factory reset my phone. I will do this,
but I have data on my phone that I really do not want to lose that I want
to be able to access before wiping it. Is there any way for me to do that
even though I have not enabled usb debugging or rooted the device?

Error inflating fragment in fragmentdialog

Error inflating fragment in fragmentdialog

I am trying to display an already created listviewfragment inside of a
fragmentdialog. I used the answer from the question below to do it and it
is not working.
How to display an existing ListFragment in a DialogFragment
I am getting an Error inflating class fragment when I try to open the
fragment dialog and the app crashes
Below is the dialog_fragment_with_list_fragment layout
<?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" >
<fragment
android:id="@+id/flContent"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding = "10dp"
class="com.OptimusApps.stayhealthy.AndroidXMLParsingActivity" />
</LinearLayout>
and it is not the androidxmlparsingactivity fragment that is causing it to
fail, I have tried it with other fragments and they did not work either
Below is my dialog fragment class
public class BodyDialogue extends DialogFragment {
int mNum;
/**
* Create a new instance of MyDialogFragment, providing "num"
* as an argument.
*/
static BodyDialogue newInstance(int num) {
BodyDialogue f = new BodyDialogue();
// Supply num input as an argument.
Bundle args = new Bundle();
args.putInt("num", num);
f.setArguments(args);
return f;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mNum = getArguments().getInt("num");
// Pick a style based on the num.
int style = DialogFragment.STYLE_NORMAL, theme = 0;
switch ((mNum-1)%6) {
case 1: style = DialogFragment.STYLE_NO_TITLE; break;
case 2: style = DialogFragment.STYLE_NO_FRAME; break;
case 3: style = DialogFragment.STYLE_NO_INPUT; break;
case 4: style = DialogFragment.STYLE_NORMAL; break;
case 5: style = DialogFragment.STYLE_NORMAL; break;
case 6: style = DialogFragment.STYLE_NO_TITLE; break;
case 7: style = DialogFragment.STYLE_NO_FRAME; break;
case 8: style = DialogFragment.STYLE_NORMAL; break;
}
switch ((mNum-1)%6) {
case 4: theme = android.R.style.Theme_Holo; break;
case 5: theme = android.R.style.Theme_Holo_Light_Dialog; break;
case 6: theme = android.R.style.Theme_Holo_Light; break;
case 7: theme = android.R.style.Theme_Holo_Light_Panel; break;
case 8: theme = android.R.style.Theme_Holo_Light; break;
}
setStyle(style, theme);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view =
inflater.inflate(R.layout.dialog_fragment_with_list_fragment, null);
return view;
}
}
and this is how i call the dialogfragment
public void onClick(View v) {
BodyDialogue dialogFragment = BodyDialogue.newInstance(1);
dialogFragment .setRetainInstance(true);
dialogFragment .show(getFragmentManager(), "bodydialogue");
}
this was the cause in the logcat
08-17 19:43:15.702: E/AndroidRuntime(3605): Caused by:
java.lang.IllegalArgumentException: Binary XML file line #7: Duplicate id
0x7f0a0031, tag null, or parent id 0x0 with another fragment for
com.OptimusApps.stayhealthy.AndroidXMLParsingActivity
08-17 19:43:15.702: E/AndroidRuntime(3605): at
android.support.v4.app.FragmentActivity.onCreateView(FragmentActivity.java:285)

Cube process incremental 1 partition vs multiple

Cube process incremental 1 partition vs multiple

I have a large cube where processing times have become too long. I want to
change my cube partitioning and processing options. I understand that
process incremental will pull new records into the cube. My question is,
is there an advantage of having multiple partitions and performing process
incremental rather than just having one partition and performing process
incremental? I do not expect a large volume of new records each time I
process.

How to explain this output of a C program

How to explain this output of a C program

int main()
{
unsigned int a = 0xfffffff7;
char *b = (char *)&a;
printf("%08x",*b);
}
the output is fffffff7.my machine is little-endian. Of course I know *b
equals 0xf7,but I don't know why the output of printf() is like this.

Difference between core java based client and axis2 based client

Difference between core java based client and axis2 based client

I am novice to java based webservices.
I have learnt how to create and consume webservice using core java
libraries but now I came to know that Apache Axis2 is a good tool for java
webservices.
So, my question here is what is more beneficial for creating and consuming
webservices ?
Should I go with simple java libraries or Apache Axis2 ?
One more thing, what is difference between Apache CXF, Apache Axis2?

Saturday, 17 August 2013

How to use select into statement?

How to use select into statement?

I want to insert records from Table1 and Table2 into Table3 and my Table3
has Two columns:
studentId
subjectId
And I want to insert these 2 values from Table1(contains 1000 student
Id's) and From Table2(contains 5 subjects). To achieve that I have used
following query but it gave me error
Query:
INSERT INTO StudentSubject(studentId,subjectId)
SELECT studentId FROM Table1 UNION SELECT subjectId FROM Table2
But I got this error message:
Msg 120, Level 15, State 1, Line 1 The select list for the INSERT
statement contains fewer items than the insert list. The number of SELECT
values must match the number of INSERT columns.

How could I get the response data from sending POST data using the WebBrowser control?

How could I get the response data from sending POST data using the
WebBrowser control?

Okay, so basically I am wanting to know how I can get the response data
after using the WebBrowser control's overload "Navigate" method. Here is
an example of what I am doing:

wb.Navigate("https://live.xbox.com/en-US/Friends/List", "",
Encoding.ASCII.GetBytes(post), "Content-Type:
application/x-www-form-urlencoded\r\n");
This is navigating my page to the first parameter but I have no idea how
to just get the response data from calling this. Also the result I want is
the response's body. Could somebody please help me. I tried using the
WebRequest and WebResponse ways, but they don't allow me to sign the user
into the Xbox Live website for some reason, resulting in myself not being
able to do anything and get 411 errors. I want to be able to do this with
the WebBrowser though. But if I can't, any help would be greatly
appreciated. Thanks guys.

Possible bounding_box type in place Object : twitter streaming Api

Possible bounding_box type in place Object : twitter streaming Api

what are possible type of bounding_box possible in place information
Twitter returned by streaming API . I can only see "polygon" is present .
Is there any other type possible ?
https://dev.twitter.com/docs/platform-objects/places

Drop and drag pin with google maps api

Drop and drag pin with google maps api

I am using Google map api in my project. I am trying drop a pin and get
the coordinates of the pin in json format. I dont know how to do it. I
just added map in the View like that;
<iframe width="285" height="285" frameborder="0" scrolling="no"
marginheight="0"
marginwidth="0"
src="http://maps.google.com/?ie=UTF8&amp;ll=41.028375,28.975671&amp;spn=0.00947,0.026157&amp;t=p&amp;z=10&amp;output=embed">
</iframe>

jQuery Use Loop for Validation?

jQuery Use Loop for Validation?

I have rather large form and along with PHP validation (ofc) I would like
to use jQuery. I am a novice with jQuery, but after looking around I have
some code working well. It is checking the length of a Text Box and will
not allow submission if it is under a certain length. If the entry is
lower the colour of the text box changes Red.
The problem I have is as the form is so large it is going to take a long
time, and a lot of code to validate each and every box. I therefore
wondered is there a way I can loop through all my variables rather than
creating a function each time.
Here is what I have:
var form = $("#frmReferral");
var companyname = $("#frm_companyName");
var companynameInfo = $("#companyNameInfo");
var hrmanagername = $("#frm_hrManager");
var hrmanagernameInfo = $("#hrManagerInfo");
form.submit(function(){
if(validateCompanyName() & validateHrmanagerName())
return true
else
return false;
});
Validation Functions
function validateCompanyName(){
// NOT valid
if(companyname.val().length < 4){
companyname.removeClass("complete");
companyname.addClass("error");
companynameInfo.text("Too Short. Please Enter Full Company Name.");
companynameInfo.removeClass("complete");
companynameInfo.addClass("error");
return false;
}
//valid
else{
companyname.removeClass("error");
companyname.addClass("complete");
companynameInfo.text("Valid");
companynameInfo.removeClass("error");
companynameInfo.addClass("complete");
return true;
}
}
function validateHrmanagerName(){
// NOT Valid
if(hrmanagername.val().length < 4){
hrmanagername.removeClass("complete");
hrmanagername.addClass("error");
hrmanagernameInfo.text("Too Short. Please Enter Full Name.");
hrmanagernameInfo.removeClass("complete");
hrmanagernameInfo.addClass("error");
return false;
}
//valid
else{
hrmanagername.removeClass("error");
hrmanagername.addClass("complete");
hrmanagernameInfo.text("Valid");
hrmanagernameInfo.removeClass("error");
hrmanagernameInfo.addClass("complete");
return true;
}
}
As you can see for 50+ input boxes this is going to be getting huge. I
thought maybe a loop would work but not sure which way to go about it.
Possibly Array containing all the variables? Any help would be great.

Admob - Didn't receive june payment

Admob - Didn't receive june payment

Did you already receive your june payment? It's the 17th and I still don't
get anything. But they send me an email that the payment is in process!
Maybe the payment is cancelled because of the new Admob version? Please
help! The support is not answering.. Do you already have your payment?I
use Paypal. Thx in advance ;D

Lin a DataTable Coumn to a Object.Property

Lin a DataTable Coumn to a Object.Property

I am currently working on some sort of downloadmanager as part of a bigger
project. For each download I use a custom class FileTransfer that is
responsible for the download of a single file.
When large quantities of files are downloaded, they are stored in a
List<FileTransfer> within the DownloadManager class.
What I want is a live representation of those downloads in a DataGridView.
I now manually add all FileTransfers to a DataTable linked to a
DataGridView. This is static though, so the progress needs to be updated
manually.
I have created this function:
for (int i = 0; i < transfers.Count; i++)
{
if (transfers[i].State == DownloadState.Active)
{
DataRow row = null;
try
{
row = dtTransfers.Select("ID=" + transfers[i].ID)[0];
}
catch { }
if (row != null)
row["progress"] = transfers[i].Progress;
}
}
This is way to dirty, error-prone, to time-consuming, etc.
Is there a way to have to value in the DataTable change automaticly when
the FileTransfer.Progress value changes?

Friday, 16 August 2013

Uservoice updating an article doesn't work

Uservoice updating an article doesn't work

I'm writing to Uservoice articles via API. I write using following code:
data = {
:article =>
{
:question => question_name,
:answer_html => html,
:published => true
}
}
site = "http://myapp.uservoice.com"
puts "Remote site = #{site}"
consumer = OAuth::Consumer.new(APP_CONFIG["uservoice"]["key"],
APP_CONFIG["uservoice"]["secret"],
{:site => site})
accesstoken = OAuth::AccessToken.new(consumer,
user.helpdesk["uservoice"]["oauth_token"],
user.helpdesk["uservoice"]["oauth_token_secret"])
response = JSON.parse(accesstoken.post("/api/v1/articles.json",
data).body)
flow.uservoice_id = response['article']['id']
flow.save!
puts "Save successful at #{response['article']['url']}"
This works. But when I want to do an update i.e PUT,
response =
JSON.parse(accesstoken.put("/api/v1/articles/#{article_id}.json",
data))
I get a
{"errors"=>{"type"=>"unauthorized", "message"=>"Admin required: Not signed
or not admin. Unverified; Signature verification failed; User not signed:
oauthenticate failed"}}
As response. I am an admin as well. Writing (POST) works, but updating
doesn't.

Thursday, 8 August 2013

BandWidth Monitor

BandWidth Monitor

New to Ubuntu, I want a application which monitor my Bandwidth usage in
GUI for Particular time. Is any application is available for my
requirement? For ex: If I need to monitor for a month at a specific time
10 to 6.
Please share your views.

Cannot update varchar column with special characters

Cannot update varchar column with special characters

Originally i thought that this issue is related to C# TransactionScope or
Dapper.NET. But since i have tested the sql in SSMS and the issue remains
i assume that it's a pure sql issue.
This is the (simplified) update which should update a varchar(40) column.
I don't get any errors and row-count is 1. The old SparePartDescription is
EC801/¦USB/Exch Acc/JP/PE bag:
declare @rowCount int
UPDATE [tabSparePart] SET
[SparePartDescription] = 'EC801/&#9569;USB/Exch Acc/JP/PE bag'
WHERE ([idSparePart] = 13912)
set @rowCount = @@ROWCOUNT
select @rowCount
So the only difference are these special characters: &#9569; and ¦.
Maybe you have an idea why i cannot update this column.

Readability of Scientific Python Code (Line Continuations, Variable Names, Imports)

Readability of Scientific Python Code (Line Continuations, Variable Names,
Imports)

Do Python's stylistic best practices apply to scientific coding?
I am finding it difficult to keep scientific Python code readable.
For example, it is suggested to use meaningful names for variables and to
keep the namespace ordered by avoiding import *. Thus, e.g. :
import numpy as np
normbar = np.random.normal(mean, std, np.shape(foo))
But these suggestions can lead to some difficult-to-read code, especially
given the 79-character line width. For example, I just wrote the following
operation:
net["weights"][ix1][ix2] += lrate * (CD / nCases -
opts["weightcost_pretrain"].dot(net["weights"][ix1][ix2]))
I can span the expression across lines:
net["weights"][ix1][ix2] += lrate * (CD / nCases -
opts["weightcost_pretrain"].dot(net["weights"][ix1][ix2]))
but this does not seem much better, and I am not sure how deep to indent
the second line. These kinds of line continuations become even trickier
when one is double-indented into a nested loop, and there are only 50
characters available on a line.
Should I accept that scientific Python looks clunky, or are there ways to
avoid lines like the example above?
Some potential approaches:
using shorter variable names
using shorter dictionary key names
importing numpy functions directly and assigning them short names
defining helper functions for combinations of arithmetic operations
breaking operations into smaller pieces, and placing one on each line
Any wisdom is much appreciated.

why can't I run my games in python

why can't I run my games in python

I am learning to program in python and thought it would be fun to try to
start a little bit with pygame. But for some reason when I run the code it
always comes up errors, even when I copy the code letter by letter. I have
tried to import pygame in the IDLE (or what it's called) and it succeded
so I think pygame is properly installed. Can anyone help me to fix this
problem or should I just get another computer?
By the way, sorry if I spelled anything wrong, ain't a native english
speaker... :D

Dynamically change text color of all items in ListView

Dynamically change text color of all items in ListView

I want to change my activity theme dynamically without recreating
activity, the only solution I could find was to change items properties
(like background, textColor) in place, but I have a ListView with number
of items, I could iterate through all items in ListView and change
textColor, but I think it's kinda ugly solution.
Is there any better way to achieve this?
Thank you in advance

How to send current url in javacript

How to send current url in javacript

I have contact form. Javascript with ajax calls another contact-form.php
file. Is any way to send with this javascript function current url to php
file? I want to see from witch page my clients have contacted with me.
In contact-form.php
$message .= "\n\Url: http://"
.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']; obviously does not work.
My contact.js
jQuery(function ($) { var contact = { message: null, init: function () {
$('#contact-form input.contact, #contact-form a.contact').click(function
(e) { e.preventDefault();
// load the contact form using ajax
$.get( CI.base_url+"js/contact.php", function(data){
// create a modal dialog with the data
$(data).modal({
closeHTML: "<a href='#' title='Close'
class='modal-close'>x</a>",
position: ["15%",],
overlayId: 'contact-overlay',
containerId: 'contact-container',
onOpen: contact.open,
onShow: contact.show,
onClose: contact.close
});
});
});
},
open: function (dialog) {
// dynamically determine height
var h = 280;
if ($('#contact-subject').length) {
h += 26;
}
if ($('#contact-cc').length) {
h += 22;
}
var title = $('#contact-container .contact-title').html();
$('#contact-container .contact-title').html('Galvoju...');
dialog.overlay.fadeIn(200, function () {
dialog.container.fadeIn(200, function () {
dialog.data.fadeIn(200, function () {
$('#contact-container .contact-content').animate({
height: h
}, function () {
$('#contact-container .contact-title').html(title);
$('#contact-container form').fadeIn(200, function
() {
$('#contact-container #contact-name').focus();
$('#contact-container
.contact-cc').click(function () {
var cc = $('#contact-container #contact-cc');
cc.is(':checked') ? cc.attr('checked', '')
: cc.attr('checked', 'checked');
});
});
});
});
});
});
},
show: function (dialog) {
$('#contact-container .contact-send').click(function (e) {
e.preventDefault();
// validate form
if (contact.validate()) {
var msg = $('#contact-container .contact-message');
msg.fadeOut(function () {
msg.removeClass('contact-error').empty();
});
$('#contact-container .contact-title').html('Sending...');
$('#contact-container form').fadeOut(200);
$('#contact-container .contact-content').animate({
height: '80px'
}, function () {
$('#contact-container .contact-loading').fadeIn(200,
function () {
$.ajax({
url: CI.base_url+'js/contact.php',
data: $('#contact-container form').serialize()
+ '&action=send',
type: 'post',
cache: false,
dataType: 'html',
success: function (data) {
$('#contact-container
.contact-loading').fadeOut(200, function
() {
$('#contact-container
.contact-title').html('Aèiû!');
msg.html(data).fadeIn(200);
});
},
error: contact.error
});
});
});
}
else {
if ($('#contact-container
.contact-message:visible').length > 0) {
var msg = $('#contact-container .contact-message div');
msg.fadeOut(200, function () {
msg.empty();
contact.showError();
msg.fadeIn(200);
});
}
else {
$('#contact-container .contact-message').animate({
height: '30px'
}, contact.showError);
}
}
});
},
close: function (dialog) {
$('#contact-container .contact-message').fadeOut();
$('#contact-container .contact-title').html('Iki:)');
$('#contact-container form').fadeOut(200);
$('#contact-container .contact-content').animate({
height: 40
}, function () {
dialog.data.fadeOut(200, function () {
dialog.container.fadeOut(200, function () {
dialog.overlay.fadeOut(200, function () {
$.modal.close();
});
});
});
});
},
error: function (xhr) {
alert(xhr.statusText);
},
validate: function () {
contact.message = '';
if (!$('#contact-container #contact-name').val()) {
contact.message += 'Pamirðote savo vardà. ';
}
var email = $('#contact-container #contact-email').val();
if (!email) {
contact.message += 'Pamirðote savo E-Mail ';
}
else {
if (!contact.validateEmail(email)) {
contact.message += 'E-mail klaidingas... ';
}
}
if (!$('#contact-container #contact-message').val()) {
contact.message += 'Message is required.';
}
if (contact.message.length > 0) {
return false;
}
else {
return true;
}
},
validateEmail: function (email) {
var at = email.lastIndexOf("@");
// Make sure the at (@) sybmol exists and
// it is not the first or last character
if (at < 1 || (at + 1) === email.length)
return false;
// Make sure there aren't multiple periods together
if (/(\.{2,})/.test(email))
return false;
// Break up the local and domain portions
var local = email.substring(0, at);
var domain = email.substring(at + 1);
// Check lengths
if (local.length < 1 || local.length > 64 || domain.length < 4 ||
domain.length > 255)
return false;
// Make sure local and domain don't start with or end with a period
if (/(^\.|\.$)/.test(local) || /(^\.|\.$)/.test(domain))
return false;
// Check for quoted-string addresses
// Since almost anything is allowed in a quoted-string address,
// we're just going to let them go through
if (!/^"(.+)"$/.test(local)) {
// It's a dot-string address...check for valid characters
if (!/^[-a-zA-Z0-9!#$%*\/?|^{}`~&'+=_\.]*$/.test(local))
return false;
}
// Make sure domain contains only valid characters and at least
one period
if (!/^[-a-zA-Z0-9\.]*$/.test(domain) || domain.indexOf(".") === -1)
return false;
return true;
},
showError: function () {
$('#contact-container .contact-message')
.html($('<div
class="contact-error"></div>').append(contact.message))
.fadeIn(200);
}
};
contact.init();
});
Im greedy in javascript, so I hope you guys can help me.