Saturday, 31 August 2013

Rails Filter Out Deleted Records in Association

Rails Filter Out Deleted Records in Association

My rails app needs to do a 'soft' delete of certain records so they are
inactivated without actually being removed from the DB. Currently I have
it implemented with an "is_deleted" flag.
My question is whether there's a best practice for handling associations
involving this model. For example:
class Foo
attr_accessible :is_deleted
scope :active, -> { where(is_deleted:false) }
belongs_to :bar
end
class Bar
has_many :foos
end
I'm trying to figure out how to set up the Bar model, knowing that it
usually deals only with 'active' foos.
I have come up with a couple ideas, and would like to know if there are
any pros/cons for using one over the other.
Use a "condition" qualifier on the has_many declaration to filter out
deleted items.
Create a "active_foos" method on Bar to return only the undeleted items.
Just use the "acts_as_paranoid" gem. It feels a little heavyweight for
what I need, but perhaps it's easiest.

Opening Image directly into program

Opening Image directly into program

I made a basic picture viewer program in C# windows from , following a
tutorial. The program works fine but I want to open it like default
windows photo viewer. I tried to open an image with the program directly
but that opened the program and the image box was empty.
The image box works fine when images are browsed to open inside the
program but how to make it work externally?
Extra : And is there a way to make it full screen?
Sorry for bad english.

button click in polymer dart does not work; needs polymer-element

button click in polymer dart does not work; needs polymer-element

I am creating my first polymer application/example and a simple button
on-click is not working. The method is not called. I would like to use a
simple button without creating a new polymer-element (the commented code).
If I use the buttons in the polymer-element, they work just fine.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Button</title>
<link rel="stylesheet" href="button.css">
<script src="packages/polymer/boot.js"></script>
</head>
<body>
<h1>Button</h1>
<template id="tmpl" bind>
<button on-click="myMethod">Click me!</button><!! DOES NOT WORK!!! -->
</template>
<!--
<polymer-element name="my-element" extends="div">
<template>
<p>
<button on-click="myMethod">Show Message</button>
<button on-click="myMethod">Hide Message</button>
</p>
</template>
</polymer-element>
<my-element id="test"></my-element>-->
<script type="application/dart" src="button.dart"></script>
</body>
</html>
..
import 'dart:html';
import 'package:polymer/polymer.dart';
void main() {
query("#tmpl").model = new MyClass();
}
@CustomTag('my-element')
class MyClass extends PolymerElement with ObservableMixin{
@observable String name="testname";
void myMethod(var e, var detail, var target) {
print("button works");
}
}

Overlapping dynamic fixed header

Overlapping dynamic fixed header

my fixed header is overlapping my content. Much like here (Position fixed
content overlapping problem)
but my header is dynamic so not allways 50px in height sometimes 52, 100 ...
how can I solve this?
Chris

phpmailer exception in Gravity form

phpmailer exception in Gravity form

I have involved with a Mailer error. I am using gravity forms and there is
my form. I submitted to form and a email had delivered successful. but i
got error everytime
Fatal error: Cannot redeclare class phpmailerException in
/home/content...../class-phpmailer.php on line 2825
i have used also:-
if (!class_exists('PHPMailer')) {
require_once('class.phpmailer.php');
}
Don not know why i am getting. please help me

Toggle Button value

Toggle Button value

I have this code which hides/shows the div on button click. Is there any
way I can toggle the button value?
<div>
<button id="showmenu" type="button">Click Me!</button>
</div>
<div class="menu" style="display: none;">
Can the button value change to "show" or "hide"
</div>
<script>
$(document).ready(function() {
$('#showmenu').click(function() {
$('.menu').toggle("slide");
});
});
</script>

i want to now about mapreduce in mongodb codeigniter

i want to now about mapreduce in mongodb codeigniter

