Saturday 31 August 2013

Javascript return enclosing function

Javascript return enclosing function

I have a simple scenario in which I check if something exists before
adding it, if it does, I return the function (hence exiting). I use this
pattern many times and I would like to decouple it in another simple
function.
function onEvent(e){
if( this.has(e) )
return
this.add(e);
// More logic different on an event-basis
}
I would like to decouple it like so:
function safeAdd(e){
if( this.has(e) )
return
this.add(e);
}
function onEvent(e){
safeAdd(e);
// More logic
}
But obviously doing so just returns safeAdd and doesn't exit from onEvent,
and the rest of the logic gets executed anyways.
I know I could do something like:
function safeAdd(e){
if( this.has(e) )
return false
this.add(e);
return true
}
function onEvent(e){
if( !safeAdd(e) )
return
// More logic
}
But, since I repeat this a lot, I would like to be as concise as possible.

Jenkins: How to modify PATH environment variable for build steps?

Jenkins: How to modify PATH environment variable for build steps?

I'm trying to follow the instructions here to prepend a directory to path
for my build steps. However, the instructions reference the deprecated
SetEnv plugin. I tried playing with the new EnvInject plugin, setting
PATH=mydir:$PATH in Script Content field of the "Inject Build Environments
to the build process" section. However, the path is not updated when my
build step shell scripts execute.

Is there an efficient way to snapshot in-memory sqlite database with System.Data.Sqlite?

Is there an efficient way to snapshot in-memory sqlite database with
System.Data.Sqlite?

I want to be able to go to and from a byte[] representation of an
in-memory SQLite database. The only solution I know of right now is using
SQLiteConnection.BackupDatabase method, which can copy an active in-memory
database to another database on disk. I can then load that database with
File.ReadAllBytes, but I find this approach terribly inefficient for my
needs.

Perforce Server connection error in Mac OS X

Perforce Server connection error in Mac OS X

Good Day everyone!
I am trying to configure perforce server in OS X(10.8.4) . I tried to
follow instructions from here. In fact i am not sure if i am doing it
right ! Please check the commands below that i entered in Terminal.
Last login: Sun Sep 1 02:13:19 on ttys000
MDs-MacBook-Pro:~ Emon$ export PATH=~/perforce:$PATH export P4PORT=1666
MDs-MacBook-Pro:~ Emon$ cd ~/perforce chmod a+x p4d p4d -d
MDs-MacBook-Pro:perforce Emon$ chmod a+x p4
MDs-MacBook-Pro:perforce Emon$ mkdir ~/myws cd ~/myws p4 client myws
mkdir: /Users/Emon/myws: File exists
mkdir: p4: File exists
MDs-MacBook-Pro:perforce Emon$
After that i tried to to connect from p4v, but the following occurs !
In connection setup assistance i tried (as instructed in the link)
Host : localhost
Port : 1666
And the connection continues to refuse showing this...
Connect to server failed;check $P4PORT.
TCP Connection to localhost:1666 failed.
Connect: 127.0.0.1:1666 : Connection refused.
Please someone guide me in this regard. Thank you in advance. :)

jquery click on span which generated by ajax

jquery click on span which generated by ajax

How to catch $(".tag") click which added by ajax, I try to use "live",
"on" and "bind" but where is no result
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var content = $("#ad_content").val();
$.ajax({
type: "GET",
url: "tags/check",
data: {
content: content
},
dataType: "text",
success: function(tags) {
var tag, tags_html, _i, _len, _ref;
if (tags === "[null]") {
return $(".tags").html("");
} else {
tags_html = "";
_ref = jQuery.parseJSON(tags);
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
tag = _ref[_i];
tags_html += "<span class=\"tag\">" + tag + "<a
class=\"websymbol\" href=\"javascript:;\">Î</a></span>";
}
$(".tags").html(tags_html);
}
}
});
$(".tag").on("click", function() {
alert("123");
});
});
</script>
<textarea id="ad_content">2222</textarea>
<div class="tags"></div>

jquery mobile- swipe for the same page with different content

jquery mobile- swipe for the same page with different content

i am trying to swipe for the same page with different content but with the
slide animation? i am using jquery mobile. however, after the page is
changing the page disappear. What am i amissing
function swipeleftHandler( event ){
$.mobile.changePage.defaults.allowSamePageTransition = true;
$.mobile.changePage( '#MatchStats' , {
transition: "slide",
});
if (indexMathces==0)
indexMathces=listMatches.length;
indexMathces--;
getMatchStats(indexMathces,GroupID);
}
function swiperightHandler( event ){
indexMathces++;
if (indexMathces==listMatches.length)
indexMathces=0;
getMatchStats(indexMathces,GroupID);
$.mobile.changePage.defaults.allowSamePageTransition = true;
$.mobile.changePage( '#MatchStats' , {
transition: "slide",
});

Friday 30 August 2013

Setting Multiple alarms on my alarm application

Setting Multiple alarms on my alarm application

In my application I am able to play alarm tone on specified time using
timepicker..But when i press the set alarm button again it replaces the
previous alarm.. Could anyone help to store multiple alarms...and also
please tell where the time for ringing the alarm is stored in application?
Alarmreceiver.java
package com.example.alaram;
import java.io.IOException;
import android.app.Activity;
import android.content.Context;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
public class AlarmReceiver extends Activity{
private MediaPlayer mPlayer;
private WakeLock mWakeLock;
Button stopalarm;
@SuppressWarnings("deprecation")
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
PowerManager pm=(PowerManager) getSystemService(Context.POWER_SERVICE);
mWakeLock =pm.newWakeLock(PowerManager.FULL_WAKE_LOCK, "my wakelock");
mWakeLock.acquire();
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN |
WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED |
WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON,
WindowManager.LayoutParams.FLAG_FULLSCREEN |
WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED |
WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON );
setContentView(R.layout.alarmreceiver);
//Stop the alarm music
stopalarm=(Button) findViewById(R.id.btnStopoAlarm);
stopalarm.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
mPlayer.stop();
finish();
return;
}
});
PlaySound(this,getAlarmUri());
}
private void PlaySound(Context context,Uri alert){
mPlayer=new MediaPlayer();
try{
mPlayer.setDataSource(context,alert);
final AudioManager am=(AudioManager)
getSystemService(Context.AUDIO_SERVICE);
if(am.getStreamVolume(AudioManager.STREAM_ALARM)!=0);
{
mPlayer.setAudioStreamType(AudioManager.STREAM_ALARM);
mPlayer.prepare();
mPlayer.start();
}
}catch(IOException e)
{
Log.i("AlaramReciever", "no audio file");
}
}
//Get an alarm sound. If none set, try notification, Otherwise, ringtone.
private Uri getAlarmUri()
{
Uri alert=
RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
if(alert==null)
{
alert=
RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
if(alert==null)
{
alert=RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
}
}
return alert;
}
protected void onStop(){
super.onStop();
mWakeLock.release();
}
}
SetAlarm.java
package com.example.alaram;
import java.util.Calendar;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TimePicker;
import android.widget.Toast;
public class SetAlarm extends Activity {
TimePicker timePicker;
Button ok;
int hrs,min;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.setalarm);
//Operation of Ok button or Setting Alaram Time
ok=(Button) findViewById(R.id.btnOk);
ok.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent=new Intent(SetAlarm.this,AlarmReceiver.class);
PendingIntent pi=PendingIntent.getActivity(SetAlarm.this, 2,
intent,PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager alm=(AlarmManager)
getSystemService(Context.ALARM_SERVICE);
timePicker=(TimePicker) findViewById(R.id.timePicker1);
hrs=timePicker.getCurrentHour();
min=timePicker.getCurrentMinute();
Calendar calendar=Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY,hrs);
calendar.set(Calendar.MINUTE, min);
calendar.set(Calendar.SECOND, 0);
alm.set(AlarmManager.RTC_WAKEUP,calendar.getTimeInMillis(), pi);
Toast.makeText(getBaseContext(), "Alaram is
Set",Toast.LENGTH_SHORT).show();
finish();
}
});
}
}

How to compare two JSONArray and find differencer when JSONArrays itself contain JSONObject which in turn contain JSONArray

How to compare two JSONArray and find differencer when JSONArrays itself
contain JSONObject which in turn contain JSONArray

I am new to this forum.I am trying to compare two directory structure one
that is on remote and another one that is on local. Currently what I am
doing is based on certain things I am making a JSONArray of directury
structure from server side(remote) . Same way I am making a JSONArray of
directory structure of client side. Now I want to compare those two
JSONArray and get the difference between them.
Also I want to maintain the level of directory structure also . Meaning
that in the resulting JSONArray the difference should be at proper level
which I can may directly with directory.
Please guide me If I make any mistake here as I am new to the forum.
Thanks

Thursday 29 August 2013

How to model a polymorphic list in Haskell?

How to model a polymorphic list in Haskell?

