Monday, 30 September 2013

warning: /service/railo-jetty: unable to open supervice/ok: file does not exist

warning: /service/railo-jetty: unable to open supervice/ok: file does not
exist

I'm trying to start railo-jetty using supervisor and I'm getting an error:
warning: /service/railo-jetty: unable to open supervice/ok: file does not
exist
What could be the issue?

Wifi not appearing on my list

Wifi not appearing on my list

So here's my problem: I have an ASUS RT-G32 Wifi Router that I am using
for my connection and when I'm at home I can connect from Ubuntu,Windows 8
& My CyanogenMod 10.1.3 Galaxy S4....when I'm at college(I am on the same
provider,made contract with them,I live on a rent) My windows 8 sees the
WiFi and connects to it,My android sees the connection but doesn't connect
to it and Ubuntu doesn't even see it.A week ago i tested this with another
router Asus RT-N10E and the problem was the same(then i thought it was
from the router) but now I'm running out of ideeas.
Help Please???

Slick opening a session

Slick opening a session

New to slick. I downloaded the slick_2.10-2.0.0-M2.jar linked it in
eclipse with scala library 2.10.2
I would like to have access to an SQLite db. Following instructions from
http://slick.typesafe.com/doc/1.0.1/gettingstarted.html , I get the
SQLiteDriver.simple._ OK but impossible to import
Database.threadLocalSession
Where do I find it?
I do have a Database.dynamicSession: Is this the same?
best G

How to write an SQL query to get records based on the order they were entered in?(no date col) [on hold]

How to write an SQL query to get records based on the order they were
entered in?(no date col) [on hold]

I need to write a SQL query that returns records in the order in which
they were entered in.
No. I can't add a column to the table or change the table in any way. I
can insert into and select from the table.
Say I execute three insert queries like insert into x values(a,1); insert
into x values(d,4); insert into x values(u,42);
when I select from the table x I need to get the records in this order. a
1 d 4 u 42

Sunday, 29 September 2013

using elements of one ruby array as indices to another

using elements of one ruby array as indices to another

Still struggling with my first ruby program. In the following code, I am
trying to get the index from each time a certain letter, 'guess', appears
in array 'secret_word' and then using those indices to insert the same
letter into another array, 'user_word', without disturbing any of the
other letters that might already be in user_word. I decided to store the
indices selected from 'secret_word' in an array, 'indices'. The error
message implies that each element of indices is an array, not a fixnum as
expected. Bottom line, it will not let me use the element from indices to
index into user_word. Help?
if secret_word.include?(guess) #secret_word is an array of chars. guess is
a char.
indices = Array.new
indices<< secret_word.each_index.select{ |letter| secret_word[letter] ==
guess } #verified that this array fills correctly
indices.each do |e|
user_word[e] = guess
end
end
I have tried variations on the innermost block but to no avail

How do I access my query when using Haystack/Elasticsearch?

How do I access my query when using Haystack/Elasticsearch?

I originally followed this tutorial
(https://django-haystack.readthedocs.org/en/latest/tutorial.html), and
have so far been able to highlight my query within my returned results.
However, I want to highlight this same query when visiting the next page
that I load with a separate template. Is there any way to save/access this
query so that I can highlight the same results within this other template?
Whenever I try and include a statement like this, I get an error, which
I'm thinking is because I'm not trying to access the query properly.
{% highlight section.body with query html_tag "span" css_class
"highlighted" %}

crop an image responsively keeping the center of the image visible (horizonally)

crop an image responsively keeping the center of the image visible
(horizonally)

Here is the website I need help with: www.aaronrhoades.com/blog The header
image grows when it's on a bigger browser (e.g. on a TV screen) and
shrinks when it's on a smaller browser. BUT, it stops shrinking at a
certain point because I don't want it to get too small.
The problem: once the image stops shrinking then it stays glued in one
spot horizontally based on the left side of the image. I want it to move
left so that the logo stays visible. Something like a "margin-left:-50%;"
would work for mobile, but obviously that messes it up on a full screen.
CSS only would be great if possible, otherwise I am ok with jquery. PHP
might be good since this is a wordpress, I'm just not too familiar with
it. Here is my code:
#nicelogo img{
width: 100%;
min-width: 683px;
min-height: 250px;
text-align:center;
margin-left:auto;
margin-right:auto;
}
and the html:
<div id="header">
<div id="nicelogo">
<img src="http://www.aaronrhoades.com/images/web-header-home.jpg"
width="1366" height="500">
</div>!-- end of #nicelogo -->
</div>!-- end of #header -->

How do i select multiple values from Multiple select box(as in image) using selenium webdriver?

How do i select multiple values from Multiple select box(as in image)
using selenium webdriver?

the multiple select box in which we have to hold the control key and click
on the values to select it. how to perform this action using selenium web
driver? Thanks in advance

Saturday, 28 September 2013

SVN+SSH On Ubuntu: Locking down security - Passwords

SVN+SSH On Ubuntu: Locking down security - Passwords

Good day,
I have setup a server running Ubuntu 12.04 LTS. I have left the default
SSH port as-is for now, and have set up a DynDNS.org account.
From a machine, running linux, on a separate network, I am able to query
my server via SVN+SSH:
svn --username myName ls
svn+ssh://myName@superdude.dyndns.org/usr/local/svn/repos/private
So far so good: I am queried for the user's password, and an SSH
private/public key pair appears to be generated. However, I am concerned.
I thought the point of private/public keys was that I'd have to provide
the client with the appropriate key in advance. I want to lock down this
server so that the people connecting to my SVN server have both a keyfile
I gave them in advance, and the password for user "myName". Is there
something I'm missing? At this point, all someone appears to need is the
URL to my SVN server, and the password for user "myName", and they are in.
How can I lock this down tighter?
Thank you!

javascript/DOM event name convention

javascript/DOM event name convention

Hi when I started doing web development, I realized javascript event names
were all in lower case with no separators, i.e. "mousedown", "mouseup",
etc. And when working with the jQuery UI library, I noticed they also use
the same convention; i.e. "dropdeactivate" as in the following example
javascript $( ".selector" ).on( "dropdeactivate", function( event, ui ) {} )
While this works well for names that are only 2 or 3 words, it is really
awful for names with more words on it.
Despite of this I followed that convention too when I have to fire custom
(synthetic) events that I created, until recently when I decided it was
better to start using some form of separator. Now I use something like
"drop:deactivate", or "app:ready".
on iOS apple recently added this event for the HTML 5 Airplay API, and I
agree with the autor of this post
http://www.mobilexweb.com/blog/safari-ios7-html5-problems-apis-review when
he says:
I think "webkitcurrentplaybacktargetiswirelesschanged" has won the record:
the longest JavaScript event name ever.
What is the reason behind this weird convention? why not use any form of
separator or camelCase convention to name the events in a more readable
way?
I think there is a reason for that, lot of clever people worked on this...
But after a while I'm still wondering why?

Project Euler 22, off by 18,609

Project Euler 22, off by 18,609

I'm working on problem 22 of Project Euler:
Using names.txt (right click and 'Save Link/Target As...'), a 46K text
file containing over five-thousand first names, begin by sorting it into
alphabetical order. Then working out the alphabetical value for each name,
multiply this value by its alphabetical position in the list to obtain a
name score.
For example, when the list is sorted into alphabetical order, COLIN, which
is worth 3 + 15 + 12 + 9 + 14 = 53, is the 938th name in the list. So,
COLIN would obtain a score of 938 × 53 = 49714.
What is the total of all the name scores in the file?
My code (below) getst the answer 871179673. The correct answer should be
87119828, which makes me off by about 18k.
def score(name, pos):
score = 0
for letter in name:
if letter == "A": score += 1
elif letter == "B": score += 2
elif letter == "C": score += 3
elif letter == "D": score += 4
elif letter == "E": score += 5
elif letter == "F": score += 6
elif letter == "G": score += 7
elif letter == "H": score += 8
elif letter == "I": score += 9
elif letter == "J": score += 10
elif letter == "K": score += 11
elif letter == "L": score += 12
elif letter == "M": score += 13
elif letter == "N": score += 14
elif letter == "O": score += 15
elif letter == "P": score += 16
elif letter == "Q": score += 17
elif letter == "R": score += 18
elif letter == "S": score += 19
elif letter == "T": score += 20
elif letter == "U": score += 21
elif letter == "V": score += 22
elif letter == "W": score += 23
elif letter == "X": score += 24
elif letter == "Y": score += 25
elif letter == "Z": score += 26
else: score += 0
# end for loop.
return score * pos

Using %string% instead of {{string}} in a RegEx

Using %string% instead of {{string}} in a RegEx

To translate some strings in my HTML, I'm using the following function
which is working totally fine to replace every string coming in double
curly braces:
var translation = html.replace(/\{[^\}]*\}/g, function(match){
// where the magic happens
});
How can I change the RegEx to match the pattern %string% instead of
{{string}}?

Friday, 27 September 2013

Can't change permissions for header.php

Can't change permissions for header.php

Here is my official WordPress forum support plea:
http://wordpress.org/support/topic/headerphp-is-not-updating?replies=4
I changed all the permissions via FTP, currently set to 777. Originally
666, but that didn't work, so here we are.
I cleared all of my browser caches.
I added:
define('DISABLE_CACHE', true);
to wp-config.php
I don't know what else to do at this point. The file on my server reflects
the changes I made, but if you look at the source on the website, via
Firebug or whatever, it isn't there.
From the native WordPress editor, it says I can't edit the file because
the permissions aren't set. What's really absurd is that this is a custom
theme specifically for this website. Whose business is it if I want to
change it?
Can anyone please at least verify that the correct 'header.php' is in
wp-content/themes/themeofchoice?
I greatly appreciate any assistance.

How to execute NFC commands without removing the tag from the HF field between commands in Android?

How to execute NFC commands without removing the tag from the HF field
between commands in Android?

I am trying to execute NFC commands without removing the tag from the HF
field between commands. In other words, once the user places the Android
phone or tablet in the vicinity of the tag, the user should be able to use
one command after another without first removing the phone or tablet
before the next command.

html center text to image

html center text to image

This is the code I did:
<div>
<p>
<span class="pic"
style="background-image:url(resources/{image})"></span>
<span class="name"> bla</span>
</p>
</div>
how can I make the text to be in the center and the picture only at the
left? I tried text-align:center and it didn't work