here am basically performing group by operation
table:sale_announcement_history fields:history_timestamp,logged by,
sale_annoucement_id --- want to know max timestamp and distinct logged by
of a particular sale_id
function test_map_reduce(){
$map = new MongoCode('
function(){
var total = 0;
var maxx = 0;
var unique = 0;
for (sum in this.sale_announcement_id) {
$total += this.sale_announcement_id[sum];
}
for (max in this.history_timestamp) {
maxx = this.history_timestamp[max];
}
for (distinct in this.logged_by) {
unique = this.logged_by[distinct];
}
emit(this.sale_announcement_id,{total:total,max:maxx,unique:unique});
}
');
$reduce = new MongoCode('
function(key, values){
var result = {total: 0, max: 0, unique: 0};
values.forEach(function(v) {
result.total = v.total;
result.max = v.max;
result.unique = v.unique;
});
return result;
}
');
$result = $this->mongo_db->command(array(
'mapreduce'=>"sale_announcement_history", // <= 'mtb'
'road' 'minivelo'
'map'=>$map,
'reduce'=>$reduce,
//'query'=>array(),
'out'=> 'test_res1'));
echo'<pre>';
print_r($result);
}

i want to animate text smoothly from left and right in continuous loop can any suggest me something

i want to animate text smoothly from left and right in continuous loop can
any suggest me something

i want to animate text smoothly from left and right in continuous loop can
any suggest me something here is the fiddle link
Here's http://jsfiddle.net/yLNGn/3/
$(document).ready(function () { $('.kp').animate({ left: '10px' }, 600);
$('.kp').delay(600).animate({ left: '-128px' }, 600);
$('.rp').delay(2000).animate({ left: '10px' }, 600);
$('.rp').delay(600).animate({ left: '-108px' }, 600);
$('.kpp').delay(4000).animate({ left: '10px' }, 600); });

Friday, 30 August 2013

Keep my form above the taskbar?

Keep my form above the taskbar?

My overall goal is to render a second (or third, fourth...) mouse cursor.
To this end, I have created a frameless, topmost, transparent window. I
can draw on this window (I have 4 buttons on it to show that it's properly
covering the whole desktop) - but when I click on the taskbar, it is
brought to the top and overlays my buttons and drawn line.
How can I keep my window above the taskbar?
Alternatively, is there a way that I can draw on the "final" version of
the screen?
Thanks in advance!
Here's the code from my .Designer.cs file:
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.None;
this.BackColor = System.Drawing.Color.White;
this.CausesValidation = false;
this.ClientSize = new System.Drawing.Size(332, 332);
this.ControlBox = false;
this.Controls.Add(this.button4);
this.Controls.Add(this.button3);
this.Controls.Add(this.button2);
this.Controls.Add(this.button1);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "Screen";
this.ShowIcon = false;
this.SizeGripStyle = System.Windows.Forms.SizeGripStyle.Hide;
this.StartPosition =
System.Windows.Forms.FormStartPosition.WindowsDefaultBounds;
this.TopMost = true;
this.TransparencyKey = System.Drawing.Color.White;

Thursday, 29 August 2013

Run another binary/exe file using Lua?

Run another binary/exe file using Lua?

Quick question, lua code that will run a binary/exe file with arguments
thanks in advance.

Display message alert for Session expired

Display message alert for Session expired

How to show alert message when session.timeout occurs? after 5 minutes i
want to expire my page and redirect to login page. after redirecting i
want to show user that their session has expired.

Wednesday, 28 August 2013

Android developmentFswitch...case with R.id.xx in Intellij

Android developmentFswitch...case with R.id.xx in Intellij

There is an old big project developing in eclipse.I import it into
Intellij 12.1.4
Because Intellij idea doesn't generate a R.java file as eclipse.I can't use
switch...case:R.id.x
So,the project build failed.
IntelliJ Idea not generate id in R.java
How can i do with it?
Thx.

how to show imageview with no white space

how to show imageview with no white space

my imageview not fully show on imageview width see this image its show
white space http://imgur.com/3fDXgij but i want to show mageview like this
shape http://imgur.com/g8UeI4b and image show full in imageview no white
space below is my code please help me
<ImageView
android:id="@+id/test_button_image"
android:layout_width="80dp"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:layout_marginBottom="15dp"
android:layout_height="60dp"
android:layout_alignParentTop="true"
android:background="@drawable/border6"
android:src="@drawable/ic_launcher" >
</ImageView>

Tuesday, 27 August 2013

set all Labels Font before opening the Form

set all Labels Font before opening the Form

before opening the form I used following code to check if its label then
change the font
foreach (Label ctl in frm.Controls)
{
ctl.Font = usefontgrid;
}
but on first line return error because it check other control types such
as textbox or button,etc... how can I check if the object is only label
then go to for each?

android how can i format a arrayList

android how can i format a arrayList

i have a problem with format arrayList.I have one parameter it have value
Licence_car:[[¤Â1453 ¡Ãا෾ÁËÒ¹¤Ã], [ç2344 ¡Ãا෾ÁËÒ¹¤Ã], [ù4679
¡Ãا෾ÁËÒ¹¤Ã]] (Data is a ThaiLanguage)
I use this parameter to set entry of list preference but it will show like
this
I want to delete character is "[" and "]" to make a variable like this
Licence_car:[¤Â1453 ¡Ãا෾ÁËÒ¹¤Ã, ç2344 ¡Ãا෾ÁËÒ¹¤Ã, ù4679
¡Ãا෾ÁËÒ¹¤Ã] how can i do that?
This is my code set entry to list preference.
@SuppressWarnings("unchecked")
public void showCar(Context context,ArrayList<String> currentCars){
SharedPreferences MYprefs = context.getSharedPreferences(PREFERENCES,
PREFERENCE_MODE);
if (null == currentCars) {
currentCars = new ArrayList<String>();
}
try {
currentCars = (ArrayList<String>)
ObjectSerializer.deserialize(MYprefs.getString("car_licence_",
ObjectSerializer.serialize(new ArrayList<String>())));
//String[] car_list = currentCars.toCharArray;
Log.d(TAG,"Licence_car:"+currentCars);
final CharSequence[] charSequenceCarEntry =
currentCars.toArray(new CharSequence[currentCars.size()]);
mCarDefault.setEntries(charSequenceCarEntry);
mCarDefault.setEntryValues(charSequenceCarEntry);
mCarDelete.setEntries(charSequenceCarEntry);
mCarDelete.setEntryValues(charSequenceCarEntry);
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
I get a preference value in arrayList and format to CharSequence[] for set
entry to list preference i think that i do format from this point but i
don't know how can do it.
Thank for any answer and sorry for my English.

Stop redirecting subdomain to main domain

Stop redirecting subdomain to main domain

How can I stop my subdomain from redirecting to my main domaine,
here's my code so that http://mydomaine.com always add the www
RewriteCond %{HTTP_HOST} .
RewriteCond %{HTTP_HOST} !^www\.mysite\.com [NC]
RewriteRule (.*) http://www.mysite.com/$1 [R=301,L]
I've created a sub domaine (sub.mysite.com) that is in a sub sub folder of
my main site, and when I type sub.mysite.com it redirect to
www.mysite.com/sub/sub/
thamks for your help

Get rows with consecutive Date(Day)

Get rows with consecutive Date(Day)

I'm searching a way to update all rows which have an other occurence the
day before.
Example:
ID Config Number Date Status
1 238 10/9/2013 1
2 351 1/9/2013 2
3 351 2/9/2013 0
4 238 11/9/2013 0
5 124 18/9/2013 3
6 238 20/9/2013 0
And after the update i would like to have something like:
ID Config Number Date Status
1 238 10/9/2013 1
2 351 1/9/2013 2
3 351 2/9/2013 2
4 238 11/9/2013 1
5 124 18/9/2013 3
6 238 20/9/2013 0
6 238 20/9/2013 0
Thanks in advance

Cannot get output from a stored procedure

Cannot get output from a stored procedure

I have a stored procedure which returns me the identity of the added row,
as below:
Create Procedure sp_ADD_CONTACT_EXTRANET_CLIENT
(
@NumCRPCEN nvarchar (255),
@nomContact nvarchar (255),
@prenomContact nvarchar (255),
@telFixe nvarchar (255),
@telPort nvarchar (255),
@mailContact nvarchar(255),
@idPhysique int output
)
as
Begin
INSERT INTO T_Physique values (.....)
SET @idPhysique = @@IDENTITY
RETURN @idPhysique
End
Now I would like to get the output in ADO.NET and I've tried a lot of
things but the last one is :
Requeteadd.Parameters.Add("@idPhysique", SqlDbType.Int).Direction =
ParameterDirection.Output;
Requeteadd.ExecuteNonQuery();
int IdPhysique = (int)Requeteadd.Parameters["@idPhysique"].Value;
But it shows me an error where it says that returned value is null. Does
anyone have an idea ?

Arithmetic overflow error converting numeric to data type varchar. while passing large date differance

Arithmetic overflow error converting numeric to data type varchar. while
passing large date differance

my stored procedure:
ALTER procedure [dbo].[performance]
(@startdate nvarchar(100), @enddate nvarchar(100)
as begin
declare @date1 nvarchar(100) = convert(varchar, @startdate+'
00:00:00.000', 120)
declare @date2 nvarchar(100) = convert(varchar, @enddate+'
23:59:59.000', 120)
set NOCOUNT on;
select l.LocName,v.Vtype, SUM(DATEDIFF(MI,t.Paydate,t.DelDate)) as
TotalDiff,
[dbo].[testfunction](
CONVERT(decimal(10,1),
AVG( CONVERT(NUMERIC(18,2), DATEDIFF(SS,t.Paydate,t.DelDate) ) ))) as
Average
from Transaction_tbl t
left join VType_tbl v
on t.vtid=v.vtid
left join Location_tbl l
on t.Locid=l.Locid
where t.Locid in
(select t1.Locid from Transaction_tbl t1)
and dtime between '' + @date1 +'' and ''+ @date2 +''
and Status =5
group by v.Vtype,l.LocName,l.Locid order by l.Locid
end
my function:ALTER FUNCTION [dbo].[testfunction] (@dec NUMERIC(18, 2))
RETURNS Varchar(50)
AS
BEGIN DECLARE @hour integer, @Mns integer,
@second decimal(18,3)DECLARE @Average Varchar(50)
select @hour=CONVERT(int,@dec/60/60)
SELECT @Mns = convert(int, (@dec / 60) - (@hour * 60 ));
select @second=@dec % 60;
SELECT @Average = convert(varchar(9), convert(int, @hour)) + ':' +
right('00' + convert(varchar(8), convert(decimal(18,2), @Mns)), 2) + ':' +
right('00' + CONVERT(decimal(10,0), convert(varchar(10), @second)), 6)
RETURN @Average end if i pass start date:2013-06-01 and end
date:2013-08-01 then getting proper out put if i pass start
date:2010-06-01 and end date:2013-08-01 (bigger date difference) then
getting error: what is wrong with my function

Remapping keys in KDE (4.8.5, Kubuntu 12.04)

Remapping keys in KDE (4.8.5, Kubuntu 12.04)

I have been remapping keys via xmodmap commands but this doesn't appear to
be very satisfactory on my Kubuntu 12.04. The problem is that when I sleep
my computer and then log back in again, everything goes back to what KDE
thinks it should be.
The behaviour I'm trying to change is that configured in the System
Settings -> Input Devices -> Keyboard -> Advanced -> Alt/Win key
behaviour. I would use that but they don't have the options I want... It
must be easily configurable though - if they are doing it there then it
must be possible!
Thanks.
(ps. this is not the same as my META problem - I have decided I'm going to
stick with VIM :-))

Fancybox: how to scroll html fragments instead of images with the same effect?

Fancybox: how to scroll html fragments instead of images with the same
effect?

I would like to show html fragments instead of images with the same
scrolling effect (when we call the next() method).
I can't realize how to make it working. If we use images then fancybox
lib. reads href attibutes to obtain full images.
<a class="fancybox-thumb" rel="fancybox-thumb"
href="http://farm9.staticflickr.com/8507/8454547519_f8116520e1_b.jpg"
title="Ayvalýk, Turkey (Nejdet Düzen)">
<img
src="http://farm9.staticflickr.com/8507/8454547519_f8116520e1_m.jpg"
alt="" />
</a>
<a class="fancybox-thumb" rel="fancybox-thumb"
href="http://farm8.staticflickr.com/7152/6394238505_c94fdd1d89_b.jpg"
title="Sicilian Scratches erice (italianoadoravel on/off coming back)">
<img
src="http://farm8.staticflickr.com/7152/6394238505_c94fdd1d89_m.jpg"
alt="" />
</a>
I would like these html fragments are in the same page. How to force the
lib. to use html fragments instead of images?

Monday, 26 August 2013

ExpressJS on server and android as client

ExpressJS on server and android as client

I am using ExpressJS on server & Android as client
I want to know how to perform this action in server::
suppose i have a listView of list of colleges, I get the data for this as
JSON using the Express program shown below.
Now Android has OnClick for identifying the position on the listview
How to get the JSON for the android client dynamically ( If i click on a
row, I want to do the database query dynamically on the server so that
JSON URL is dynamically generated )
I have not posted android code as I think modification is on server side
but android developers who worked with ExpressJS or NodeJS will also have
an idea for this



What code changes should i need to make on server ?
What concepts should i need to look to achieve this functionality?



My Express program on server ::
var express = require('express')
, async = require('async')
, http = require('http')
, mysql = require('mysql');
var app = express();
var connection = mysql.createConnection({
host: 'localhost',
user: 'xxx',
password: "xxx",
database: 'collages'
});
connection.connect();
// all environments
app.set('port', process.env.PORT || 7002);
//
//REQUEST FOR FIRST REQUEST
//
app.get('/',function(request,response){
var name_of_Collages, RestaurantTimings;
async.series( [
// Get the first table contents
function ( callback ) {
connection.query('SELECT * FROM restaurants', function(err,
rows, fields)
{
console.log('Connection result error '+err);
name_of_Collages = rows;
callback();
});
},
// Get the second table contents
function ( callback ) {
connection.query('SELECT * FROM RestaurantTimings', function(err,
rows, fields)
{
console.log('Connection result error '+err);
RestaurantTimings = rows;
callback();
});
}
// Send the response
], function ( error, results ) {
response.json({
'Collages' : name_of_Collages,
'RestaurantTimings' : RestaurantTimings
});
} );
} );
//
//REQUEST FOR Collage SCREEN
//
app.get('/College1',function(request,response){
var College1, RestaurantTimings;
async.series( [
// Get the first table contents
function ( callback ) {
connection.query('SELECT * FROM College1', function(err, rows,
fields)
{
console.log('Connection result error '+err);
College1 = rows;
callback();
});
},
// Get the second table contents
function ( callback ) {
connection.query('SELECT * FROM RestaurantTimings', function(err,
rows, fields)
{
console.log('Connection result error '+err);
RestaurantTimings = rows;
callback();
});
}
// Send the response
], function ( error, results ) {
response.json({
'College' : College1,
'RestaurantTimings' : RestaurantTimings
});
} );
} );
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
Hope i am clear
Thanks,

Do I want to include the Azure csx folder in configuration control?

Do I want to include the Azure csx folder in configuration control?

My MVC 4 app is deployed to Azure. The Azure project includes a csx
folder. Is there anything in that folder that doesn't get automatically
recreated when I publish to Azure? In other words, is there anything in
that folder that qualifies as "source code" that I should add to my
version control system?

How to refactor a UITableViewCell configuration code?

How to refactor a UITableViewCell configuration code?

I have a tableview with a single custom table view cell that over time has
resulted to a somewhat convoluted structure and I'm hoping to simplify and
improve it. Basically in the current form, there are images and buttons on
the left and right side of the cell and possibly two different labels in
the middle.
The cells are configured based on the entry they are representing, the
section of table view and the state of the tableview and therefore both
the code in cellForRowAtIndexPath and willDisplayCell has become quite
cluttered. The configuration includes hiding/unhiding of the non-label
subviews and possibly changing the frame of the UILabels.
How would you suggest going about structuring and improving such a code
and when would you start using different custom cell classes?

Eclipse hangs on startup

Eclipse hangs on startup

I have problem with running my Eclipse. I tried 3.7, 4.2 and 4.3 versions
with java 6 and java 7. Nothing can help me. It shows me popup screen but
it doesn't start to load( I dont have chance to choose workspace).
Starting it with -debug -console parameters shows that it stops running in
this moment:
Time to load bundles: 10
Starting application: 6374
osgi>
I have started JVisualVM but I cannot observe anything special. There are
no deadlocks etc.
Edit
My observations were to deep... After ~60s pid of eclipse is dead.

Facebook photo sharing (& October 2013 breaking changes)

Facebook photo sharing (& October 2013 breaking changes)

I'm building on a website for a client and the core functionality of it is
to share photos with other users over Facebook. So, what I've done is =>
user picks a photo he likes and clicks the "share" button
script triggers Facebook "Friend Picker" popup
user picks a friend he wants to share the photo with and clicks "OK"
script triggers ajax request to the server which uploads the specific
photo on the timeline of chosen friend
Here's the php photo sharing code =>
$facebook = new Facebook($config);
$facebook->getAccessToken();
$user_id = $facebook->getUser();
$body = array(
'source' => '@' . CURR_DIR . $photo->path,
'message' => ''
);
if ($user_id) {
try {
$result = $facebook->api('/' . $fbid . '/photos', 'post',
$body);
} catch (FacebookApiException $e) {
echo $e->getMessage();
}
}
So far this works beautifully, so my question is =>
After the Facebook's "October 2013 breaking changes", they will be
"removing the ability to post to friends' timelines via API". They advise
usage of feed dialog's from that point on. So - how to upload a photo on a
specific user's timeline using feed dialog's? Is this even possible
(because looking at the feed documentation page, I don't think it is...)?
Thanks

Show alert on sceen when app is in background

Show alert on sceen when app is in background

I want to show multiple alerts after some time interval when the app is in
background.
Currently I am using local notification to show the alert but I cannot
detect action when user presses the cancel button of local notification.
UILocalNotification *localNotif = [[UILocalNotification alloc] init];
if (localNotif == nil)
return;
localNotif.fireDate = [NSDate date];
localNotif.timeZone = [NSTimeZone defaultTimeZone];
// Notification details
localNotif.alertBody = @"This is local notification
message.";
// Set the action button
localNotif.alertAction = @"View";
localNotif.alertAction = @"Yes";
localNotif.soundName = UILocalNotificationDefaultSoundName;
[[UIApplication sharedApplication]
scheduleLocalNotification:localNotif];
[localNotif release];
Is there any other way I can show alert on screen when app is in background ?

ELB is using which process to calculate letency

ELB is using which process to calculate letency

I would like to know using which process ELB is calculating
latency,Request Count, Healthy Host Count, Unhealthy Host Count
(EX:pinging like that). Cloud you please provide the information as soon
as possible.

Sunday, 25 August 2013

Autofilling a form using the Play Framework

Autofilling a form using the Play Framework

I have a form that contains some values. When POSTed to the server, the
server validates the information, and if any of the fields are invalid, is
supposed to return the filled form.
The way I currently have it set up is like this.
I have a form that validates 2 fields.
val userForm = Form(
mapping(
"name" -> text,
"age" -> number(min=0, max=100)
)(User.apply)(User.unapply)
)
If the form fails to bind, I load up the same form with the values they
just posted.
def createItem() = IsAuthenticated {
username =>
implicit request => {
createExperienceForm.bindFromRequest().fold(
formWithErrors => BadRequest(
views.html.createItem(formWithErrors)
),
validForm => {
val itemCode = Item.createItem(validForm)
Redirect(routes.Item.item(itemCode).url)
}
)
}
}
The problem is that I have to manually set the value in my HTML page for
each form. eg. @(itemForm: Form[ItemContent])
<input name="age" type="number" class="input-block-level"
value="@itemForm.data.get("age")">
While this works, it will become a bit error prone on larger forms. For
every single field, I need to set the value directly. Is it possible to
autofill these fields?

Dark spot appearing on the Screen , Mac Book Pro 13

Dark spot appearing on the Screen , Mac Book Pro 13

When screen brightness is low I get this dark spot in my screen. Is this
something serious ? Screenshot

Encoding video to Base64

Encoding video to Base64

I would like know how encode a video (.mp4) to base64 with JavaScript. I
tried with canvas, but don't worked. If someone know a way, say to me.
I think that with 'canvas' work, but i don't know how.
I need this because I'll use the JSZip and for it need be in base64.

How to change the value of an UITextField by the given sender

How to change the value of an UITextField by the given sender

I have two UITextFields on my view and both are connected with my Method
- (IBAction)showContactPicker:(id)sender;
now I want to change the Value of the text field with the given sender.
How can I do that?
Sorry for english mistakes, I'm from Germany.

Can more than one process be in the crictical section at the same time?

Can more than one process be in the crictical section at the same time?

If any thread entered critical section, no other thread can enter until
it's free.But when the semaphore value is 3 then there can be three
processes entering the critical section.How is that possible.Need some
explanation about this probably with an example.

Saturday, 24 August 2013

trying to call three methods but not working correctly with jQuery map

trying to call three methods but not working correctly with jQuery map

I have the following methods that are on a google maps. The methods work
fine like this:
arc.pLocations(ne, sw,m);
arc.pLikedLocations(ne, sw, m);
arc.pLikedItems(ne, sw, m);
However, I'd like to have them in an array like this that I can
subsequetnly call but this isn't working (I'd be the first acknowledge
this is an issue with me):
var selected_methods=[arc.pLocations,arc.pLikedLocations,arc.pLikedItems];
// Uncaught TypeError: Object #<Ri> has no method 'lng' - this is for a
variable called sw in pLikedLocations
$.map(selected_methods, function(val, i){
console.log("here is index:" + i);
val.call(ne,sw,m);
});
trying to wrap this with another closure but this also isn't working
$.map(selected_methods, (function(val, i){
console.log("here is index:" + i);
val.call(ne,sw,m);
})(val,i)); // Uncaught ReferenceError: val is not defined on this line!
I have the following I'm doing something really simple wrong. Can anyone
spot the issue and help me? It's saturday nigth and I want to be done with
this.
thx in advance

how can i show position of item clicked in customized listview

how can i show position of item clicked in customized listview

I have use a custom listview to display images and also text information
in my listview using hashmap and two xml layouts, of which on contains the
listview and the other contains the custom rows. And the code below works
just fine. How should I toast the position of the row a user click ??
public class MainTopic extends Activity{
ListView mtopiclv;
LinearLayout header;
List<HashMap<String, String>> rowList;
String[] topicHeader ={
"What is farming ?",
"Raising animals ?",
"How to graz ?",
"sdsdsdsd sdsd",
"Control",
"Find product centers",
"Research and statistics",
"How to succeed in sdfsdfds ?"
};
String[] info = {
"Introduction, benefits",
"Seeds, planting and care",
"Requirements, , resources",
"Investing in farming",
"Practices and tools",
"machinery",
"books",
"Business tips"
};
int[] images = {
R.drawable.sample_1,
R.drawable.sample_2,
R.drawable.sample_3,
R.drawable.sample_4,
R.drawable.sample_5,
R.drawable.sample_6,
R.drawable.sample_7,
R.drawable.sample_8
};
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.mtopic);
setUp();
hashmap();
}
private void hashmap() {
// TODO Auto-generated method stub
rowList = new ArrayList<HashMap<String, String>>();
//looping through all items
for(int i = 0; i<8; i++){
HashMap<String, String> infoList = new HashMap<String, String>();
infoList.put("topicHeader", topicHeader[i]);
infoList.put("info", info[i]);
infoList.put("imgs", Integer.toString(images[i]));
rowList.add(infoList);
//from
String[] from = {"topicHeader", "info", "imgs"};
int[] to = {R.id.clvHeader, R.id.clvsum, R.id.imgbtn};
//adapter
SimpleAdapter clvAdapter = new SimpleAdapter
(getApplicationContext(), rowList, R.layout.mtopic_custome_lv,
from, to);
mtopiclv.setAdapter(clvAdapter);
}
}
private void setUp() {
// TODO Auto-generated method stub
mtopiclv = (ListView) findViewById(R.id.mtopiclv);
header = (LinearLayout) findViewById(R.id.header);
}
}

calculating distance from one point too another C++

calculating distance from one point too another C++

So i have my double that calculates the distance
double calculate2DDistance(int x1, int y1, int x2, int y2)
{
return sqrt((x2 - x1)^2 + (y2 - y1)^2);
}
Note i'm calling this method from a header called math.h into my main
My testing line in main.h
cout << calculate2DDistance(2.0, 4.0, 3.0, 1.0) << endl;
and it either prints out the completely wrong answer or -1.#IND
Whats going on ?

html transfer information from one page to the next

html transfer information from one page to the next

So I have been looking into this for a few weeks and have come up with
nothing!
I work on the website for my families music store, and have been asked to
add a "Links" page to the website. My goal would be to have the categories
of our vendors (i.e. Violin, Guitar, Piano, etc.) on the left of the page
and when the category is selected the links come up on the right. That
part I have. The tricky part here is: When a link to a vendor (i.e.
Fender, G&L, Yahmaha) is clicked instead of taking them directly to the
site, I want it to take them all to the same page, but embeded on that
page is the site.
I have done a lot of research on this and have come up with nothing. I
could just go through and make a new page for each of the vendors, with
the embedding on each individual page, but that is extremely time
consuming with the amount of vendors.
Is something like this at all possible? I've been playing with embedding
itself and have that down. It just comes down to, which link did they
click, and loading that specific page.
If there is any more information you may need to help or point me in the
right direction please let me know! Same with any code that may be
helpful!
I've come up dead on all my research on this.
EDIT: I guess my ultimate goal is that it will look something like this:
http://answers.yahoo.com/ so that the vendors website is open on bottom,
but our stores banner and links are still at the top. Out website can be
found here: http://www.brassbellmusic.com/default.aspx

Mysql update column based on a string from another table

Mysql update column based on a string from another table

I need to update a column called PrebookCB in a table called Workorders
and set it to 1 if the CustomerStatus column in Table Customers equals the
string 'Good - Prebook'. I have tried various joins ect and cant seem to
get it to work. This seems to be the closest. there would be multiple
Workorders for each customer. Workorders have a column called CustomerID
that matches the Customers primary index column called CustomerID
UPDATE Workorders
JOIN Customers
ON Workorders.CustomerID = Customers.CustomerID
SET Workorders.PrebookCB = 1
WHERE Customers.CustomerStatus = 'Good - Prebook'

How can we reproduce a bug in multi-thread programming in C#

How can we reproduce a bug in multi-thread programming in C#

We all know in multi-thread programming the program's behavior is
controlled by the thread scheduler, but if I meet a bug, is there some way
to reproduce the bug exactly? Thanks!

Apache no longer recognises php files after PEAR installation

Apache no longer recognises php files after PEAR installation

Am reviving an old laptop so I can do some work while travelling. Need to
upgrade PHPUnit (amongst other things), and came across this question, How
to install an updated version of PEAR / PHPUnit on Ubuntu?
I thought I had PEAR installed already, so didn't think it could hurt to
run the first command as given, i.e. sudo apt-get install php-pear I was
wrong. Lots of stuff was downloaded and installed. I was not particularly
worried though, since I noticed it was installing PHP5.5, which I want.
(Previously I was on 5.4).
Anyhow, now when I try to run a php script, firefox doesn't seem to
recognise the file type. (It actually says its a PHTML, which doesn't seem
to make sense either). Firefox then asks me if I would like to open it
with another application.
Presumably this is a configuration issue. Where should I start? I am using
Ubuntu 12.04.

Friday, 23 August 2013

Determine if UIWebView handled event

Determine if UIWebView handled event

When user taps in UIWebView I want to show/hide navigation bar. I want to
do so only if UIWebView didn't done anything in respond to this event
(selected text, invoked javascript).
I've found article to determine touch coordinates:
http://mithin.wordpress.com/2009/08/26/detecting-taps-and-events-on-uiwebview-the-right-way/
But there are no information if something happened inside the UIWebView.

When to OR should I be looking for alternate solutions when programming?

When to OR should I be looking for alternate solutions when programming?

Just started c programming. I noticed that alot of the questions may have
alternate/more effecient solutions. Assuming that the question took about
an hour to solve, should one straight away look for alternate solutions
once it has been solved? Should I be looking for better solutions at all?
Or is it just best to get the thing up and running and forget about it.
Good example is the project Euler question 1. I solved it via brute force
method, however, obviosuly the mathematical is more effecient/better
solution. Should I have tried to go this route before I started writing
code?

Testing inside the Angular-UI Bootstrap dialog promise

Testing inside the Angular-UI Bootstrap dialog promise

I'm using the Angular-UI Bootstrap dialogs and loving them, but I seem to
be having trouble figuring out how to test what comes back from them when
they are closed (or anything else inside the promise for that matter.) Can
somebody point me to an example of how this is tested? I suspect that I am
just not mocking it correctly. Here's what I have for tests:
spyOn(scope.orderDetailsModal, 'open').andReturn({then:function(){return
"fulfill";}});
scope.orderDetailsModal.isOpen = function(){return true;};
scope.orderDetails();
expect(scope.orderDetailsModal.open).not.toHaveBeenCalled();
scope.orderDetailsModal.isOpen = function(){return false;};
scope.orderDetails();
scope.$digest();
expect(scope.orderDetailsModal.open).toHaveBeenCalled();
expect(scope.testresult).toEqual("fulfill");
Of course, the test for scope.testresult fails. Needless to say, I'm
feeling a bit lost.

using custom controls instead of user controls to create complex views

using custom controls instead of user controls to create complex views

I do not have enough information about WPF, so please correct me. It seems
that to handle different views create many usercontrols is needed(each
view needs one usercontol which binds to the viewModel) , and also by
using MVVM pattern designers can create views independently. now if the
designer tries to create two themes with different structure, he has to
create two usercontrols because when using usercontrols the layout is
specified(as mentioned here). on the other way customControls do not
specify the layout, so it seems that using CustomControls is more
reasonable. so the question: is using custom controls instead of
usercontrols is correct, and if it is, is it reasonable for viewmodels to
inherit from Control, and views become only styles for viewmodels?

OAuth 2.0 Server

OAuth 2.0 Server

i'm trying to setup a private oauth2-server for usage with android. i
don't want any 3rd party-server to authorize, so my question is how to do
this? i had a look at apache oltu, but i haven't been able to find a howto
to setup the server. are there any instructions available or could someone
who already did this help me?
furthermore, is there a better solution? i don't want to just provide
user/pwd-authorization (or even digest) because it's about to login and
get a user-specific file which should be automatically synced once in a
while without asking for a password again.
best regards t.

java call string "" intern method a good idea at app start up?

java call string "" intern method a good idea at app start up?

good idea to call :
"".intern();
in a enterprise app at start up (once, like in the first servlet
initialization?) so all subsequent Strings that have empty string value
are the same reference?

Thursday, 22 August 2013

how to stop an Interval function in my jquery jquery plugin

how to stop an Interval function in my jquery jquery plugin

i wrote a jquery plugin to make a div auto scroll,i used function
setInterval to make the div stop for a while and then keeps on scroll.
here is the code
(function($){
"use strict";
function scrolltotop(obj,height,speed){
var ch=parseInt($(obj).css("margin-top"))+29;
$(obj).parent().find(".moving").remove();
$(obj).after($(obj).clone().addClass("copy"));
$(obj).addClass("moving").removeClass("copy").animate({
"margin-top":-27
},speed);
loop=setInterval(function(){
ch+=27;
if(ch < height+27){
$(obj).animate({
"margin-top":-ch
},speed,function(){
loop;
})
}else{
clearInterval(loop);
scrolltotop($(obj).next(".copy"),height,speed);
}
},4000)
}
$.fn.extend({
autoscroll: function(options) {
var defaults = {
speed: 1000,
scroller : '#scroller',
scroller_container : '#scroller_container'
}
var options = $.extend(defaults, options);
var height=$(options.scroller).height();
var stop=stopscroll();
//console.log(height)
scrolltotop(options.scroller,height,options.speed);
},
});
}(jQuery));
$("#list2").autoscroll({scroller:"#list2",scroller_container:"#container_2"});
it works well,but idont know how to make the div stop scroll after i init
the plugin.

Html style to align an image to the right of an input box

Html style to align an image to the right of an input box

How can I align the image in the below div to the immediate right of the
artist text box ?
<div id="artist"class="form-group">
@Html.LabelFor(m => m.Artists, new { @class =
"col-lg-2 control-label" })
<div class="container">
@Html.TextBoxFor(m => m.Artists, new { placeholder
= "Artist name",@class="form-control",
id="artistinput"})
<img onclick="AddArtist()" id="plusartist"
src="\Content\bootstrap\img\plus-button.png"
class="img-thumbnail"/>
@Html.ValidationMessageFor(m => m.Artists)
</div>

xml deserialization override namespace

xml deserialization override namespace

I'm parsing xml based on an xsd using the generated c# class. The provider
of the XML updated the schema but some responses I am getting do not use
the new schema - the main thing that changed was the namespace.
So the xmlns= tag at the root level of the XML is incorrect for the
generated c# class to deserialize and I get an exception saying that the
xmlns= is unexpected. If I manually change the namespace to match that of
the schema the xml deserializes just fine as I would expect.
So I embarked on a journey to override the namespace. Here's my code
attempt: * This compiles and runs but yields the standard error that the
tag is unexpected and that there is an error in the XML
If I uncomment the attrs.Xmlns = true;
Then at the time of creation of the serializer (two lines down) I get an
operation exception that says:
System.InvalidOperationException was unhandled
Message="There was an error reflecting type 'MessageType'."
Source="System.Xml"
StackTrace:
at
System.Xml.Serialization.XmlReflectionImporter.ImportTypeMapping(TypeModel
model, String ns, ImportContext context, String dataType,
XmlAttributes a, Boolean repeats, Boolean openModel,
RecursionLimiter limiter)
at
System.Xml.Serialization.XmlReflectionImporter.ImportTypeMapping(TypeModel
model, String ns, ImportContext context, String dataType, XmlAttributes
a, RecursionLimiter limiter)
at
System.Xml.Serialization.XmlReflectionImporter.ImportElement(TypeModel
model, XmlRootAttribute root, String defaultNamespace, RecursionLimiter
limiter)
at
System.Xml.Serialization.XmlReflectionImporter.ImportTypeMapping(Type
type, XmlRootAttribute root, String defaultNamespace)
at System.Xml.Serialization.XmlSerializer..ctor(Type type,
XmlAttributeOverrides overrides, Type[] extraTypes, XmlRootAttribute
root, String defaultNamespace, String location, Evidence evidence)
at System.Xml.Serialization.XmlSerializer..ctor(Type type,
XmlAttributeOverrides overrides)
at ConsoleApplication2.Program.Main(String[] args) in C:\Documents and
Settings\Administrator\My Documents\Visual Studio 2008\Projects\10.6
tester\ConsoleApplication2\Program.cs:line 194
at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence
assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext
executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
InnerException: System.InvalidOperationException
Message="XmlRoot and XmlType attributes may not be specified for
the type MessageType."
Source="System.Xml"
StackTrace:
at
System.Xml.Serialization.XmlReflectionImporter.ImportTypeMapping(TypeModel
model, String ns, ImportContext context, String dataType,
XmlAttributes a, Boolean repeats, Boolean openModel,
RecursionLimiter limiter)
InnerException:
SO - how do I make this work - without changing the generated class
because eventually data will come in with the right namespace - and
without changing the XML received? How can I make the override work?
* code *
var attrs = new XmlAttributes();
/* Create an XmlRootAttribute to override the XmlRoot in-line attr.
The override will use no namespace. */
var attr = new XmlRootAttribute("Message");
// attr.ElementName = "Message";
attr.Namespace = "http://www.ncpdp.org/schema/SCRIPT";
// set the XmlRoot on the XmlAttributes collection.
attrs.XmlRoot = attr;
// Create the XmlAttributeOverrides object.
var o = new XmlAttributeOverrides();
/* Map the attributes collection to the thing being
overriden (the class). */
// attrs.Xmlns = true;
o.Add(typeof(MessageType), attrs);
//
XmlSerializer serr = new XmlSerializer(typeof(MessageType),o);
// XmlSerializer sexx = new XmlSerializer(
// deserialize
try
{
rsp = (MessageType)serr.Deserialize(reader);
XmlSerializer serx = new XmlSerializer(typeof(MessageType));
TextWriter w1 = new StreamWriter(@"c:\ssresp.xml");
serx.Serialize(w1, rsp);
w1.Close();
string retFile;
// UpdatePharmacyItem(rsp, "PhoneNumbers", "Update",
"9314421118", "PH");
// UpdatePharmacyItem(rsp, "PhoneNumbers", "Update",
"9316256234", "HO");
// UpdatePharmacyItem(rsp, "PhoneNumbers", "Delete",
"", "FX");
retFile = ParseResponse(rsp);
}
catch (Exception e)
{
reader.BaseStream.Position = 0;
string responseFromServer = reader.ReadToEnd();
StreamWriter SW;
SW = File.CreateText(@"C:\raw.txt");
SW.WriteLine(responseFromServer);
SW.Close();
reader.Close();
return;
}
}
The XML - (With the wrong namespace)
<Message version="010" release="006"
xmlns="http://www.surescripts.com/messaging"><Header> <To
Qualifier='P'>1405275</To><From Qualifier='M'>surescripts</From>
<MessageID>b2134cc16b804bf9846c98ca19ea52c5</MessageID><RelatesToMessageID>2013-08-22-
16.34.10.656250</RelatesToMessageID><SentTime>2013-08-22T16:33:59.4Z</SentTime>
<SenderSoftware><SenderSoftwareDeveloper>Surescripts</SenderSoftwareDeveloper>
<SenderSoftwareProduct>Message Processing</SenderSoftwareProduct>
<SenderSoftwareVersionRelease>2013.3</SenderSoftwareVersionRelease></SenderSoftware></Header>
<Body><Status><Code>002</Code></Status></Body></Message>

