Friday, 27 September 2013

Q: AudioSteamer sometimes doesn't change to AS_PLAYING state

Q: AudioSteamer sometimes doesn't change to AS_PLAYING state

My Music app need to show real-time when the music is playing.I get the
time value from audioStreamer's progress.But if audioStreamer doesn't
change to AS_PLAYING state, the progress value is always 0.0. OK,if I play
next song by allocating a new audioStreamer with a new Song URL,it may be
work correctly. I am confused about this situation. So,I need help.Thanks!

How to append straight markup to HEAD without jQuery?

How to append straight markup to HEAD without jQuery?

I have a string containing HTML for stylesheets (created via the Rails
asset pipeline), and I need to append this to the head and have the
stylesheets actually load, in all major browsers. The string looks like
this:
<link
href="https://www.v.me/assets/core-28020ec7a202f8bc47a5d70d5aeb8477.css"
media="screen" rel="stylesheet" type="text/css" />
<link
href="https://www.v.me/assets/widgets-d4c93376a05ffe6d726371b89bc58731.css"
media="screen" rel="stylesheet" type="text/css" />
<link
href="https://www.v.me/assets/flowplayer-minimalist-3254ab41f4865c79282728f0012bb98d.css"
media="screen" rel="stylesheet" type="text/css" />
<link
href="https://www.v.me/assets/main-12765c4980ba6d109852c52830b34586.css"
media="screen" rel="stylesheet" type="text/css" />
I need to do this without using jQuery. Is this possible?
I wish I had the URLs in an array, but I don't. As a last resort, I could
consider using a regex to parse out the URLs, but I'd like to avoid this.

Hash map iteration

Hash map iteration

How do I iterate through a hash map to find the first 10 elements for eg
if my map contains string as key and int as value, I want to fetch the
first 10 values with highest integer?

Connect to MongoDB/mongoHQ with HotTowel localy in visual studio

Connect to MongoDB/mongoHQ with HotTowel localy in visual studio

i am trying wthout success to post a json file in MongoDB/mongoHQ using
ajax but all i recieve is :
XMLHttpRequest cannot load
https://api.mongohq.com/databases/myFirsttry/collections/customers/documents?_apikey=bblctgd9pffzwhrrq5oo.
Origin http://localhost:56936 is not allowed by
Access-Control-Allow-Origin. localhost:56936/:1
error
first i was thinking it s due tu same origin policy but after a time i
find out that it was not the problem since i can run Get
can anyone help me solving this ?

octave-optim: minimize function applied to only partial list of parameters

octave-optim: minimize function applied to only partial list of parameters

I'm trying to minimize a scalar function of two variables, but I only want
to minimize with respect to the first argument:
function val = f( x, y )
val = (y*x-1.2345)^2;
endfunction
I'd like to pass the value y=2.345 and minimize on x only.
[ xret, fval ] = minimize( @f, ['x'], ??? )
How do I pass y to the f() function, without minimizing on y also?

Insert selected text file after existing text in PowerPoint

Insert selected text file after existing text in PowerPoint

I have created a macro in PowerPoint that does the following: User clicks
text frame on the slide. It names the frame and opens a dialog for them to
choose from a list of text documents. They choose one and the text is read
and inserted into the named text frame.
Here's the insert part of the code:
Dim file As Object
Dim Text As String
Set file =
CreateObject("Scripting.FileSystemObject").OpenTextFile(vrtSelectedItem,
1)
Text = file.ReadAll
oShape.TextFrame.TextRange.Text = Text 'Insert the text into the text frame
The problem I have is that it clears any existing text in the frame,
instead of adding to it. I really need to add the newly selected text
after any existing content in the frame. For instance, if they are adding
in a selection of quotes, they need to add one after the other.
Can anyone advise on ways of doing this?

Thursday, 26 September 2013

Many links with same jquery animation, how to organize them better?

Many links with same jquery animation, how to organize them better?

I have an question about jQuery - I'm working on big system's menu
simulation, so others can play with that and decide, how it should be
better organized - usability and user experience stuff.
Menu is multilevel and every part must be draggable - so it's important (I
guess) to stay all parts in same page. But this not what I want to ask
actually. I have submenu's menu, so it opens using slideToggle() class by
clicking on the menu link.
<script>
$( "#terms" ).click(function() {
$( "#1" ).slideToggle( "slow" );
});
$( "#tc" ).click(function() {
$( "#tc-2" ).slideToggle( "slow" );
});
</script>
I have a lot of that kind of links, so I don't want to write code for
every link, I want to create something like
<script>
$( "a" ).click(function() {
$( "#href" ).slideToggle( "slow" );
});
</script>
So by clicking on the link it opens only this div, which have same id, as
link href.
Sorry for lame question, I really don't know how to explain google what I
want.

Thursday, 19 September 2013

SVN: Revision Numbers on a Branch

SVN: Revision Numbers on a Branch

There are a couple of points about SVN revision numbering on a branch
which are not clear to me:
When I create a branch, does the branch get its own revision number?
How does SVN does handle the revision numbering on the branch? Does branch
have its own sequence of revision numbers separate from the Trunk and
other branches? Or there is only one single sequence numbering for the
whole SVN server? To clarify, please explain what happens when a commit is
done on a branch.

Using while loop as input validation

Using while loop as input validation

I'm trying to use while loop to ask the user to reenter if the input is
not an integer
for eg. input being any float or string
int input;
Scanner scan = new Scanner (System.in);
System.out.print ("Enter the number of miles: ");
input = scan.nextInt();
while (input == int) // This is where the problem is
{
System.out.print("Invalid input. Please reenter: ");
input = scan.nextInt();
}
I can't think of a way to do this. I've just been introduced to java

Search for an existing item in database and fill out a webform

Search for an existing item in database and fill out a webform

For my work we fill in the names for engineers who are working for us that
day. Every time we write the name, phonenumber, company and other data.
I made an App where I can fill in all the required data, but I want to
(auto) fill or choose the existing engineers, phonenumber, company in the
form fields, which worked for us before.
Can you please help me in the right direction?

trigger upgrade from sql server 2005 to sql server 2012

trigger upgrade from sql server 2005 to sql server 2012

I have a serious problem. I have about 200 sql server 2005 databases and
every database has at least 30-40 tables, each with about 10 triggers.
Now the problem is that we have upgraded from sql server 2005 to 2012 and
the triggers are syntactically incorrect now.
How do I change the syntax for so many triggers? Or better still, how do I
make them work in sql server 2012?
Any help would be highly appreciated!! Thanks in advance!
Please help.

Best way to pass css class attribute to grails fields plugin custom template

Best way to pass css class attribute to grails fields plugin custom template

Working with the Grails Fields plugin, I have some custom templates for
which I'd like to pass in an attribute named class (for CSS styling).
e.g. Here's what I want to do:
<f:field property="someProperty" class="someCustomCssClass" />
The problem is I can't simply look for the "class" property in the custom
template, as that's a reserved word. I'd rather not use a different
attribute name like "cssClass", because then I can't easily swap between
default fields template usage and custom fields template usage.
The only thing I can think of so far is to parse the "widget" property and
grab the class out of that String, but is there a better way to grab the
value of the class attribute in a custom fields template?

MS Access enter parameter value

MS Access enter parameter value

I have a form and in the form is a sub form that displays rows from a
query. One of the columns in the subform is the DNANumber. The report
works 100%. Problem is, when I call the report using the following code,
strWhereClause = "[DNANumber]=" & strText
DoCmd.OpenReport "Certificate", acViewPreview, , strWhereClause, , acHidden
I get a popup message asking for the parameter value, also displaying that
exact value it is looking for above the textfield. I have checked all the
spelling in the queries, forms , subforms and tables and controlls.
Everything is fine. Why do I get this popup message. Further, If I type in
the value, it displays the report without a problem.
TIA

Handling 3 finger tap in Android

Handling 3 finger tap in Android

I am using OnTouchListener to capture multitouch events for ex. a 3 finger
tap , I could able to detect up to 2 fingers. i.e event.getPointerCount()
returns upto 2. Even same with onTouchEvent(). Is there any other API for
handling this ? I have enabled 3 finger tap detection on my test device.
This is what I have done so far:
package com.example.toucheventsample;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.VideoView;
public class TouchEventActivity extends Activity implements OnTouchListener{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
VideoView videoView = (VideoView) findViewById(R.id.video);
videoView.setOnTouchListener(this);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.touch_event, menu);
return true;
}
public boolean handleTouchEvent(MotionEvent event) {
boolean handled = true;
int action = event.getAction();
int count = event.getPointerCount();
switch (action & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_POINTER_UP:
if (3 == count) {
// handle 3 finger tap
}
break;
}
return handled;
}
@Override
public boolean onTouch(View view, MotionEvent event) {
int count = event.getPointerCount();
handleTouchEvent(event);
return true;
}
}

Not null column to shift left in mysql

Not null column to shift left in mysql

I am working on MySQL database. I have a table empreporting, this table
contains employeeid and reportingemployeeid columns
SELECT e3.`ReportingEmployeeId` AS Level0,e2.`ReportingEmployeeId` AS
Level1,e1.`ReportingEmployeeId` AS Level2,e1.`EmployeeId` AS Level3
FROM empreporting e1
LEFT JOIN empreporting e2 ON e1.`ReportingEmployeeId` = e2.`EmployeeId`
LEFT JOIN empreporting e3 ON e2.`ReportingEmployeeId` = e3.`EmployeeId`
the above query giving below result:
Level0 Level1 Level2 Level3
\N \N 379 369
\N 379 484 372
\N \N \N 379
Required result format is :
Level0 Level1 Level2 Level3
379 369 \N \N
379 484 372 \N
379 \N \N \N
Pls any one help me. Thanks in advance
Prakash

Wednesday, 18 September 2013

Compare Two Character Arrays in C

Compare Two Character Arrays in C

I have a string struct.
struct string
{
char *c;
int length;
int maxLength;
}
I want to check if two strings are equal.
So I want to run a for loop.
for(int i = 0; i < length; i++)
if(s1[i] != s2[i]) // This code is more C# than C.
s1 and s2 are both string structs.
How do I do this if(s1[i] != s2[i]) ?
EDIT: I just did this, is it over kill?
for(i = 0; i < length; i++)
if((*s1).c[i] != (*s2).c[i])
{
printf("Failed");
return 0;
}