Python: extract substitution vars from format string

Python: extract substitution vars from format string

I have to 'parse' a format string in order to extract the variables.
E.g.
>>> s = "%(code)s - %(description)s"
>>> get_vars(s)
'code', 'description'
I managed to do that by using regular expressions:
re.findall(r"%\((\w+)\)", s)
but I wonder whether there are built-in solutions (actually Python do
parse the string in order to evaluate it!).

Thursday, 26 September 2013

External CSS - How do I write/apply tags in HTML page (beginner)

External CSS - How do I write/apply tags in HTML page (beginner)

My External CSS and template was created by a friend fluent in CSS. But my
friend isn't understanding that I don't know HOW to 'apply' (write) the
tags in the HTML page to 'call' the CSS.
I know the difference between id (#whatever) and class (.whatever) But I
don't know if a CSS entry like
.header caption (with styles listed) translates then to 'p class="header
caption" with opening/closing tags ???
What I'm looking for, but not finding on the web, is a listing of how the
most common tags are written as css. For example, I know
p class="left" applies the CSS to align left, instead of HTML tag
align="left" But How do I write the actual tag for .table .td .tr
Is there a website to show: "This is the tag in HTML, no External CSS"
"This is the way to write the same tag for External CSS"
Second question... Other than for the 'p class' or easy tags, do I start
every tag with: class="" ? p class="" ? div class="" ?
When do I use SPAN vs DIV ?
I have searched for how to apply External CSS, for what tags to use--yes,
I understand that every person might use different naming for divs and
classes-- but I really need examples that will show the basic tags so I
can plug in the 'different naming' from my
'external css'
Is there one website that shows (all on one page) examples of the tags? A
website tutorial that doesn't assume novices already know how to write the
tags to apply css?
Thanks Lifes

Thursday, 19 September 2013

Rumors of performance PHP

Rumors of performance PHP

Once, I heard in a lecture that use ?> to close PHP files were causing the
performance fall, is this true?
It's funny that many php applications, and frameworks really do not close
the files with ?>. Could be due boilerplate or performance?
The spaces in the code, influences the application performance?

How can I get a view by id from a layout in Android?

How can I get a view by id from a layout in Android?

This is the only way I can find but it seems hacky:
public View getViewByIdFromLayout(int id) {
for (int i = 0; i < layout.getChildCount(); i++) {
View v = layout.getChildAt(i);
if (v.getId() == id)
return v;
}
return null;
}
Is there a better way to do this? These views were created
programmatically, not via xml, and the views' ids will be unique in a
given layout but may be reused in other layouts.

Java script - Google Maps API info window for multiple markers

Java script - Google Maps API info window for multiple markers

I have the following code:
jQuery(document).ready(function(){
var map;
var initialized = false;
// Lets use self instead of this.
var self = this;
// Lets only load the map if were on this tab.
// Also only intialize the map ONCE.
$('#siteDetail').find('.ui-tabs-nav li').each(function() {
if($(this).find('a').text() === 'Map') {
if($(this).hasClass('ui-state-active')) {
initialize();
initialized = true;
} else {
$(this).click(function() {
if(!initialized) {
self.initialize(self.collectSitesGPS(),
self.collectSingleSiteGPS());
initialized = true;
}
});
}
}
});
// Google Maps API vs3
self.initialize = function(locations, singleLocation){
console.log(singleLocation);
var pinColor = "97CBE6";
var pinImage = new
google.maps.MarkerImage("http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|"
+ pinColor,
new google.maps.Size(21, 34),
new google.maps.Point(0,0),
new google.maps.Point(10, 34));
var pinShadow = new
google.maps.MarkerImage("http://chart.apis.google.com/chart?chst=d_map_pin_shadow",
new google.maps.Size(40, 37),
new google.maps.Point(0, 0),
new google.maps.Point(12, 35));
var singleLocationObject = singleLocation[0];
var mapOptions = {
zoom: 13,
center: new google.maps.LatLng(singleLocationObject['lat'],
singleLocationObject['long']),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
for(i = 0; i < locations.length; i++){
marker = new google.maps.Marker({
position : new google.maps.LatLng(locations[i]['lat'],
locations[i]['long']),
map: map
});
}
currentLocation = new google.maps.Marker({
position: new google.maps.LatLng(singleLocationObject['lat'],
singleLocationObject['long']),
map: map,
icon: pinImage,
shadow: pinShadow
});
google.maps.event.trigger(map, "resize");
}
self.collectSitesGPS = function(){
var parsedObject;
CT.postSynch('site/detail/grabAllSites', {}, function(data){
parsedObject = JSON.parse(data);
});
return parsedObject;
}
self.collectSingleSiteGPS = function(){
var siteId =
$('#mainContent').find('#siteWrapper').find('#sitePreview').attr('siteid');
var parsedObject;
CT.postSynch('site/detail/grabSingleSite', {id : siteId},
function(data){
parsedObject = JSON.parse(data);
});
return parsedObject;
}
// Load the map.
google.maps.event.addDomListener(window, 'load', self.initialize);
});
This code has two functions inside, collectSitesGPS which returns and
creates about 800+ markers. Each of those need an info window when clicked
... each of those info windows will be unique...
Any ideas how to do something like this?

Using devenv.exe from the command line and specifying the platform

Using devenv.exe from the command line and specifying the platform

I'm attempting to compile a visual studio solution using devenv.exe from
the command line. I can get it to work but all the projects in the
solution are compiled for AnyCPU and I want them to be compiled for x86.
Both the debug and release configurations are set to x86 for all projects.
When I compile from within the IDE it works fine. But when I try to build
the solution from the command line it always builds all projects for
AnyCPU. Is there a way to devenv.exe to build in x86 only?
We are using Visual Studio 2012

Style to the table without ID & class

Style to the table without ID & class

I have several tables in a Web page The tables not have id and class How
can I give style to any table? i want without giving id & class, Giving
Style
Thnx

Passing result variable to nested SELECT statement in Sqlite

Passing result variable to nested SELECT statement in Sqlite

I have the following query which works:
SELECT
SoftwareList,
Count (SoftwareList) as Count
FROM [assigned]
GROUP BY SoftwareList
This returns the following result set:
*SoftwareList* | *Count*
-----------------------------------
Office XP, Adobe Reader | 3
Adobe Reader, Dreamweaver | 3
Dreamewaver | 2
I can also run the following query:
SELECT
GROUP_CONCAT(LastSeen) as LastSeen
FROM [assigned]
WHERE SoftwareList = 'Dreamweaver';
Which would return the following result set:
*LastSeen*
----------
2007-9-23,2012-3-12
I wish to combine both of these queries into one, so that the following
results are returned:
*SoftwareList* | *Count* | *LastSeen*
-------------------------------------------------------------------
Office XP, Adobe Reader | 3 | 2001-2-12,2008-3-19,2002-2-17
Adobe Reader, Dreamweaver | 3 | 2008-2-12,2009-3-20,2007-3-16
Dreamewaver | 2 | 2007-9-23,2012-3-12
I am trying this but don't know how to refer to the initial SoftwareList
variable within the nested statement:
SELECT
SoftwareList,
Count (SoftwareList) as Count,
(SELECT GROUP_CONCAT(LastSeen) FROM [assigned] WHERE SoftwareList =
SoftwareList) as LastSeen
FROM [assigned]
GROUP BY SoftwareList;
How can I pass SoftwareList which is returned for each row, into the
nested statement?

Get exact date by providing week number of month and day?

Get exact date by providing week number of month and day?

Is there any php function where i can get exact date, by providing week
number of the month and day as,
function required_date($week_num, $day) {
// should return 20th of September, if i pass (3, 'Friday')
}
I am getting week number of the month as
ceil(substr(date('Y-m-d'), -2) / 7);
and day as,
date('l');
Any help, please!

Magmi bulk image import (associate by sku)

Magmi bulk image import (associate by sku)

I have a folder with about 6000 images, all named according to the sku
being imported in magento via csv. I have installed magmi and the Image
Attributes Processor. If I put these images in media/import, will they
associate themselves by sku, or do I have to do something specific in my
configuration/scripts?

Wednesday, 18 September 2013

PhoneGap - exec() call to unknown plugin

PhoneGap - exec() call to unknown plugin

I've been trying to use Phonegap Image Resizer plugin in my project, but I
couldn't make it work.
The error log returns: D/PluginManager(13992): exec() call to unknown
plugin: com.webXells.imageResizer
I've moved all the necessary things into my project folder. Here's the
structure:
/assets
/js
cordova.js
imageresize.js
/www
index.html
upload.html
/src
/com
/webXells
/ImageResizer
ImageResizerPlugin.java
I've also include the plugin into config.xml in /res/xml:
<feature name="imageResizer">
<param name="android-package"
value="com.webXells.imageResizer.ImageResizePlugin"/>
</feature>
In upload.html I've included the plugin like so:
<script type="text/javascript" charset="utf-8"
src="../js/imageresize.js"></script>
And this is how I call a method to use it:
function onPhotoDataSuccess(imageData) {
window.imageResizer.resizeImage(
function(data) {
var smallImage = document.getElementById('smallImage');
smallImage.style.display = 'block';
image.src = "data:image/jpeg;base64," + imageData;
//image.src = imageData;
},
function (error) {
console.log("Error : \r\n" + error);
},
imageData,
0.5,
0.5,
{
imageDataType:ImageResizer.IMAGE_DATA_TYPE_BASE64,
resizeType:ImageResizer.RESIZE_TYPE_FACTOR,
format:'jpg'
}
);
}
So, inside the imageresize.js the method that I wanna use looks like this.
You can refer to the above link if necessary:
ImageResizer.prototype.resizeImage = function(success, fail, imageData,
width,
height, options) {
if (!options) {
options = {}
}
var params = {
data : imageData,
width : width,
height : height,
format : options.format,
imageDataType : options.imageType,
resizeType : options.resizeType,
quality : options.quality ? options.quality : 70
};
return
cordova.exec(success,fail,"com.webXells.imageResizer","resizeImage",[params]);
}
In the above code, I noticed that com.webXells.imageResizer didn't called
as reported in the logcat. What confuses me is the fact that I have
included it in config.xml and moved the java file in src folder. Why can't
it be called even though I have done all the stuff that is necessary?
Some researches I made, says to declare the plugin in plugin.xml, but I
don't have the file inside res/xml. So, I put it in config.xml instead.
Other recommend to use <gap:plugin name="com.phonegap.plugins.example" />
but Eclipse found error to this.
So, how do I get around this? Have I called the method in HTML correctly?
Or there is something I missed?

python: TypeError: 'long' object is not callable

python: TypeError: 'long' object is not callable

I get this error when trying to convert possible integer variables:
for page in domain.page_set.all():
filename = str(domain.url) + '_page_' +str(page.id())+ '.html'
The error:
File
"/Applications/djangostack-1.4.7-0/apps/django/django_projects/controls/polls/models.py",
line 40, in make_config_file
filename = str(domain.url)+"_page_"+str(page.id())+".html"
TypeError: 'long' object is not callable
What is wrong here? what does "long is not callable" means?

Content not appearing on scroll in Safari

Content not appearing on scroll in Safari

I made a site for a client recently and I've been told that they are
seeing a bug that is safari specific. The site content fills up the
browser window, but when they scroll down, the rest of the site will not
load all the way. They fix this by resizing the browser window, in which
case the rest of the content begins to appear.
I've tried to recreate this bug to no avail. Maybe you can? Or maybe you
know what the issue is? I was thinking maybe an overflow problem?
the site is http://theherbalosophy.com
you can see a screenshot of the bug at
http://michaelthomasrichards.com/bug.jpg
Thank you in advance for your help.

Perfect forwarding and ambiguity of function-parameter binding

Perfect forwarding and ambiguity of function-parameter binding

I am experimenting with the perfect forwarding feature of C++11. Gnu g++
compiler reports an ambiguity issue of function-parameter binding (the
error is shown after the source code below). My question is why is it so,
as following the function-parameter binding process I don't see the
ambiguity. My reasoning is as follows: call to tf(a) in main() binds to
tf(int&) since a is an lvalue. Then function tf forwards the lvalue
reference int& a to function g hence the function void g(int &a) should be
uniquely invoked. Thus I do not see the reason for ambiguity. The error
disappears when the overloaded function g(int a) is removed from the code.
This is strange as g(int a) cannot be a candidate for binding with int &a.
Here is my code:
void g(int &&a)
{
a+=30;
}
void g(int &a)
{
a+=10;
}
void g(int a) //existence of this function originates the ambiguity issue
{
a+=20;
}
template<typename T>
void tf(T&& a)
{
g(forward<T>(a));;
}
int main()
{
int a=5;
tf(a);
cout<<a<<endl;
}
Compilation g++ -std=c++11 perfectForwarding.cpp reports the following
errors:
perfectForwarding.cpp: In instantiation of 'void tf(T&&) [with T = int&]':
perfectForwarding.cpp:35:7: required from here
perfectForwarding.cpp:24:3: error: call of overloaded 'g(int&)' is ambiguous
perfectForwarding.cpp:24:3: note: candidates are:
perfectForwarding.cpp:6:6: note: void g(int&&) <near match>
perfectForwarding.cpp:6:6: note: no known conversion for argument 1 from
'int' to 'int&&'
perfectForwarding.cpp:11:6: note: void g(int&)
perfectForwarding.cpp:16:6: note: void g(int)

XLConnect is loaded automatically when I start R session

XLConnect is loaded automatically when I start R session

I got a problem with the R package "XLConnect".
Every time I open R, this package is automatically loaded.
So I thought it had been included in the default packages for some strange
reason, and I wrote like this:
getOption('defaultPackages') [1] "datasets" "utils" "grDevices" "graphics"
"stats" "methods"
It does not appear in the default packages; now I really don't know what
to do.
I ask for a help.
Thanks in advance.

linq Group By from DataTable

linq Group By from DataTable

I have DataTable Like this
Size | Type | FB | FP
2 | typeA | FB1 | A1
3 | typeB | FB1 | A1
4 | typeC | FB2 | A2
5 | typeD | FB2 | A2
6 | typeE | FB2 | A2
I want to have some thing like that
Size | Type | FB | FP
2 | typeA | FB1 | A1
3 | typeB | |
4 | typeC | FB2 | A2
5 | typeD | |
6 | typeE | |
how can i make it? I can make Group By
var result = from row in cableDataTable.AsEnumerable()
group row by new
{
FB = row.Field<string>("FB"),
FP = row.Field<string>("FP"),
Size = row.Field<int>("Size"),
Type = row.Field<int>("Type")
} into g
select new
{
FB = g.Key.FB,
FP = g.Key.FP,
Size = g.Key.Size,
Type = g.Key.Type
};
but it that could't give the result
thank you for your attention

Powershell script to find files in restricted folders (other user folders)

Powershell script to find files in restricted folders (other user folders)

I'm making a script which would search for a file. If file is found it
will write txt file on server with computer's name and path where file is
located.
$filePath = "c:"
$fileName = "somefile"
$Computer = Get-Content env:computername
$srvpath = "\\server\share$\FindFileScript\$Computer.txt"
#SEARCH FOR FILE ON C DISK
$fileResult = (Get-ChildItem -Recurse -Force $filePath -ErrorAction
SilentlyContinue
| Where-Object { $_.Name -like "*$fileName*" } | Select-Object FullName |
format-Table * -AutoSize)
if ($fileResult -eq $Null)
{
Write-Host "File named $fileName on disk C was not found."
}
Else
{
Write-Host "File named $fileName on disk C was found."
Out-File -FilePath $srvpath -InputObject $fileResult
}
1) We are using 3rd party program that can deploy programs and launch
powershell script as well.
The problem is though that program launch script as Administrator user so
powershell script is not allowed to search for files on
C:\Users[some_other_user] folder.
Is there a way to force search on restricted folders as well?
2) Second question is not so important but is it possible somehow to
include in $filePath not only C: but D: as well?