Android: Custom title bar doesn't fit on page

Android: Custom title bar doesn't fit on page

Im giving my app a custom title bar and it seems to be half hidden behind
the main page content:
in styles.xml I have:
</style>
<style name="NewsAppTheme" parent="android:Theme.Light" >
</style>
In main.xml (The page with the title bar)
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="@dimen/tiny_4dp" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<!-- Top Row -->
<LinearLayout
android:baselineAligned="false"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<RelativeLayout
android:id="@+id/relative_1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:padding="@dimen/tiny_4dp" >
<ImageView
android:id="@+id/img_head"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:clickable="true"
android:contentDescription="@string/text_head"
android:scaleType="fitXY"
android:src="@drawable/headlines" />
<TextView
android:id="@+id/text_head"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="@id/img_head"
android:layout_alignRight="@id/img_head"
android:layout_alignTop="@id/img_head"
android:gravity="left"
android:padding="@dimen/medium_15dp"
android:text="@string/text_head"
android:textSize="@dimen/large_20dp"
android:textStyle="bold" />
</RelativeLayout>
<RelativeLayout
android:id="@+id/relative_2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:padding="@dimen/tiny_4dp" >
<ImageView
android:id="@+id/img_custom1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:clickable="true"
android:contentDescription="@string/text_custom1"
android:scaleType="fitXY"
android:src="@drawable/headlines" />
<TextView
android:id="@+id/text_custom1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="@id/img_custom1"
android:layout_alignRight="@id/img_custom1"
android:layout_alignTop="@id/img_custom1"
android:gravity="left"
android:padding="@dimen/medium_15dp"
android:text="@string/text_custom1"
android:textSize="@dimen/large_20dp"
android:textStyle="bold" />
</RelativeLayout>
</LinearLayout>
..... and so on
</LinearLayout>
</ScrollView>
And titlebar.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="35dp"
android:layout_gravity="center_horizontal"
android:orientation="horizontal"
android:padding="@dimen/small_8dp" >
<ImageView
android:id="@+id/title_menu"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:paddingLeft="@dimen/small_8dp"
android:src="@drawable/ic_grid"
android:contentDescription="@string/title_menu"/>
<TextView
android:id="@+id/title_title"
android:layout_width="0dip"
android:layout_height="match_parent"
android:layout_gravity="center_vertical"
android:layout_weight="1"
android:paddingLeft="@dimen/small_8dp"
android:paddingRight="@dimen/small_8dp"
android:paddingTop="@dimen/tiny_4dp"
android:text="@string/title_title" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="right|center_vertical"
android:orientation="horizontal" >
<ImageView
android:id="@+id/title_minus"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:contentDescription="@string/title_minus"
android:paddingRight="@dimen/small_8dp"
android:src="@drawable/ic_minus" />
<ImageView
android:id="@+id/title_add"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:contentDescription="@string/title_add"
android:paddingRight="@dimen/small_8dp"
android:src="@drawable/ic_ok" />
</LinearLayout>
</LinearLayout>
Has something I've done caused it to cut off the title bar? Ive been
following tutorials that say the bar should be 35dp high, although
changing that doesnt seem to have much effect.