I'm trying to model some polymorphic-type data in haskell. I understand
why the following code doesn't work, but I'm hoping it illustrates what
I'm trying to do. My question is: what is an idiomatic way to model this
with Haskell? (You don't need to keep the input format the same if there
is a better way - I don't have any existing code or data.)
data Running = Sprint | Jog deriving (Show)
data Lifting = Barbell | Dumbbell deriving (Show)
data Time = Time Integer deriving (Show)
data Pounds = Pounds Integer deriving (Show)
data TimedActivity = TimedActivity Running Time deriving (Show)
data WeightedActivity = WeightedActivity Lifting Pounds deriving (Show)
class Activity a
instance Activity TimedActivity
instance Activity WeightedActivity
-- I have a list of activities
main :: IO ()
main = putStrLn $ show [ TimedActivity Sprint (Time 10)
, WeightedActivity Barbell (Pounds 100)
]
-- I then want to apply functions to generate summaries and
-- reports from those activities, i.e.:
extractLifts :: (Activity x) => [x] -> [WeightedActivity]
extractTimes :: (Activity x) => [x] -> [TimedActivity]

Bash/command line - Count occurances of string in output from qstat

Bash/command line - Count occurances of string in output from qstat

I am trying to write a line of shell code that will tell me how many jobs
I have in a queue.
The command qstat will return a list of jobs with the following attribute
Job id, Name, User, Time Use Queue name
The command is labelled qstat(1B) in the man page.
My attempt to count how many jobs I have running uses grep:
grep -c my_username | qstat
As I understand it, this should count the number of occurrences of
my_username in the output from qstat. It doesn't work though. Any ideas
where I am going wrong?

How can I use default page in magento?

How can I use default page in magento?

I will try like that! first I create A category and then enable magento
default page but it was not showing in that category.

Wednesday 28 August 2013

Grails with Taggable crashes if deleting all but 1 tag

Grails with Taggable crashes if deleting all but 1 tag

I have a simple Grails application and one of the classes implements
Taggable. When testing with the Grails scaffolding and very basic user
interface for tags. When I delete a tag, everything is fine. When I delete
all the tags on an object, everything is fine. But if I try to delete all
but one, I get a Grails Runtime Error with the message, "Cannot cast
object 'groovytag' with class 'java.lang.String' to class
'java.util.List'" where groovytag was the single tag remaining. The error
sites this line:
objectInstance.tags = params.tags
Can anyone suggest what I need to do to get an object with only one tag?

Cookie not being created and stored websphere

Cookie not being created and stored websphere

pI've a WEB project deployed in WAS 6.1 server which creates and stores a
cookie for session management. I've upgraded WAS to v7.0.0.27 and now the
cookie is not being stored nor created. I'm using jdk1.6_19, WEB Module
2.5 and EJB 3.0./p pThis is the way I create the cookie:/p precode Cookie
cookie = new Cookie(user, divison); cookie.setMaxAge(Integer.MAX_VALUE);
cookie.setPath(/); res.addCookie( cookie ); /code/pre pI've spent 2 weeks
on this but nothing seems to be working. I've patch my RSA to have
7.5.5.5.001 Fix, I've gone thru Websphere console for setting cookies,
I've deployed the same application in Tomcat and the cookie is getting
created but in WAS Websphere v7.0.0.27 I can't make it./p pAny idea or
solution for this issue will be appreciated/p

What are the geographic locations in Windows Aero theme?

What are the geographic locations in Windows Aero theme?

Does anyone know the geographic locations of photos displayed in Windows'
7 Aero theme, specifically for United States and Landscapes themes?

why my main function couldn't return at last?

why my main function couldn't return at last?

I build a win32 console application program, here is the source code:
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
using namespace std;
struct CPassenger
{
string name;
string ID;
string seat;
};
struct CFlight
{
string flNum;
string destination;
int amount;
int booking;
string departureTime;
string fallTime;
vector<CPassenger> list;
};
class CFlightSystem
{
public:
CFlightSystem();
~CFlightSystem();
private:
vector<CFlight> flight;
};
CFlightSystem::CFlightSystem()
{
ifstream infile("flight.txt");
if(!infile)
{
cerr<<"No input file!"<<endl;
exit(1);
}
while(!infile.eof())
{
CFlight plane;
infile>>plane.flNum>>plane.destination
>>plane.amount>>plane.booking
>>plane.departureTime>>plane.fallTime;
for(int i=0;i!=plane.booking;++i)
{
CPassenger tmp;
infile>>tmp.name>>tmp.ID>>tmp.seat;
plane.list.push_back(tmp);
}
flight.push_back(plane);
}
infile.close();
}
CFlightSystem::~CFlightSystem()
{
ofstream outfile("flight.txt");
if(!outfile)
{
cerr<<"No output file!"<<endl;
exit(1);
}
for(vector<CFlight>::iterator iter=flight.begin();
iter!=flight.end();++iter)
{
outfile<<iter->flNum<<' '<<iter->destination<<' '
<<iter->amount<<' '<<iter->booking<<' '
<<iter->departureTime<<' '<<iter->fallTime<<' '
<<endl;
for(vector<CPassenger>::iterator it=(iter->list).begin();
it!=(iter->list).end();++it)
{
outfile<<it->name<<' '
<<it->ID<<' '
<<it->seat<<endl;
}
}
outfile.close();
}
int main()
{
CFlightSystem management;
return 0;
}
when I debug the code , I found that the console didn't return any messege
that is to say, the main function is still called ? and I don't know if my
destructor is working as I hope..
I'm a c++ freshman, and it's my first time posting here... (sorry for my
poor English..I hope I can get some help ..T.T)

Create sysfs entries under /sys/devices/system/edac/

Create sysfs entries under /sys/devices/system/edac/

I am trying to implement fault handling using EDAC for Freescale processor
(MPC85XX) on 2.6.34 kernel (powerpc arch). But I couldn't create sysfs
entries under /sys/devices/system/edac/ for mc and pci. Though the 'mc'
device is being registered under edac, the csrow elements mc* are not
being created.
I have got the following warning while building the kernel.
WARNING: "vMC_alloc_sel_record" [drivers/char/ipmi/vmc.ko] has no CRC!
Does this warning has any impact on the behavior of the code? The
following is the dmesg log for edac.
EDAC MC: Ver: 2.1.0 Aug 28 2013
EDAC DEBUG: in /home/usr/src/linux/drivers/edac/edac_mc_sysfs.c, line at
1069: edac_sysfs_setup_mc_kset()
EDAC DEBUG: in /home/usr/src/linux/drivers/edac/edac_mc_sysfs.c, line at
1086: edac_sysfs_setup_mc_kset() Registered '.../edac/mc' kobject
Freescale(R) MPC85xx EDAC driver, (C) 2006 Montavista Software
The following config options are enabled for EDAC
CONFIG_EDAC=y
# CONFIG_EDAC_VMC is not set
CONFIG_EDAC_DEBUG=y
CONFIG_EDAC_MM_EDAC=m
CONFIG_EDAC_MPC85XX=m
# CONFIG_EDAC_DUMP_IRQ_REGS is not set
Could anyone please help on how to register devices under edac?

renderDisplayFunc in opengl/glut is calling myfunc more than once

renderDisplayFunc in opengl/glut is calling myfunc more than once

#include "GL/glut.h"
#include "GL/gl.h"
#include <iostream>
#include <stdlib.h>
using namespace std;
#define XWidth 700 // Clipping window size 700*700
#define YHeight 700
void renderFunction() {
/*Clear Information from last draw
Sets the current clearing color for use in clearing
color buffers in RGBA mode.
*/
glClearColor(0.0, 0.0, 0.0, 0.0);
glClear(GL_COLOR_BUFFER_BIT);
//Set line width
glLineWidth(1);
//(x,y) coordinates as in pixels
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0, XWidth, 0, YHeight, -1, 1);
//Set line color
glColor3f(1.0, 0.0, 0.0);
//random num generated
for(int i=0;i<4;i++){
int r1 = rand() % 1000;
int r2 = rand() % 1000;
int r3 = rand() % 1000;
int r4 = rand() % 1000;
//Begin LINE coordinates
glBegin(GL_LINES);
glVertex2d(r1, r2);
glVertex2d(r3,r4);
//End LINE coordinate
glEnd();
cout<<r1<<" "<<r2<<" "<<r3<<" "<<r4<<" i is "<<i<<endl;}
//Forces previously issued OpenGL commands to begin execution
glFlush();
}
// Driver program to test above functions
int main(int argc, char** argv) {
//Initialize GLUT
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_SINGLE);
//Set Output Window Size
glutInitWindowSize(XWidth,YHeight);
//Set the position of Output window corresponding to Screen
glutInitWindowPosition(100,100);
//Create the Window
glutCreateWindow("OpenGL - Classify line among three classes");
//Set handler functions for drawing
glutDisplayFunc(renderFunction);
//Start the main loop
glutMainLoop();
return 0;
}
When I'm executing the above program, it's working fine. But the issue is
that when I'm printing the values of randomly generated variables r1 r2 r3
r4, they are being printed 8 or sometimes 12 times. It means
glutDisplayFunc(renderFunction); is calling renderFunction more than once
which is not required.
How to control this behavior. I want renderFunction to be called just once.
UPDATE: I want 4 lines to be created and exactly 4 Lines are being formed
but when I'm printing the coordinates, they are showing unexpected
behavior as I mentioned above.

sqldatasource select parameter issue

sqldatasource select parameter issue

the code :
<asp:SqlDataSource ID="ProductSource" runat="server"
SelectCommand="SELECT [PRODUCT_ID],[PRODUCT_NAME] from products where
STORE_ID=@STORE_ID"
ConnectionString="<%$ ConnectionStrings:Kernel_dbConnectionString %>" >
<SelectParameters><asp:SessionParameter Name="STORE_ID"
SessionField="SelectedStoreID" /></SelectParameters>
</asp:SqlDataSource>
an error accrued and it's : invalid column name STORE_ID

Tuesday 27 August 2013

Getting RefToDate of the Previous Row to become the RefFromDate of the next Row TSQL

Getting RefToDate of the Previous Row to become the RefFromDate of the
next Row TSQL

I have a table with data on the below format:
ProjID ProjName RefDate
-------- ----------- ----------
1 A 08/02/2013
1 A 08/03/2013
1 A 08/15/2013
2 B 08/02/2013
2 B 08/03/2013
2 B 08/15/2013
2 B 08/20/2013
I want a resultset that looks like below:
ProjID ProjName StartDate EndDate
-------- ----------- ---------- ------------
1 A 08/02/2013 08/02/2013
1 A 08/02/2013 08/03/2013
1 A 08/03/2013 08/15/2013
2 B 08/02/2013 08/02/2013
2 B 08/02/2013 08/16/2013
2 B 08/16/2013 08/20/2013
2 B 08/20/2013 08/22/2013
The StartDate is copied from the refdate of the previous row.
How to have a TSQL statement to come up with the resultset mentioned
above? I can do an iteration but it's not the optimal way to do it IMHO.

Priors and Loss in R

Priors and Loss in R

I am fairly new to R and data mining concepts and am trying to understand
the rpart package in R. I am a bit confused about the role of priors and
loss in the making of a decision tree. I am referring to the
http://cran.r-project.org/web/packages/rpart/vignettes/longintro.pdf
document and would appreciate any explanation on this topic

CSS only rendering after jQuery animation completes. How to fix that?

CSS only rendering after jQuery animation completes. How to fix that?

I have a hidden element which I am sliding down using simple .slideDown()
function. This element has another element inside, but that does not show
up until the sliding down is complete.
Here is a fiddle with a demo. Code are pretty straight forward
$("a").on("click", function() {
$("#test").slideDown(1000);
});
And
<div id="test">
<div class="hiddenbar">
</div>
Long Para
</div>
<a>Click Here</a>
The .hiddenbar shows up after slideDown completes. Any way to overcome this?