Tuesday, 17 September 2013

Is it possible to add sub-items to a YML list?

Is it possible to add sub-items to a YML list?

Given the following YML format, is it possible, or advisable to map URLs
so that components like nav lists can be both populated and linked?
It can be populated:
products:
- Wizzy Widgets
- Doohickeys
- Thingamabobbers
renders via the following ERB (where the file is /data/product_types.yml):
<% data.product_types.products.each do |product_type| %>
<li><a href="#"><%= product_type %></a></li>
<% end %>
to output the following markup
<li><a href="#">Wizzy Widgets</a></li>
<li><a href="#">Doohickeys</a></li>
<li><a href="#">Thingamabobbers</a></li>
but can it be linked also
products:
- Wizzy Widgets:
- url: "/wizzy-widgets"
- Doohickeys:
- url: "/doohickeys"
- Thingamabobbers
- url: "/thingamabobbers"
through ERB like so:
<% data.product_types.products.each do |product_type, product_url| %>
<li><a href="<%= product_url %>"><%= product_type %></a></li>
<% end %>
so that it outputs the following markup?
<li><a href="/wizzy-widgets">Wizzy Widgets</a></li>
<li><a href="/doohickeys">Doohickeys</a></li>
<li><a href="/thingamabobbers">Thingamabobbers</a></li>
I know this particular example doesn't work. I'm just trying to give an
example of what I'm looking to do. Is this a bad practice? If so, how
would you approach it?

findViewById in android doesn't return child layout

findViewById in android doesn't return child layout

I inflate a view. Using the newly created layout, I find a child to set a
property. But the child I get (mealName here) is not the good one. Having
my mealList containing multiple mealName, it's always the first one that
is returned.
RelativeLayout mealNameLayout = (RelativeLayout)
inflater.inflate(R.layout.planner_list_item_meal_title, mealList);
TextView mealName = (TextView) mealNameLayout.findViewById(R.id.mealName);
//Set meal name.
mealName.setText(meal.name);
By making this modification (not attaching automatically the relative
layout to the list):
RelativeLayout mealNameLayout = (RelativeLayout)
inflater.inflate(R.layout.planner_list_item_meal_title, mealList, false);
I'm having better results, but still very weird behavior. Looks like using
findViewById when having multiple items with the same id is not a good
idea. Even though there is only one item having this id in the children.
Any idea on what's going on?

Time complexity for c*c?

Time complexity for c*c?

Got time complexity questions here:
for i = 1 to n
if something
p = p*c
c = c*c
For line 1, the time complexity should be n, but what about line 3 and 4?
is that n^2? or n^n?

Application works with app.all but not with app.use... not sure why

Application works with app.all but not with app.use... not sure why