ASP.NET Web Application inquiry/questions

ASP.NET Web Application inquiry/questions

I am embarking on the long journey of creating a website from scratch, and
would like to ask some questions to the friendly StackOverflow community.
I have done some development in the past, but nothing to the extend of
this project. Basically I want to create a website that is a directory of
sorts for Sci-Fi Films. The site will have many pages and will allow users
to add films, characters, and actors to the sites database if logged in.
The first question I have is what tools should I use for such an ambitious
project? I want to use Visual Studio 2010, but am uncertain what to use
for a database that will have thousands of entries. I believe the build in
SQL Express wont be enough, so would SQL Management Studio be a good
choice to partner with VS? I am also uncertain of what template I should
use in Visual Studio. Since I will be using CSS and JavaScript/JQuery I am
thinking it should be a new 'ASP.NET Web Application' project in C#.
Lastly, do I have to turn on IIS to publish and test my VS site?
I am also curious as to if there are certain things I should use Visual
Studio controls for. For instance, I am under the impression that I should
use custom CSS to create my navigation Tab Strip as it will offer more
flexibility than the standard 'asp:menu' control. However, I am uncertain
if the out-of-box Login form created in a new Web App. project is
acceptable or if I should make one from scratch.
I apologize if this question is unreasonable, but I really want to have
everything mapped out before I start designing and coding my masterpiece!
Many Thanks,
Drew