Custom taxonomy subcategories template page

Custom taxonomy subcategories template page

I want to create template page on which i could list and display all child
categories of my custom category parent! That's the first level, and when
those child categories are displayed i would like to link them to a page
template where all of the child category posts would be displayed!
Is this doable?
Thanks!

What does the ISO/IEC 9899 6.8.4.2 ->2 phrase mean?

What does the ISO/IEC 9899 6.8.4.2 ->2 phrase mean?

I don't get it what this means. I already thought this could mean code as
in my code snippet of this Question:
Skipping switch cases via false loop is a valid operation?
But as the answerers just where going to improve the code and ignored my
question about the c99 quote, I'm going to ask this here now explicitly:
If a switch statement has an associated case or default label within the
scope of an identifier with a variably modified type, the entire switch
statement shall be within the scope of that identifier.135)
And here's the footnote:
135) That is, the declaration either precedes the switch statement, or it
follows the last case or default label associated with the switch that is
in the block containing the declaration.
could any one be so kindly and explain it to me in other words? Thanks for
the effort.

Monday 26 August 2013

How to calculate a logarithmic sensor reading in java?

How to calculate a logarithmic sensor reading in java?

I have a sensor that's output is a logarithmic representation. For example
every 56mV (millivolts) represents a decade of value. So I get a mV
reading for 100 and it's -30mV and a mv reading that is +26mv that
represents a value of 1000 and going further a mV reading of +82mV
represents a value of 10,000 (56mV between each decade). These numbers are
just an example I'll have two calibration mV values so I'll know what 100
and 1000 mV readings are. My question is, is there an easy way to
calculate the value given a mV reading? I can think of a few ways to go
about it programically but it seems there must be a function to do this.
I'm guessing that function is log(x) but I'm not certain how to go about
it. Especially since the mV value can be negative. As you can probably
guess math is not my strong suit.
Any insight will be greatly appreciated.

PowerShell console won't close after execution of a script

PowerShell console won't close after execution of a script

I have a PowerShell script that, as its last instruction, is calling a C#
program. This PowerShell script is being run on a Windows server on a
scheduler. The problem is that the PowerShell console window that the
script is using won't close or go away after the script is done executing.
We need the console window to close or else the scheduler will have
multiple PowerShell.exe programs on the task manager.
We have tried adding exit and break but the window still stays up.
Is there any way in a PowerShell script to force the console window to
close after a script is done executing?

Use of ! in VIM

Use of ! in VIM

I have seen that sometimes :q works but sometimes we have to use :q!. This
is the case for many commands. I was wondering what is the general use of
! in vim and when to use it. I tried to google this, but it seems the
search is omitting the exclamation mark.

Dgrid does not render after domConstruct.place

Dgrid does not render after domConstruct.place