Including Capital & Non Capital Letters in Regex

Including Capital & Non Capital Letters in Regex

I'm attempting to create an SQL filtering system which notifies the user
when the request contains any of the included words.
Currently my regex only supports all caps & I was wondering whether it
would be possible to have it also accept non-caps as-well as other
combinations of letters for example SElEcT
I understand entering this manually would be possible, however, this is
not the most productive way to perform such a task.
This is my current code:
function checkString($string)
{
if(preg_match('[SELECT|FROM|DATABASE|TABLE|DROP|ALTER|LIKE|IN|BETWEEN|UNION|NULL|CHECK|JOIN|AVG|SUM|COUNT|FIRST|LAST|MAX|MIN|GROUP]',
$string
Thanks.

Is it possible that setting -Xmx to high on a 32 JVM can shrink the space available to JNI such that JNI fails?

Is it possible that setting -Xmx to high on a 32 JVM can shrink the space
available to JNI such that JNI fails?

I have a problem where allocating to much -Xmx causes a problem of the
most unusual kind.
The Problem: Setting -Xmx to 3072m on a 32bit JVM on a 64bit Linux OS
works except for one condition where a servlet attempts to communicate
with many outside entities via JNI IPC. When we lower the -Xmx to 2048m it
works. No errors within tomcat are ever seen. The only errors that are
seen are within the JNI logging code.
This leads me to believe that since this is a 32bit process, setting the
max java heap space to 3072m leaves to little space for the JNI C++ native
code. It cannot allocate enough space for.. threads, or whatever.
I've investigated: Maximum Java heap size of a 32-bit JVM on a 64-bit OS
and this isn't what I'm asking.
The Question:
Is it possible that setting -Xmx to high on a 32 JVM can shrink the space
available to JNI such that it fails? How might we determine for a given
situation what is available to that JNI process?
The list of Knowns:
Linux 64bit HCOS-130:~ # uname -a Linux HCOS-130 2.6.27.19-5-default #1
SMP 2009-02-28 04:40:21 +0100 x86_64 x86_64 x86_64 GNU/Linux
java 6 32bit jre1.6.0_45
CATALINA_OPTS="-server -Xmx3072m -XX:+HeapDumpOnOutOfMemoryError
-XX:HeapDumpPath=$CATALINA_HOME/logs"
ps aux | grep -i jsvc
root 19827 0.0 0.0 2344 368 ? Ss 17:32 0:00 jsvc.exec
-user tomcat -home /usr/java/jre1.6.0_45
-Dcatalina.home=/usr/java/apache-tomcat
-Djava.security.auth.login.config=/usr/java/apache-tomcat/conf/jaas.conf
-Djavax.net.ssl.trustStore=/usr/java/apache-tomcat/conf/truststore.ks
-Djavax.net.ssl.trustStorePassword=changeit -Djava.awt.headless=true
-Djava.io.tmpdir=/usr/java/apache-tomcat/temp
-Djavax.net.ssl.trustStore=/usr/java/apache-tomcat/conf/truststore.ks
-Djavax.net.ssl.trustStorePassword=changeit -outfile
/usr/java/apache-tomcat/logs/catalina.out -errfile
/usr/java/apache-tomcat/logs/catalina.err -server -Xmx3072m
-XX:+HeapDumpOnOutOfMemoryError
-XX:HeapDumpPath=/usr/java/apache-tomcat/logs -cp
/usr/java/apache-tomcat/conf:/usr/java/apache-tomcat/bin/bootstrap.jar:/usr/java/apache-tomcat/bin/commons-daemon.jar:/usr/java/apache-tomcat/bin/tomcat-juli.jar:/usr/java/apache-tomcat/shared/lib/jni.jar:/usr/java/apache-tomcat/shared/lib/log4j-1.2.14.jar:/usr/java/apache-tomcat/shared/lib/dhcajni.jar:/usr/java/apache-tomcat/shared/lib/activejni.jar
org.apache.catalina.startup.Bootstrap
tomcat 19829 1.5 0.1 2863864 162164 ? Sl 17:32 0:10 jsvc.exec
-user tomcat -home /usr/java/jre1.6.0_45
-Dcatalina.home=/usr/java/apache-tomcat
-Djava.security.auth.login.config=/usr/java/apache-tomcat/conf/jaas.conf
-Djavax.net.ssl.trustStore=/usr/java/apache-tomcat/conf/truststore.ks
-Djavax.net.ssl.trustStorePassword=changeit -Djava.awt.headless=true
-Djava.io.tmpdir=/usr/java/apache-tomcat/temp
-Djavax.net.ssl.trustStore=/usr/java/apache-tomcat/conf/truststore.ks
-Djavax.net.ssl.trustStorePassword=changeit -outfile
/usr/java/apache-tomcat/logs/catalina.out -errfile
/usr/java/apache-tomcat/logs/catalina.err -server -Xmx3072m
-XX:+HeapDumpOnOutOfMemoryError
-XX:HeapDumpPath=/usr/java/apache-tomcat/logs -cp
/usr/java/apache-tomcat/conf:/usr/java/apache-tomcat/bin/bootstrap.jar:/usr/java/apache-tomcat/bin/commons-daemon.jar:/usr/java/apache-tomcat/bin/tomcat-juli.jar:/usr/java/apache-tomcat/shared/lib/jni.jar:/usr/java/apache-tomcat/shared/lib/log4j-1.2.14.jar:/usr/java/apache-tomcat/shared/lib/dhcajni.jar:/usr/java/apache-tomcat/shared/lib/activejni.jar
org.apache.catalina.startup.Bootstrap

Getting error "Arithmetic exception" on debugging

Getting error "Arithmetic exception" on debugging

While answeing this question I tried to run this code (for generating
random numbers in a given range);
#include<stdio.h>
#include <stdbool.h>
#include <stdlib.h>
#include <time.h>
int main()
{
int max_range, i = 0, rand_num;
bool digit_seen[max_range + 1]; // VLAs For C99 only
srand((unsigned)time(NULL));
printf("Enter your maximum of range: ");
scanf("%d", &max_range);
for (int i = 1; i <= max_range; i++)
digit_seen[i] = false;
for (;;)
{
rand_num = rand() % max_range + 1;
if(rand_num !=3)
if(!digit_seen[rand_num])
{
printf("%d ", rand_num);
digit_seen[rand_num] = true;
i++;
}
if( i == (max_range - 1) )
exit(0);
}
return 0;
}
It worked fine upto a max_range of 47 but after that I got this error on
debugging

Any idea why I am getting this?

Ruby gsub regex doesn't match end of string

Ruby gsub regex doesn't match end of string

I'm trying to add <p> tags to user-generated text in place of line breaks.
Here is my code:
def prep_ug_text string, tags=[]
tags = tags.empty? ? ['p'] : tags
sanitize string.gsub(/(.*)[\n\r\Z$]+/, "<p>\\1</p>"), tags: tags
end
The replacement works exactly as expected for the first paragraph, but it
only wraps the final block of text if I add an extra carriage return. It
seems like the \Z and $ are not matching as I expect them to.
What am I doing wrong?
Examples:
This...
Lorem ipsum dolor sit amet.
Vestibulum laoreet erat id quam.
...turns into this
<p>Lorem ipsum dolor sit amet.</p>
Vestibulum laoreet erat id quam.

YAF: user-friendly URLs for user profiles

YAF: user-friendly URLs for user profiles

I'm using YAF Framework,
and want to make the user's profile link to be user-friendly by using
their usernames, if username is abdelhady so I want the url to be
www.mysite.com/abdelhady
which of course will route back to something like this
www.mysite.com/profile/get/username/abdelhady
I've tried something like this, but it didn't work:
$config = array(
"community" => array(
"type" => "rewrite",
"match" => "/:username",
"route" => array(
'controller' => "profile",
'action' => "get",
)
)
);
Yaf_Dispatcher::getInstance()->getRouter()->addConfig(
new Yaf_Config_Simple($config));
It only works if I used a match like this "match" => "/profile/:username",
, but it is not what I want for my project !!! Do you have any
suggestions?

How do I fix the scala autoindent script for vim?

How do I fix the scala autoindent script for vim?

The current vim indent script for Scala has a strange behavior, in that it
seems to indent after the first line of a code block; indenting the code
package akka.tutorial.first.scala
import akka.actor._
import akka.routing.RoundRobinRouter
import scala.concurrent.duration._
object PdfsFrecpo extends App {
def calculate(nrOfWorkers: Int, nrOfElements: Int, nrOfMessages: Int) {
// Create an Akka system
val system = ActorSystem("PiSystem")
// create the result listener, which will print the result and shutdown
the system
val listener = system.actorOf(Props[Listener], name = "listener")
// create the master
val master = system.actorOf(Props(new Master(
nrOfWorkers, nrOfMessages, nrOfElements, listener)),
name = "master")
// start the calculation
master ! Calculate
}
calculate(nrOfWorkers = 4, nrOfElements = 10000, nrOfMessages = 10000)
}
yields
package akka.tutorial.first.scala
import akka.actor._
import akka.routing.RoundRobinRouter
import scala.concurrent.duration._
object PdfsFrecpo extends App {
def calculate(nrOfWorkers: Int, nrOfElements: Int, nrOfMessages: Int) {
// Create an Akka system
val system = ActorSystem("PiSystem")
// create the result listener, which will print the result and
shutdown the system
val listener = system.actorOf(Props[Listener], name = "listener")
// create the master
val master = system.actorOf(Props(new Master(
nrOfWorkers, nrOfMessages, nrOfElements, listener)),
name = "master")
// start the calculation
master ! Calculate
}
calculate(nrOfWorkers = 4, nrOfElements = 10000, nrOfMessages = 10000)
}
I don't know if this is intentional, but I would personally prefer no
additional indentation after the first line of the code block, i.e. the
lines // create the result listener... and following should be aligned
with val system = ....
Any pointers?

CodeGear Delphi 2009 CPU Debug Window keeps coming

CodeGear Delphi 2009 CPU Debug Window keeps coming

When i debug the cpu debug window keeps coming up. Most oft the time i'm
unable to debug.
Infos: CodeGear Delphi 2009 Version 12.0.3420.21218 Windows 7 Professional
64-Bit-Version(6.1, Build 7601) Service Pack 1
I allready tried:
Projektname:
(1) Backup all project files (2) Delet all projectname.* files exept
projectname.dpr (3) Build projectname.dpr new
System.pas
(1) backup system.dcu and sysinit.dcu out of the lib directory (2) Add
D-,C-,L-,Y- to system.pas (3) Start cmd and change dir to
C:\programme\CodeGear\RAD Studio\6.0\bin (4) use: dcc32 -m -y -z
..\source\win32\rtl\sys\system.pas (5) Move the system.dcu and sysinit.dcu
from source dir to lib dir
Non-User Breakpoints
Tools->Options->Debugger Options->Codegear Debuggers Ignore non-user
breakpoints -> check
Add to Regedit
HKCU\Software\Borland|Delphi\7.0\Debugging: EnableCPU (stringvalue):0
Change in Regedit
HKEY_CURRENT_USER/software/Borland/Delphi/6.0/Debugging/Integrated
Debugging = 0
.DCU and .DCP
(1) delete all .dcu and .dcp files (2) Build project new
Don't Use Debug .dcus
Project-> Delphi Compiler -> Compiling Use debug .dcus = false
Library Path make sure that you don't have the $(BDS)\Lib\Debug value set
in the Library or Browsing paths (Project->Options->Compiler); (Set it to
$(BDS)\Lib)
I have no idear how to reproduce this or how to fix it.

I need some help about config in Projekktor HTML5 Video player

I need some help about config in Projekktor HTML5 Video player

How can I config Projekktor HTML5 Video player video scaling option I try
to use
videoScaling: 'aspectratio'
but not have any change. the default from library is fill full width and
height.

Tuesday, 17 September 2013

MVC in android populating listview from resources

MVC in android populating listview from resources

It seems their should be a way to statically populate a listview with an
array of buttons using only xml using android:resource or android:entries
possibly. I would prefer a resource xml file seperate from my main layout.
If I understand MVC the view is more of a static thing where as the
controller has listeners for the view and makes changes to the view. I
don't know if string array can hold button objects or where I am going
wrong. Any suggestions? Oh and the buttons all should have the same
properties but maybe that is another question?
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/MainFrameLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
package="com.union.doogie"
android:animateLayoutChanges="true"
android:layoutMode="opticalBounds"
android:visibility="visible"
tools:context=".MainActivity" >
<ListView
android:id="@+id/listViewmain"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:entries="@buttons/Buttons" >
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent" >
</TextView>
</ListView>
</FrameLayout>

How to find the number of special characters in a HTML field?

How to find the number of special characters in a HTML field?

Well, it's just as the title says. I wanted to count the number of special
characters, number of uppercase, lowercase characters in a HTML text field
using java script. How do I do that?
Surprisingly, I was not able to find any answer for this when I searched.
Thanks.

C# double to float convert

C# double to float convert

I have a little problem with converting double to float. Code
float volume = 0.5;
Double i = Volume.Value;
volume = (float)i / 100F;
Bass.BASS_SetVolume(volume);
As You can see I'm using BASS Library. Volume is a Slider that gives me a
value from 1 to 100. The problem is I'm getting this error:
error CS0664: Literal of type double cannot be implicitly converted to
type 'float'; use an 'F' suffix to create a literal of this type
Why? I Searched on google, found nothing. Please help.

Click event not bubbling when image clicked

Click event not bubbling when image clicked

I have the following markup:
<ul>
<li class="tgt"><img src="http://placehold.it/48x48" width="48px"
height="48px"></li>
<li class="tgt"><img src="http://placehold.it/48x48" width="48px"
height="48px"></li>
<li class="tgt"><img src="http://placehold.it/48x48" width="48px"
height="48px"></li>
</ul>
Code from the fiddle:
$('.tgt').on('click', function (e) {
if ($(e.target).hasClass('tgt')) {
$(e.target).addClass('active');
}
});
I attach a click handler using jquery's event delegation to all .tgt
elements. For some reason, if I click on the image, the event does not
bubble up to the li. Instead the event target is revealed to be the image.
Here's a fiddle: http://jsfiddle.net/CgC4V/
Why is the event not bubbling up to li.tgt?

datetimepicker jumps back to 1899 on focus, how can I fix it?

datetimepicker jumps back to 1899 on focus, how can I fix it?

I am using date time picker
http://trentrichardson.com/examples/timepicker/ to select date and time.
However, there is something weird is happening when I click on the input
field to select the data. the input field will show a value dated back to
1899. I am not sure why it is doing this.
Please note that I am creating these inputs "on the fly" using ajax
request. The following is how I created those inputs
var new_code = returnMeetingDuration('newCall_onCalendar',
'onCalendar[]', 0, min_val, max_val, min_val);
$('#listNextCallDates').append('<input type="text" value=""
name="triggerOn[]" class="triggerOnPicker" readonly="readonly"
style="width: 175px;">' +
'<input type="hidden"
name="engine_ids[]"
value="outbound" />' +
'<div style="display:block;
margin: 5px;">'+
'<input type="checkbox"
id="isAppointment"
name="isAppointment[]"
value="outbound" /> Make an
appointment</div>'+
'<div style="display:block;
margin: 5px;">' +
'<input type="checkbox"
id="calendarAddBox"
name="calendarAdd[]"
value="outbound" />Add to my
Calendar</div>' + new_code);
Then I generate the dattimepicker using the following codes
$('.triggerOnPicker').datetimepicker({
timeFormat: "hh:mm TT",
changeMonth: true,
changeYear: true,
stepMinute: 5,
beforeShowDay: $.datepicker.noWeekends,
HourMin: 5,
HourMax: 17,
minDate: 0
});
I have tried this code but it is not working.
$('.triggerOnPicker').datetimepicker({
timeFormat: "hh:mm TT",
changeMonth: true,
changeYear: true,
stepMinute: 5,
beforeShowDay: $.datepicker.noWeekends,
HourMin: 5,
HourMax: 17,
minDate: 0
}).on('focus', function(){
$(this).not('.hasDatePicker').datepicker();
});
The weird thing is that it works correctly and sometimes it does not. Can
someone help me with this please? Thanks

How to see if number in column from file1 is between numbers from columns in file2 using Bash - nested loops?

How to see if number in column from file1 is between numbers from columns
in file2 using Bash - nested loops?

I would like to do the following in the bash command line...
I have 2 files. File1 looks like.
585 1504 13 10000 10468 ID1
585 3612 114 10468 11447 ID2
585 437 133 11503 11675 ID1
File2 looks like.
400220 10311 10311
400220 11490 11490
400220 11923 11923
for each number in File2 column 2, I would like to know if it is between
any of the number pairs in File1 columns 4 and 5 And create File3.txt with
the output as follows...
If yes, I want to write column 2 from File2 and column 6 from File1 to
File3. If no, I want to write column 2 from File2 and the string "NoID" to
File3. So for the example data File3.txt should look like so.
10311 ID1
11490 NoID
11923 NoID
I am used to working in Python and in there would write a script using a
nested for loops and if statements, but would prefer to use Bash for this
(of which I am still a relative beginner). It seems to me that using a
similar nested loop approach combined with awk and other conditional
statements could be the way to go. can anyone suggest good ideas with
maybe example syntax?
NB. The actual files contain over 3 million rows data
Cheers muchly in advance

Sunday, 15 September 2013

Ext.data.Store.loadRawData reading only last record

Ext.data.Store.loadRawData reading only last record

I am trying to read a JSON response into Ext.grid.Panel using Ajax .
However, Grid is showing only last record out of 5 results, can anyone
please help:
JSON Response:
{"tweets":[{"text":"T 1156 -On #KBC the 1 crore winner Taj Mohammed
Rangrez ... requires great maturity and guts to leave #KBC at 1crore and
2 lifelines
unused","date":"1379273177","user":"\/SrBachchan","id":"145125358"},{"text":"T
1156 -Taj Mhammed Rangrez wins 1 crore rupees at #KBC .. what a game he
played .. and he, such a beautiful human !! write in to
#KBC","date":"1379272401","user":"\/SrBachchan","id":"145125358"},{"text":"T
1156 -SO ... what did you think of the 1st Crorepati winner on #KBC ...
send in your comments to me through the #KBC tag .. love ya
!!","date":"1379272302","user":"\/SrBachchan","id":"145125358"},{"text":"T
1156 -The last 2 tweets should have been numbered T 1156 ... apologies
!!","date":"1379272226","user":"\/SrBachchan","id":"145125358"},{"text":"T
1155 -Ashok Chakradhar writes : \u092a\u094d\u0930\u0936\u094d\u0928 2.
\u0905\u0928\u093e\u0921\u093c\u0940 \u091c\u0940,
\u0906\u091c\u0915\u0932 \u0926\u0942\u0938\u0930\u094b\u0902
\u0915\u093e \u092d\u0932\u093e \u0915\u0930\u0928\u0947
\u0935\u093e\u0932\u094b\u0902 \u0915\u094b
\u092c\u0947\u0935\u0915\u0942\u092b \u0938\u092e\u091d\u093e
\u091c\u093e\u0924\u093e \u0939\u0948\u0964 (cont)
http:\/\/tl.gd\/n_1rmfn3e
","date":"1379270895","user":"\/SrBachchan","id":"145125358"}]}
Ext Code:
var tweetModel = Ext.define('Tweet', {
extend: 'Ext.data.Model',
fields: [
{ name: 'text', type: 'string' },
{ name: 'date', type: 'string' },
{ name: 'user', type: 'string' },
{ name: 'id', type: 'string' }
]
});
var v= Ext.create('Ext.data.Store', {
model: tweetModel,
proxy: {
type: 'ajax',
url: '',
reader: {
type: 'json',
root: 'tweets'
}
}
});
var trailerPanel= Ext.create('Ext.grid.Panel', {
title: 'Tweets List',
store: v,
columns: [
{text: 'Text', dataIndex:'text',filterable: true},
{text: 'Date', dataIndex:'date',filterable: true},
{text: 'User', dataIndex:'user',filterable: true},
{text: 'ID', dataIndex:'id',filterable: true}
],
width: 1000,
forceFit: true,
});
var frmTrailerPanel = Ext.create('Ext.form.Panel', {
title: 'Hashtag Form',
width: 300,
bodyPadding: 10,
renderTo: Ext.getBody(),
items: [{
xtype: 'textfield',
itemId:'hashtag',
name: 'hashtag',
fieldLabel: 'Enter Hashtag',
allowBlank: false // requires a non-empty value
}
],
//renderTo:ext.getBody(),
buttons: [{
text: 'Search',
handler: function() {
var form = this.up('form').getForm();
if(form.isValid()){
form.submit({
url: '../../assignment/index.php',
waitMsg: 'Fetching tweets...',
success: function(form, action) {
},
failure: function(form, action) {
var myData = Ext.JSON.decode(action.response.responseText);
v.loadRawData(myData,true);
trailerPanel.render(Ext.getBody());
}
});
}
}
}
]
});
Output:

making a self made html fixer handle universal tags

making a self made html fixer handle universal tags

what this following code does is, it takes a set open tag and a end tag,
and if there are any unclosed tags of that type, it will close them. the
problem with this is, it wont handle font tags, as there is more to font
tags then just <font>. i was thinking that there would be a way to use
regex to have it match the tags before hand then pass it to this html
fixer so that way it could handle any type of tag. any suggestions? the
regex would probably look like <+[\w ="\']+?> for the start tag and </+[\w
="\']+?> for the end tag. and this is in 3.x if you are wondering about
the odd syntax i use.
def check_html(otag, etag, text):
ret = ['f', text, otag, etag] if text.count(otag) != text.count(etag)
else ['a', text, otag, etag]
return fix_html(ret)
def fix_html(x):
grade, text, otag, etag = x
ret = [otag + text if text.endswith(etag) else s for s in
text.split()] if grade == 'f' else text
ret = [text + etag if text.startswith(otag) else s for s in ret] if
grade == 'f' else text
return ret[0] if grade == 'f' else ret

iPhone 4" simulator opening 3.5" app

iPhone 4" simulator opening 3.5" app

My app uses Storyboard and on the storyboard it looks fine with the bigger
4" screen. But, on the simulator it opens the 3.5" app and puts some black
space up and down the screen.
Storyboard:
Simulator:

jquery background image styling

jquery background image styling

I'm having trouble styling a background image that I'm using jQuery to
cycle the source of. The image is inserted in the css as a background and
stretched to cover the entire window. Here's my css:
html {
background: url(images/image_1.jpg) no-repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
Before adding the jQuery swapper the image looks as intended. When I add
the swapper, however, the css styling fails. The cover effects seem to
drop and I'm left with a fixed-size image. The swapping works perfectly,
though. I would think the jQuery css would add to to css but it's almost
as if it's overriding all the properties for the html element and just
leaving me with the background source but no covering. Here's the script
and the html:
Here's what my html and javascript look like:
<html>
<head>
<script
src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script language="javascript">
<!--
var ctr = 0;
$(document).ready( function () {
nextBg();
});
function nextBg()
{
++ctr;
if( ctr <= 3 )
{
$("html").css( "background", "url(images/repurpose2/image_" +
ctr + ".jpg) no-repeat center center fixed" );
if( ctr == 3 )
ctr = 0;
}
}
//-->
</script>
<link rel="stylesheet" type="text/css" href=style.css>
</head>
<body>
<div class="image-swapper">
<a href="#" onclick="nextBg();" />Next</a>
</div>
</body>
</html>
I'm using the background image swapping approach I found here: Loop thru
100 background-images onClick
Can anyone tell me why I am unable to style my html with the style.css file?
Thanks very much!

Nest an AJAX function in a Javascript Function

Nest an AJAX function in a Javascript Function

I have AJAX code
<!-- Body Code -->
Listeners: <span id="cc_stream_info_listeners"></span>
<!-- Footer Code -->
<script type="text/javascript"
src="http://mysite.com/system/streaminfo.js"></script>
<script type="text/javascript"
src="http://mysite.com/js.php/radio/streaminfo/rnd0"></script>
Which returns dynamic listener count for an online radio stream. This code
works fine, but the js files are on a remote host. So I don't really know
how they work.
I want the page title of one of my pages to dynamically include the
listener count. Much like a twitter page counts the new tweets that are
available in your feed.
E.g. (5) My Dashboard | My Site Name Where the number is the dynamic
listener count from the AJAX function.
Here is what I have so far.
<!-- START: PAGE TITLE LISTENER CONTENT -->
<script>
function updatetitle()
{
var txt1 = "(";
var txt2 = "5";
var txt3 = ") My Dashboard | My Site Name";
var n = txt1.concat(txt2,txt3);
document.title = n;
}
</script>
<script>
window.onload = function()
{
updatetitle();
};
</script>
Simply replacing the text "5" with <span id="cc_stream_info_listeners">
doesn't work. But at least I know I have the page update component
correct. As it's working as expected with the plain text.
How can I merge these two functions - So that listener count is updated
dynamically?

copy title from anchor and show in another div

copy title from anchor and show in another div

I need to make youtube video gallery play videos on the same page when one
click's on the link it should play related video and copy title from the
link and show it as tag under video. .
So far i have do the video part need to how i can copy title from anchor
link to a title div.
I would also appreciate a more professional way on going the whole thing.
CODE on jsFiddle
$(document).ready(function () {
$('.vid_button').click(function (e) {
e.preventDefault();
var URL = $(this).attr('href');
var htm = '<iframe width="438" height="250"
src="http://www.youtube.com/embed/' + URL +
'?wmode=transparent&rel=0&theme=light&color=white&autoplay=0"
frameborder="0" allowfullscreen ></iframe>';
$('#video_container').html(htm);
return false;
});
});

SQL Server not using all CPU cores/threads

SQL Server not using all CPU cores/threads

After upgrading our SQL Server's hardware, we noticed in the Windows Task
Manager that the SQL instance is only using half of the "threads"
available to it (see screenshot).
The server has the following hardware and software:
Windows 2008 R2 Enterprise 64bit SP1
Intel Xeon E7-4870 - 4 processors (40 cores, 80 threads)
Microsoft SQL Server 2012 Enterprise Edition (64-bit)
Running select cpu_count from sys.dm_os_sys_info returns 40.
The OS sees all 80 threads. SQL Server Standard Edition supports 4
Physical CPUs which is what we have here.
Why is only half the server's processing power being used?
We have the same hardware and software on two servers and they both
exhibit the same behavior.

What does the @routes map to in playframework

What does the @routes map to in playframework

In the playframework samples I see the syntax:
<a href="@routes.Application.index" class="btn">Cancel</a>
Inspite of having a controller class called Application.index the above
throws an exception. So I would like to know what does @routes expand to
at runtime and where does it point to since I have modified the code quite
a bit to remove some other routes. I need to remove this non existing
route but I would like to know how play actually maps them.

Saturday, 14 September 2013

Download FLV video

Download FLV video

I am making a program that helps me download whole seasons of anime from
crunchyroll (Legally, of course) for private use, since my internet
connection goes down on the regular. I know its and FLV but I am not sure
how to extract it from the video.
http://www.crunchyroll.com/hunter-x-hunter/episode-36-a-big-debt-x-and-x-a-small-kick-592035
Here is an example video, can someone walk me through what I should
do/need? Finding the ID/Signature/whatever will be easy since I have some
experience with XPath Thank you

how can i use admob in delphi xe5?

how can i use admob in delphi xe5?

Can anybody tell me how to include admob adv in android app made by delphi
xe 5 ? If it is not possible to do that. Then what adv network can be
implemented there?

SqlCe sorts automatically c#

SqlCe sorts automatically c#

I'm having a problem with Sql Ce in C#. I have a database with ids like
that for example *sS1 , ss2, ss3 ss4, ss5, ss6 ... ss10 ss1*1 etc... and
this is the order I have when I display the value with visual studio. But
if I execute this query for example
SELECT SubSectionID FROM Section_SubSection WHERE(SectionID=@SectionID)
I get the Ids sorted like this automatically. ss1, ss10, ss11, ss2, ss3
etc...
I can't understand why is this happening. Can someone tell me why ? I got
2 different versions of the same application I'm making and in the first
one it doesn't have that behavior and in the second one it does. I'm also
wondering does it have a relation with the fetch order: Backward or
Forward. I can't seem to find anything related to that online.

What is "detached" instances in grails?

What is "detached" instances in grails?

What are detached intances in grails. ?
Please explain with an example.
Thanks in advance.

SWT Composite Touchable as smartphone

SWT Composite Touchable as smartphone

I using SWT to write program. I want write one class extends Composite, it
contains some buttons (as smatphone items). This composite can Touchable
to display others items.
Please help me some code?
thanks all.

RewriteRule: cannot compile regular expression

RewriteRule: cannot compile regular expression

i am getting the follwoing error
RewriteRule: cannot compile regular expression
'^/?(\d+)/?([a-zA-Z0-9-_]*)(\.html|/)?$'\n
My htaccess configuration below:
RewriteRule ^/?mokuji - [S=1] RewriteRule
^/?(\d+)/?([a-zA-Z0-9-]+)/([a-zA-Z0-9-/]+)(.html)?$
index.php?pid=$1&pkey=$2&pkey_ext=$3&%{QUERY_STRING}
Where i am making mistake?
Thank you.

Linq To SQL Query for counting same records

Linq To SQL Query for counting same records

I have a working code to check input with database & if the same record
found its shown that no other same record can be made
but i want to change it little bit by counting the same numbers of records
& shows the count in text box
var a = from b in ContactDB.GetTable<ContactInfo>() select b;
foreach (var x in a)
{
if (x.Extra == txtname.Text.ToString())
{
// code
}
How to count the total x.Extra found same as thxname.Text & shows the
count in info.TextBox

Friday, 13 September 2013

what is "static{}" in Java?

what is "static{}" in Java?

I'm not a programming in OOP so please bear with me.
This piece of code is from android's auto generate Master/Detail Flow
project :
static {
// Add 3 sample items.
addItem(new DummyItem("1", "Item 1"));
addItem(new DummyItem("2", "Item 2"));
addItem(new DummyItem("3", "Item 3"));
}
What is that? I mean is it a method?a constructor?or what?

SQL Database Dump

SQL Database Dump

there is this website for my state and i will post the link below the
website just lists all the Senate members, and congressmen and
representatives and such. There is a hyperlink for each one of their names
and when you click the name it brings you to contact information for that
person's, name, party affiliation, current assignments, office address,
and contact info, it is all public information.
The problem I am having is that I want to get the entire database to dump
it's contents, so that i can build a data structure for it. Nothing
illegal....I looked at sql injects and such, and one of my friends said
that it can be done but he wanted a hundred bucks. I figured I would dig
around and try to make fun with it and do it myself....please help!
here is the link:
http://mgaleg.maryland.gov/webmga/frmmain.aspx?pid=legisrpage&tab=subject6

How to perform an order logic in SSIS package for inserting value from source to destination by an oder of column being not null

How to perform an order logic in SSIS package for inserting value from
source to destination by an oder of column being not null

I have 4 columns in source table.
Source Table : Column 1, Column 2, Column 3, Column 4
Among those 4 columns from source table, I want to insert only 2 columns
in the destination table.
Destination table : has column A and Column B
To insert value in Column A and Column B. Now i want to perform order
operation in SSIS package.
So I want to have an oder logic in SSIS .
If there is a value in Column 1, then use that in Destination Column A and
insert from column 1 value into Column A . So, if there is value in Column
1, then Column A in destination table will be inserted.
IF there is no value in Column 1, then check the Column 2 in the source
table and if there is value in Column 2, insert that value in Column A.
Now suppose, Column 1 was null and Column 2 had value, Column 2 value will
be inserted into column A in the destination table.
Now check the column 3 in source and see if there is value, if it has
value then insert that value in Column B in Destination table. If there is
no value in Column 3 then check column 4 from source.
So basically check in those 4 columns in the order (which is specified)
and 1st value that we come across, use that in the destination Column A
and Column B.
There is tricky part is there, so 1st not null value goes into the
Destination column A and 2nd not null value goes into 2nd destination
column B, how can i figure it out which one is 2nd not null value?
I guess we can do this in SQL but I want to do in SSIS package.
I will really appreciate your help. Thank you in advance.

render from another index scaffold

render from another index scaffold

I continue with this problem
Another Post
But somebody told me that if i want i can pass parameteres in the render,
but i dont know how to do it, I mean here
<%= render :file => "userscuentas/index" %>
SO maybe I can pass the @userscuentas as parameteres I really need your help
Thanks

django python: storing foreign key, not from the form POST method, but by from data I already have

django python: storing foreign key, not from the form POST method, but by
from data I already have

I am a noob guys, I am storing 'payment' model instance via form POST
method but I have the data of the foreign key field already, because I am
coming from a page which list the objects of 'student' model. I am storing
the field of foreign key by input type="hidden" html element.
but when I submit, it shows error
Cannot assign "u'1'": "payment.student" must be a "student" instance.
Request Method: POST Django Version: 1.5.2 Exception Type: ValueError
Exception Value:
Cannot assign "u'1'": "payment.student" must be a "student" instance.
Exception Location: /usr/local/lib/python2.7/dist-> > > >
>packages/django/db/models/fields/related.py in set, line 405 Python
Executable: /usr/bin/python Python Version: 2.7.3
class payment(models.Model):
Id = models.AutoField(primary_key=True)
student = models.ForeignKey('student',db_column='student')
dateTime = models.DateField(auto_now_add=True)
amountDue = models.DecimalField(max_digits=5, decimal_places=2)
I added db_column='student', later, might not have really taken effect in
mysql database.

Custom class MPMoviePlayerController can be rotate in Fullscreen mode iOS

Custom class MPMoviePlayerController can be rotate in Fullscreen mode iOS

For now i want to create a custom class of MPMoviePlayerController and it
can be rotate when video player in FullScreen mode. It mean when user
click on Fullscreen button, video play in FullScreen mode and if user
rotate iphone, video player rotate,too .How can i do that? I don't know
how to create it. Thanks so much

Thursday, 12 September 2013

Java to python Transition

Java to python Transition

I am doing developing in java for last 3 years and now I want to do a
project on python.
After a thorough search I found "learn python the hard way" as a great
book to learn python.
But then I found this article
How should I learn python considering my 3 years of experience in Java

Responsive CSS design - large or small screen to start

Responsive CSS design - large or small screen to start

I plan to design a web app with Phonegap. As I need to deal with different
screen sizes, I will have to work with responsive design and CSS3 media
queries.
I have a 1080x720 resolution android phone, and I want to start with this
(large) resolution, and say the css is base.css. And for smaller screens,
I will add something like small.css to overwrite base.css (places where
needed).
Assume the css would be complicated, will it incur more workload for small
screen phones (whose capability tends to be weaker than large ones)? Is it
better to start with small.css as base.css, and overwrite it with big.css
on large phones? Or it doesn't matter in web app scenario (as css file
size is not a big issue)?
Any design considerations and hints?

Uncaught exception: Error: Syntax error, unrecognized expression:

Uncaught exception: Error: Syntax error, unrecognized expression:

Using the following jQuery (a lot of manipulating here, because I can only
do this in the body tag):
<script type="text/javascript">
if(!window.jQuery)
{
var script = document.createElement("script");
script.type = "text/javascript";
script.async = false;
script.src = "//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js";
var oScripts = document.getElementsByTagName("script");
var s = oScripts[0];
s.parentNode.insertBefore(script, s);
}
function wrapForum() {
jQuery(document).ready(function($) {
var $smf_content = $("#smf_col").html();
$("#smf_col").empty();
var $dptable = $(".dp_main").html();
var $dpPrev = $(".dp_main").prev();
$(".dp_main").remove();
$($smf_content).insertAfter($dpPrev);
var $body = $("body").html();
$("body").html($dp_table);
$("#smf_col").html($body);
});
}
addLoadEvent(wrapForum);
The page is here: http://devs.dream-portal.net/smf205/index.php?action=forum
I am trying to take the contents of the $dp_table after removing stuff
from it and appending what was removed to the body tag, and than remove
the entire html within the body tag and insert it into the same place
where some html was originally removed and than add it all to the body
tag.
What am I doing wrong here? Do I need to escape html? I never had a
problem doing this before with jQuery...

Scaling Databases and Servers

Scaling Databases and Servers

If you had a server and database that was getting way too much traffic,
for lets say a simple online game, how would you consider scaling the
server and database?
My thoughts are to future-proof it and scale both the server and database
horizontally. I know this creates much greater complexity, but I feel like
it's the best option.
Can someone offer me their thoughts? How would you identify the
bottlenecks and issues within the database? What are the main things to
look for before jumping in and scaling? How would you scale the server?
How would you scale the database?
Thanks :)

Adding setTimeOut to Google Analytics Funtion

Adding setTimeOut to Google Analytics Funtion

I'm having trouble passing Google Analytics parameters on link clicks. It
seems that the problem is that the new page opens before the parameters
are picked up. This leads to a red line in httpfox "ns binding error".
From SO and Google it seems the solution is to use setTimeOut with a
1,000ms delay.
Within Google-Tag-Manager I have the following custom html:
<script>
$('.submit-incident.clearingfix a').click(function(event){
dataLayer.push({
'event':'GAevent',
'eventCategory': 'Report Submit',
'eventAction': 'Link Click',
'eventLabel': 'CTA'
});
});
</script>
I'm not actually sure how to integrate setTimeOut without simply delaying
the whole thing by 1 second.
This didn't work.
<script>
setTimeOut($('.submit-incident.clearingfix a').click(function(event){
dataLayer.push({
'event':'GAevent',
'eventCategory': 'Report Submit',
'eventAction': 'Link Click',
'eventLabel': 'CTA'
});
});),1000);
</script>
And even if it did it wouldn't make sense to me. How would I delay the
page opening for a second so that Google Analytics has enough time to pick
up the dataLayer parameters?

Avoid checking if error is nil repetition?

Avoid checking if error is nil repetition?

I'm currently learning go and some of my code looks like this:
a, err := doA()
if err != nil {
return nil, err
}
b, err := doB(a)
if err != nil {
return nil, err
}
c, err := doC(c)
if err != nil {
return nil, err
}
... and so on ...
This looks kinda wrong to me because the error checking takes most of the
lines. Is there a better way to do error handling? Can I maybe avoid this
with some refactoring?

Explicitly expressing ownership in Delphi

Explicitly expressing ownership in Delphi

I'm primarily a C++ programmer, and I've grown used to having class
templates like std::unique_ptr, std::shared_ptr, etc for expressing
ownership of my objects. Does Delphi have anything that is similar in its
standard library? Are there any best-practices out there for expressing
object ownership that I should be following as I write my code?
Edit: Since C++11 became standard, there are two lightweight helper
classes, std::shared_ptr and std::unique_ptr.
If I create a variable of type std::shared_ptr<int>, it represents a
pointer to an int with shared ownership: under the hood is
reference-counted, and when the ref-count reaches zero then the pointer is
automatically freed. This type expresses a kind of "shared ownership",
where many objects share the responsibility of destroying the resource
when they are done with it.
In contrast, std::unique_ptr expresses single ownership. When the
unique_ptr goes out of scope, the resource is automatically freed.
std::unique_ptr cannot be copied: there can be exactly one object owning
this resource at a time, and there is exactly one object who is
responsible to clean the object up.
Contrast these lightweight classes with a naked pointer to int, where it
can represent either shared ownership, unique ownership, or it can just be
a reference to an object somewhere else! The type tells you nothing.
My question is: as Delphi supports holding references to objects, are
there any mechanisms for explicitly stating "I am the sole owner of this
object, when I'm done with it, I will free it", vs "I am merely keeping a
reference to this object around for the purpose of interacting with it,
but somebody else will clean it up" vs "I share this object with many
other objects, and whoever has it last gets to clean it up."
I know that Collections.Generics has different collections such as TList
vs TObjectList, where TObjectList will free the members stored within it,
but TList won't. You can say that TObjectList "owns" it's elements,
whereas TList doesn't. This is the essence of my question, really. When
designing my own classes, are there ways of directly expressing these
kinds of ownership issues within the language? Or are there any best
practices/naming conventions that are common amongst developers?

What is the short way of writing this validation Error code?

What is the short way of writing this validation Error code?

I am using error validation on my winform and if there is a nice and short
way of writing this code please share with me. Thanks.
if (string.IsNullOrEmpty(txtSrcUserID.Text))
{
errorProvider1.SetError(txtSrcUserID, "Please enter Source
User_ID");
return;
}
else if (string.IsNullOrEmpty(txtSrcUserPassword.Text))
{
errorProvider1.SetError(txtSrcUserPassword, "Please enter
Source Password");
return;
}
else if (string.IsNullOrEmpty(txtSrcUserDatabase.Text))
{
errorProvider1.SetError(txtSrcUserDatabase, "Please enter
Source Database");
return;
}
else if (string.IsNullOrEmpty(txtTrgUserID.Text))
{
errorProvider1.SetError(txtTrgUserID, "Please enter Target
User_ID");
return;
}
else if (string.IsNullOrEmpty(txtDesPassword.Text))
{
errorProvider1.SetError(txtDesPassword, "Please enter
Target Password");
return;
}

Wednesday, 11 September 2013

How can I use Distinct operator in C# LINQ query

How can I use Distinct operator in C# LINQ query

I would like to select unique EventYear using following code in c# Its
giving duplicate values. my table (EventMasters) structure is (EventYear
(string), EventCode, EventDescription) I want to select unique or distinct
EventYear
public ActionResult EventYearsMenu()
{
var eventyears = storeDB.EventMasters
.Distinct()
.ToList()
.OrderByDescending(c => c.EventYear ==
c.EventYear.Distinct());
return PartialView(eventyears);
}

Linear interpolation of three 3D points in 3D space

Linear interpolation of three 3D points in 3D space

I have three 3D points like p1(x1,y1,z1),p2(x2,y2,z2), p3(x3,y3,z3). I
have another point, but I know only x, y value of that point like
p4(x4,y4,Z), in which Z is the value I like to compute. I am sure
p4(x4,y4) point is inside a triangle formed by p1(x1,y1),p2(x2,y2),
p3(x3,y3) by checking with delaunay triangulation approach. How can I
compute Z value of point p4? I like to implement it in C programming.
Actually I am trying to implement griddata in Matlab. Thanks

scores not being generated from princomp, unable to generate biplot

scores not being generated from princomp, unable to generate biplot

I am having issues with princomp, specifically biplot, when I want to use
a covariance or correlation matrix not generated by princomp itself. For
simplicity I will use a much smaller dataset than the one I am dealing
with.
cr <- cw.wt(USArrests)
biplot(princomp(data = USArrests, covmat = cr))
gives me the error
Error in biplot.princomp(princomp(data = USArrests, covmat = cr)) :
object 'princomp(data = USArrests, covmat = cr)' has no scores
Seems like something simple going on here, but google has thus far been
unhelpful.

How to add a copy of an Object at the end of an Array? ( JavaScript )

How to add a copy of an Object at the end of an Array? ( JavaScript )

How could I add a copy of the first tag at the end of an Array, since
push() ,as I understand can't be used in this situation...
<p>A</p>
<p>B</p>
<p>C</p>
<script>
var pArray=document.getElementsByTagName("p");
//now I would like to add pArray[0]
</script>

Aligning button and text in navbar in twitter bootstrap

Aligning button and text in navbar in twitter bootstrap

I have written the following html with Bootstrap 2.3.2 included:
<div class="navbar navbar-fixed-top">
<div class="navbar-inner">
<div class="container">
(...)
<div class="nav-collapse collapse">
<ul class="nav">
(...)
</ul>
<form id="login-form" class="navbar-form pull-right">
<span class="navbar-text">Hello, username!</span>
<button id="logout" class="btn">Log out</button>
</form>
</div>
</div>
</div>
</div>
How can I make it so that the button aligns with the text and .navbar
correctly? Currently the button sticks to the bottom of the line, which is
the bottom of the .navbar because of the .navbar-text.

Error to create the Indexed View

Error to create the Indexed View

I create this View with Schemabinding:
CREATE VIEW RANKING_OPTIMIZATION_VIEW
WITH SCHEMABINDING
AS
SELECT USERS.[USER_ID],
USERS.GAMERTAG,
CLASSIFICATION.WIDGET_ID,
CLASSIFICATION.CLASSIFICATIONTYPE_ID,
ROW_NUMBER() OVER(PARTITION BY CLASSIFICATION.WIDGET_ID,
CLASSIFICATION.CLASSIFICATIONTYPE_ID
ORDER BY CLASSIFICATION.[SCORE] DESC ) AS
RANKING,
CLASSIFICATION.WIN,
CLASSIFICATION.LOSE,
CLASSIFICATION.SCORE
FROM [dbo].[GMW_CLASSIFICATION] AS CLASSIFICATION
INNER JOIN [dbo].[GMW_USERS] AS USERS
ON USERS.[USER_ID] = CLASSIFICATION.[USER_ID]
INNER JOIN [dbo].[GMW_WIDGET_GAMETYPES] AS GAMETYPE
ON GAMETYPE.[WIDGET_ID] = CLASSIFICATION.[WIDGET_ID]
AND GAMETYPE.[GAMETYPE_ID] =
CLASSIFICATION.[CLASSIFICATIONTYPE_ID]
I got this error: Cannot create index on view
"GameRoomDev.dbo.RANKING_OPTIMIZATION_VIEW" because it contains a ranking
or aggregate window function. Remove the function from the view definition
or, alternatively, do not index the view.
Any ideas how to change the query?? Thanks

cpumemory.pdf - cache optimized matrix multiplication

cpumemory.pdf - cache optimized matrix multiplication

I'm reading cpumemory.pdf from Ulrich Drepper and I'm unable to understand
following part about optimizing cache access in matrix multiplication from
chapter 6.2.1 (page 49-50):
First naive method for matrix multiplication is shown:
for (i = 0; i < N; ++i)
for (j = 0; j < N; ++j)
for (k = 0; k < N; ++k)
res[i][j] += mul1[i][k] * mul2[k][j];
mul2 is accessed by columns so for each column one cache is wasted. Ulrich
says:
With sizeof(double) being 8 this means that, to fully utilize the cache
line, we should unroll the middle loop 8 times.
For brevity I unrolled middle loop only 2 times.
for (i = 0; i < N; ++i)
for (j = 0; j < N; j += 2)
for (k = 0; k < N; ++k) {
res[i][j+0] += mul1[i][k] * mul2[k][j+0];
res[i][j+1] += mul1[i][k] * mul2[k][j+1];
}
Now it's obvious that if cache line is 2 double values wide it'll be fully
utilized. But then Ulrich continues:
Continuing this thought, to effectively use the res matrix as well, i.e.,
to write 8 results at the same time, we should unroll the outer loop 8
times as well.
For brevity I unrolled outer loop only 2 times again.
for (i = 0; i < N; i += 2)
for (j = 0; j < N; j+=2)
for (k = 0; k < N; ++k) {
res[i+0][j+0] += mul1[i+0][k] * mul2[k][j+0];
res[i+0][j+0] += mul1[i+0][k] * mul2[k][j+0];
res[i+1][j+0] += mul1[i+1][k] * mul2[k][j+0];
res[i+1][j+1] += mul1[i+1][k] * mul2[k][j+1];
}
To me it seems even worse than previous version because now mul1 is
accessed by columns. Please explain what Ulrich meant.

Adding WSS security to apache axis 1.3 stub

Adding WSS security to apache axis 1.3 stub

i am new to webservices and have a requirement to call a webservice
secured with WSS security into one of my application. My app server is
very old one running on jdk 1.4 version still.
I created all the web service proxy classes using the eclipse web service
proxy from wsdl url.
Call call = (Call) service.createCall();
call.setUsername("XXXX");
call.setPassword("XXXXXXX");
//call.addParameter("password",
org.apache.axis.Constants.XSD_STRING,
javax.xml.rpc.ParameterMode.IN);
call.setTargetEndpointAddress(new java.net.URL(endpoint));
call.setOperationName("getEntityPendingClaims");
call.addParameter("entity-number",
org.apache.axis.encoding.XMLType.XSD_STRING,ParameterMode.IN );
call.addParameter("entity-type",
org.apache.axis.encoding.XMLType.XSD_STRING,ParameterMode.IN );
call.setReturnType(XMLType.XSD_STRING);
msg = (String)call.invoke(new Object[] {entity,type});
but this is giving me a
faultString: An error was discovered processing the &lt;wsse:Security&gt;
header
in SOAP UI if i set the WSS-Password type to Password Text i am getting
the correct out put.
My question is how could i implement the same in apache axis 1.3? How
could i implement wss security to this client call. After few days search
i still could not find a complete example demonstrating this. So if
anybody is having code sample, then it will be very helpful.

returning a little square :s

returning a little square :s

Hey fellow stack overflowerssss,
I have written;
public class testing
{
public String subString(int start, int end)
{
char[]content = new char[]{0,1,2,3,4,5,6,7,8,9};
String output ="";
for (int i = 0; i < content.length;i++)
{
if (content[i] >= start && content[i] < end)
{
output = output + content[i];
}
}
return output;
}
/**
* @param args
*/
public static void main(String[] args)
{
testing test1 = new testing();
System.out.println( test1.subString(1,2));
}
}
Returns:
[]
It works in a way no matter how I try and split it will return the correct
number of little square. I'm guessing its because I am trying to put an
array element in a string ?
The return needs to be string also.
Can anyone help me out.
P.S I know there is a function for this :)

Tuesday, 10 September 2013

How to reference non-static variable name from static context?

How to reference non-static variable name from static context?

I am trying to write a code that lets the user enter a team name. Here is
my code:
public class Team {
public String name;
public static void main(String[] args) {
System.out.println("Enter name team");
Scanner tn = new Scanner(System.in);
name = tn.nextLine();
}
}
I understand that "non-static variable name cannot be referenced from a
static context". I know that if I take the "static" away from the main
then it will work, but:
a) How can I reference it without taking the "static" out?
b) Is there a way to get the users input and assign it straight to the
variable "name" i.e. without the:
Scanner tn = new Scanner(System.in);
name = tn.nextLine();
Basic questions I know, but I am still a beginner! Many thanks, Miles

IOS - Stop or Pause MPMoviePlayerController inside UITabbarcontroller

IOS - Stop or Pause MPMoviePlayerController inside UITabbarcontroller

I'm using UITabBarController from StoryBoard, each one TabBar, i have a
MPMoviePlayerController, when I play it in tab 1 and touch tab 2
MpMoviePlayer still play. I don't know how do stop or pause when move to
tab 1 to tab 2.
Can you help me?

Downloading images using AFNetworking - Memory won't release after poping ViewController using ARC

Downloading images using AFNetworking - Memory won't release after poping
ViewController using ARC

I've experienced some weird memory issues with my app. After some
debugging I've isolated the problem to a new project with one View
controller. So right now my testing app contains a UINavigationController
connected to a ViewController with a button that pushes the next
ViewController:
#import "ViewController.h"
#import "AFNetworking.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
for(int i=0;i<100;i++)
{
NSString *rightImageUrl = [NSString
stringWithFormat:@"%@/%@-iphone%@.png",ImagesURL,[NSString
stringWithFormat:@"%d",i],@"4"];
UIImageView *rightImageView = [[UIImageView
alloc]initWithFrame:CGRectMake(6, 50*i , 139, 200)];
[rightImageView setImageWithURL:[NSURL URLWithString:rightImageUrl]];
[self.view addSubview:rightImageView];
}
}
The above is all the code I have in my testing app right now.
According to Instruments the above takes X amount of memory (10mb, 20mb ..
Depending on the amount of loops) The problem is that the memory allocated
from the above won't be released when I'll pop the ViewController.
I've tried wrapping the code inside the for loop with @autoreleasepool but
that didn't do much.
Am I doing something wrong?

Rails: Floats, Decimals, or Integers

Rails: Floats, Decimals, or Integers

I have a rails app that needs to process some data, and some of this data
includes numbers with decimals such as 1.9943 and division between these
numbers and other integers. I just wanted to know what the best way to
store this was. Originally I thought of storing the numbers that would
stay integers as integers and numbers that could become decimals as
decimals.
This is my first time using decimals for rails, and although it was in a
weird format like
#<BigDecimal:7fda470aa9f0,'0.197757E1',18(18)>
It seems to be able to perform the correct arithmetic when I divide 2
decimal numbers or a decimal with an integer.
The thing that doesnt work correctly is when I try to divide integers with
integers. I thought rails would automatically convert the result into a
proper decimal, but it seems to keep it in integer form and strip the
remainders. Is there anything I can do about this?
And what would be the best way to store this type of information? Should I
store it all as decimals, or maybe floats

Android fullscreen image gallery with images from web

Android fullscreen image gallery with images from web

I'm trying to implement a fullscreen image gallery on Android. I have a
couple of URLs where the images are located and would like them to be
shown (=downloaded asynchronously) one after another, while each image
covers the full screen. By swiping right or left, the next or previous
image should be shown. It's very important that the images are getting
loaded in the background, so the user doesn't have to wait everytime he
scrolls to the next picture.
I have already implemented something like that, but for some reason it's
kinda faulty on Android >4.0. After scrolling, the images suddenly get
cropped to a very narrow strip. I have been using the Android Gallery
widget inside a LinearLayout.
Maybe someone of you guys has a link to a good tutorial or can point me
into the right direction.
Thanks in advance.

Adding option in select based on current options

Adding option in select based on current options

I have a function that loops through data and dynamically creates options
inside a select. The problem is I only want one "please select" option to
show up, not one for each time the loop runs. So basically, if this option
already exists don't add it again. I tried this code but it will not work,
it doesn't show this option at all.
if ($("#level"+num+" option[value = 'base']").length < 0) {
$("#level"+num ).prepend($("<option></option>")
.attr("value", "base")//.id )
.text( "Please select an option" )
);
};

Events are performed, but changes are not visible on UI

Events are performed, but changes are not visible on UI

I will describe my problem with an example. I try to change seekBar
progress using seekBar.setProgress(value). I can get progress later using
seekbar.getProgress(), but nothing changes on UI. I tried running it on in
runOnUIThread(), but it didn't work. However, Toast is visible if I print
right after the seekBar.setProgress().
Maybe somebody has had similar problem?
seekBar.post(new Runnable() {
@Override
public void run() {
//Toast.makeText(getActivity(), "Test",
5).show();
seekBar.setProgress(progress);
seekBar.postInvalidate();
DevLog.d("RABL",
seekBar.getContext().getClass().getSimpleName(),
getActivity().getClass().getSimpleName(),
progress, seekBar.getProgress(), "\n" +
"=====================");
}
});

Find common substring between two strings

Find common substring between two strings

I'd like to compare 2 strings and keep the matched, splitting off where
the comparison fails.
So if I have 2 strings -
string1 = apples
string2 = appleses
answer = apples
Another example, as the string could have more than one word.
string1 = apple pie available
string2 = apple pies
answer = apple pie
I'm sure there is a simple Python way of doing this but I can't work it
out, any help and explanation appreciated.

Linq select in query in c#

Linq select in query in c#

I have two lists containing data.
List<changeLogUsers> users;
UserID
List<changeLogQualifications> userQualifications;
UserID
QualificationID
I want to select only those userQualifications for which UserID is
available in users list.
Can anyone help?

Monday, 9 September 2013

want to show wait gif while changing image source through jquery

want to show wait gif while changing image source through jquery

I have this code by which I am changing main image on click of thumbnails
$(".thumb").click(function() {
$("#mainimage").attr("src", $(this).attr("alt"));
});
I want to show wait gif while the news image loads. thanks

loading UITableViewCell from xib results in loaded the nib but the view outlet was not set

loading UITableViewCell from xib results in loaded the nib but the view
outlet was not set

Let me start by saying I've read all the other questions with the same
title before posting this question again, so please bare with me.
I'm trying to create a UITableViewController that it's UITableViewCell is
a xib file. The Xib file is empty(0 controls) all the controls are created
programatically like this
- (id) initWithTitle: (NSString*)p_title andImage: (UIImage*)p_image
{
//adding checkbox & title
MMCheckbox* myCheckbox = [[MMCheckbox alloc] initWithTitle:p_title
andHeight:20];
myCheckbox.frame = CGRectMake(self.frame.size.width -
myCheckbox.frame.size.width -15,20, myCheckbox.frame.size.width, 20);
myCheckbox.flat = YES;
myCheckbox.strokeColor = [UIColor whiteColor];
myCheckbox.checkColor = [UIColor magentaColor];
myCheckbox.uncheckedColor = [UIColor clearColor];
myCheckbox.tintColor = [UIColor clearColor];
[self addSubview:myCheckbox];
//adding the image
UIImageView* imageView = [[UIImageView alloc] initWithFrame:CGRectMake
(15, 10, 20, 20)];
[imageView setImage: p_image];
return self;
}
In the xib file I placed a UITableViewCell and set it's class to my class
MMCheckboxTableViewCell

in my tableViewController I'm creating the cell loading it from NIB like so
- (UITableViewCell *)tableView:(UITableView *)p_tableView
cellForRowAtIndexPath:(NSIndexPath *)p_indexPath
{
//create a UI tableViewCell
UITableViewCell* cell = [p_tableView
dequeueReusableCellWithIdentifier:@"comboBoxCell"];
if(cell == nil)
{
UIViewController *temporaryController = [[UIViewController alloc]
initWithNibName:@"MMComboBoxTableCell" bundle:nil];
// Grab a pointer to the custom cell.
cell = (MMComboBoxTableCell *)temporaryController.view;
}
}
As mentioned in the beginning I've looked at many post with the same
question and checked to see I've got every thing right according to this
please let me know what I'm missing

Upper-triangular loop idiom for Scala Lists

Upper-triangular loop idiom for Scala Lists

From my background in imperative programming, I'm accustomed to doing
for (i = 0; i < 1000000; i++) {
for (j = i + 1; j < 1000000; j++) {
doSomething(array[i], array[j])
}
}
to examine all unique pairs in a million element array. doSomething is
some operation that yields trivial results on diagonal and symmetric or
antisymmetric results off diagonal--- that's why I only want to work on
the upper triangle. (There's a minor variant of this where the i == j case
is interesting; that's easy to fix.)
I find myself oddly stuck trying to do this in Scala. I have a large List
and want to do something to all the pairwise combinations, but
list.flatMap(x => list.map(y => doSomething(x, y))
includes all the redundant or trivial cases (a factor of two too much
work) and
(0 until 1000000).flatMap({i =>
(0 until 1000000).map({j =>
doSomething(list(i), list(j))
})
})
would be very wrong because Lists are not random access (a factor of N^2
too much work). I could convert my Lists to Arrays, but that feels like it
misses the point. Lists are linked lists, so the j + 1 element from my
imperative example is only a step away from the i I'm currently examining.
I'm sure I could write an efficient upper-triangular loop over linked
lists in C/Python/whatever.
I suppose I can just swallow the factor of two for now, but this is such a
common situation to run into that it feels like there ought to be a nice
solution to it.
Also, does this "upper-triangular loop" have a common name? I couldn't
find a good search string for it.

Joining SELECT variable into different table columns ( multiple tables in one query )

Joining SELECT variable into different table columns ( multiple tables in
one query )

I'm trying to join the result from one specific SELECT variable into a a
different colum from another table.
user_friends table:
+-------------------------------------------+
| friend_id | friend_one | friend_two |
+-------------------------------------------+
users table:
+------------------+
| uiD | username |
+------------------+
The following query retrieves random friends that my followers are
following and suggests them to me, currently it's only retriving their
uiD(id). I'm unsure of how to join these two tables together and get the
GROUP BY possible_friend below to connect to the users table.
$sth = $this->db->prepare("
SELECT friend_two AS possible_friend
FROM user_friends
WHERE friend_one IN (SELECT friend_two
FROM user_friends WHERE friend_one = :uiD)
AND friend_two NOT IN (SELECT friend_two
FROM user_friends WHERE friend_one = :uiD)
AND NOT friend_two = :uiD
GROUP BY possible_friend
ORDER BY RAND()
");
$sth->execute(array(':uiD' => $uiD));
$data = $sth->fetch();
return $data;
As an example, I'm user 10.
uiD = 10 : Username : Jonathan
uiD = 20 : Username : Gabriel
uiD = 30 : Username : Lisa
uiD = 40 : Username : Emily
I'm logged in as Jonathan, that is following Gabriel, but Jonathan is not
following Lisa nor Emily. Then it should show on a div.
Follow Suggestions: Emily or Lisa
With the query above, I'm just able to get their ID's randomly but I'm
unable to join the Username from the users table with the possible_friend
from the user_friends table.
I've tried the following.
$sth = $this->db->prepare("
SELECT F.friend_two AS possible_friend,
U.username
FROM user_friends F, users U
WHERE F.friend_one IN (SELECT friend_two
FROM user_friends WHERE friend_one = :uiD)
AND F.friend_two NOT IN (SELECT friend_two
FROM user_friends WHERE friend_one = :uiD)
AND NOT F.friend_two = :uiD
GROUP BY possible_friend
ORDER BY RAND()
");
$sth->execute(array(':uiD' => $uiD));
$data = $sth->fetch();
return $data;
but it just returns another username, since I'm unable to connect the
U.username with the possible_friend.

Rounding a decimal number to down

Rounding a decimal number to down

When we divide 5 by 2 we got a decimanl number: 2.5
When rounding the number we got a 3, well, I need to retrieve the 2
instead 3, I will round the number to down, to the unprecedented digit
instead to the precedent digit.
I've tried with a lot of Math class functions but I can't find anything to
do this.
PS: I'm looking to an improved way to do it, I don't want to do a
substring to the decimal output.

Prolog: How to capture the whole result of term or pattern matching

Prolog: How to capture the whole result of term or pattern matching

In Erlang and Haskell there is way to capture the whole pattern match. For
example, in Erlang:
% We can capture the whole match of list, and not only inner part of
structure
% like head and tail.
match_list([H|T]=F) -> hd(F).
I wonder how this can be done in Prolog. How to get the whole term without
reconstructing it by hand:
match_list([H|T]) :-
% quite awkward, how to back-reference to it automatically?
F = [H|T], ...
I've tried to solve next task. There are a lot of family-relations
specified as a set of facts(resembles part of chapter4 Bratko book). I
want to create predicate which returns specific family from this set of
families. Currently solution looks like this:
family(
person(tom, fox, date(7,may,1950), works(bbc,15200)),
person(ann, fox, date(9,may,1951), unemployed),
[
person(pat, fox, date(5,may,1973), unemployed),
person(doris, fox, date(8,may,1973), unemployed),
person(kate, fox, date(5,may,1973), unemployed),
person(jim, fox, date(6,may,1973), unemployed)]).
% ... here goes another family
foxs(F) :-
family(person(_, fox, _, _), W, CL),
family(H, W, CL),
F = family(H, W, CL).
As you can see, at first foxs-goal looks-up into family database and
capture wife(W) and children(CL). In second clause it captures husband(H).
In third it reconstructs family. And I don't like this stuff. In Erlang or
Haskell I can match family and capture it, so there is no need for second
and third part.
I googled and stackoverflowed, but without a luck. Maybe somebody can
point me in a right direction?
PS: I use SWI-Prolog.

sed replace a word at a line wich begins with a specific pattern using

sed replace a word at a line wich begins with a specific pattern using

How can I do so on FreeBSD? Considering the following file contents:
this is to test that was for test
I want to replace "test" at the line which begins with "this".

Sunday, 8 September 2013

how to validate URL in iphone app

how to validate URL in iphone app

How to check in iphone app that if URL is valid then it should open it
other wise it may show alert that it is invalid URL.I am using following
code but problem is that if i enter www.google.com it shows valid if i
enter nice.com also it show valid.
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
[textField setUserInteractionEnabled:YES];
[textField resignFirstResponder];
test=textField.text;
NSLog(@"Test is working and test is %@",test);
if ([self urlIsValiad:test]) {
NSURL *url = [NSURL URLWithString:test];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[webView setScalesPageToFit:YES];
[self.webView loadRequest:request];
} else {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Please enter
Valid URL" message:@"" delegate:self cancelButtonTitle:@"OK"
otherButtonTitles:nil];
[alert show];
[alert release];
}
return YES;
}
- (BOOL) urlIsValiad: (NSString *) url
{
NSString *regex =
@"((?:http|https)://)?(?:www\\.)?[\\w\\d\\-_]+\\.\\w{2,3}(\\.\\w{2})?(/(?<=/)(?:[\\w\\d\\-./_]+)?)?";
/// OR use this
///NSString *regex =
"(http|ftp|https)://[\w-_]+(.[\w-_]+)+([\w-.,@?^=%&:/~+#]*
[\w-\@?^=%&/~+#])?";
NSPredicate *regextest = [NSPredicate predicateWithFormat:@"SELF MATCHES
%@", regex];
if ([regextest evaluateWithObject: url] == YES) {
NSLog(@"URL is valid!");
test=@"Valid";
} else {
NSLog(@"URL is not valid!");
test=@"Not Valid";
}
return [regextest evaluateWithObject:url];
}

java.lang.InstantiationException usign jGraph when trying to display the Weight of a lable

java.lang.InstantiationException usign jGraph when trying to display the
Weight of a lable

Hi everyone I'm tring to display a graph using jGraph. Instead of labling
an edge with the name of the source and target notes I want to display the
weight of the edge. For that, I created an aditional class to overwrite
the toString method of DefaultWeightedEdge this way
class MyWeightedEdge extends DefaultWeightedEdge {
@Override
public String toString() {
return Double.toString(getWeight());
}
}
and instead of using DefaultWeightedEdge I use MyWeightedEdge everywhere,
but I'm getting a java.lang.InstantiationException
Exception in thread "main" java.lang.RuntimeException: Edge factory failed
at
org.jgrapht.graph.ClassBasedEdgeFactory.createEdge(ClassBasedEdgeFactory.java:86)
at
org.jgrapht.ext.JGraphModelAdapter$ShieldedGraph.addEdge(JGraphModelAdapter.java:1091)
at
org.jgrapht.ext.JGraphModelAdapter.handleJGraphInsertedEdge(JGraphModelAdapter.java:506)
at
org.jgrapht.ext.JGraphModelAdapter.handleJGraphChangedEdge(JGraphModelAdapter.java:474)
at
org.jgrapht.ext.JGraphModelAdapter$JGraphListener.handleChangedEdges(JGraphModelAdapter.java:964)
at
org.jgrapht.ext.JGraphModelAdapter$JGraphListener.graphChanged(JGraphModelAdapter.java:893)
at org.jgraph.graph.DefaultGraphModel.fireGraphChanged(Unknown Source)
at org.jgraph.graph.DefaultGraphModel$GraphModelEdit.execute(Unknown Source)
at org.jgraph.graph.DefaultGraphModel.insert(Unknown Source)
at
org.jgrapht.ext.JGraphModelAdapter.internalInsertCell(JGraphModelAdapter.java:769)
at
org.jgrapht.ext.JGraphModelAdapter.handleJGraphTAddedEdge(JGraphModelAdapter.java:651)
at
org.jgrapht.ext.JGraphModelAdapter$JGraphTListener.edgeAdded(JGraphModelAdapter.java:1036)
at
org.jgrapht.graph.DefaultListenableGraph.fireEdgeAdded(DefaultListenableGraph.java:317)
at
org.jgrapht.graph.DefaultListenableGraph.addEdge(DefaultListenableGraph.java:182)
at Visual.JGraphAdapterDemo.init(JGraphAdapterDemo.java:135)
at Visual.JGraphAdapterDemo.<init>(JGraphAdapterDemo.java:89)
at world.Conection.paint(Conection.java:268)
at world.Conection.<init>(Conection.java:56)
at world.Conection.main(Conection.java:44)
Caused by: java.lang.InstantiationException:
Visual.JGraphAdapterDemo$MyWeightedEdge
at java.lang.Class.newInstance(Unknown Source)
at
org.jgrapht.graph.ClassBasedEdgeFactory.createEdge(ClassBasedEdgeFactory.java:84)
... 18 more
If somebody knows how can I fix this will help me a lot.
Thanks,

OpenSSL - LNK 2019

OpenSSL - LNK 2019

I'm getting LNK 2019 when trying to link in the OpenSSL libraries for a
project I'm working on. I compiled the OpenSSL libraries and ran the test
and all of them passed. I played with openssl.exe and got it to correctly
create and MD5 hash. When I try to use the functions provided by the API
though, it just won't recognize them. I even used dumpbin -headers on the
.lib files to make sure that the ones I was using contained the correct
references for the functions I was using.
(I don't have enough reputation to post images) I made sure to include the
correct files and paths (I also included the header which isn't pictured
here). http://i.imgur.com/mdY65wI.png
Here are the actual files and their paths http://i.imgur.com/zGrrywY.png
Here's the actual errors. http:// i.imgur.com/4VVYkDb.png
How do I fix this? Did I put the files in the right place or did I forget
an include? I've spent a few days trying to fix this already, this is my
last resort :/

What's the SSE equivalent of fstp?

What's the SSE equivalent of fstp?

pCorrect me if I'm mistaken, but fstp pops the value from the top of the
FPU stack such as st0?/p pi.e. fstp tword [rsp]/p pIf I have values in an
SSE register, xmm0, what's the equivalent? I want to print the values
stored in the registers./p

UITextField set placeholder color

UITextField set placeholder color

I've been mocking about on the internet for a while and found this bit of
code:
.h
IBOutlet UITextField *TextField;
.m
[TextField setValue:[UIColor lightGrayColor]
forKeyPath:@"_placeholderLabel.textColor"];
It's not working I'm using IOS 6.1 Running in the Simulator. Is it because
I haven't subclassed the given UITextField?
Regards, Daniel

Saturday, 7 September 2013

Redirect all sub-domain to parent domain except one

Redirect all sub-domain to parent domain except one

I am able to access my website with random sub-domains like this
abcd.theonlytutorials.com
abc.theonlytutorials.com
etc.theonlytutorials.com/otherpage/otherpage
I have one real sub-domain where my blog is
blog.theonlytutorials.com
Is there any possible way to redirect all my fake sub-domains to root
domain except the 'blog' one?

Value of Graphics g in paint(Graphics g) method Container class

Value of Graphics g in paint(Graphics g) method Container class

The official documentation paint(Graphics g) method says:
Paints the container. This forwards the paint to any lightweight
components that are children of this container. If this method is
reimplemented, super.paint(g) should be called so that lightweight
components are properly rendered. If a child component is entirely clipped
by the current clipping setting in g, paint() will not be forwarded to
that child. g - the specified Graphics window
But nowhere I found what is the function of Graphic object passed as
parameter.
Can anybody explain its significance.
Thanks.

how to replace all instances of "[" and "]"

how to replace all instances of "[" and "]"

I have a string that looks like this: [hello world] and i want to get
hello world
having hard time finding the right regex for the replaceAll method for java
String s = s.replaceAll("[[]]",""); throws an exeption
what is the right regex for it ?