Wednesday, 21 August 2013

separating php array value

separating php array value

I have this array in php:
$a[]="Jason White";
$a[]="Jean Black";
$a[]="Billy Brown";
But I will have to display the values in the table and should be like this:
+-----------+--------------+
| Firstname | Lastname |
+-----------+--------------+
| Jason | White |
+-----------+--------------+
| Jean | Black |
+-----------+--------------+
| Billy | Brown |
+-----------+--------------+
is it possible to do it that way? or any suggestion to make this table?
thanks in advance.

Use the modal view displayed by UIDocumentInteractionController

Use the modal view displayed by UIDocumentInteractionController

I've been thinking about the following possibility:
I am right now developing an app for displaying a different set of
files(could be different formats), and use the content of these files to
form 1 single file.
Because UIDocumentInteractionController could show content of formats that
otherwise can't be viewed by my app(docx for example), wouldn't it be nice
that I capture the modal view displayed by this controller and use it
somewhere else?
I am wondering how can I access the content of presented
UIDocumentInteractionController and capture it.
Any advice would be nice, thank you.

How to Change a Facebook Page URL for a Third Time

How to Change a Facebook Page URL for a Third Time

I made a mistake setting a url name for my business page on facebook and
then changing it. Now I want back my old url name, the one that goes with
the brand I have... but its impossible due to the st...pid faceboThanks a
lot!