I'm having some problems trying to implement some middleware in my app.
Specicially, the app.use() does not seem to catch and I don't understand why.
Below is roughly what I have.
routes/index.js
var Sessions = require('../events');
module.exports = exports = function(app) {
app.use(Sessions.isLoggedIn);
//app.use() does not catch but this does
//app.all('*', Sessions.isLoggedIn);
// Home Page
app.get('/', displayHome);
app.get('/:library/:books', displayLibrary);
}
events.js
module.exports = exports = {
isLoggedIn: function(req, res, next) {
console.log('isLoggedIn');
return next();
}
Any suggestions as to why app.use() is not catching?

Button onclick not redirecting to correct URL

Button onclick not redirecting to correct URL

<button id="promoCodeSubmit"
onclick="window.location.href='http://www.test.com'+document.getElementById('promoCodeValue').value;">Apply</button>
Trying to use the code above to redirect a page. console.log is printing
out the correct URL, but page gets redirected incorrectly. Any ideas why?

problems implementing secured images on google app engine blob store?

problems implementing secured images on google app engine blob store?

Our project requires the images to be secure. The solution right now is,
to implement an authorization header. The front end makes an http call to
the image url with authorization credentials. once the image is
downloaded, an image tag is created and the url is assigned as a src.
Since the url was just called, its being served from the cache the second
time, and it works.. mostly.. we have some issues, where safari handles
cache differently.. also in chrome it fails when the web console is open.
We would like to have a more reliable method. Appreciate any input.

Sunday, 15 September 2013

Javascript library combinations

Javascript library combinations

Question, lately I have been wandering around with Backbone.js, and
underscore/require and other libraries, what other combinations are out
there for Backbone? or Angular.js? I mean what are other stable and
reliable combinations to make with JS libraries?
All your answers are appreciated.

How can I use an open API In my code?

How can I use an open API In my code?

I'm fairly new to coding and I would like to use someone's open API in my
code. Can someone help me with A. Which language to use. And B. the code
to call an API

Creating inheritance on revealing modular pattern objects

Creating inheritance on revealing modular pattern objects

I'm trying to create some kind of inheritance between objects:
var foo = (function(){
function doFooStuff(){
console.log(arguments.callee.name);
}
return {
doFooStuff: doFooStuff
}
})();
var bar = (function(){
$.extend(this, foo);
function doBarStuff(){
console.log(arguments.callee.name);
doFooStuff();
}
return {
doBarStuff: doBarStuff,
}
})();
bar.doBarStuff();
bar.doFooStuff(); //<-- Uncaught TypeError:
//Object #<Object> has no method 'doFooStuff'
http://jsfiddle.net/wRXTv/
Why isn't doFooStuff accessible here? Would you recommend another approach
than using $.extend?

Rails: unable to destroy post

Rails: unable to destroy post

I'm building forum app based on Ruby on Rails. I have problem with destroy
action in Post Controller. My Posts Controller:
class PostsController < ApplicationController
before_action :authenticate_user!
before_action :set_topic, only: :create
def new
@post = @topic.posts.new
end
def create
@post = @topic.posts.new(post_params)
@post.user = current_user
if @post.save
flash[:notice] = 'Post created successfully!'
redirect_to(:back)
else
render 'shared/_post_form'
end
end
def destroy
@post = Post.find(params[:id])
@post.destroy
redirect_to(:back)
flash[:error] = "Post was destroyed!"
end
private
def set_topic
@topic = Topic.find(params[:topic_id])
end
def post_params
params.require(:post).permit(:content)
end
end
This is my routes:
resources :contact_forms, only: [:new, :create]
match '/contact', to: 'contact_forms#new', via: 'get'
root 'static_pages#home'
resources :forums, only: [:index, :show] do
resources :topics, except: :index
end
resources :topics, except: :index do
resources :posts
end
devise_for :users
resources :users, only: :show
I go to topic show action and i have link to delete post:
= link_to "Delete", topic_post_path(post.topic.forum.id, post.topic.id),
method: :delete, data: {confirm: "You sure?"}, class: 'label alert
When i click it i have following error:
ActiveRecord::RecordNotFound in PostsController#destroy
Couldn't find Post with id=46
Any ideas?

store.load() triggers read + create

store.load() triggers read + create

I'm developing a app where a list is automatically refreshed every 15 sec.
To do so, I load the store every 15 sec from server (sending the params)
via php page linked to a postgreSQL DB. So far, so good, and it works OK.
Buy I have noticed that every time the store is loaded, it sends two
requests to the server (read + create). While the read request is
necessary to load new elements to the store, the create is completely
useless, because it sends the whole store as payload and receives nothing
making use of the network for nothing. How can I make the store to read,
and only read, from the server when it loads?
Thanks

Not logging Console.ReadLine output?

Not logging Console.ReadLine output?

How can I NOT show the output when a user inserts something in
Console.ReadLine so the console won't show what the user entered? Thanks!

Saturday, 14 September 2013

Where AND clause with 2 columns sqlite query

Where AND clause with 2 columns sqlite query

"select * from TABLE_NAME where colx='"+value1+"' and coly='"+value2+"'";
How to use this in android sqlite database?

Most pythonic way to convert a string to a octal number

Most pythonic way to convert a string to a octal number

I am looking to change permissions on a file with the file mask stored in
a configuration file. Since os.chmod() requires an octal number, I need to
convert a string to an octal number. For example:
'000' ==> 0000 (or 0o000 for you python 3 folks)
'644' ==> 0644 (or 0o644)
'777' ==> 0777 (or 0o777)
After an obvious first attempt of creating every octal number from 0000 to
0777 and putting it in a dictionary lining it up with the string version,
I came up with the following:
def new_oct(octal_string):
if re.match('^[0-7]+$', octal_string) is None:
raise SyntaxError(octal_string)
power = 0
base_ten_sum = 0
for digit_string in octal_string[::-1]:
base_ten_digit_value = int(digit_string) * (8 ** power)
base_ten_sum += base_ten_digit_value
power += 1
return oct(base_ten_sum)
Is there a simpler way to do this?

Code translation from PASCAL to C++ giving unexpected results

Code translation from PASCAL to C++ giving unexpected results

I am trying to implement the PASCAL code given in this paper in C++ and my
attempt is
#include <iostream>
using namespace std;
int GenFact(int a, int b)
{ // calculates the generalised factorial
// (a)(a-1)...(a-b+1)
int gf = 1;
for (int jj = (a - b + 1); jj < a + 1; jj++)
{
gf = gf * jj;
}
return (gf);
} // end of GenFact function
double GramPoly(int i, int m, int k, int s)
{ // Calculates the Gram Polynomial ( s = 0 ),
// or its s'th
// derivative evaluated at i, order k, over 2m + 1 points
double gp_val;
if (k > 0)
{
gp_val = (4.0 * k - 2.0) / (k * (2.0 * m - k + 1.0)) *
(i * GramPoly(i, m, k - 1, s) +
s * GramPoly(i, m, k - 1.0, s - 1.0)) -
((k - 1.0) * (2.0 * m + k)) /
(k * (2.0 * m - k + 1.0)) *
GramPoly(i, m, k - 2.0, s);
}
else
{
if ((k == 0) && (s == 0))
{
gp_val = 1.0;
}
else
{
gp_val = 0.0;
} // end of if k = 0 & s = 0
} // end of if k > 0
return (gp_val);
} // end of GramPoly function
double Weight(int i, int t, int m, int n, int s)
{ // calculates the weight of the i'th data
// point for the t'th Least-square
// point of the s'th derivative, over 2m + 1 points, order n
double sum = 0.0;
for (int k = 0; k < n + 1; k++)
{
sum += (2.0 * k + 1.0) *
GenFact(2.0 * m + k + 1.0, k + 1.0) *
GramPoly(i, m, k, 0) * GramPoly(t, m, k, s);
} // end of for loop
return (sum);
} // end of Weight function
int main()
{
double z;
z = Weight(-2, -2, 2, 2, 0);
cout << "The result is " << z;
return 0;
}
however, when I run the code the output is 1145 whilst I'm expecting 31/35
= 0.88571 as per equation 12 and the tables given in the paper. Where is
my error?

Calculate a trig function with an input and output in degrees

Calculate a trig function with an input and output in degrees

I'm trying to make a calculator for some calc homework, but the
information is given in degrees and the answer must be in degrees. I tried
using the Math.toDegrees and Math.toRadians but the answer isn't correct.
public static double crossProduct() {
Scanner in = new Scanner(System.in);
System.out.println("enter angle in degrees");
double angle = in.nextDouble();
System.out.println("x1 = ");
double x1 = in.nextDouble();
System.out.println("y1 = ");
double y1 = in.nextDouble();
System.out.println("z1 = ");
double z1 = in.nextDouble();
System.out.println("");
System.out.println("x2 = ");
double x2 = in.nextDouble();
System.out.println("y2 = ");
double y2 = in.nextDouble();
System.out.println("z2 = ");
double z2 = in.nextDouble();
double mag1 = Math.sqrt((x1 * x1) + (y1 * y1) + (z1 * z1));
double mag2 = Math.sqrt((x2 * x2) + (y2 * y2) + (z2 * z2));
double res = mag1 * mag2 *
Math.toDegrees(Math.sin(Math.toRadians(angle)));
System.out.println("cross product = " + res);
return res;
}
inputting <0,2,0> and <0,5,0> and angle = 90 degrees should give the
answer as 10. instead it returns:
572.9577951308232
Any ideas?
EDIT: Also, if anyone has a better/shorter way for inputting the
components, that would be amazing.

I get an exception bounds error, idk what to do

I get an exception bounds error, idk what to do

The code : package maze;
public class Maze {
private int N; // dimension of maze
private boolean[][] north; // is there a wall to north of cell i, j
private boolean[][] east;
private boolean[][] south;
private boolean[][] west;
private boolean[][] visited;
private double size;
private boolean done = false;
public Maze(int N) {
this.N = N;
StdDraw.setXscale(0, N+2);
StdDraw.setYscale(0, N+2);
init();
generate();
}
private void init() {
// initialize border cells as already visited
visited = new boolean[N+2][N+2];
for (int x = 0; x < N+2; x++) visited[x][0] = visited[x][N+1] = true;
for (int y = 0; y < N+2; y++) visited[0][y] = visited[N+1][y] = true;
// initialze all walls as present
north = new boolean[N+2][N+2];
east = new boolean[N+2][N+2];
south = new boolean[N+2][N+2];
west = new boolean[N+2][N+2];
for (int x = 0; x < N+2; x++)
for (int y = 0; y < N+2; y++)
north[x][y] = east[x][y] = south[x][y] = west[x][y] = true;
}
// generate the maze
private void generate(int x, int y) {
visited[x][y] = true;
// while there is an unvisited neighbor
while (!visited[x][y+1] || !visited[x+1][y] || !visited[x][y-1] ||
!visited[x-1][y]) {
// pick random neighbor (could use Knuth's trick instead)
while (true) {
double r = Math.random();
if (r < 0.25 && !visited[x][y+1]) {
north[x][y] = south[x][y+1] = false;
generate(x, y + 1);
break;
}
else if (r >= 0.25 && r < 0.50 && !visited[x+1][y]) {
east[x][y] = west[x+1][y] = false;
generate(x+1, y);
break;
}
else if (r >= 0.5 && r < 0.75 && !visited[x][y-1]) {
south[x][y] = north[x][y-1] = false;
generate(x, y-1);
break;
}
else if (r >= 0.75 && r < 1.00 && !visited[x-1][y]) {
west[x][y] = east[x-1][y] = false;
generate(x-1, y);
break;
}
}
}
}
// generate the maze starting from lower left
private void generate() {
generate(1, 1);
// delete some random walls
for (int i = 0; i < N; i++) {
int x = (int) (1 + Math.random() * (N-1));
int y = (int) (1 + Math.random() * (N-1));
north[x][y] = south[x][y+1] = false;
}
// add some random walls
for (int i = 0; i < 10; i++) {
int x = (int) (N / 2 + Math.random() * (N / 2));
int y = (int) (N / 2 + Math.random() * (N / 2));
east[x][y] = west[x+1][y] = true;
}
}
// solve the maze using depth-first search
private void solve(int x, int y) {
if (x == 0 || y == 0 || x == N+1 || y == N+1) return;
if (done || visited[x][y]) return;
visited[x][y] = true;
StdDraw.setPenColor(StdDraw.BLUE);
StdDraw.filledCircle(x + 0.5, y + 0.5, 0.25);
StdDraw.show(30);
// reached middle
if (x == N/2 && y == N/2) done = true;
if (!north[x][y]) solve(x, y + 1);
if (!east[x][y]) solve(x + 1, y);
if (!south[x][y]) solve(x, y - 1);
if (!west[x][y]) solve(x - 1, y);
if (done) return;
StdDraw.setPenColor(StdDraw.GRAY);
StdDraw.filledCircle(x + 0.5, y + 0.5, 0.25);
StdDraw.show(30);
}
// solve the maze starting from the start state
public void solve() {
for (int x = 1; x <= N; x++)
for (int y = 1; y <= N; y++)
visited[x][y] = false;
done = false;
solve(1, 1);
}
// draw the maze
public void draw() {
StdDraw.setPenColor(StdDraw.RED);
StdDraw.filledCircle(N/2 + 0.5, N/2 + 0.5, 0.375);
StdDraw.filledCircle(1.5, 1.5, 0.375);
StdDraw.setPenColor(StdDraw.BLACK);
for (int x = 1; x <= N; x++) {
for (int y = 1; y <= N; y++) {
if (south[x][y]) StdDraw.line(x, y, x + 1, y);
if (north[x][y]) StdDraw.line(x, y + 1, x + 1, y + 1);
if (west[x][y]) StdDraw.line(x, y, x, y + 1);
if (east[x][y]) StdDraw.line(x + 1, y, x + 1, y + 1);
}
}
StdDraw.show(1000);
}
// a test client
public static void main(String[] args) {
int N = Integer.parseInt(args[0]);
Maze maze = new Maze(N);
StdDraw.show(0);
maze.draw();
maze.solve();
}
}
What it supposed to do :
Display a maze graphically
What the problem is:
Line 155 i.e int N = Integer.parseInt(args[0]); gives a bounds error. Any
recommendations ?

Different types of Users with simplemembership in ASP.NET EF code first

Different types of Users with simplemembership in ASP.NET EF code first

In my app I want to have two different types of users. This types differ
not only in role but also in attributes. I am using simpleMembership for
userManagement and I want to ask what's the best way or practise to create
data model for my situation in EF using code first. I was thinking about
creating two another tables UsersType1 and UsersType2 which will have one
to one relationship with table userProfiles so in the model I would have:
public class UserType1{
attr1
attr2
....
public int userProfileID {get; set;}
public virtual UserProfile userProfile {get; set;}
}
And same way for table UserType2.
I want to ask if this is a good way to go and if so, how should I modify
userProfiles table to be able to access UserType1 and UserType2 through
userprofile in code.
Thank you.

Friday, 13 September 2013

XSI: namespaces removing

XSI: namespaces removing

As part of my requirement, I need to route a response coming from my
dp:url-open in Datapower tool, serialize it and then send it to another
link.
Issue is that response is holding so many namespaces in its every element.
I know its the kind of format generated automatically, but i need to
remove them completely.
I went through few posts in internet and used exclude-result-prefixes at
start of my XSLT and i am able to get rid of most of namespaces like dp
and dpconfig related to Datapower, but xsi: and xmlns: are still appearing
in my string. How to get rid of that one also?
Please note that i cant use another XSLT as suggested in few posts. Is
there any other way, please suggest.
Below is my xml serialized.
xmlns:SOAP-ENV=http://schemas.xmlsoap.org/soap/envelope/">
W123
rogers
L1
Thansk for help.

Python can't keep up with time

Python can't keep up with time

Can anybody explain the following?
timex = [2012, 3, 1]
epoch = calendar.timegm(datetime.datetime(*timex).utctimetuple())
date = datetime.date.fromtimestamp(epoch)
print date # [2012, 2, 29]
timex = [2012, 3, 15]
epoch = calendar.timegm(datetime.datetime(*timex).utctimetuple())
date = datetime.date.fromtimestamp(epoch)
print date # [2012, 3, 14]
I'm not sure if it has to do with my misunderstanding of tuples, lists or
time in general, but python is always a day behind :P

using fopen to open file in database

using fopen to open file in database

I have PHP code for downloading file from mysql database. Im trying to
buffer my download into chunk each chunk 1024. But its look fopen can't
open my file from the database it give error. "Warning: fclose() expects
parameter 1 to be resource, boolean given in
/var/www/html/download/get_file_work.php on line 40" How to open file in
database using fopen function.
My php code
<?php
ob_start();
$company = $_GET['company'];
if(isset($_GET['id']))
{
$id = intval($_GET['id']);
if($id <= 0)
{
die('The ID is invalid!');
}
else
{
$dbLink = new mysqli('localhost', 'sqldata', 'sqldata', 'balhaf');
if(mysqli_connect_errno())
{
die("MySQL connection failed: ". mysqli_connect_error());
}
$query = "SELECT mime, name, size, data FROM $company WHERE id = $id";
$result = $dbLink->query($query);
if($result)
{
if($result->num_rows == 1) {
$row = mysqli_fetch_assoc($result);
$size = $row['size'];
$filename = $row['name'];
$data = $row['data'];
$mime = $row['mime'];
if ($fd = fopen ($data, "r")) {
ini_get('zlib.output_compression');
ini_set('zlib.output_compression', 'Off');
header('Content-Type: application/pdf');
while (@ob_end_clean());
header('Content-Disposition: attachment; filename='.($filename));
header('Content-Length:'.($size));
while(!feof($fd)) {
$buffer = fread($fd, 1024);
echo $buffer;
}
}
fclose ($fd);
exit;
}
else
{
echo 'Error! No image exists with that ID.';
}
mysqli_free_result($result);
}
else
{
echo "Error! Query failed: <pre>{$dbLink->error}</pre>";
}
mysqli_close($dbLink);
}
}
else
{
echo 'Error! No ID was passed.';
}
?>

Is there a way to set the filter type in kendo grid

Is there a way to set the filter type in kendo grid

Regarding filtering on the Kendo Grid. Is there away to set the filter
type to a different type other than type of the bound column? or, Any
example of this using attribute on the property?

The views didn't return an HttpResponse object

The views didn't return an HttpResponse object

I use django on linux to bulid a register website.It can't works!!
The error message: The view blog.views.register didn't return an
HttpResponse object.
models.py
from django.db import models
class User(models.Model):
username = models.CharField(max_length = 20)
headImg = models.FileField(upload_to = './upload/')
def __unicode__(self):
return self.username
views.py
class UserForm(forms.Form):
username = forms.CharField()
headImg = forms.FileField()
def register(req):
if req.method == "POST":
uf = UserForm(req.POST)
if uf.is_valid():
print uf.cleaned_data['username']
print uf.cleaned_data['headImg'].name
user = User()
user.username = uf.cleaned_data['username']
user.headImg = uf.cleaned_data['headImg']
user.save()
return HttpResponse('ok')
else:
uf = UserForm()
return render_to_response('register.html',{'uf':uf})

mysql query optimization with multiple groupings or order bye

mysql query optimization with multiple groupings or order bye

This is what my current query looks like:
SELECT act.*, group_concat(act.owner_id order by act.created_at desc) as
owner_ids
FROM (select * from activities order by created_at desc) as act
INNER JOIN users on users.id = act.owner_id
WHERE (users.city_id = 1 and act.owner_type = 'User')
GROUP BY trackable_type, recipient_id, recipient_type
order by act.created_at desc
limit 20 offset 0;
Doing an explain
I have played around with this query a lot including indexes etc. Is there
any way to optimizes this query?

Linux Threads and process - CPU affinity

Linux Threads and process - CPU affinity

I have few queries related to threads and Process scheduling.
When my process goes into sleep and wakes back, is it always that it will
be scheduled on the same CPU that it got scheduled before?
When i create a thread from the process, Will it also be executed on the
same CPU always? Even if other CPU's are free and sleeping.
I would like to know the mechanism in Linux in specific. Also i am
creating the threads through pthread library. I am facing a random hangup
issue which is always not reproducible. Need this information to proceed
in the right direction.

Thursday, 12 September 2013

Why this opcode doesn't work properly on ARM

Why this opcode doesn't work properly on ARM

Writing the opcodes on ARM, I face an error.
8054: e92d1fff push {r0, r1, r2, r3, r4, r5, r6, r7, r8, r9, sl, fp, ip}
The above is the result of disassembly by objdump; \xe9\x2d\x1f\xff is the
same to push {r0-r12}.
But in another program, this opcode doesn't work properly like:
1e75: e9 .byte 0xe9
1e76: 1f2d .short 0x1f2d
1e78: Address 0x06001e78 is out of bounds.
Any ideas?

FullCalendar: How to re-add events that were part of original events array?

FullCalendar: How to re-add events that were part of original events array?

Why can't a removed event be re-added to FullCalendar if it was part of
the original events array at calendar creation?
This works (http://jsfiddle.net/fTu98/1/):
// A simple event object
e = {id: 1, title: 'a', start: Date.now()/1000 };
// Create calendar with no events
$("#calendar").fullCalendar({ events: [] });
// Add event to calendar
$("#calendar").fullCalendar('renderEvent', e);
// Remove event from the calendar
$("#calendar").fullCalendar('removeEvents', 1);
// Re-add event
$("#calendar").fullCalendar('renderEvent', e);
While this doesn't (http://jsfiddle.net/BNmrQ/2/):
// A simple event object
e = {id: 1, title: 'a', start: Date.now()/1000 };
// Create calendar with the event
$("#calendar").fullCalendar({ events: [e] });
// Remove event from the calendar
$("#calendar").fullCalendar('removeEvents', 1);
// Try re-adding event, doesn't work!
$("#calendar").fullCalendar('renderEvent', e);
Thanks!

Project euler benchmark

Project euler benchmark

I recently started solving Project euler for fun. and I thought it would
be awesome to have benchmarks shared out here. No solution algorithms,
just times and results for comparison (so anyone can still solving
problems on their own, but also check if is there faster solution).
I know its not really a question but still i think it could help. If you
can add your results (if they are better than others already here) in
similar format as mine.
so here are my so far (i will add missing ones when finished):
Project Euler
CPU(AMD A8-5500 3.2GHz) lang(BDS2006 32bit C++) OS(Win7 x64)
----------------------------------------------------
time ID reference my solution
----------------------------------------------------
[ 0.003 ms] Problem001. 233168 | 233168
[ 0.001 ms] Problem002. 4613732 | 4613732
[ 2.189 ms] Problem003. 6857 | 6857
[ 3.035 ms] Problem004. 906609 | 906609
[ 232.551 ms] Problem005. 232792560 | 232792560
[ 0.002 ms] Problem006. 25164150 | 25164150
[ 35.563 ms] Problem007. 104743 | 104743
[ 0.006 ms] Problem008. 40824 | 40824
[ 0.876 ms] Problem009. 31875000 | 31875000
[ 438.284 ms] Problem010. 142913828922 | 142913828922
[ 0.023 ms] Problem011. 70600674 | 70600674
[ 234.680 ms] Problem012. 76576500 | 76576500
[ 0.020 ms] Problem013. 5537376230 | 5537376230
[ 385.829 ms] Problem014. 837799 | 837799
----------------------------------------------------

Xcode Autolayout - Constraint equal to another constraint

Xcode Autolayout - Constraint equal to another constraint

I am finally trying to adopt autolayout in IB and I am having trouble
setting the constraints for some objects. I basically want 5 views to be
equally distributed vertically throughout the superview. I have 3 buttons
separated by 2 lines. I want the spacings D1, D2, D3, and D4 to be equal
WITHOUT resizing the height of anything. How can this be set up in IB?

Cut the output of a command

Cut the output of a command

I have the following output of the command "xm list":
Name ID Mem VCPUs State
Time(s)
Domain-0 0 505 4 r-----
11967.2
test1 28 1024 1 -b----
137.9
test2 33 1024 1 -b----
3.2
I execute a shellscript with: ./myscript test2 In this script, I need the
ID of test2 (shown at the command "xm list" (ID33)) I tried it with grep
and cut like this:
xm list | grep $1 | cut ???
How does this work?

Wednesday, 11 September 2013

java.net.BindException: Address already in use: JVM_Bind

java.net.BindException: Address already in use: JVM_Bind

I am sending files from client to server but each time i run it says, port
already in use. So i want to run this without changing the port for each
time or is there any alternate ways to do it. so can anyone tell how can
do this. Thanks in advance.

Define web root dir - consant works on include but not redirect

Define web root dir - consant works on include but not redirect

I'm trying to create a constant which defines my web root dir, which I can
use for constructing paths for requires, header redirects, images, etc.
I need the constant to work when used in files in the root folder and sub
folders. I know I could easily hard code the paths with ../ etc, but the
main reason I'm trying to get this to work (apart from clean code) is so I
can re-use the code on various sites on different servers, where the path
may vary.
my dir structure
/
index.php
/library
libSetPathRoot.php
Document Root
echo $_SERVER["DOCUMENT_ROOT"];
Returns: /home/james/web/sites/
The "sites" dir contains various document roots defined in sites-available
(so I can work on different scripts).
File contents
/index.php
require_once('library/libSetPathRoot.php'); //works fine.. of course
/library/libSetPathRoot.php
define("PATHROOT", realpath(__DIR__ .'/..').'/');
The above returns my root correctly:
echo PATHROOT;// /home/james/web/sites/site3/
I've tried the following and various other code to define a root path.
These, and others, didn't work for redirect(), include(), nothing at all:
define ('PATHROOT', getenv("DOCUMENT_ROOT"));
define ('PATHROOT', basename(dirname((__DIR__))));
echo PATHROOT;
Everything else seemed to return "site3" only.
The working define works for include() and require() regardless of where
in the dir structure it is placed. ie if in file in sub dir to root
calling root or other sub dir to root, in a file in root, included file
etc.
But I just cannot get this working for header() redirect. Again,
regardless of where I use it - root scripts, sub folder scripts, included
scripts. Maybe I need another approach, but have read numerous options and
tried them extensively (half a day spent).
Why is my define working for includes but not header redirect, and how can
I make it work on all? Or do I have to use two methods, one for include
and one for redirects?

Finding Interfaces

Finding Interfaces

Supposing i have a dictionary that I have created using defaultdict like
this one(many hundred points long):
L [(32.992, 22.861, 29.486, 'TYR'), (32.613, 26.653, 29.569, 'VAL'),
(30.029, 28.873, 27.872, 'LEU')
A [(1.719, -25.217, 8.694, 'PRO'), (2.934, -21.997, 7.084, 'SER'), (5.35,
-19.779, 8.986, 'VAL')
H [(-0.511, 19.577, 27.422, 'GLU'), (2.336, 18.416, 29.649, 'VAL'), (2.65,
19.35, 33.322, 'GLN')
I then want to loop over every value in each key and check the distance
from that value to every other residue under the other keys. I know how to
check the distance using a simple formula, but I am having problems
getting the loop to work properly. Ideally it would check each point in L
against each point in A and H and then move on to checking each_value in A
against L and H etc...
I have tried simple comprehensions but I always get only one chain to
check one other chain before it finishes. Any help is appreciated.

How can I use a db through different Activities in android?

How can I use a db through different Activities in android?

I created an SQLite database in my Android project to store information
about homes using SqliteOpenHelper.I have two Activities.One is a list
activity containing a list of all homes, and one that is started by the
listActivity to add a new home. My question has to do with the usage of
the db. Which is better? Have an instance of the db in both activities? Or
have a static instance of the db in only one activity and use it in every
other activity that need acces to it? What is the better way to use a db
through different Activities?
public class HomeDatabaseHandler extends SQLiteOpenHelper{
//Database Version
private static final int DATABASE_VERSION = 1;
//Database name static value
private static final String DATABASE_NAME = "homeManager";
//Table name
private static final String HOMES_TABLE = "homes";
//more code here for adding creating etc...
}
public class MainActivity extends ListActivity{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Here is my db for populating listView
HomeDatabaseHandler db = new HomeDatabaseHandler(this);
}
//in Activity to add home
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_add_done:
//more code here to get values from views
//create new db to add values
HomeDatabaseHandler db = new HomeDatabaseHandler(this);
//method to add home
db.addHome
}
}
This is how it looks right now, creating to instances of the Handler and
adding. So what do you think?I feel this is not the best way...

Test classes with common behavior

Test classes with common behavior

I have to write some integration test classes in the Hybris Commerce Suite
and most of them share a common behavior to set up the system (Site,
Store, Catalog, Country, ...) or to perform some common action like create
a customer.
I created an abstract class that perform all the initialization with
constant values in the @Before method and with some common methods like
createDefaultCustomer().
All my test classes inherit from this class.
The constant values are separated in different constant classes like
abstract class AbstractTest {
protected static final class USER_CONSTANTS {
};
protected static final class CATALOG_CONSTANTS {
};
protected UserModel createDefaultUser() {
}
}
Now, in order to test, in my subclasses i can do
createDefaultUser();
UserData userData = userFacade.getUserById(USER_CONSTANTS.ID);
assertEquals(USER_CONSTANTS.ID, testUser.getId());
If I don't do this there is a lot of duplication in test classes.
My doubt is whether this is acceptable because the abstract class tends to
be long and rich of methods or I need to change the design. I would to
avoid the creation of separate classes for each group of constants.

IPad use as a monitor with an Hdmi feed into it

IPad use as a monitor with an Hdmi feed into it

am trying to find out if a live HDMI signal can be fed into an iPad , so
that the iPad is becoming a monitor for that live HDMI Video signal feed.
wifi is not an option , because of the delay.
i called apple, and have virtually had 2 contradictory answers, one senior
advisor asked the tech dept and came back and said its not possible, no
incoming signal is possible, only outgoing.
then the second call they said it would work, hence the data of an SD
memory card can be imported , otherwise such imports would not be possible
neither.
i would like to find out with a blue prints reasoning what the story is now.
any technical proof what the case is would be greatly appreciated.

What is the alternative tag to false for Menu Items

What is the alternative tag to false for Menu Items

I am using "false" tag to show Menu items in the given text style instead
of showing in All Caps. But this tag is working only in above API level 14
devices only. I need this functionality in Below API level 14 also. Is
there any another tag for this?
Thanks in advance.

Wordpress ACF: Image field, change image on mouse over

Wordpress ACF: Image field, change image on mouse over

I have a flexible content field containing a name, a link to a personal
page and 2 image fields (both returning object id): the original image and
a "mouse-over" image.
I want to display these fields on a page, so i added the following code
(between a while-statement, but that messes up the code:
<?php if(get_row_layout() == "medewerker"): // layout: Content ?>
<div class="medewerker_blok">
<div class="med_naam">
<?php the_sub_field("med_naam"); ?>
</div>
<a href="<?php the_sub_field('medewerkers_pagina'); ?>" >
<div class="med_foto">
<?php $image =
wp_get_attachment_image_src(get_sub_field('med_foto'),
'medium'); ?>
<?php $thumb =
wp_get_attachment_image_src(get_sub_field('med_foto'),
'thumbnail'); ?>
<img src="<?php echo $image[0]; ?>" alt="<?php
the_sub_field('med_naam');?>" rel="<?php echo $thumb[0];
?>" />
</div>
</a>
</div>
<div class="clear"></div>
<?php endif; ?>
This works fine: it shows the name field, the image. So far so good. But
now I would like an option where it replaces this image with the second
image field when you hover over the picture.
I cant get it working, must be missing something.
Please note, it is a flexible field, so the mouseover shouldn't trigger al
the other repeated blocks.
I hope someone can help me with this!
Cheers,
Bram

Convert string formatted as yyyymmddhhnn to datetime

Convert string formatted as yyyymmddhhnn to datetime

I have a table in an SQL Server database with a date field in it,
presented as varchar in yyyymmddhhnn format (where nn is minutes). For
example, 200012011200 would be 01 Dec 2000 12:00. I need to convert this
to a datetime value, but none of the convert codes seems to cover it. It's
closest to ISO format yyyymmdd but that doesn't include the time part, so
calling convert(datetime, MyDateField, 112) fails.
The time part is important, so I can't just strip it off. How can I
convert this to datetime?

Tuesday, 10 September 2013

to read unicode character in java

to read unicode character in java

i am trying to read Unicode characters from a text file saved in utf-8
using java my text file is as follows
&#2309;, &#2309;&#2342;&#2375;&#2348;&#2366;&#2344;&#2367;
,&#2309;&#2344;, &#2309;&#2344;&#2360;&#2369;&#2354;&#2366;,
&#2309;&#2344;&#2360;&#2369;&#2354;&#2367;,
&#2309;&#2344;&#2347;&#2366;&#2357;&#2352;&#2367;,
&#2309;&#2344;&#2332;&#2366;&#2354;&#2369;,
&#2309;&#2344;&#2342;&#2381;&#2354;&#2366;, &#2309;&#2350;&#2366;,
&#2309;&#2352;, &#2309;&#2352;&#2327;&#2366;,
&#2309;&#2352;&#2327;&#2375;, &#2309;&#2352;&#2344;,
&#2309;&#2352;&#2366;&#2351;, &#2309;&#2354;&#2326;&#2342;,
&#2309;&#2360;&#2375;, &#2309;&#2361;&#2366;,
&#2309;&#2361;&#2367;&#2306;&#2360;&#2366;,
&#2309;&#2327;&#2381;&#2352;&#2306;,
&#2309;&#2344;&#2381;&#2341;&#2366;&#2311;,
&#2309;&#2347;&#2381;&#2352;&#2367;, &#2348;&#2367;&#2351;&#2344;,
&#2326;&#2367;&#2351;&#2344;, &#2347;&#2367;&#2351;&#2344;,
&#2348;&#2344;, &#2327;&#2344;, &#2341;&#2344;, &#2361;&#2352;,
&#2361;&#2350;, &#2332;&#2350;, &#2327;&#2354;, &#2327;&#2341;,
&#2342;&#2352;&#2360;&#2375;, &#2342;&#2352;&#2344;&#2376;,
&#2341;&#2344;&#2376;, &#2341;&#2341;&#2366;&#2350;,
&#2360;&#2341;&#2366;&#2350;, &#2326;&#2347;, &#2327;&#2354;,
&#2327;&#2341;, &#2350;&#2367;&#2326;, &#2332;&#2341;,
&#2332;&#2366;&#2341;, &#2341;&#2366;&#2341;, &#2342;&#2342;,
&#2342;&#2375;&#2326;, &#2344;, &#2344;&#2375;&#2341;, &#2348;&#2352;,
&#2348;&#2369;&#2306;&#2341;, &#2348;&#2367;&#2341;,
&#2348;&#2367;&#2326;, &#2348;&#2375;&#2354;, &#2350;&#2350;, &#2310;,
&#2310;&#2311;, &#2310;&#2313;, &#2310;&#2327;&#2342;&#2366;,
&#2310;&#2327;&#2360;&#2367;&#2352;
i have tried with the code as followed
import java.io.*;
import java.util.*;
import java.lang.*;
public class UcharRead
{
public static void main(String args[])
{
try
{
String str;
BufferedReader bufReader = new BufferedReader( new
InputStreamReader(new FileInputStream("research_words.txt"), "UTF-8"));
while((str=bufReader.readLine())!=null)
{
System.out.println(str);
}
}
catch(Exception e)
{
}
}
}
getting out put as ???????????????????????? can anyone help me

Phonegap EmailComposer plugin bug

Phonegap EmailComposer plugin bug

I'm getting the following errors (from the EmailComposer phonegap plugin)
when i try to build from Xcode. I'm not familiar with Obj-C so i'm not
sure if this is the result of an error i've made or if it is because the
plugin is out-dated. I'm using the latest version of Phonegap (3?) & Xcode
4.6.3.
EmailComposer.m:132:6: 'release' is unavailable: not available in
automatic reference counting mode
EmailComposer.m:132:6: ARC forbids explicit message send of 'release'
EmailComposer.m:175:21: Cast of Objective-C pointer type 'NSString *' to C
pointer type 'CFStringRef' (aka 'const struct __CFString *') requires a
bridged cast
EmailComposer.m:179:11: Cast of C pointer type 'CFStringRef' (aka 'const
struct __CFString *') to Objective-C pointer type 'NSString *' requires a
bridged cast

DictionaryBase - Get specific item

DictionaryBase - Get specific item

I have a Class that inherits DictionaryBase. The Dictionary is <Object,
DataSources>.
Given all Key, Value pairs, there should only be one CustomClass that has
a property of isPrimary. I want to create a property that returns the
Primary object and I can't seem to find the best way to approach this:
Public Class DataSources
Inherits DictionaryBase
Friend Sub New()
MyBase.New()
End Sub
Public Sub Add(ByVal Key As Object,
ByVal NewDataSource As DataSource)
Dictionary.Add(Key, NewDataSource)
End Sub
Default Public Property Item(ByVal Key As Object) As DataSource
Get
Return CType(Dictionary.Item(Key), DataSource)
End Get
Set(ByVal Value As DataSource)
Dictionary.Item(Key) = Value
End Set
End Property
Public Shadows Function GetEnumerator() As IEnumerator
Return Dictionary.Values.GetEnumerator
End Function
Public Sub Remove(ByVal Key As Object)
Dictionary.Remove(Key)
End Sub
End Class
I'd like to do two things:
1) Prevent 2 isPrimaries. Search the dictionary and throw an error if
isPrimary already exists and we try to insert another.
2) Get the Primary Value for the Dictionary.
I cant' seem to find good examples using DictionaryBase...

Django - logging each view's action

Django - logging each view's action

I'm thinking of creating a log system for my django web application. The
web application is quite comprehensive in its use (covers all aspects of a
business's processes) so I'd like to track every event that happens.
Specifically, I'd like to log every view that runs and not just the "main"
ones and, potentially, log what is happening within the view as its
executed.
While I'm in the "idea" stage of the logging system, I've quickly hit a
few questions that leave me unsure how to proceed. Here are the main
questions I have:
I'm thinking of logging all of the events in the same MySQL database that
the main web app holds its data. The concern I have is bloating the MySQL
database into a massive DB. Also, if the DB crashes or is destroyed
somehow (yes I have backups) I'll loose my log too which blows away any
ability to track down the problem. Do I use a seperate DB or just go with
text files?
How granular do I go? Initially I was thinking of simply logging things
like, "Date - In view myView". However, as I'm thinking about it, it would
be nice to log all the stuff that happens within the view. Doing this
could make the log massive! and would also make my code ugly with so many
log entry lines mixed into the code. This kind of detail:
Date - entered view myView
Date - in view myView, retrieved object myObject from the DB
Date - in view myView, setting myObject field myField to myNewValue
Date - leaving myView
Those are my main thoughts at this point. Any advice on this front?
Thanks

I want to eval concatenated symbols in ruby

I want to eval concatenated symbols in ruby

I'm trying to find a way to concatenate module and class names to give me
more info. In cases where I can Enumerate things like constants, I want to
tack on to them and eval them somewhat. I've seen something like this
before but just don't remember where.
Errno.constants.sort.each do |name|
string = '#{Errno}::#{name}::#{Errno}'
puts eval("\"" + string + "\"")
end
How might I get something like this to work so that I don't have to
individually list the full name such as
puts Errno::E2BIG::Errno

How to reload the vaadin table?

How to reload the vaadin table?

Am new to vaadin. I created a table in a vertical layout which is
connected to a postgres database. I have a button on the top of a vertical
layout which is used to insert a new record in the table through a form in
a sub window. When i click on save, the record is updated in the database.
But the table still shows the old view. Its not getting updated. How do i
solve it??

CakePHP Associations Error: Call to a member function find() on a non-object

CakePHP Associations Error: Call to a member function find() on a non-object

I think I have a quiet simple error but i can't solve it... I try to
associate two tables:

projects hasMany keywords
keywords belogsTo projects
My code:
<?php
class KeywordsController extends AppController{
public function add(){
$projects = $this->Keyword->Project->find('list'); //***here is
the error***
//pr($projects);
if ($this->request->is('post')) {
$this->Keyword->save($this->request->data);
$this->redirect('/keywords');
}
}
}



<?php
class ProjectsController extends AppController{
public function add(){
if ($this->request->is('post')) {
$this->Project->save($this->request->data);
$this->redirect('/projects');
}
}
}



<?php
class Project extends AppModel{
public $hasMany = 'Keyword';
}



<?php
class Keyword extends AppModel{
public $belongsTo = 'Project';
}
Error message:
Error: Call to a member function find() on a non-object
File: /Users/me/Localhost/cakephp/app/Controller/KeywordsController.php
Line: 7

Monday, 9 September 2013

Html.ActionLink(linkText, actionname, actioncontroller, routevalues, htmlAttributes) renders wrong HTML

Html.ActionLink(linkText, actionname, actioncontroller, routevalues,
htmlAttributes) renders wrong HTML

i have the following Html.ActionLink call:
@Html.ActionLink(linkText: "dothis", actionName: "Index", controllerName:
"SelectActioncontroller", routeValues: new { actionController =
"dothisController", actionName = "dothis", actionText = "dothis" },
htmlAttributes: null)
But as result i get:
<a
href="/SelectActioncontroller?actionController=dothisController&actionName=dothis&actionText=dothis">dothis</a>
What is wrong, by all other answers I read sofar this should result in:
<a
href="/SelectActioncontroller/dothis?actionController=dothisController&actionName=dothis&actionText=dothis">dothis</a>
What do I miss?
I'm using VS2012 .net4.0 mvc4

PHP Time and JavaScript Time

PHP Time and JavaScript Time

I have a bit of a situation here. I have a simple task which is to allow a
user to do something on a web app in timed intervals. Say, I did the
action now, I should only be able to perform the action again after 10
min.
Server time and client time are in different timezones. I keep server time
in my DB. I would appreciate help in converting server time to the time
zone of the client machine so that I can do the check in the front end
instead of another extra trip to the server.

How to get the value of a Controller variable in rails console

How to get the value of a Controller variable in rails console

I set a variable inside a Controller and I'm trying to just do something
as simple as read that variable in the rails console.
I thought about just doing @test in the console which is the name of the
variable. but it shows as >null. When I do puts under where I set the
variable it traces out the correct value in my terminal window.
Any ideas what I need to do to get to this variable via the console.
I tried putting the name of the controller first and then .variable but
that threw an error
I can see what's inside my models by just using the model name and some
attributes like .first and .last

Create CSS Hover Image in Wordpress

Create CSS Hover Image in Wordpress

I have a site here...
When you look at this page, you'll see an image of a comment bubble...
Here's the CSS attached to that comment bubble...
#content .postmetadata .comments {
background-image:url(images/comment.png);
background-repeat:no-repeat;
position:absolute;
bottom:8px;
height:25px;
*bottom:18px;
margin-left:8px;
}
What I'm trying to do is, by default have the image that you see there...
(it's black with about 50% opacity).
When you hover over it, the image turns red, but keeps the background
transparent, so it's only the bubble that changes color.
I have the red image ready, or is that something I can do with CSS?
Does that make sense?

JQUERY not working with JSF

JQUERY not working with JSF

I'm using JSF 2.0 and JQUERY 1.9. I'm trying to add an attribute to a
component, but when the page is rendered, the attribute is not added.
Here is the jsf code for the component.
<h:form id="mainForm">
<h:inputText id="field" value="#{bean.value}"/>
</h:form>
and the jquery is like this:
<script type="text/javascript">
// <![CDATA[
window.onload=function(){
$("#mainForm:field").attr("placeholder","Fill me");
}
// <![CDATA[
</script>
This is being rendered like this:
<input id="mainForm:field" name="mainForm:field" type="text" value="">
Any idea on where am I wrong? Thanks!

It is possible to delete other Mac applications in Sandbox mode

It is possible to delete other Mac applications in Sandbox mode

I have tried to delete other Mac applications without sandbox mode for
some applications and it works fine. But i couldn't delete any Mac
applications from the system with the sandbox mode ?????

alternative to std::advance which doesn't modify the input

alternative to std::advance which doesn't modify the input

Cannot manage to find it, hope somebody can help. There is a function in
the std library which gets called upon an iterator and an unsigned number,
which returns the iterator pointing to the object to which the input
iterator would have pointed if advance would have been called onto it.
Which function am I referring to? I'm sure it exists!

Sunday, 8 September 2013

What is the function 'selectifr' from Ox in Matlab

What is the function 'selectifr' from Ox in Matlab

I was wondering if somebody could tell me which is the equivalent of the
function selectifr from Ox in Matlab ?
for(i = 1; i <= sizeof(vdates); i = i+1)
daily_file = selectifr([bid,ask], dates .== vdates[i]);
if empty continue
save daily_file contract_name + "_" + sprint(vdates[i]) ;
How do I translate this program into Matlab?

Return a result set as output param in a sybase stored proc

Return a result set as output param in a sybase stored proc

I have a stored procedure, in which I want to simply store result of a
select statement in an output parameter and return that , how can i do
that.
I would appreciate if you give me the right syntax of it, since i am new
to DB and Sybase specially, that's why i am just giving u a pseudo code
for that..
/pseudo code
create my_proc(in_param i,out_param o1,out_param o2){
.....
.....
if(xyz=true){
o1 = select * from emplyees
}
return o1,o2
}

Plot Smith Chart in R

Plot Smith Chart in R

I wrote some code in R to generate a Smith Chart using only base graphic.
I am satisfied with the plot itself, but I would like to improve the code.
In particular I am not sure about the 4 lapply calls, and I guess there
should be a more direct way to draw a group of lines in base R.
Below is the code I am using, and the plot it generates. I am new to
stackoverflow, so please let me know if I should include more comments or
provide additional information.
#!/usr/bin/rscript --vanilla
filename='smith_chart.pdf'
pdf(filename, 6, 6)
# given z = r + jx, calculates complex number gamma = (z-1)/(z+1)
mapping <- function(r, x) {z <- complex(real = r, imaginary = x);
(z-1)/(z+1)}
complex_line <- function(a) {lines(Re(a), Im(a), lwd = 0.5)}
plot.new()
plot.window(c(-1, 1), c(-1, 1), asp = 1)
dd <- c(seq(-100, 100, 1), seq(-10, 10, 0.1), seq(-2, 2, 0.02))
dd <- round(dd, digits = 2)
dd <- sort(unique(dd))
smith_grid <- function (value, step) {
# applies conformal mapping to lines having contast r
r_grid <- lapply(seq(0, value, step),
FUN = function(r){mapping(r, dd[dd >= -value & dd <= value])})
# applies conformal mapping to lines having contast x
x_grid <- lapply(seq(-value, value, step),
FUN = function(x){mapping(dd[dd >= 0 & dd <= value], x)})
lapply(r_grid, FUN=complex_line)
lapply(x_grid, FUN=complex_line)
}
smith_grid(50, 10)
smith_grid(10, 1)
smith_grid(2, 0.2)
smith_grid(0.6, 0.1)
dev.off()

Setting up Tor Bridge on Ubuntu VPS through SSH

Setting up Tor Bridge on Ubuntu VPS through SSH

I have a currently unused budget VPS, and I'd like to contribute to the
Tor Project by making it a bridge node in the network. However, I'm having
trouble finding a clear and reliable guide outlining how to do this
through the command line. Does anyone know of one? If one doesn't exist,
would anyone like to outline the process?

Loop over JTextPane and find certain ID

Loop over JTextPane and find certain ID

Im trying to loop over a JTextPane and find a element which has a certain
ID. I then want to be able to update the element with new text.
What i got so far:
Element root = ta.getDocument().getDefaultRootElement();
BranchElement current = (BranchElement) root.getElement(0);
if (current != null) {
Enumeration children = current.children();
while (children.hasMoreElements()) {
Element child = (Element) children.nextElement();
AttributeSet attrSet = child.getAttributes();
System.out.println(child.getAttributes());
//ImageIcon icon = (ImageIcon)
StyleConstants.getIcon(attrSet);
//System.err.println(icon.getDescription());
}
}
This is how my insert looks like:
try {
kit.insertHTML(doc, doc.getLength(), "<div style=\"padding-top:10px;
padding-bottom:10px;\" id=\"X\">" + "<div>" + from + " at
" + tid + ":</div>" + "<div style=\"padding-top:4px;" +
align + "\">" + msg + "</div>" + "</div>", 0, 0, null);
} catch (BadLocationException ex) {
Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
}
Any ideas how i can find my div element based on ID? And how to update it
with new text? (the div i want to update is the inner one with msg inside

Rails create and new creating different objects

Rails create and new creating different objects

I have a model Project and a model Test. Project has many Tests.
My tests_controller has:
def new
@project = Project.find(params[:project_id])
@test = @project.tests.new
end
def create
@project = Project.find(params[:project_id])
@test = @project.tests.create(test_params)
end
So in my new.html.erb, I present a form, and when submit is pressed,
create is called. I'm confused however because what is apparently
happening is that I am creating one test in new and a whole different test
in create. What is the correct paradigm for what I am trying to achieve?

windows 7 clean and pure registry file - where to obtain?

windows 7 clean and pure registry file - where to obtain?

where can I obtain clean and pure windows 7 registry file?
by pure and clean I mean registry file that does not contain any records
from an other software than windows
...obviously I do not want to reinstall windows ...my goal is to compare
the registry in the current state with the original clean registry...in
order to identify all changes done to it since installation
Anybody?

Radgrid get cell value when in edit mode

Radgrid get cell value when in edit mode

I have a radgrid and a textbox where I would like to show the value of a
column when the record is in edit mode. The value I would like to get is
contained in a readonly column and it is listed in DataKeyNames, it is
basically the transaction id given by the SQL database when the item is
created.
<MasterTableView CommandItemDisplay="TopAndBottom"
DataSourceID="SqlDataSource1" AutoGenerateColumns="False"
DataKeyNames="TransazioneID" AllowFilteringByColumn="True">
I cannot get it out.
protected void RadGrid1_ItemDataBound(object sender, GridItemEventArgs e)
{
if (e.Item is GridEditableItem && e.Item.IsInEditMode)
{
GridEditableItem item = e.Item as GridEditableItem;
string str = item["TransazioneID"].Text;
TextBox1.Text = str;
The code doesn't give me errors but shows nothing. How can I get the value
of "TransactionID" for the record in edit mode?

Saturday, 7 September 2013

Role of placeholder in Boost::bind in the following example

Role of placeholder in Boost::bind in the following example

There are numerous example on SO regarding the use of placeholders however
I am still a little bit confused and would appreciate it if someone could
explain the difference between the following two statements
void SomeMethod(int a)
{
std::cout << "Parameter pass " << a << "\n";
}
Statement 1 : boost::bind(&SomeMethod,_1)(12);
Statement 2 : boost::bind(&SomeMethod,12)();
I believe I understand statement 1 which is chaining. The output of
boost::bind(&SomeMethod,_1) gets to have a parameter of 12 attached to it.
However I have difficulty understanding whats happening in statement 2. If
a parameter could be passed directly using boost::bind (as in statement 2)
then why the need of a placeholder ?

Adding "Comments" to my site

Adding "Comments" to my site

I tried to follow the instructions to add the comments to my website, but
I'm cant seem to get it right. I signed up and got the code (s). Pasted
them in an HTML box, but noting shows on my page. The community center
does not seem to answer that particular question for me (obviously I'm a
little tech challenged). Can someone help? my site: www.pinctv.com Thanks

Paypal Sandbox IPN no Repsonse

Paypal Sandbox IPN no Repsonse

I am using Zend Framework 2 as my listener for a Paypal payment. My
listener is triggered when the payment is made in the sandbox environment,
but when i generate the request to reply to Paypal in order to get a
VERIFIED or INVALID respone i do not get a response. There is nothing
coming up in the web server logs, no errors and no exception is thrown.
Have tried both the dispatch and Send methods
Is there any way i can see if the request is sent to Paypal sandbox?
Anywhere in the sandbox i can see this? Or is there anyway i can see the
response come back. Am using Amazon WS but i dont think its getting
blocked as the listener is initially triggered.
Many thanks
Code for IPN listenter is below: $request = $this->getRequest();
// Follow Paypal IPN protocol
// First send back to PayPal received request
$request = new Request();
$request->setMethod(Request::METHOD_POST);
$client = new Client();
$client->setRequest($request);
$client->setUri('https://www.sandbox.paypal.com/cgi-bin/webscr?cmd=_notify-validate');
$postArray = $request->getPost()->getArrayCopy();
$client->setParameterPost($postArray);
$requestHeaders = $client->getRequest()->getHeaders();
try {
$response = $client->send();
//$response = $client->dispatch($request);
} catch (Exception $e) {
$logger->info("Exception:");
$logger->info($e->getMessage());
}