I have a dgrid with its own headers and data store, and I would like to
switch it out with another dgrid when a tab is clicked. The code below
sucessfully replaces grid1 with grid2 (firebug shows it in the DOM), but
the content panel that contained grid1 is left empty. Does anyone have an
idea why grid2 never renders? Note: this is AMD dojo
// create the dgrid
window.grid = new (declare([Grid, Selection]))({
// use Infinity so that all data is available in the grid
bufferRows: Infinity,
columns: {
//data derived from ArcGIS server database
}
}, "grid1");
window.grid2 = new(declare([Grid, Selection]))({
bufferRows: Infinity,
columns: {
//columns derived from ArcGIS server database
}
}, "grid2");
//on click event
var tab2 = query("#dijit_layout_TabContainer_0_tablist_panel2");
on(tab2, "click", showSecondGrid);
//function to switch grid1 with grid2
function showSecondGrid(){
var otherGrid = domConstruct.toDom("<div id='grid2'
style='width:100%;height:100%;'
data-dojo-props='rowsPerPage:'5', rowSelector:'10px',
autoheight:'true', autowidth:'true''></div>");
return domConstruct.place(otherGrid, "grid1", "replace");
parser.parse(dom.byId("grid2"));
};
And here is how grid1 appears in the body
<div id="rightPanel_content" class="panel_content"
dojotype="dijit/layout/ContentPane">
<div id="grid1" style="width:100%;height:100%;"
data-dojo-props="rowsPerPage:'5',
rowSelector:'10px', autoheight:'true',
autowidth:'true'">
</div>
</div>

locked out by google

locked out by google

My daughter got locked out of her tablet by google we have been the
correct information in but still no luck to make matters worse we are
unable to connect to the internet is there a way around the google log in
page to get to the settings

Dynamical positioning of a Div

Dynamical positioning of a Div

I've got the following construct
Text Details
Show Details
Text
Show Details ...
When i press now Show Details I want the details appear on the same height
as the pressed link. (Imagine 100 Text/Links.)
I've put together a small JSfiddle where the absolute positioning of the
element is possible, but somehow I can't get it to work dynamically based
on the scrollposition. http://jsfiddle.net/uRN64/201/
I have tried the following javascript functions to set the position:
var div = document.getElementById('update');
//div.style.top = window.pageYOffset;
//div.style.top = document.body.parentElement.scrollTop;
//div.style.top = document.body.scrollTop;
div.style.top = '100px';

C# - Loading XML file in parts

C# - Loading XML file in parts

My task is to load new set of data (which is written in XML file) and then
compare it to the 'old' set (also in XML). All the changes are written to
another file.
My program loads new and old file into two datasets, then row after row I
compare primary key from the new set with the old one. When I find
corresponding row, I check all fields and if there are differences with
the old one, I write it to third set and then this set to a file.
Right now I use:
newDS.ReadXml("data.xml");
oldDS.ReadXml("old.xml");
and then I just find rows with corresponding primary key and compare other
fields. It is working quite good for small files.
The problem is that my files may have up to about 4GB. If my new and old
data are that big it is quite problematic to load 8GB of data to memory.
I would like to load my data in parts, but to compare I need whole old
data (or how to get specific row with corresponding primary key from XML
file?).
Another problem is that I don't know the structure of a XML file. It is
defined by user.
What is the best way to work with such a big files? I thought about using
LINQ to XML, but I don't know if it has options that can help with my
problem. Maybe it would be better to leave XML and use something
different?

Sunday 25 August 2013

how to use avconv to record streaming audio (how to define sources)?

how to use avconv to record streaming audio (how to define sources)?

I have never used avconv before. I've been reading the manual and asking
questions on various forums and IRC for the last couple weeks but I have
not found an answer yet. (This question is one part of a larger question I
asked here. I am breaking it down because this key part is where I need
help first. I may delete the other question because it may be too broad or
ill-defined.)
I used pacmd list-cards to list my streaming audio sources. Below are the
two that I need to define as inputs to avconv.
alsa_output.usb-Focusrite_Scarlett_2i2_USB-00-USB.analog-stereo.monitor/#2:
Monitor of Scarlett 2i2 USB Analog Stereo
alsa_input.usb-Focusrite_Scarlett_2i2_USB-00-USB.analog-stereo/#3:
Scarlett 2i2 USB Analog Stereo
So my question is simply, How do I define those sources as inputs to avconv?
More info/background follows:
Once I know how to define the audio inputs I plan to use them similarly to
this:
#!/bin/bash
OUTPUT="audio_`date +%Y-%m-%d_%H%M`"
avconv \
-f alsa -ac 2 -i
<alsa_output.usb-Focusrite_Scarlett_2i2_USB-00-USB.analog-stereo.monitor>
\
-f alsa -ac 1 -i
<alsa_input.usb-Focusrite_Scarlett_2i2_USB-00-USB.analog-stereo> \
-map 0:0 -map 1:0 \
-acodec flac \
-threads 0 \
-y $OUTPUT
I assume I need to replace what is in angle brackets with the correct
notation. And I have no idea if the rest of the above script is even
close...
Here's my hardware info:
$ pacmd list-cards
Welcome to PulseAudio! Use "help" for usage information.
>>> 3 card(s) available.
[snip other cards]
index: 2
name: <alsa_card.usb-Focusrite_Scarlett_2i2_USB-00-USB>
driver: <module-alsa-card.c>
owner module: 6
properties:
alsa.card = "1"
alsa.card_name = "Scarlett 2i2 USB"
alsa.long_card_name = "Focusrite Scarlett 2i2 USB at
usb-0000:04:00.0-2, high speed"
alsa.driver_name = "snd_usb_audio"
device.bus_path = "pci-0000:04:00.0-usb-0:2:1.0"
sysfs.path =
"/devices/pci0000:00/0000:00:1c.4/0000:04:00.0/usb3/3-2/3-2:1.0/sound/card1"
udev.id = "usb-Focusrite_Scarlett_2i2_USB-00-USB"
device.bus = "usb"
device.vendor.id = "1235"
device.vendor.name = "Novation EMS"
device.product.id = "8006"
device.product.name = "Scarlett 2i2 USB"
device.serial = "Focusrite_Scarlett_2i2_USB"
device.string = "1"
device.description = "Scarlett 2i2 USB"
module-udev-detect.discovered = "1"
device.icon_name = "audio-card-usb"
profiles:
output:analog-stereo: Analog Stereo Output (priority 6000)
output:analog-stereo+input:analog-stereo: Analog Stereo Duplex
(priority 6060)
output:analog-stereo+input:iec958-stereo: Analog Stereo Output +
Digital Stereo (IEC958) Input (priority 6055)
output:iec958-stereo: Digital Stereo (IEC958) Output (priority 5500)
output:iec958-stereo+input:analog-stereo: Digital Stereo (IEC958)
Output + Analog Stereo Input (priority 5560)
output:iec958-stereo+input:iec958-stereo: Digital Stereo Duplex
(IEC958) (priority 5555)
input:analog-stereo: Analog Stereo Input (priority 60)
input:iec958-stereo: Digital Stereo (IEC958) Input (priority 55)
off: Off (priority 0)
active profile: <output:analog-stereo+input:analog-stereo>
sinks:
alsa_output.usb-Focusrite_Scarlett_2i2_USB-00-USB.analog-stereo/#1:
Scarlett 2i2 USB Analog Stereo
sources:
alsa_output.usb-Focusrite_Scarlett_2i2_USB-00-USB.analog-stereo.monitor/#2:
Monitor of Scarlett 2i2 USB Analog Stereo
alsa_input.usb-Focusrite_Scarlett_2i2_USB-00-USB.analog-stereo/#3:
Scarlett 2i2 USB Analog Stereo
ports:
analog-output: Analog Output (priority 9900, available: unknown)
properties:
analog-input: Analog Input (priority 10000, available: unknown)
properties:
iec958-stereo-input: iec958-stereo-input (priority 0, available:
unknown)
properties:
iec958-stereo-output: Digital Output (S/PDIF) (priority 0,
available: unknown)
properties:

00:00:00 DateTime toString become 12:00:00

00:00:00 DateTime toString become 12:00:00


I have a datetime '2013-8-5 0:00:00'.
When I parse it to string using .ToString("yyyy-MM-dd hh:mm:ss"), it
returns "2013-08-05 12:00:00"
Did I write it wrong?
new SqlParameter("@StartDate", SqlDbType.DateTime)
{
Value = startDate.ToString("yyyy-MM-dd hh:mm:ss")
}

How to enumerate in reverse order

How to enumerate in reverse order

I want to enumerate Dave-Letterman Style with the last listed first as in
enumerating top ten items and having them listed in 10 9 8 7 6 5 4 3 2 1.
Is the etaremune package the only way to go?

[ Polls & Surveys ] Open Question : Can you eat a whole tub of butter?

[ Polls & Surveys ] Open Question : Can you eat a whole tub of butter?

I tried it once and barfed.

Saturday 24 August 2013

php / mysql divide result displays as 6.2E-5

php / mysql divide result displays as 6.2E-5

Have such mysql query SELECT CurrencyRate/Units AS FinalCurrencyRate
Value for CurrencyRate is 0.06200000 and value for Units is 1000.
So 0.06200000 / 1000 and get 6.2E-5
The same result if echo $result = 0.06200000 / 1000 . '<br>';
If echo $result = number_format( (0.06200000 / 1000), 10, '.', '' ) .
'<br>'; then can get 0.0000620000
What is solution for mysql query to get normal number instead of 6.2E-5?
Found round(CurrencyRate/Units,10)
But what if do not know number of 00000 after decimal? For example
0.06200000 / 1000000000000000000

Determine birthdate from age in r

Determine birthdate from age in r

Assigning a birth date to a simulated sample; the following works, but
ignores leap years.
Wondered if there is a more precise (and elegant) r approach?
# Simulate 10 persons with age evenly distributed 0 to 21
age <- runif(10, 0, 21)
# calc age in seconds
agesecs <- age*365*24*60*60
# subtract from right now to establish 'birthdate'
bday <- as.Date(Sys.time() - agesecs)
bday
[1] "2008-03-28" "1998-06-12" "2010-05-02" "2007-01-11" "2007-06-07"
[6] "1999-05-22" "2004-01-29" "2013-03-29" "1998-06-01" "2006-10-14"

Run-Time Check Failure #2 - stack around the variable 'osvi' was corrupted on mfc application

Run-Time Check Failure #2 - stack around the variable 'osvi' was corrupted
on mfc application

I've been searching around the internet and I have no idea why this
happens, it's not really an obvious array issue.
Here's the function:
BOOL IsOsCompatible()
{
BOOL retVal = 0;
OSVERSIONINFO osvi;
ZeroMemory(&osvi, sizeof(OSVERSIONINFOEX));
osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);
GetVersionEx(&osvi);
if(osvi.dwMajorVersion == 6)
{
if(osvi.dwMinorVersion == 0)
{
if(SendErrorM("This program has not been tested on Windows
Vista(TM).\nAre you sure you want to use it?",MB_YESNO) ==
IDYES)
retVal = 1;
}
else if(osvi.dwMinorVersion == 1)
{
retVal = 1;
}
else if(osvi.dwMinorVersion == 2)
{
if(SendErrorM("This program has not been tested on Windows
8(TM).\nAre you sure you want to use it?",MB_YESNO) == IDYES)
retVal = 1;
}
}
else
SendErrorM("Your windows verison is incompatible with the minimum
requirements of this application.",NULL);
return retVal;
}
Any ideas?

How can I access the data on this Seagate dying HDD?

How can I access the data on this Seagate dying HDD?

It seems my main disk was dying and eventually, Windows displayed a
message to immediately reboot into recovery, make a full backup and
replace the HDD.
I turned the computer off and plugged the HDD into another computer. I was
able to still see the disk and navigate the file structure on both
partitions (I had one for the OS and another for Data). I actually didn't
try to open any file, I just browsed a few files to see if I was able to
at least see what was in there.
I then downloaded and booted up SeaTools. I first ran the short test, it
failed immediately. The HDD was definitely dying... I then ran the long
test trough the night to see if it could mark all the bad sectors so that
I could copy everything else to another drive.
It showed a lot of errors and attempted to repair a lot of them but I
think it only made the problem worse. Cause now I can't even browser the
files. Actually, Windows (on the other computer, of course) takes ages to
boot with this dying disk connected. It boots quickly if it's not
connected.
I first tried a Live CD of Linux Mint and it also failed to boot. I then
tried a Live CD based on Knoppix and I was now able to boot, but couldn't
do anything. The HDD does not appear for me to browse (other HDDs do) and
all tools available report lots of I/O errors, damaged partition table and
boot sectors, etc...
It's not the end of the world if I'm not able to access the data on this
particular HDD, my important data was backed up on another disk. But it
would be nice if I could still copy some data off of it, or at least try
to browse the file system and see what was there.
Any ideas on how can I fix this since I was able to browse the HDD before
running the SeaTools long test?

untitled

untitled

I am using html tag to display image on application :
<img src ="https://servername/Images/Imagename.JPG" alt ="Logo"/>
but image is not coming on page.
I also tried
<img src="<%=sHttps%>//servername/Images/Imagename.JPG" alt ="Logo"/>
but still is not working.

I killed everyone in Almeria in Avernum 4. Is there any way to restore the town?

I killed everyone in Almeria in Avernum 4. Is there any way to restore the
town?

In Avernum 4 (Spiderweb Software), before completing one of the main story
quests, everyone in Almeria attacks the player's characters on sight. I
thought I had to fight my way through Almeria to access the rest of the
Great Cave, but later I completed the afore-mentioned quest.
Now Almeria is open to me, but all the townspeople are dead. Is there a
way I can edit my save file to reset that area, or will I have to start
the game all over again?

Friday 23 August 2013

MySQL INNER/LEFT JOIN on 3 tables, where records in 3rd table might not exist

MySQL INNER/LEFT JOIN on 3 tables, where records in 3rd table might not exist

I've got a problem that I can't seem to figure out after a bunch of failed
attempts.
I've got three tables that I need to do a join on for some reporting, and
in the 3rd table a record might not exist. But if the record in the 3rd
table doesn't exist, I need to report a null value for the data that comes
from the 3rd table and get all records that match the other conditions.
Stripped down to the relevant columns, here are the table structures:
members - this table holds all members that register to a website
| memberId | insertDate |
| ==========|=====================|
| 1 | 2013-08-01 18:18:16 |
| 2 | 2013-08-02 18:18:16 |
| 3 | 2013-08-03 18:18:16 |
| 4 | 2013-08-04 18:18:16 |
| 5 | 2013-08-05 18:18:16 |
registration_steps - this table holds the progress of the registration
processes and whether the registration was completed or not
| memberId | completed |
| ==========|===========|
| 1 | 1 |
| 2 | 1 |
| 3 | 1 |
| 4 | 0 |
| 5 | 1 |
purchases - this table holds, well.. purchases
| memberId | insertDate |
| ==========|=====================|
| 1 | 2013-08-02 18:18:16 |
| 1 | 2013-08-03 17:18:16 |
| 1 | 2013-08-03 18:18:16 |
| 5 | 2013-08-07 18:18:16 |
This is the query I've come up with so far:
SELECT `m`.`memberId`,
DATE(`m`.`insertDate`) AS `regDate`,
COUNT(`p`.`memberId`) AS `totalTransactions`,
DATE(MIN(`p`.`insertDate`)) AS `firstPurchaseDate`,
DATE(MAX(`p`.`insertDate`)) AS `latestPurchaseDate`,
DATEDIFF(DATE(MIN(`p`.`insertDate`)), DATE(`m`.`insertDate`)) AS
`daysBetweenRegAndFirstPurchase`
FROM `db`.`members` `m`
INNER JOIN `db`.`registration_steps` `r` ON `m`.`memberId` =
`r`.`memberId`
INNER JOIN `db`.`purchases` `p` ON `m`.`memberId` = `p`.`memberId`
WHERE `m`.`insertDate` BETWEEN '2013-07-01 00:00:00' AND '2013-07-31
23:59:59'
AND `r`.`completed` = 1
GROUP BY `m`.`memberId`
;
It shows me everything I want but the members with a missing record in
table purchases.
Here is what I get:
| memberId | regDate | totalTransactions | firstPurchaseDate
| latestPurchaseDate | daysBetweenRegAndFirstPurchase |
|
==========|=====================|===================|=====================|=====================|================================|
| 1 | 2013-08-01 18:18:16 | 3 | 2013-08-02
18:18:16 | 2013-08-03 18:18:16 | 1 |
| 5 | 2013-08-05 18:18:16 | 1 | 2013-08-07
18:18:16 | 2013-08-07 18:18:16 | 2 |
But what I need is:
| memberId | regDate | totalTransactions | firstPurchaseDate
| latestPurchaseDate | daysBetweenRegAndFirstPurchase |
|
==========|=====================|===================|=====================|=====================|================================|
| 1 | 2013-08-01 18:18:16 | 3 | 2013-08-02
18:18:16 | 2013-08-03 18:18:16 | 1 |
| 2 | 2013-08-02 18:18:16 | 0 | NULL
| NULL | -1 |
| 3 | 2013-08-03 18:18:16 | 0 | NULL
| NULL | -1 |
| 5 | 2013-08-05 18:18:16 | 1 | 2013-08-07
18:18:16 | 2013-08-07 18:18:16 | 2 |
In order to achieve this, I tried to change the second inner join to a
left join, a left outer join and put the where conditions to the first
inner join condition. However, I wasn't able to get the desired result.
(Must admit I interupted a few VERY long running queries that might have
been correct(?) though (total count for members in real scenario is about
20k).)
Anyone?
Thanks in advance!

Best way to read stdin that may include newline?

Best way to read stdin that may include newline?

I have to write a program in C that handles the newline as part of a
string. I need a way of handling the newline char such that if it is
encountered it doesn't necessarily terminate the input. So far I've been
using fgets() but that stops as soon as it reaches a '\n' char. Is there a
good function for processing the input from the console that doesn't
necessarily end at the newline character?
To clarify: I need a method that doesn't terminate at the newline char
because in this particular exercise when the newline char is encountered
it's replaced with a space char.

Can't save instance state in android

Can't save instance state in android

In my app I try to save ArrayList state with putSerializable method in
onSaveInstanceState. And restore it in onCreate and
onRestoreInstanceState. In my app if there is no saved instance of this
object it will be create from internet data. But all the time I try to
test this solution ArrayList start to downloading from network. Can anyone
help me?
public class Activity extends SherlockActivity {
ListView listView;
SlidingMenu slidingMenu;
ArrayList<HashMap<String, String>> newsList = null;
String url = "/////here_my_url////";
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setTitle(R.string.news_vatican);
listView = (ListView) findViewById(R.id.newslist);
slidingMenu = new SlidingMenu(this);
slidingMenu.setMode(SlidingMenu.LEFT);
slidingMenu.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);
slidingMenu.setFadeDegree(0.35f);
slidingMenu.attachToActivity(this, SlidingMenu.SLIDING_CONTENT);
slidingMenu.setMenu(R.layout.slidingmenu);
slidingMenu.setBehindOffset(150);
if (savedInstanceState != null){
newsList = (ArrayList<HashMap<String, String>>)
savedInstanceState.getSerializable("list");
Log.e("Activity", "RESTORING");
} else {
Log.e("Activity", "PARSING NEW");
JSONParser parser = new JSONParser(this);
parser.execute(url);
try {
newsList = parser.get();
} catch (InterruptedException e) {
e.printStackTrace();
Log.e("Activity", "Failed to get newslist");
} catch (ExecutionException e) {
e.printStackTrace();
Log.e("Activity", "Failed to get newslist");
}
}
listView.setAdapter(new NewsAdapter(getApplicationContext(), newsList));
}
@Override
protected void onSaveInstanceState(Bundle savedInstanceState) {
savedInstanceState.putSerializable("list", newsList);
super.onSaveInstanceState(savedInstanceState);
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
newsList = (ArrayList<HashMap<String, String>>)
savedInstanceState.getSerializable("list");
}

ZF2 redirect on public dir

ZF2 redirect on public dir

Hello i dont know what is the best way to redirect all on publuic. Am
doing on server,no on local. On local i can make VHost and editd host file
but when i put with ftp on server www.example.com i cant make vhost.
How now can do redirection on public ?
On www.example.com he list me directory structire :
config/
data/
init_autoloader.php
module/
public/
vendor/
I realy dont know apache .htaccess any example how to do that redirection.
Thanks.

find max important neighbours

find max important neighbours

We have a rectangle with n rows and m columns filled with numbers from 1
to n*m. Cell (i,j) of the rectangle is important iff: * i = 1 and j = 1
(or) *there is an important cell (a,b) such that (a,b) is a neighbor of
(i,j) and the number on (i,j) is greater than number on cell (a,b) and all
of (a,b)'s neighbors except for ( (i,j) itself
Two cells are considered to be neighbors if they share a common edge
between them. Unfortunately the number in some of the cells has been
erased. We want to write a number to those cells such that the resultant
rectangle has all the numbers between 1 to n*m and it contains as many
important cells as possible. In case there are several ways to do that, we
are interested with the rectangle which is lexicographically smallest. A
table is lexicographically smaller that the other if the string of its
row-major view is lexicographically smaller than the other. Input: The
first line of the input contains two integers n and m, Each of the next n
lines contains m tokens. Each token is either an integer between 1 and n*m
or '?'. Output: Print the maximum number of important cells that can be
obtained in the first line of the output and print the rectangle in the
next n lines.
Constraints: 1 <=n,m <=6
Sample input #00: 2 3 2 ? ? ? ? 3
Sample output #00: 3 2 1 4 5 6 3
Sample input #01: 6 6 ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?
? ? ? ? ? ? ? ? ? ?
Sample output #02: 24 1 2 3 13 14 15 4 6 8 10 11 16 5 7 9 12 19 17 28 26
24 22 20 18 29 27 25 23 21 36 30 31 32 33 34 35

Microsoft Player Framework not playing local files

Microsoft Player Framework not playing local files

I am developing a windows 8 app in winjs and one of its features is to be
able to play local video files. So far I am using:
Windows.System.Launcher.launchFileAsync
Which works fine but obviously suspends the app and opens the video with
their default video program. I would rather keep the user in the app so I
tried to implement it using the Microsoft Player
Framework(http://playerframework.codeplex.com/). I know the framework is
referenced correctly etc because it can play video files both in the 'app
data' directory and online.
However when I try to play files within a folder that the user has picked
(with the folder picker) or the videos library that the app has declared
access to, the video fails to play. The app can however change the name,
create new files in the directory and delete files so I struggle to see a
permissions problem.
To get the path of the file I am using getFileAsync( and using the path
property and simply using that to set the src property of the MediaPlayer
control.
Do any windows 8 app gurus have any suggestions as to why it is not working?
Thanks in advance
p.s. let me know if any further info is required

Thursday 22 August 2013

Whether Python suppports audio processing?

Whether Python suppports audio processing?

I am an m.tech student. I would like to do speaker recognition as my
m.tech main project. And i would like to do this project in python. but i
dont know whether python supports audio processing or not. So please help
me.

Ruby: Can I get an instance by its ID?

Ruby: Can I get an instance by its ID?

In Ruby, if I have the ID of an object instance as a string, such as
"#<Meeting:0x4531860>", can I get the instance its self by this ID?
# what I want
meeting = SOME_MAGIC_HERE "#<Meeting:0x4531860>"
# and then I can handle the meeting itself
meeting.name # => 'BLABLABLA'

Adaptive Payments Pay API Error 580001

Adaptive Payments Pay API Error 580001

I'm making a PAY request to the paypal adaptive payments API in python and
getting a generic error id 580001 with no additional information.
headers = {
# API credentials for the API caller business account
'X-PAYPAL-SECURITY-USERID': config.PAYPAL_API_USER_ID,
'X-PAYPAL-SECURITY-PASSWORD': config.PAYPAL_API_PASSWORD,
'X-PAYPAL-SECURITY-SIGNATURE': config.PAYPAL_API_SIGNATURE,
'X-PAYPAL-APPLICATION-ID': 'APP-80W284485P519543T',
'X-PAYPAL-REQUEST-DATA-FORMAT': 'JSON',
'X-PAYPAL-RESPONSE-DATA-FORMAT': 'JSON'
}
payload = {
"actionType": "PAY",
"currencyCode": "USD",
"receiverList": {
"receiver": [{
"amount": "1.00",
"email": "sandbox_test_user_email@gmail.com"
}]
},
# where the sender is redirected
"returnUrl": config.SUCCESS_URL,
"cancelUrl": config.SUCCESS_URL,
"requestEnvelope": {
"errorLanguage":"en_US",
# error detail level
"detailLevel":"ReturnAll"
}
}
import urllib2, urllib
payload = urllib.urlencode(payload)
request =
urllib2.Request(url='https://svcs.sandbox.paypal.com/AdaptivePayments/Pay',
data=payload,
headers=headers)
f = urllib2.urlopen(request)
contents = f.read()
Response:
{"responseEnvelope":
{"timestamp":"2013-08-22T15:44:50.97507:00",
"ack":"Failure",
"correlationId":"df4f39293971f",
"build":"6941298"
},
"error"[ {"errorId":"580001",
"domain":"PLATFORM",
"subdomain":"Application",
"severity":"Error",
"category":"Application",
"message":"Invalid request: {0}"}
]
}
Curling with my credentials works, it's just going through urrllib that's
failing. I read others with the same error code were sending an HTTP GET
by accident, I have confirmed via request.get_method() that this is indeed
POSTing. Any ideas?

Subdomains on the Fly

Subdomains on the Fly

We're a trying to accomplish the following on a Ubuntu Server 13.04
installation.
We host SaaS apps for customers are are currently moving off shared
hosting environments due to limitations with resources and fats growth.
We'd like the best environment to host customer's web apps in a
subdomain'ed environment. For example, customers purchase custom developer
business apps from us. Their domain names could be anything from:
customer1.domain.com powerhouse.domain.com healthcare.domain.com
The domain.com represents our domain. We'd like to set up a single server
to host a few customer apps. We'd like to do with without a plesk/cpanel
environment if possible to save on cost. I have no idea where to start or
to look. We have a LAMP server up (ubuntu as mentioned above) that hosts a
single site perfectly fine. We'd like to host more than one though. We
want a single IP address assigned to the box as well.
If anyone can provide direction or insight on this, that would be great.
Extra Info:
We use HyperV to manage a ubuntu instance.
Requirements:
Single IP per box.
Thanks again.

.htaccess redirect by adding parameter if required

.htaccess redirect by adding parameter if required

I need to add a parameter to my current URL (but only if the paramter
isn't set yet). The other parameters should be kept (I think I can do so
by adding %{QUERY_STRING}?).
Example:
index.php?page=1
So, let's say I want to always add a parameter for the language- the URL
should look like this:
index.php?page=1&lang=1
But if lang is already set, it should do nothing.

Html getting distorted in mobile browser when rotating the device (changing orientation from landscape to portrait and vice versa)

Html getting distorted in mobile browser when rotating the device
(changing orientation from landscape to portrait and vice versa)

I have website www.xyz.com, when I load this url in mobile in portrait
mode it looks nice, it even looks good when I load in landscape mode, but
suppose when I load the page in landscape mode and rotate the mobile to
portrait mode then design gets zoomed out and suppose I loaded the page in
portrait mode and rotated to landscape mode then design gets zoomed in.
Can you please suggest?

Wednesday 21 August 2013

Can we display the second section first???

Can we display the second section first???

Statically I have mentioned the number of sections for the
UICollectionView as 3 as shown in the below:
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView
*)collectionView{
return 3;
}
Now I am trying to display the second section when the application
launches instead of showing the first section.As UICollectionView is a
subclass of UIScrollView. I wrote the code that:
[mCollectionView scrollRectToVisible:CGRectMake(0, 600, 320, 568)
animated:YES];
but it was displaying the first section only.Is there any other way to
display the second section in UICollectionView.

How to select option from Right Click using Sikuli API

How to select option from Right Click using Sikuli API

I am using Sikuli Java API to verify screens in a Eclipse Based
Application. Now I am struck with Performing Right Click on a Task and Do
a Right Mouse Click and select a Option
I have heard about Key Modifiers but how to use it I am not sure.
Kindly suggest your ways

Wordpress Url redirect

Wordpress Url redirect

I have a big problem with a Wordpress project, I just downloaded a
Wordpress project with it's Mysql contents.
I want to run it in my localhost, All sets up, but when i launch the url
in my localhost it goes to another url.
I edited some parameters here :
wp-config.php : 'DOMAIN_CURRENT_SITE'
and from Mysql i edited "siteurl" & "home" from wp_options table. I also
edit RewriteCond %{HTTP_HOST} = from .htaccess
So it doesn't redirect to url but Wordpress not launch. without any
error!! it seems you enter wrong url in your browser.
Do you know where is the problem?

Dropbox or Backup Manager

Dropbox or Backup Manager

I want to give my users the ability to backup/restore their app data
(database) and therefore sync it across multiple devices.
Would you recommend going the cloud storage like DropBox (where they use
their account to backup/restore data on demand)?Or do you recommend using
the backup manager feature of Android?
Thank you

Why do FormsAuthentication.Cookieless and HttpSessionState.CookieMode have different default values?

Why do FormsAuthentication.Cookieless and HttpSessionState.CookieMode have
different default values?

There's FormsAuthentication.Cookieless which is set to UseDeviceProfile by
default and there's HttpSessionState.CookieMode that is set to UseCookies
by default.
Although they control different subsystems they essentially have the same
consequences and it'd be reasonable to expect that they have the same
defaults and so if anyone is uncomfortable with the defaults he just
changes both settings together.
Why do their default values different?

django time does not work correctly

django time does not work correctly

I have a django application and I Setting up Django and my web server with
uWSGI and nginx. I have a function that sets access time for my file, this
is my function:
from shutil import move
from time import mktime
from os import utime
def spool(self, time=None):
if time:
try:
time = mktime(time.timetuple())
utime(path(self.tempdir) / path(self.filename), (time, time))
except (error, AttributeError, OverflowError, ValueError):
raise InvalidTimeError
try:
move(path(self.tempdir) / path(self.filename),
path(self.spool_dir) / path(self.filename))
except IOError:
raise NoSpoolPermissionError
when I run this function with python command the access time is correct:
root@demo:~# stat /var/spool/asterisk/outgoing/tmp_4BmDa.call
File: `/var/spool/asterisk/outgoing/tmp_4BmDa.call'
Size: 56 Blocks: 8 IO Block: 4096 regular file
Device: 801h/2049d Inode: 561550 Links: 1
Access: (0600/-rw-------) Uid: ( 0/ root) Gid: ( 0/ root)
Access: 2013-08-21 11:27:30.000000000 +0430
Modify: 2013-08-21 11:27:30.000000000 +0430
Change: 2013-08-21 11:24:00.142143170 +0430
Birth: -
but when I run the function in my django application the output is:
root@demo:~# stat /var/spool/asterisk/outgoing/tmp_4BmDa.call
File: `/var/spool/asterisk/outgoing/tmp_4BmDa.call'
Size: 242 Blocks: 8 IO Block: 4096 regular file
Device: 801h/2049d Inode: 561542 Links: 1
Access: (0666/-rw-rw-rw-) Uid: ( 0/ root) Gid: ( 0/ root)
Access: 2013-08-21 21:15:00.000000000 +0430
Modify: 2013-08-21 21:15:00.000000000 +0430
Change: 2013-08-21 11:44:42.982093206 +0430
Birth: -
as you can see the access time is <<2013-08-21 21:15:00>> but It must be
<<2013-08-21 11:44:42>> and I have no idea what happend. linux date
command output is:
root@demo:~# date
Wed Aug 21 11:44:55 IRDT 2013
and python datetime output:
>>> datetime.datetime.now()
datetime.datetime(2013, 8, 21, 11, 45, 57, 886360)

Tuesday 20 August 2013

$\liminf E_k \subset \limsup E_k $

$\liminf E_k \subset \limsup E_k $

I am wondering if my proof is correct? Thank you for whoever willing to
take a look at it for me.
Proof $\liminf E_k \subset \limsup E_k $
Consider $x \in \liminf E_k$, then $x \in E_1 \cup E_2 \cup \cdots$, and
$x \in E_2 \cup E_3 \cup \cdots$ and so on, that is to say, $x \in
\bigcap_{m=1}^\infty E_m \cup E_{m+1} \cup \dots$. Since $x \in E_r \cup
E_{r+1} \cup \dots$, we showed $x \in \limsup E_k$.

android TextView setText not working

android TextView setText not working

I know there are a lot of similar threads but I've gone through them and
still can't figure out the problem. My program reaches the Handler but it
always returns the catch exception "Message isn't handled."
I declared the TextView private TextView chatbox;
Under onCreate I have:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
setUpViews();
setUpListener();
}
where setUpViews() snippet looks like:
private void setUpViews() {
chatbox = (TextView) findViewById(R.id.chatbox);
}
Handler:
public Handler mHandler = new Handler(Looper.getMainLooper()){
@Override
public void handleMessage(Message msg){
try{
chatbox.setText("Got it!");
}catch(Exception e){
Log.i("MYLOG", "Message was not handled.");
}
}
};
Snippet in main.xml file:
<TextView
android:id="@+id/chatbox"
android:layout_width="200dp"
android:layout_height="200dp"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:textAppearance="?android:attr/textAppearanceLarge" />

Toggle Video on Click

Toggle Video on Click

I'm trying to get a button when clicked to swap out a video for another
which is autoplaying and looping.
Really cant seam to figure this one out, any help would be great!
Heres my code,
<script>
$('#button').click(
$('#container').toggle(
function() {
$('#container').html("video src="video/1.mp4" type="video/mp4"
preload="preload" autoplay="autoplay" loop="loop"></video>";
}, // end first click
function() {
$('#container').html("<video src="video/2.mp4" type="video/mp4"
preload="preload" autoplay="autoplay" loop="loop"></video>");
} // end second click
); // end toggle
</script>

Importance of giving an initial value to the variables "Local or global " javascript

Importance of giving an initial value to the variables "Local or global "
javascript

I am wondering what is the importance of having an initial value for a
variable in JavaScript.
function data() {
var self = this;
self.formatLength;
}
function data() {
var self = this;
self.formatLength = null;
}
What if you do not give an initial value such as null or whatever value to
that variable then operate on it .
would it make a difference? Since I am new in JavaScript and trying to
keep good habits and I was wondering about it.

Creating a multi-layered matrix-ish Collection in C#

Creating a multi-layered matrix-ish Collection in C#

The setup
I have a List<Room>() which I get back from a service. The list refreshes
every 10 seconds, and rooms get added and removed.
class Room
{
public int ID {get;set;}
}
My job
To display these rooms on the screen, I have a Matrix-like view of
variable size. Sometimes the matrix is 3 x 3 cells, other times it is 4 x
2 or 5 x 1.
I needed a way to "remember" which slot/cell a room has been placed in, so
I thought a DataTable would give me that option.
To store the cells I use a DataTable, which has 3 Columns:
"Column" (int)
"Row" (int)
"Room" (Room)
So If I have a 2 x 4 matrix, it would look like this.
Column | Row | Room
-----------------------------
0 | 0 | rooms[0]
-----------------------------
1 | 0 | rooms[1]
-----------------------------
2 | 0 | rooms[2]
-----------------------------
0 | 1 | rooms[3]
-----------------------------
1 | 2 | rooms[4]
And so forth...
Once I have this DataTable I am then able to refresh the screen, knowing
that each room will be displayed at the position it was before. This can
probably be achieved in a smarter way.
The problem
Now I need to enumerate the List<Room> and fill the matrix/DataTable.
If I have more rooms than cells, then I need to start at position 0,0
again (like adding a new matrix as a layer), until all rooms have been
assigned a cell.
The approach so far
I have tried a few for(...) loops that look like:
int totalTiles = area.TileColumns * area.TileRows;
int totalLayers = (int)Math.Ceiling((double)area.Rooms.Count / totalTiles);
for (int i = 0; i < totalLayers; i++)
{
for (int j = 0; j < area.TileRows; j++)
{
for (int k = 0; k < area.TileColumns; k++)
{
// This is going nowhere :-(
}
}
}
In my brain
When I first came across this problem, I immediately thought: "Nothing a
simple LINQ query won't fix!". And then I bricked ...
What would be the most efficient / best performing approach to fill this
matrix?

Embed node inside node in umbraco

Embed node inside node in umbraco

I'm working on embedding content in rich editor, but not sure where to
start. Iv'e got a bunch of nodes that contains data that i want embedded
in other nodes.
Now what i want, is to make a macro, where i can choose one of these
nodes, and insert some of the data from them, in the rich editor. For
starters it could just be via node ID.
I really haven't worked so much with macro's in umbraco, so i'm kinda
lost, is this easily achieved?
Any pointers, or maybe a simple example?

Gmail chat/hang out - reg

Gmail chat/hang out - reg

Actually for the past 10 days i couldnt open my chat box in my account. I
have not done any changes in the settings. I need some help to resolve
this problem. When I open chat box or hang out it says like "We're having
trouble contacting our servers. We're going to keep trying" but here i
dont have any problem with the server. Hope to hear ur response. Thanks

Monday 19 August 2013

Visual Studio through MSDN: Can they know it is not mine?

Visual Studio through MSDN: Can they know it is not mine?

So, I was arguing with a great friend of mine about Visual Studio 2012 and
Microsoft being able to detect which one you used. According to him if you
get your hands on a direct MSDN download of Visual Studio 2012
Professional, and you end up creating an app, like a game or something,
and then you submit it to the Windows App Store, they will never know
which visual studio version you truly used to develop the App, or if you
were the owner of it or not.
Is he right? Because I thought Visual Studio some how left a footprint
behind on the .exe file letting Microsoft know about licensing
information. Or should I go apologize to him for calling him a f...ing
liar.
If you guys say it does leave a print, can you show some proof, or a link
to read more about it? Thanks guys.

Is $\sum_{k=0}^{\infty}\frac1{2^{k^2}}$ rational? Transcendental?

Is $\sum_{k=0}^{\infty}\frac1{2^{k^2}}$ rational? Transcendental?

Is $\sum_{k=0}^{\infty}\frac1{2^{k^2}}$ rational?
Clearly this series is convergent (compare to geometric series with ratio
1/2). I'm sure it's irrational since a rational number written in base 2
will have either a terminating or repeating decimal representation. But
the hard part is to show this representation in question doesn't repeat.
(cf
https://www.google.com/search?q=periodic+rational+base&ie=utf-8&oe=utf-8&aq=t&rls=org.mozilla:en-US:official&client=firefox-a
)
Can you show this number is transcendental?

Visualize the amount of two factors

Visualize the amount of two factors

In the following example I want to give a overview for all factors in all
levels during the time. To give a overview for one factor I could do this:
times<-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 hour")
key<-factor(sample(LETTERS[1:2],2*length(times),T,prob=c(0.4,0.6)))
ref<-factor(sample(LETTERS[1:2],2*length(times),T,prob=c(0.2,0.8)))
df<-data.frame(times=c(times,times),key=key,ref=ref)
p <- ggplot(df, aes(x=times, y = ..count.., fill = key))
p<-p + geom_bar(binwidth=60*60*24)
p
But if I want to add factor "ref" I have no idea what kind of plot I
should use. That means I want also plot the amount of
df[,"key"]=="A" & df[,"ref"]=="A"
And in my opinion to use a factor like
factor(paste(df$ref,df$key))
is not a solution. What else could you propose?

display the image from database

display the image from database

I have created a program in JSP to fetch the image and display it on web
page. Program is working correctly image is displayed but other contents
are not displaying. Below is the code
<%
byte[] imgData = null ;
Class.forName("com.mysql.jdbc.Driver");
Connection
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/buysell","root","root");
Statement stmt = con.createStatement();
ResultSet resultset =stmt.executeQuery("select * from imagemain where
id=1;") ;
while(resultset.next())
{
Blob bl = resultset.getBlob(2);
byte[] pict = bl.getBytes(1,(int)bl.length());
response.setContentType("image/jpg");
OutputStream o = response.getOutputStream();
%>
<img src="<%o.write(pict);%>" width="10" height="10">
<h1>Vishal</h1>
<%
out.print("1");
o.flush();
o.close();
}
%>
the program is not displaying the <h1>Vishal</h1>. Please assist on this

Sunday 18 August 2013

Connecting to Oracle with encrypted pwd

Connecting to Oracle with encrypted pwd

I am reading my userid , pwd from a file with 400 permissions to connect
to the external oracle application.
Now my requirement is that i should not use the plain text pwd present in
the file . I should use some encrypted pwd to connect. How i can do this ?

.on not firing for dynamic list

.on not firing for dynamic list

I'm having issues with the .on firing on a dynamically generated table. I
have my code setup so it populates a div with a table dynamically when the
page loads. I'm using images as icons and for some reason I can't get the
.on to fire when the user clicks on an icon.
The ajax code I have works fine and fills my div with the required info.
Here is the php file that returns the data that the .on should work with:
(I'm new to jquery and just a hobby programmer! )
Here is the ajax code:
$.ajax({url: "load_agency_list.php",
data: "query=SELECT * FROM manual.agency_list",
type: "POST",
success: function(data){
//when user clicks info display Agency Information
$("#agency_list_window").html(data);
}
});



// start of .php file //
<table id="agency_table" class="inputtable ui-widget-content">
<th class="tbl_title_item"></th><th class="tbl_title_item">Agency Name:
</th><th class="tbl_title_item">V</th><th class="tbl_title_item">E</th>
<th class="tbl_title_item">D</th>
<?php
include("/includes/serv_connect.php");
$query = '';
if(!isset($_POST['query']))
{
echo("Sorry there was a problem loading the agency list.");
exit;
}
else
{
$query = mysql_escape_string($_POST['query']);
}
$getitems = mysql_query($query,$link);
while($eachrow = mysql_fetch_array($getitems, MYSQL_ASSOC))
{
echo("<tr class=\"tbl_item_format\">
<td>{$eachrow["agency_id"]}</td><td style=\"width:
400px\">{$eachrow["agency_name"]}</td>
<td>
<img alt=\"{$eachrow['agency_id']}\" class=\"ui-icon ui-icon-info
agencyitem\" src=\"/img/blank.png\"></td>
<td><img alt=\"{$eachrow['agency_id']}\" src=\"/img/blank.png\"
title=\"Edit Agency Information\"
class=\"ui-icon ui-icon-wrench editagencyitem\"></td>
<td><img alt=\"{$eachrow['agency_id']}\" src=\"/img/blank.png\"
class=\"delagency ui-icon ui-icon-trash\"></td></tr>");
}
?>
</table>
//end php file.
Now the code in the main file that is suppose to fire when click on the
info icon image.
$('#agency_table').on('click','.agencyitem',function() {
...some stuff here
});
Now I have tried narrowing down my selectors like $("#agency_table tr td
.agencyitem)... etc etc, but nothing.
I've tried various solutions with no success. Any help would be appreciated.
Thanks!

How does Facebook Like button code work, and how can I do something similar?

How does Facebook Like button code work, and how can I do something similar?

I've got a web page that has 250 different items on it, each with its own
Like button using the standard Facebook "Like" code:
div class="fb-like" data-href="http://www.mywebpage.com/myproductpage"
data-send="false" data-layout="button_count" data-width="80"
data-show-faces="false" etc.
This page works fine in all browsers on all computer platforms, as well as
on Android devices. Unfortunately, all the separate Facebook Like buttons
seem to create a memory issue for iPads and iPhones, and Safari crashes on
our page on these devices.
The div class="fb-like" etc. part of each like button is not something I
can easily change on our thousands of pages to make iPads happy, but I can
easily remove the standard Facebook code that appears at the top of those
pages which makes the Like buttons work. What I'd like to do is replace
the Facebook code at the top of each of our pages with my own HTML that
grabs the data in each of these "Like buttons" and generates my own
buttons that function a bit differently. (Perhaps they each will link to a
separate page that will then be a sharing page when the pages is loaded on
an iOS device.) Only issue is I don't quite grasp the HTML/CSS/Javascript
required to cause each of these items with class="fb-like" to trigger
something to generate content within them. I imagine this is what the
Facebook code linked to at the top of a page with Like buttons does.
Can someone briefly explain to me how to access the data in a
class="fb-like" part of my page, and put my own item there? I can then
dynamically do something different on iPads/iPhones so they don't crash,
perhaps by just turning the like buttons into sharing page links.
I can write my own Javascript/HTML code for that just fine, but only after
I have some understanding of how to access the data values in each
"fb-like" DIV and how to cause my generated code to trigger to appear on
that page in each of those 250 places.
Any examples of accessing the data within a class="fb-like" part of my
page and then generating something in them would be appreciated. Even the
very simplest of examples should be enough for me to understand how to
program whatever I need from there. Can someone just help get me started?

How can I stream to Airplay and Bluetooth simultaneously?

How can I stream to Airplay and Bluetooth simultaneously?

I have an iMac with airport express and I also have a logitech bluetooth
speaker adapter.
Seemingly I cannot play through both at the same time.
I have even tried going to the MIDI settings and creating an 'aggregate'
audio device but it just flips back after a few seconds of it being
selected (to a working method)

what does the word boundary's functionality in perl

what does the word boundary's functionality in perl

$string = "Aa Aa 122";
/\b[A-Z][a-z]*\b/
\b \b => does it search for duplicates of Aa Aa or it searches for that is
not in [] ?
and what does the followin regex do,
/(.).*\1/

Why the non-root user can't login with a key in putty?

Why the non-root user can't login with a key in putty?

I read an article and found it very useful:
http://www.howtoforge.com/ssh_key_based_logins_putty
I made two key pairs for root and the other user. But it only works for root
When it comes to the other one, the server shows:
Using username "theotheruser".
Server refused our key
theotheruser@mydomain.com's password:

Saturday 17 August 2013

public void itemStateChange(ItemEvent objEvent){

public void itemStateChange(ItemEvent objEvent){

C:\sample java>javac checkbox1.java
checkbox1.java:4: checkbox1 is not abstract and does not override abstract
method itemStateChanged(java.awt.event.ItemEvent) in
java.awt.event.ItemListener
public class checkbox1 extends Applet implements ItemListener{
^
1 error

Intuiting Product of Elimination Matrices (and NOT by Matrix Multiplication)

Intuiting Product of Elimination Matrices (and NOT by Matrix Multiplication)

I want to intuit, and NOT compute with matrix multiplication,
$M:=\color{green}{E_{P_3 \rightarrow P_4}}\color{#CA790F}{E_{P_2
\rightarrow P_3}}E_{P_1 \rightarrow P_2},$ where:
$E_{P_1 \rightarrow P_2} = \begin{bmatrix} 1 & 0 & 0 & 0 \\ -1 & 1 & 0 & 0
\\ 0 & -1 & 1 & 0 \\ 0 & 0 & -1 & 1 \\ \end{bmatrix},
\color{#CA790F}{E_{P_2 \rightarrow P_3} = \begin{bmatrix} 1 & 0 & 0 & 0 \\
0 & 1 & 0 & 0 \\ 0 & -1 & 1 & 0 \\ 0 & 0 & -1 & 1 \\ \end{bmatrix}},
\color{green}{E_{P_3 \rightarrow P_4} = \begin{bmatrix} 1 & 0 & 0 & 0 \\ 0
& 1 & 0 & 0 \\ 0 & 0 & 1 & 0 \\ 0 & 0 & -1 & 1 \\ \end{bmatrix}} $.
$\fbox{1st row :}$ None of these elimination matrices affect the first row.
So the first row of $M = (1, 0, 0,0)$.
$\fbox{2nd row :}$ By $E_{P_1 \rightarrow P_2}$, $-R_1 + R_2 \rightarrow
R_2$. So the 2nd row of $M = (-1, 1, 0,0)$
$\fbox{3rd row :}$ By $E_{P_1 \rightarrow P_2}, -R_2 + R_3 \rightarrow
R_3^{*}.$
By $\color{#CA790F}{E_{P_2 \rightarrow P_3}}$, $-R_2 + R_3^* \rightarrow
R_3^{**}$.
So the 3rd row of $M = (0, -1\color{#CA790F}{-1}, 1,0)$.
Here, the third column is $1$ and NOT $2$ because $R_3$ is not being added
to itself twice. It only needs to appear once.
$\fbox{4th row :}$ By $E_{P_1 \rightarrow P_2}$, $-R_3 + R_4 \rightarrow
R_4^*$.
By $\color{#CA790F}{E_{P_2 \rightarrow P_3}}$, $-R_3 + R_4^* \rightarrow
R_4^{**}$.
By $\color{green}{E_{P_3 \rightarrow P_4}}$, $-R_3 + R_4^{**} \rightarrow
R_4^{***}$.
So the 4th row of $M = (0, 0, -1\color{#CA790F}{-1}\color{green}{-1},1)$.
Here, the 4th column is $1$ and NOT $3$ because $R_4$ is not being added
to itself thrice. It is $-R_3$ which is added (to $R_4$) thrice.
Altogether, my $M = \begin{bmatrix} 1 & 0 & 0 & 0 \\ -1 & 1 & 0 & 0 \\ 0 &
-2 & \color{#668FE2}{1} & 0 \\ 0 & 0 & -3 & \color{#668FE2}{1} \\
\end{bmatrix}.$ However, the correct $M = \begin{bmatrix} 1 & 0 & 0 & 0 \\
-1 & 1 & 0 & 0 \\ \color{red}{1} & -2 & \color{#668FE2}{1} & 0 \\
\color{red}{-1} & \color{red}{3} & -3 & \color{#668FE2}{1} \\
\end{bmatrix}.$
How and why did I miss the three red entries?
Also, is there a better explanation why the $\color{#668FE2}{1}$s are not
$2$ in the 3rd row and $3$ in the 4th row?

How to install SimpleCV on OSX 10.8

How to install SimpleCV on OSX 10.8

I believe SimpleCV has installed correctly. When I run:
sudo pip install SimpleCV
And then in python try to import the library, I run into this error:
ImportError: No module named pygame
Is pygame required to run SimpleCV? I wouldnt have thought so, so then I
try to use pip to install pygame and I get another error, saying I have a
bad link or something:
TTP error 400 while getting
http://www.pygame.org/../../ftp/pygame-1.6.2.tar.bz2
(from http://www.pygame.org/download.shtml)
Could not install requirement pygame because of error HTTP Error
400: Bad Request
What am I missing? How should I try to install SimpleCV and pygame? Or do
I even need pygame to run SimpleCV in python?

WordPress More Tag Not Displaying content

WordPress More Tag Not Displaying content

I have been using the WordPress More tag on a custom page template. The
content before the more tag will display fine but when i click the read
more link the page re-loads but no content after the tag is displayed.
Here is the custom page code for i was told would fix the issue of the tag
not displaying but now i am getting the new issue i just described. The
previous issue i had was that the more tag would not display so i added
the code below which now displays it but the content after the tag will
not display no matter that i do
<?php global $more; $more = 0; ?>
<?php the_content('Continue Reading'); ?>

How can I change this form into li? PHP

How can I change this form into li? PHP

Hey it looks like I had most the code correct just that it was not
working. I got some suggestions and we did beautify if not dotted a $theme
but the code does not work. I want to convert this form into a li but I am
having some issues, here is the original form:
<?php
$theme1 = business;
$theme2 = modern;
$theme3 = web2;
if(isset($_POST['style']))
{setcookie('style', $_POST['style'], time()+(60*60*24*1000));
$style=$_POST['style'];}
elseif(isset($_COOKIE['style']))
{$style=$_COOKIE['style'];}
else
{$style=$theme1;} ?>
<link href="<?PHP echo $style; ?>.css" rel="stylesheet" type="text/css" />
<select name="style">
<option type="submit" <?php echo "value='$theme1'";if($style ==
$theme1){echo "selected='selected'";}?>><?php echo $theme1; ?></option>
<option type="submit" <?php echo "value='$theme2'";if($style ==
$theme2){echo "selected='selected'";}?>><?php echo $theme2; ?></option>
<option type="submit" <?php echo "value='$theme3'";if($style ==
$theme3){echo "selected='selected'";}?>><?php echo $theme3; ?></option>
</select>
<input type="submit">
</form>
I want to transform this form into a li form where there are not select,
option, or input in the form. I got some of the code but the form is not
changing my value. It looks like I might be missing the if($style..) and
the name"style" somewhere on my li form. Here is my code:
<form action='".$_SERVER['PHP_SELF']."' method='post' id='myForm'>
<li name='style' onclick='myForm.submit();' value='".$theme1."'";
;if($style == $theme1){echo "selected='selected'";};
echo">".$theme1."</li>
</form>
I think I am messing up on the if($style..) and the
name='name'....somewhat I do not think they are being inputted right. How
would I be able to correct the li form to make it functional?

Execute link then redirect again

Execute link then redirect again

i've got a mybb board where I provide a certain link, looking like this
<a href="/member.php?action=login&do=switch">Klick</a>
The link changes the session and reloads the page, so I need it executed
for the change in the session. However afterwards I would like to redirect
the user to another page like "/private.php"
I've already tried different versions of combining href and onclick but it
always takes me to the page stated in href, ignoring the onclick bit. So
my code looks somewhat like this:
<a href='/member.php?action=login&amp;do=switch&amp;uid={$others['uid']}'
onclick='window.location.href({$mybb->settings['bburl']}/private.php);'>Link</a>";
I must say I'm pretty much a noob when it comes to javascript so I would
need some help on that. I would like to solve this problem with javascript
or php, so no meta tags, please ;)
Any help and tips would be appreciated! Thank you in advance!
Senya

Android listView ArrayList similar Search

Android listView ArrayList similar Search

I use ArrayList for my Dictionary Index Data
I want to make similar search system
for example)
dictionary data : 'abcd' 'bcde' 'cdef' 'fghi' 'ijkl'
if i search 'cd' i want to get index '3'
in my source
for (String st : wordList) {
if (st.indexOf(searchWord) == 0) {
ListView.setSelection(index); //set listView scroll
break;
}
index++;
}
but it took too many time :(
what is the best way to make this system?

Friday 16 August 2013

It is about random choice in python

It is about random choice in python

I was trying to create the Buffoon's Needle experiment through a
simplistic way of using randomness as a replacement of probability. The
value of pi can be found from the equation pi = 2*ln/th where l= length of
needle, n = number of times the needle is dropped, t = breadth of lines, h
= number of times needle crosses a line. I have assumed l = t thereby
reducing my equation to pi = 2*n/h. Now I have made two codes. Code 1:
import math, random
h = 0.0
n = 0.0
for i in range(0,10000):
a = random.random()
if a > 0.64:
h = h+1
else:
n = n+1
re = 2*(n+h)/n
print "Value of pi is ", re
err = (math.pi - re)*100/(math.pi)
print "Percentage error is ", abs(err)
Now this one is running fine and giving me good enough results. But the
following code is repeating the same answer over and over again. Code 2:
import random, time, math
h=1.0
n=1.0
err = 0.0
while err < 0.1:
a = random.random()
if a > 0.64:
h = h+1
else:
n = n+1
re = 2*(n+h)/n
err = (math.pi - re)*100/(math.pi)
print "Number of attempts is ", n+h
Can someone tell me why??

Saturday 10 August 2013

Create a file with another languajes characters in php

Create a file with another languajes characters in php

i'm trying to create a file with name
"&#1044;&#1080;&#1089;&#1082;&#1086;&#1075;&#1088;&#1072;&#1092;&#1080;&#1103;"
but in the folder appears with the name Ð"иÑкографиÑ.
The php file is in UTF-8.
i have this:
<?php
$nombre =
"&#1044;&#1080;&#1089;&#1082;&#1086;&#1075;&#1088;&#1072;&#1092;&#1080;&#1103;";
$fp = fopen("C:/$nombre", 'w+');
fclose($fp);
?>

mouse functions api for windows

mouse functions api for windows

im working on a proggram that i wanto set the position of my joints in
kinect to mouse cursor. i dont know the api that work with mouse and its
functions and which namespace i have to add. for example some function to
set the position to mouse pointer and some function for right click and
left click and double click. for example i want "if my hand joint is upper
my left joint mouse be clicked. i can work with kinect sdk but i dint know
about win api about it.
thanks for helping .

implementation of tab bar programmatically not in the rootView

implementation of tab bar programmatically not in the rootView

I asked the same question before for the some but now i changed the way to
implement my tab bar i have this view

i want when i push a button it will make a tab bar composed in 5 buttons
the some that i can choose it in the first view
- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen]
bounds]] autorelease];
// Override point for customization after application launch.
AcceuilViewController *viewController =[[[AcceuilViewController alloc]
initWithNibName:@"AcceuilViewController"
bundle:nil]autorelease];
self.navController = [[[UINavigationController
alloc]initWithRootViewController:viewController]
autorelease];
self.window.rootViewController = self.navController;
[self.window makeKeyAndVisible];
return YES;
}

Python printing special Characters

Python printing special Characters

In Python how would I print special characters such as ¡î, ¡Ä, ©÷,©ø, ¡Â,
¡Ã, ¡¾, ¡Á
When I try printing them to the console I the get this error:
print("¡î")
SyntaxError: Non-ASCII character '\xe2' in file
/Users/williamfiset/Desktop/MathAid - Python/test.py on line 4, but no
encoding declared; see http://www.python.org/peps/pep-0263.html for
details
How do I get around this?

Updating a string from a text box in C#

Updating a string from a text box in C#

In the program I'm making, I made a string in Settings, called "Tickers".
The scope is Application, and the value is "AAPL,PEP,GILD" without the
quotes.
I have a RichTextBox, called InputTickers where a user should put in stock
tickers, such as AAPL, SPLS, and more. You get the point. When they click
the button below the InputTickers, I need it to get
Settings.Default["Tickers"]. Next, I need it to check is any of the
tickers they typed in, are already in the Tickers list. If not, I need
them added in.
After adding them in, I need to turn it back into the Tickers string to
store in the Settings again.
I'm still learning coding, so this is my best guess, for how far I have
gotten on this. I can't quite think of how to get this done correctly,
though.
private void ScanSubmit_Click(object sender, EventArgs e)
{
// Declare and initialize variables
List<string> tickerList = new List<string>();
try
{
// Get the string from the Settings
string tickersProperty = Settings.Default["Tickers"].ToString();
// Split the string and load it into a list of strings
tickerList.AddRange(tickersProperty.Split(','));
// Loop through the list and do something to each ticker
foreach (string ticker in tickerList)
{
if (ticker !== InputTickers.Text)
{
tickerList.Add(InputTickers.Text);
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}