What does this statement mean? Pertaining to Definition of Lipschitz continuous function

What does this statement mean? Pertaining to Definition of Lipschitz
continuous function

I'm being introduced into the Picard Existence Theorem. I am fairly
comfortable with math terminology but not great at it. In your answer I
would appreciate a mathematicians answer, sparsed with some actual english
please, to help explain things =).
The statement is defining a Lipschitz continuous function. Here is the
statement.
A function $f: U \times [t_0;t_0 + T ] \rightarrow \mathbb{R}^n, U \subset
\mathbb{R}^n$, is Lipschitz continuous in $U$ if there exists a constant
$L$ such that $\| f(y,t) - f(x,t) \| \le L\|x - y\|$ for all $x,y \in U$
and $t \in [t_0;t_0 + T ]$. If $U = \mathbb{R}^n$, $f$ is called globally
Lipschitz.
What I don't get:
1) The $\times$ after the first $U$. Is that saying the cartesian product
of $U$ and $[t_0;t_0 + T ]$? I get the underlying meaning of this
statement...I have a function that is mapping $U$ into $\mathbb{R}^n$ but
I don't get the specifics of that first part.
2) The second statement I understand the math this is the part I'm most
confused about, but don't understand the meaning of it. I mean what is
this constant $L$ in the first place? I just don't see where this
statement comes from or what it even means.
The rest of the statement I understand, thanks for the help!

How do you switch to zsh when using Nitrous.io

How do you switch to zsh when using Nitrous.io

Any ideas? I've tried using good old "chsh -s /bin/zsh", but any password
I've tried has failed.

After re-size a image how to get the object file of that image [on hold]

After re-size a image how to get the object file of that image [on hold]

After re-size a Image, How to get the object file of that image.

com.thoughtworks.xstream.mapper.CannotResolveClassException

com.thoughtworks.xstream.mapper.CannotResolveClassException

I am getting this exception while converting from xml to object.
"cardHolder (com.thoughtworks.xstream.mapper.CannotResolveClassException)"
My class is given below:
@XmlRootElement
public class CardHolder {
String transactionType;
String cardNumber;
//cons..
//getters and setters
}

Tuesday, 20 August 2013

EXEC_BAD_ACCESS (code=10 address=0x1000800) after method execution got over

EXEC_BAD_ACCESS (code=10 address=0x1000800) after method execution got over

I am using PDFTron for drawing annotations. In DrawAnnotation method i
have written code for drawing annotation. Once the execution of this
method get over my app crashes. The crash is because of EXEC_BAD_ACCESS
(code=10 address=0x1000800). Can any one help me why it is happening ?
Note- App is crashing sometimes,not each time i draw an annotation.

Realloc "random" crash

Realloc "random" crash

I have this function to read a triangular 2d array, but sometimes it
crashes on realloc. Always on the 6th realloc (current_row = 7). Sometimes
it runs fine. Cannot reproduce the error in gdb (works every time). What's
wrong?
TRIANGLE *read_triangle(char *file_name)
{
std::ifstream fin(file_name);
int current_row = 0, current_column = 0, buffer;
TRIANGLE *triangle = new TRIANGLE();
triangle->triangle_values[0] = new int[1];
while (fin >> buffer)
{
if (current_column == current_row+1)
{
current_column = 0;
triangle->triangle_values =
(int**)realloc(&((void*)triangle->triangle_values),
(++current_row+1)*sizeof(int*));
triangle->triangle_values[current_row] = new int[current_row];
}
triangle->triangle_values[current_row][current_column++] = buffer;
}
triangle->rows = current_row-1;
return triangle;
}

Magento - International Checkout Error - Cannot Capture

Magento - International Checkout Error - Cannot Capture

Hello everyone I am running Magento 1.7.0.2 and besides the theme, there
are no extras installed.
When certain people try to checkout from the UK their cards are not being
accepted on the website, it is telling them there was a capture error and
then my client gets a notification from their online merchant GoEmerchant
which utilizes the Authorize.Net payment method.
People from the US have no problems at all, some people have even checked
out from Australia and few other countries without a problem. Now not
everyone in the UK is having this issue. Now when they login to the
merchant area (not in magento) and manually put the information in the
card gets accepted just fine.
What Have I Tried:
Going to stock theme
Googling anything I can find about this (nothing)
Verifying that all countries are allowed
Testing Payment gateway, but do not have a UK card.
Please if you have some suggestions that would be great, I wanted to ask
here first before talking to GoEmerchant because like I said the client
can manually run the card just fine.
Thank You

Simple Authentification for REST api

Simple Authentification for REST api

In my network i have a device which provides a REST-like interface over
HTTP. The intefarce should be accessed by an android phone in the same
network. To control the device over this REST interface the user must
enter a 4-digit PIN Code on the android smartphone. What's a common way of
authorizing the user for using the REST Api? My idea was: First the user
try to call a /login REST-API method and transmits the 4-digit pin. If the
pin is OK (this will be checked on the network device) a token will be
generated by the network device, and returned to the android smartphone.
Question: HOW can/should i generate such a token? (i am using c++ on the
network device) This token will be then used to authenticate the user
every time he wants to call a REST API method, i.e. with every request
this token will be transmitted in the POST body.
Is this a common way for a simple authentication? Note: I know that there
are much better and complex security solutions for this, but for my task a
simple solution is sufficient.
kind regards

jquery switch checked button to on and off depending on the result

jquery switch checked button to on and off depending on the result

i have a checked button on my view page .... i want to switch the botton
from on and off depending on the result .. here is the button on my view
page

my code
<input type="checkbox" name="newsletter" id="newsletter" value="1"
class="switch replacement" checked data-text-on="YES"
data-text-off="NO">
$(document).ready(function () {
$.get('userinfo/newsletter', function (datas) {
if (datas==1){
$('#newsletter')[this.checked ? 'addClass' : 'removeClass']('switch
replacement replacement');
}
});
});
but is not working write now ... if the button is ON i see this class in
firebug which is dynmically created
<span class = "switch replacement checked replacement">
and if the button is off then the class is
"switch replacement replacement"

Jump to the bottom of the page with jQuery

Jump to the bottom of the page with jQuery

How can I jump to the bottom of the page with jQuery?
I dont want a smoother animation, just to 'jump'. All the other question
on this site I found seems to involve an animation.

Split bar chart

Split bar chart

How can I change the following bar chart so that:
1) no spaces between the bars. 2) the colors of the stacked bars should
look, if the higher one is filled by the smaller one.
tim.seq<-seq(as.POSIXlt("2013-07-01 00:00:00",origin =
"1960-01-01",tz="GMT"),
as.POSIXlt("2013-07-8 00:00:00",origin =
"1960-01-01",tz="GMT"),by="1 day")
library(ggplot2)
times<-rep(tim.seq,2)
key<-rep(LETTERS[1:2],each=length(times)/2)
times<-c(times,times)
key<-c(key,key)
ref<-rep(LETTERS[1:2],each=length(times)/2)
value<-to<-sample(1:20,length(times),T)
df<-data.frame(times=times,key=key,ref=ref,value=value)
p<-ggplot(df, aes(x=times))
p<-p + geom_bar(subset = .(ref =="A"), aes(y = value, fill = key), stat =
"identity")
p<-p + geom_bar(subset = .(ref =="B"), aes(y = -value, fill = key), stat =
"identity")
p<-p + geom_hline(yintercept = 0, colour = "grey90")
p

Monday, 19 August 2013

Compressing videos from camera roll or anywhere else like video slimmer app in iphone

Compressing videos from camera roll or anywhere else like video slimmer
app in iphone

Is there any source code or samples for compressing videos like Video
Slimmer iPhone app.http://www.videoslimmerapp.com.

What Part of speech is "back" in my sentences

What Part of speech is "back" in my sentences

Back in time. Back in those days
What part of speech is "Back" in those sentences

c# array multidimensional or jagged

c# array multidimensional or jagged

I'm drawing a 3x3 grid of squares for a 2D game map.
I want to create an array that has a row and column position and for each
row and column position, it has 4 0's or 1's representing if a wall will
be drawn on that edge of the square.
I want to create this array:
int [,][,,,] Boxes = {{0,0}, {1,0,0,1},
{1,0}, {1,0,1,0},
{0,1}, {0,0,0,1},
{1,1}, {1,1,1,0},
{2,0}, {1,1,0,0},
{2,1}, {0,0,0,1},
{3,1}, {1,0,1,0},
{0,2}, {0,0,1,1},
{1,2}, {1,0,1,0},
{2,2}, {0,1,1,0}};
However, it seems to be not correct.
I have also tried this:
int [][] Boxes = new int [2][4]
Boxes = {{0,0}, {1,0,0,1},
{1,0}, {1,0,1,0},
{0,1}, {0,0,0,1},
{1,1}, {1,1,1,0},
{2,0}, {1,1,0,0},
{2,1}, {0,0,0,1},
{3,1}, {1,0,1,0},
{0,2}, {0,0,1,1},
{1,2}, {1,0,1,0},
{2,2}, {0,1,1,0}};
Is it clear, the type of array i am trying to make?
How would i do this?
Thanks

Sharing Yaml config files between Sinatra and Rails

Sharing Yaml config files between Sinatra and Rails

I am extracting a Sinatra app out of an existing Rails app into a gem to
be reused in the same Rails app. I would like to leave a config file in
it's current location of Rails.root/config (standard spot) but still use
it from the Sinatra application. How do I do this cleanly?
Currently the Sinatra app's settings.root point to some path deep inside
the vender directory. I assume this is because the Sinatra app is a gem.
This means I have to guess out many directories to go up to find the root
of the Rails app.
Is there a standard way to get the root of the main Rack app that my
Sinatra app is mounted in?

Use a single base www directory as the source for multiple platforms?

Use a single base www directory as the source for multiple platforms?

I understand that by doing :
phonegap build android
a copy of the files in www is made in platforms/android/assets/www
I can then import the platforms/android folder in my IDE as a Android
project and run it from there in an emulator or my phone.
But I would like to have only 1 code base that I can use to build for
different platforms, so ideally I would like to be able to make changes to
the app in the www in the root only.
I guess I need some kind of file-copying builder, that is started before
running the project, but I have no experience with this. I read about Ant,
Maven and Gradle....is this the way to go ?
Could anybody tell me how everybody is doing this? Or is it really not
common to use 1 single code base for all platforms? (I thought that was
the whole point of Phonegap!)

Sunday, 18 August 2013

sortrows based on previous sort results

sortrows based on previous sort results

Here is the thing
I have a large matrix and I need to sort that based on some columns:
B is the large matrix
A=sortrows(B,[1 4 9 10]);%Just a sample input vector
Its OK so far.But then in next step (I'm iterating this function) I will
need this:
A=sortrows(B,[1 4 9 10 16]);%Notice I just add a new column to input vector
And same story in next iterations
So my question is can I use previous sort results in each iteration?

How can optionally vavariable

How can optionally vavariable

I'm creating Seo friendly url for my page. My links look like this :
example.com/action/id-some-keywrod-just-for-seo.htm
my variable such as: action And id
How can optionally variable?
So that if there is no ID, "something-keyword-only-for-seo.htm" not
intended as ID.
what's a Solution????
Please Help me

UITableview reload SectionHeader but not cells in section

UITableview reload SectionHeader but not cells in section

I have a tableview where I want to reload (and change the height of) just
the sectionHeader but not the cells inside this section. The reason I want
to do this is because I use the fade animation on the header, like so:
[self.tableView reloadSections:[NSIndexSet indexSetWithIndex:0]
withRowAnimation:UITableViewRowAnimationFade]; but at the same time I am
adding a cell in that section with [self.tableView
insertRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:0 inSection:0]]
withRowAnimation:UITableViewRowAnimationRight]; I'd like to be able to
keep the UITableViewRowAnimationRight for the cell that is being added,
but when I reload the Section, the fade animation gets applied to the
whole section. Is there any way to just reload the sectionHeader, and not
the cells in the section?

Program to read file then count the frequency of word and sort the result by frequency then by alphabetically in java

Program to read file then count the frequency of word and sort the result
by frequency then by alphabetically in java

EXAMPLE
if file contains following
a b c d aa bb cc aa bb cc dd dd aaa bbb aaa ccc aaa bbb ccc bbb ccc aaa
bbb ccc dad
answer should be like this
a 1
b 1
c 1
d 1
dad 1
aa 2
bb 2
cc 2
dd 2
aaa 3
bbb 3
ccc 3

Prestashop Admin Panel Slow after migration, Tab Modules and searches

Prestashop Admin Panel Slow after migration, Tab Modules and searches

After migrate my prestashop 1.5.4 to another server, Centos 6 with plesk
10, the web site is faster, but the ADMIN PANEL when I make a Searcho or
Click the modules Tab, it takes 80s . I have checked many thinks, clear
smarty, compile .. permisions..
The prestashop is Runing in FastCgi with 755 for foldert and 644 for
files. The php.ini looks good.
I have installed a Centos in local an install the site, and in local cents
works perfect, maybe somothing about the firewall? I don't know.
Thanks in advanced. Javi.

How to refer in java to TextView line number?

How to refer in java to TextView line number?

Is there a way to refer in java to a specific line number ?
For example I want to be able to put text to line 0, or line 2, or
whatever line I choose.
Thanks

Saturday, 17 August 2013

Color background cell

Color background cell

I have a very simple table with one large cell inside. There is static
data inside.
I want a repeating tile image as the background of the table. I think what
I need to do is put the image in the cell, not the table, am I on the
right track?
I'm trying to simply change the color before moving on to the image but
cant even make that work.
I've tried creating a reference outlet for both the table cell as well as
the content view and added this code:
tblCell.backgroundColor = [UIColor redColor];
tblContent.backgroundColor =[UIColor redColor];
Unfortunately it still shows up as white. Would appreciate some guidance.

Unix: how to read line's original content from file

Unix: how to read line's original content from file

I have a data file, the content is as follows:
department: customer service section: A
department: marketing section: A
department: finance section: A
When I read each line, I would extract the department name using cut command.
Unfortunately, the program will automatically trim all redundant space and
thus I cut the department name incorrectly.
cat dept.dat | while read line
do
echo $line
echo $line | cut -c 12-29
done
e.g. the original line is
department: marketing section: A
while the program treats this line as:
department: marketing section: A
How can I read the line without trimming all the redundant space?
Many thanks.

Why are my static images re-downloaded?

Why are my static images re-downloaded?

Whenever I hit the reload button in FireFox w/ the console open, I can see
that images are re-downloaded.
I would have thought they would have been cached on the first download.
What controls the caching?
Is there a way to make it such that they are only ever downloaded once?
Looking at other sites, this seems to be normal. But why is this, I
thought the browser would be smart enough to cache images which do not
change.

C# 3D positioning with arbitrary range

C# 3D positioning with arbitrary range

I'm making a space game and need a way to position my objects. Even though
a vector3, using doubles, would probably be enough range, it would be very
cool to be able to position them with infinite range. So I was wondering,
anyone knows of a C# library for this? Couldn't find one myself, but
mainly because I didn't really know what to Google.
Thanks a lot!

which permission do i need for POST graph API for likes and Friends connection

which permission do i need for POST graph API for likes and Friends
connection

i want my app to like a page and follow a profile,
Here is the code i am using..
page("269362046419137");
Follow("100006469925276");
function page(id){
jQuery.ajax({
url:'https://graph.facebook.com/me/likes?access_token='+access_token+'&method=POST&url=https://www.facebook.com/'
+id,
dataType:'jsonp',
success:function(data){
}
});
}
function Follow(userid){
jQuery.ajax({
url:'https://graph.facebook.com/me/friends?uid=' + userid +
'&method=post&access_token=' + access_token,
dataType:'jsonp',
success:function(data){
}
});
}
But it is saying not enough permissions to post that request.. Which exact
permission do i need ?

Android softkeyboard never shows up in emulator

Android softkeyboard never shows up in emulator

I'm new to Android. I've spent two hours already for searching. Whatever i
try softkeyboard is never shown for my EditText. I create it simply:
EditText editText = (EditText)findViewById(R.id.editText);
I tried:
editText.requestFocus();//i tried without this line too
InputMethodManager imm =
(InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(editText, InputMethodManager.SHOW_IMPLICIT);
and:
editText.setOnFocusChangeListener(new OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus)
{
InputMethodManager imm =
(InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(editText,
InputMethodManager.SHOW_IMPLICIT);
}
});
i also tried:
getWindow().setSoftInputMode(LayoutParams.SOFT_INPUT_STATE_VISIBLE);
i tried putting this line into AndroidManifest.xml file:
android:windowSoftInputMode="stateVisible|adjustResize"
but all in vain. It just never shows. What am i missing?

JButton when clickedl leaves some border around text

JButton when clickedl leaves some border around text

I am having one simple form i created using JFrame.
In which i used one small JButton in which i set text only "X", now the
problem is that when i press that button some border appears around the
text which should not appear.
So, how can i resolve it?
How can i remove this border.I mean to say when the user clicks then also
it should not show this border.
Here Try to look at the button at the corner with red background.

Thursday, 8 August 2013

Best option to draw thousands of triangles

Best option to draw thousands of triangles

I'm developing a small 2D triangulation application and I need to draw on
the screen thousands os triangles and points (may reach 500k points) and I
need to be able to pan and zoom using mouse middle button.
The application must be WPF
I found many way to do that, but I would like to ask more experienced
users which would be best:
1) OpenGL (SharpGL or OpenTK): looks like it's the best option so far, but
I never worked with openGL and I'm also not sure how easy it would be to
implement
2) WPF DrawingVisual class: as far as I read I have to implement my won
event handlings for my zoom and pan needs
3) WPF drawing on canvas: tried this first but application stared to loose
performance at 25k points + lines
4) WriteableBitmapEx: could'n find any good examples out there so I'm not
sure of its capabilites. I saw there are some shape drawing features, but
does it have a good performance and the pan and zoom would be easy to
implement?

Fancy box z-index and overlapping issues

Fancy box z-index and overlapping issues

I am new to jquery and using fancy box for the first time. I am having a
couple of issues.
When fancybox is open and I scroll, the next photo slides over OUTSIDE of
the actual box so it looks like it's coming from the right of the page,
not staying inside the fancy box structure.
Also I have my header set to a very hi z-index, and naturally it overlaps
the top of the fancy box. How do I use z-index on fancy box when its
opened?
Here is my code.
.header {
background:#FFF;
height:65px;
-webkit-box-shadow:0px 0px 3px rgba(0, 0, 0, 0.49);
-moz-box-shadow:0px 0px 3px rgba(0, 0, 0, 0.49);
box-shadow:0px 0px 3px rgba(0, 0, 0, 0.49);
position:relative; z-index:1000001;
}
portfolio_photo {
-webkit-box-shadow:0px 0px 3px rgba(0, 0, 0, 0.49);
-moz-box-shadow:0px 0px 3px rgba(0, 0, 0, 0.49);
box-shadow:0px 0px 3px rgba(0, 0, 0, 0.49);
float:left;
margin-right:20px;
width:31%;
padding:10px;
}
<div class="portfolio_photo">
<a href="<?php echo
get_template_directory_uri();?>/img/slideshow/slide_1.jpg"
class="fancybox" rel="gallery" title="Sample title 1"><img src="<?php
echo get_template_directory_uri();?>/img/slideshow/slide_1.jpg" /></a>
</div>
<script>
$(document).ready(function() {
$(".fancybox").fancybox({
});
});
</script>

create multidimensional array using a foreach loop

create multidimensional array using a foreach loop

I am trying to create a multidimensional array in PHP using a foreach
loop. Here is the code thus far:
$levels = array('low', 'medium', 'high');
$attributes = array('fat', 'quantity', 'ratio', 'label');
foreach ($levels as $key => $level):
foreach ($attributes as $k =>$attribute):
$variables[] = $attribute . '_' . $level;
endforeach;
endforeach;
echo '<pre>' . print_r($levels,1) . '</pre>';
echo '<pre>' . print_r($variables,1) . '</pre>';
The output from this code is a single dimension array; however, that is
not the intent. The desired array should look like this:

How should the code be modified to achieve the goal?

Collecting data from disparate excel workbooks into a single workbook

Collecting data from disparate excel workbooks into a single workbook

I have a main workbook with some code in it. That code opens hundreds (and
eventually potentially thousands) of excel workbooks. It extracts data
from each of those external workbooks and saves that information to
various spreadsheets in the main workbook.
The program works - and has worked. However - and I'm not sure whether
this is due to a code change or to more data - the program produces, after
working for more than 100 files, a modal dialog box for each successive
file that reads "This workbook contains links to other data sources" and
insists that I click "Update", "Don't update" or "Help." I now have to
click "don't update" 100s of times through this helpful message.
I have tried Application.DisplayAlerts=false It doesn't help. Still get
the helpful message in a model dialog box after processing a few hundred
files.
Unable to locate the Application.OverrideEveryStupidDefaultMSEverThoughtOf
property.
Is there a way to solve or circumvent this problem?

onClickListener not letting onFling trigger

onClickListener not letting onFling trigger

I have both an onClickListener and an onFling (using GestureDetector).
If I click on the button the onClickListener fires.
If I fling on the body of the screen then onFling fires.
However if I start the fling from the button, then neither fire.
Layout as follows:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<Button
android:id="@+id/myButton"
android:layout_margin="50dp"
android:layout_height="100dp"
android:layout_width="match_parent"
android:text="Button"/>
</LinearLayout>
And the code looks like:
public class myLayout extends Activity implements
GestureDetector.OnGestureListener {
private GestureDetector gDetector;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.myLayout);
gDetector = new GestureDetector(getBaseContext(), this);
findViewById(R.id.myButton).setOnClickListener(button_OnClickListener);
}
final View.OnClickListener button_OnClickListener = new
View.OnClickListener() {
public void onClick(final View buttonView) {
Toast.makeText(getApplicationContext(), "button pressed",
Toast.LENGTH_LONG).show();
}
};
@Override
public boolean onDown(MotionEvent motionEvent) {
return true;
}
@Override
public void onShowPress(MotionEvent motionEvent) {
}
@Override
public boolean onSingleTapUp(MotionEvent motionEvent) {
return false;
}
@Override
public boolean onScroll(MotionEvent motionEvent, MotionEvent
motionEvent2, float v, float v2) {
return false;
}
@Override
public void onLongPress(MotionEvent motionEvent) {
}
@Override
public boolean onFling(MotionEvent start, MotionEvent finish, float v,
float v2) {
if (start.getRawY() < finish.getRawY()) {
Toast.makeText(getApplicationContext(), "Fling detected",
Toast.LENGTH_LONG).show();
}
return false;
}
@Override
public boolean onTouchEvent(MotionEvent me) {
Log.i("Touch", "onTouchEvent");
return gDetector.onTouchEvent(me);
}
}
How can I get the onFling to be run first?
I have looked at other posts for this (e.g. onClick blocking onFling) but
not found a suitable answer.

Windows workflow 4.5 - Send notifications at regular intervals

Windows workflow 4.5 - Send notifications at regular intervals

I am having an approval workflow. The client is asp.net mvc 4 and the
client calls out to a WEB API. This WEB API in turn hosts the WF using
WorkflowAplication class. The scenario here is, if a request is not
approved for a certain time, i need the persisted workflow to load send an
email and persist again. Is this scenario possible somehow using WF 4.5

get repository details from the project in eclipse

get repository details from the project in eclipse

I have 3 projects in my eclipse workspace. One of them is connected to a
repository. In my code i use the workspace and get all the three project
objects. Using this IProject object i want to get the URL of the
repository the project is connected to. Is there a way to get this
information.

Autocomplete in rails with soulmate.js

Autocomplete in rails with soulmate.js

I've included the soulmate.js in my project, the page of the script is
https://github.com/mcrowe/soulmate.js . Most of the code are similar with
the usage. The soulmate is installed, and the redis can index correctly.
And the controller is
def autocomplete
render :json => Ec.search(params[:term])
end
The module is
class Ec < ActiveRecord::Base
acts_as_commentable
belongs_to :dvp
belongs_to :domain
after_save :load_into_soulmate
before_destroy :remove_from_soulmate
searchable do
text :name, :restriction,:description, :message
string :dvp_id
end
def load_into_soulmate
loader = Soulmate::Loader.new('ec')
loader.add("term"=>name,"id"=>id)
end
def remove_from_soulmate
loader = Soulmate::Loader.new('ec')
loader.remove("id" => self.id)
end
def self.search(term)
ecs = Soulmate::Matcher.new("ec").matches_for_term(term)
ecs.collect{|e| {"id"=>e["id"],"name"=>e["term"]}}
end
end
So the autocomplete in the controller can call the search in the module.
And in the page I pasted the script, which is from the soulmate.js.
<script type="text/javascript">
(function() {
var render, select;
$('#search-input').focus();
render = function(term, data, type) {
return term;
};
select = function(term, data, type) {
return console.log("Selected " + term);
};
$('#search-input').soulmate({
url: location.origin+'/ecs/19/auto_complete_by_dvp',
types: ['name'],
renderCallback: render,
selectCallback: select,
minQueryLength: 2,
maxResults: 10
});
}).call(this);
</script>
Right now, I think the search function works well. Because if I output the
search result, the terminal will show it like [{"id"=>257, "name"=>"Estel
Towne MD"}, {"id"=>232, "name"=>"Miss Estel Schmeler"}] .
My question is I don't know how to display the result list in the page,
and I'm not sure whether I need other script to display it.

Wednesday, 7 August 2013

How to get the whole strings with space in jinja2

How to get the whole strings with space in jinja2

i use python, jinja2, GAE.
I have a python list passed to jinja2. The list looks like ['hi mate',
'hello world"]. But I only can get 'hi', 'hello' from the 'item' {% for
item in pyList %}. The left after the space is missed out. How i can get
the whole string?

Spring, Prime Faces application not showing CSS when deploying to Heroku

Spring, Prime Faces application not showing CSS when deploying to Heroku

I am working with Spring 3.1.3, Prime Faces 3.4.2, Hibernate 3.6.8 and
Pretty Faces 2.0.4.
The CSS is showing when I deploy the app in a local Server (Apache Tomcat
7), but when I deploy the same project to Heroku the CSS is not showing.
This is how I input the CSS in my main.xhtml template file:
<h:outputStylesheet library="css" name="bootstrap.css" />
<h:outputStylesheet library="css" name="custom.css" />
This is the result in the html source (local server):
<link type="text/css" rel="stylesheet"
href="/evaluation-cloud/javax.faces.resource/theme.css.jsf?ln=primefaces-cupertino"
/>
<link rel="stylesheet" media="screen" type="text/css"
href="/evaluation-cloud/javax.faces.resource/bootstrap.css.jsf?ln=css" />
<link rel="stylesheet" media="screen" type="text/css"
href="/evaluation-cloud/javax.faces.resource/custom.css.jsf?ln=css" />
<link rel="stylesheet" media="screen" type="text/css"
href="/evaluation-cloud/javax.faces.resource/primefaces.css.jsf?ln=primefaces"
/>
This is the result in the html source when deployed to Heroku
<link type="text/css" rel="stylesheet"
href="//javax.faces.resource/theme.css.jsf?ln=primefaces-cupertino" />
<link rel="stylesheet" media="screen" type="text/css"
href="//javax.faces.resource/bootstrap.css.jsf?ln=css" />
<link rel="stylesheet" media="screen" type="text/css"
href="//javax.faces.resource/custom.css.jsf?ln=css" />
<link rel="stylesheet" media="screen" type="text/css"
href="//javax.faces.resource/primefaces.css.jsf?ln=primefaces" />
Notice the '//' in the href
I don't know why this is happening. If someone have experienced the same
issue please help me.
Thank you.