How to limit negative voltage on uC input pin – electronics.stackexchange.com
I'm trying to design a pulse induction metal detector to increase my EE
skills a little bit. I started to sketch out the transmitting stage, which
is just a MOSFET that switches current through a …
Monday, 30 September 2013
What does this ${@:2} mean in shell scripting unix.stackexchange.com
What does this ${@:2} mean in shell scripting – unix.stackexchange.com
I see this in a shell script. variable=${@:2} What is it doing?
I see this in a shell script. variable=${@:2} What is it doing?
DataTable Webmethod only works with thread.sleep
DataTable Webmethod only works with thread.sleep
I'm trying to serialize a DataTable return to use on a WebMethod its just
simple like that:
DataTable dtResult = Occurrences.Search(....);
The thing is, if I, immediatly type
return dtResult.Rows.Count.ToString();
It will return "0".
But if i add just after the first line:
System.Threading.Thread.Sleep(2000);
Everything works fine and the row count is 2.
Since when DataTable fetching is asynchronous?
I'm trying to serialize a DataTable return to use on a WebMethod its just
simple like that:
DataTable dtResult = Occurrences.Search(....);
The thing is, if I, immediatly type
return dtResult.Rows.Count.ToString();
It will return "0".
But if i add just after the first line:
System.Threading.Thread.Sleep(2000);
Everything works fine and the row count is 2.
Since when DataTable fetching is asynchronous?
collect acceleration data for 10 seconds using AsyncTask
collect acceleration data for 10 seconds using AsyncTask
I have searched for a clear answer for this but I have not found one. The
Android application will start the AsyncTask to collect accelerometer data
once a button is pressed. I want the AsyncTask to stop after 10 seconds.
Basically trying to save a 10 second chunk of acceleration data to be
process by another part of my application. Is there a way to control the
time the AsyncTask runs for?
Thank you.
I have searched for a clear answer for this but I have not found one. The
Android application will start the AsyncTask to collect accelerometer data
once a button is pressed. I want the AsyncTask to stop after 10 seconds.
Basically trying to save a 10 second chunk of acceleration data to be
process by another part of my application. Is there a way to control the
time the AsyncTask runs for?
Thank you.
Sunday, 29 September 2013
How to read '\0' from a text file?
How to read '\0' from a text file?
My text file contain '\0' characters. Thus, It is making problem. And i
need find out those files which contains '\0' character. Readlines() and
read() did not work as it marks them as terminating lines.
My text file contain '\0' characters. Thus, It is making problem. And i
need find out those files which contains '\0' character. Readlines() and
read() did not work as it marks them as terminating lines.
How to get file extension in Java?
How to get file extension in Java?
I want to get all files with a specific extension. The following code is
working fine.
String extension = "";
int i = fileName.lastIndexOf('.');
if (i > 0) {
extension = fileName.substring(i+1);
}
But, could there be any better way to do?
I want to get all files with a specific extension. The following code is
working fine.
String extension = "";
int i = fileName.lastIndexOf('.');
if (i > 0) {
extension = fileName.substring(i+1);
}
But, could there be any better way to do?
Javascript code for identicon
Javascript code for identicon
I have tried to find a good javascript idencicon generator but found none.
Can anyone give me a link/ code of a good javascript identicon generator?
I have tried to find a good javascript idencicon generator but found none.
Can anyone give me a link/ code of a good javascript identicon generator?
Fetch a page with cookies using Python requests library
Fetch a page with cookies using Python requests library
I'm just studying the requests
library(http://docs.python-requests.org/en/latest/), and got a problem on
how to fetch a page with cookies using requests.
for example:
url2= 'https://passport.baidu.com'
parsedCookies={'PTOKEN': '412f...', 'BDUSS': 'hnN2...', ...} #Sorry that
the cookies value is replaced by ... for instance of privacy
req = requests.get(url2, cookies=parsedCookies)
text=req.text.encode('utf-8','ignore')
f=open('before.html','w')
f.write(text)
f.close()
req.close()
when I use the codes above to fetch the page, it redirects to the login
page, also I see the login page in 'before.html', it refers that actually
I haven't logged in successfully.
But if I use URLlib2 to fetch the page, it works properly as expected.
parsedCookies="PTOKEN=412f...;BDUSS=hnN2...;..." #Different format but
same content with the aboved cookies
req = urllib2.Request(url2)
req.add_header('Cookie', parsedCookies)
ret = urllib2.urlopen(req)
f=open('before_urllib2.html','w')
f.write(ret.read())
f.close()
ret.close()
When I use these codes, it saves the login page in before_urllib2.html.
--
Are there any mistakes in my code?
I'm just studying the requests
library(http://docs.python-requests.org/en/latest/), and got a problem on
how to fetch a page with cookies using requests.
for example:
url2= 'https://passport.baidu.com'
parsedCookies={'PTOKEN': '412f...', 'BDUSS': 'hnN2...', ...} #Sorry that
the cookies value is replaced by ... for instance of privacy
req = requests.get(url2, cookies=parsedCookies)
text=req.text.encode('utf-8','ignore')
f=open('before.html','w')
f.write(text)
f.close()
req.close()
when I use the codes above to fetch the page, it redirects to the login
page, also I see the login page in 'before.html', it refers that actually
I haven't logged in successfully.
But if I use URLlib2 to fetch the page, it works properly as expected.
parsedCookies="PTOKEN=412f...;BDUSS=hnN2...;..." #Different format but
same content with the aboved cookies
req = urllib2.Request(url2)
req.add_header('Cookie', parsedCookies)
ret = urllib2.urlopen(req)
f=open('before_urllib2.html','w')
f.write(ret.read())
f.close()
ret.close()
When I use these codes, it saves the login page in before_urllib2.html.
--
Are there any mistakes in my code?
Saturday, 28 September 2013
Is there a way to frame a specific page element?
Is there a way to frame a specific page element?
So, I'm working on a web page, and I want to be able to let users give
feedback using google moderator. In order to help the user experience, I
want there to still be the logo and navigator bar across the top of the
page. The way I have it set up now is with frames. I have one frame on top
containing the logo and navigator bar, and the bottom frame being the
google moderator page. This is effective, but I would prefer it if there
wasn't that pesky grey navigation bar (the one with the links to search,
use youtube, etc.). I was poking around with the source-code and found
that if one where to go to
http://www.google.com/moderator/#16/e=1fe6a2/html/body/div[1]
you would have exclusively the navigation bar. Is there a way to link to
just the body? If not, is there a way to make a frame that excludes a
specific page element? If none of those would work, is there a way to crop
the top off? Any of the above options would be preferable over the current
layout. Any help is much appreciated. Thanks!
So, I'm working on a web page, and I want to be able to let users give
feedback using google moderator. In order to help the user experience, I
want there to still be the logo and navigator bar across the top of the
page. The way I have it set up now is with frames. I have one frame on top
containing the logo and navigator bar, and the bottom frame being the
google moderator page. This is effective, but I would prefer it if there
wasn't that pesky grey navigation bar (the one with the links to search,
use youtube, etc.). I was poking around with the source-code and found
that if one where to go to
http://www.google.com/moderator/#16/e=1fe6a2/html/body/div[1]
you would have exclusively the navigation bar. Is there a way to link to
just the body? If not, is there a way to make a frame that excludes a
specific page element? If none of those would work, is there a way to crop
the top off? Any of the above options would be preferable over the current
layout. Any help is much appreciated. Thanks!
save value of variable in function till the next time function calls
save value of variable in function till the next time function calls
I need some function or solution to save the value of variable in function
until the next call of function without connecting to MySQL.
function test($price){
if(isset($lastPrice)){
if($lastPrice>$price){
return true;
}
$lastPrice = $price;
}else{
$lastPrice = $price;
returne false;
}
}
$prices= array ( '1' => '2000',
'2' => '2100',
'3' => '2100'
);
foreach($prices as $key = > $price){
if($this->test($price)){
echo 'got expensive';
}
}
In this code i need $lastPrice to be save till the next time that test()
get call in foreach,...
I need some function or solution to save the value of variable in function
until the next call of function without connecting to MySQL.
function test($price){
if(isset($lastPrice)){
if($lastPrice>$price){
return true;
}
$lastPrice = $price;
}else{
$lastPrice = $price;
returne false;
}
}
$prices= array ( '1' => '2000',
'2' => '2100',
'3' => '2100'
);
foreach($prices as $key = > $price){
if($this->test($price)){
echo 'got expensive';
}
}
In this code i need $lastPrice to be save till the next time that test()
get call in foreach,...
Multiplayer Flash Game with Java Server problems
Multiplayer Flash Game with Java Server problems
Alright, basically I've been trying to find out how to set up a
multiplayer flash game, recently I have concluded to code my own server
using Java. I have finally managed to do so after hours of trying and I
have bumped into a snag. Here is my server & client code.
**Server**
import java.net.*;
import java.io.*;
public class ServerFlash
{
public static void main(String[] args) throws IOException
{
ServerSocket serverSocket = null;
Socket connection = new Socket();
InputStream in = null;
boolean listening = true;
try
{
serverSocket = new ServerSocket(14804);
System.err.println("The server is now bound to port.");
}
catch (IOException e)
{
System.err.println("Could not bind server to port.");
System.exit(-1);
}
while (listening)
{
connection = serverSocket.accept();
if(connection!=null)
{
System.err.println("Connection to client has been
established.");
in = connection.getInputStream();
listening = false;
}
}
while (!listening)
{
int data = in.read();
if(data!=-1)
{
System.err.println(data);
}
}
}
}
**Client**
var server = new Socket();
server.connect("[insertmyip]",14804);
server.addEventListener(Event.CONNECT, onConnect);
server.addEventListener(Event.CLOSE, onClose);
server.addEventListener(IOErrorEvent.IO_ERROR, onError);
server.addEventListener(ProgressEvent.SOCKET_DATA, onResponse);
server.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onSecError);
function onConnect(e:Event)
{
trace("Connection Established.");
}
function onClose(e:Event)
{
trace("Socket has been Close.");
}
function onError(e:Event)
{
trace("An Error has occured." + e);
}
function onResponse(e:Event)
{
trace("Responce has been recieved.");
}
function onSecError(e:Event)
{
trace("A SecError has occured.");
}
When I launch the server everything is okay. However when I launch the
client, it successfully connects to the server, but all of a sudden the
server receives data from the client (if you read the code the server
reads incoming data and displays it) and displays around 15 lines of code
and it does not accept any new data from the client. HOWEVER this only
happens when the client is launched from a website (or a folder) BUT it
works normally when I open the client as a test in Adobe Flash Pro.
If you require files and hand them over.
Alright, basically I've been trying to find out how to set up a
multiplayer flash game, recently I have concluded to code my own server
using Java. I have finally managed to do so after hours of trying and I
have bumped into a snag. Here is my server & client code.
**Server**
import java.net.*;
import java.io.*;
public class ServerFlash
{
public static void main(String[] args) throws IOException
{
ServerSocket serverSocket = null;
Socket connection = new Socket();
InputStream in = null;
boolean listening = true;
try
{
serverSocket = new ServerSocket(14804);
System.err.println("The server is now bound to port.");
}
catch (IOException e)
{
System.err.println("Could not bind server to port.");
System.exit(-1);
}
while (listening)
{
connection = serverSocket.accept();
if(connection!=null)
{
System.err.println("Connection to client has been
established.");
in = connection.getInputStream();
listening = false;
}
}
while (!listening)
{
int data = in.read();
if(data!=-1)
{
System.err.println(data);
}
}
}
}
**Client**
var server = new Socket();
server.connect("[insertmyip]",14804);
server.addEventListener(Event.CONNECT, onConnect);
server.addEventListener(Event.CLOSE, onClose);
server.addEventListener(IOErrorEvent.IO_ERROR, onError);
server.addEventListener(ProgressEvent.SOCKET_DATA, onResponse);
server.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onSecError);
function onConnect(e:Event)
{
trace("Connection Established.");
}
function onClose(e:Event)
{
trace("Socket has been Close.");
}
function onError(e:Event)
{
trace("An Error has occured." + e);
}
function onResponse(e:Event)
{
trace("Responce has been recieved.");
}
function onSecError(e:Event)
{
trace("A SecError has occured.");
}
When I launch the server everything is okay. However when I launch the
client, it successfully connects to the server, but all of a sudden the
server receives data from the client (if you read the code the server
reads incoming data and displays it) and displays around 15 lines of code
and it does not accept any new data from the client. HOWEVER this only
happens when the client is launched from a website (or a folder) BUT it
works normally when I open the client as a test in Adobe Flash Pro.
If you require files and hand them over.
using a javascript variable to refer to an element with id containing the variable
using a javascript variable to refer to an element with id containing the
variable
HTML In my html I have an element with id ="check1"
<span id="check1"></span>
JAVASCRPIT I have a variable a='1', which is coming from somewhere else.
Now, I want the inner HTML of span element to be "correct" with the help
of reference to its id, and using 'a'.
var a = 1;
$.(#**checka**).innerHTML="correct"
How to write the id ??
variable
HTML In my html I have an element with id ="check1"
<span id="check1"></span>
JAVASCRPIT I have a variable a='1', which is coming from somewhere else.
Now, I want the inner HTML of span element to be "correct" with the help
of reference to its id, and using 'a'.
var a = 1;
$.(#**checka**).innerHTML="correct"
How to write the id ??
Friday, 27 September 2013
Copy command line arg to a variable C
Copy command line arg to a variable C
How can I copy a command line arg to a variable in c? If was to do the
following.
myprog "Hello, world!"
I want to store the value of the parameter in a char variable. Not sure if
I am going in the right direction here.
Assuming only 1 parameter will be passed in always.
int main (int argc, char *argv[]){
int len;
len=strlen(argv[1]);
char *array;
array= malloc((len +1) * sizeof(char));
int i;
for(i=0;i<=len;i++){
// This does not work... am a little lost
array[i]=*(argv+1)[i];
}
...
}
Can someone point me in the right direction.
How can I copy a command line arg to a variable in c? If was to do the
following.
myprog "Hello, world!"
I want to store the value of the parameter in a char variable. Not sure if
I am going in the right direction here.
Assuming only 1 parameter will be passed in always.
int main (int argc, char *argv[]){
int len;
len=strlen(argv[1]);
char *array;
array= malloc((len +1) * sizeof(char));
int i;
for(i=0;i<=len;i++){
// This does not work... am a little lost
array[i]=*(argv+1)[i];
}
...
}
Can someone point me in the right direction.
Can JaxRsController access jax-rs resources that are in my custom grails plugin?
Can JaxRsController access jax-rs resources that are in my custom grails
plugin?
I'm using Grails 2.2 and the JSR 311 jax-rs plugin.
I've created a custom Grails plugin (call it MyPlugin) using jax-rs
resources, and installed it in another Grails application (call it
MyApplication), which is also built around jax-rs.
I am having issues reaching any of the MyPlugin resources from
MyApplication - it seems like the JaxRsController is not aware of the
resources embedded in MyPlugin. I seem to recall reading that it only
searches 'MyApplication/grails-app/resources' for jax-rs resources, which
would explain it.
Is there a way to make the JaxRsController aware of MyPlugin's jax-rs
resources? If not, is there a better approach than installing a jax-rs
plugin inside another jax-rs app?
plugin?
I'm using Grails 2.2 and the JSR 311 jax-rs plugin.
I've created a custom Grails plugin (call it MyPlugin) using jax-rs
resources, and installed it in another Grails application (call it
MyApplication), which is also built around jax-rs.
I am having issues reaching any of the MyPlugin resources from
MyApplication - it seems like the JaxRsController is not aware of the
resources embedded in MyPlugin. I seem to recall reading that it only
searches 'MyApplication/grails-app/resources' for jax-rs resources, which
would explain it.
Is there a way to make the JaxRsController aware of MyPlugin's jax-rs
resources? If not, is there a better approach than installing a jax-rs
plugin inside another jax-rs app?
How to force the browser to cache a page .html?
How to force the browser to cache a page .html?
Someone know how to force a page cache in the browser? I need to reload a
page several times, and the browser isn't caching the page!
Someone know how to force a page cache in the browser? I need to reload a
page several times, and the browser isn't caching the page!
soap ui call for .net soap service success but fails with http 500 in ksoap2 android
soap ui call for .net soap service success but fails with http 500 in
ksoap2 android
this is the service method
SOAPAction: "http://tempuri.org/LogInUser"
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<LogInUser xmlns="http://tempuri.org/">
<us>
<UserName>string</UserName>
<Password>string</Password>
<CityName>string</CityName>
<DistrictOneName>string</DistrictOneName>
<DistrictTwoName>string</DistrictTwoName>
<DistrictThreeName>string</DistrictThreeName>
<BloodType>string</BloodType>
<Phone>string</Phone>
<Name>string</Name>
<Surname>string</Surname>
</us>
</LogInUser>
</soap:Body>
</soap:Envelope>
this is the how I call it in android that fails with IOException and HTTP
500 error yet,
SoapObject request = new SoapObject(NAMESPACE, METHOD);
SoapObject user = new SoapObject(NAMESPACE, "us");
user.addProperty("UserName", us.UserName);
user.addProperty("Password", us.Password);
user.addProperty("CityName", "?");
user.addProperty("DistrictOneName","?");
user.addProperty("DistrictTwoName","?");
user.addProperty("DistrictThreeName", "?");
user.addProperty("BloodType", "?");
user.addProperty("Phone", "?");
user.addProperty("Name", "?");
user.addProperty("Surname", "?");
request.addSoapObject(user);
Log.d(TAG, request.toString());
SoapSerializationEnvelope envelope = new
SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransportSE transport = new HttpTransportSE(URL);
transport.call(SOAP_ACTION, envelope);
I have done well in soap ui call.
ksoap2 android
this is the service method
SOAPAction: "http://tempuri.org/LogInUser"
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<LogInUser xmlns="http://tempuri.org/">
<us>
<UserName>string</UserName>
<Password>string</Password>
<CityName>string</CityName>
<DistrictOneName>string</DistrictOneName>
<DistrictTwoName>string</DistrictTwoName>
<DistrictThreeName>string</DistrictThreeName>
<BloodType>string</BloodType>
<Phone>string</Phone>
<Name>string</Name>
<Surname>string</Surname>
</us>
</LogInUser>
</soap:Body>
</soap:Envelope>
this is the how I call it in android that fails with IOException and HTTP
500 error yet,
SoapObject request = new SoapObject(NAMESPACE, METHOD);
SoapObject user = new SoapObject(NAMESPACE, "us");
user.addProperty("UserName", us.UserName);
user.addProperty("Password", us.Password);
user.addProperty("CityName", "?");
user.addProperty("DistrictOneName","?");
user.addProperty("DistrictTwoName","?");
user.addProperty("DistrictThreeName", "?");
user.addProperty("BloodType", "?");
user.addProperty("Phone", "?");
user.addProperty("Name", "?");
user.addProperty("Surname", "?");
request.addSoapObject(user);
Log.d(TAG, request.toString());
SoapSerializationEnvelope envelope = new
SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransportSE transport = new HttpTransportSE(URL);
transport.call(SOAP_ACTION, envelope);
I have done well in soap ui call.
Wordpress Load more posts by ajax not working
Wordpress Load more posts by ajax not working
i need to get the wordpress posts while click the load more button or
something else, so i have followed the tutorial by Here
<?php
/*
Template Name: Additional Posts
*/
$offset = htmlspecialchars(trim($_GET['offset']));
if ($offset == '') {
$offset = 5;
}
$args = 'post_type=event&posts_per_page=3&offset=$offset';
$my_query = new WP_Query($args);
if ( $my_query->have_posts() ) {
while ($my_query->have_posts()) : $my_query->the_post();
$event_id = get_post_meta( get_the_ID(), '_event_id', true );
$location_id = get_post_meta( get_the_ID(),
'_location_id', true );
$custom_fields = get_post_custom(get_the_ID());
global $wpdb;
$em_states = $wpdb->get_results("SELECT *from
".EM_LOCATIONS_TABLE." WHERE location_id = '$location_id'
");
$em_ticket_price = $wpdb->get_results("SELECT *from
".EM_TICKETS_TABLE." WHERE event_id = '$event_id' ");
?>
<div class="filter-box clearfix post">
<div class="row-fluid">
<div class="span4"><?php echo
get_the_post_thumbnail(get_the_ID(),
array(269,168) ); ?> </div>
<div class="span5">
<h5><span class="switch_rest"><?php echo
$em_states[0]->location_town;?> -</span> <?php
the_title(); ?></h5>
<ul class="clearfix">
<li><i class="icon-time pad-rht"></i><?php
$star_time = get_post_meta( get_the_ID(),
'_start_ts', true ); echo date('g:i:s a
',$star_time);?>-<?php $end_time =
get_post_meta( get_the_ID(), '_end_ts', true
); echo date('g:i:s a ',$end_time); ?> </li>
<li> <i class="icon-folder-open
pad-rht"></i><?php
$terms = get_the_terms(get_the_ID(),
'event-categories' );
if ($terms && ! is_wp_error($terms)) :
$term_slugs_arr = array();
foreach ($terms as $term) {
$term_slugs_arr[] = $term->name;
}
$terms_slug_str = join( " | ", $term_slugs_arr);
endif;
echo $terms_slug_str;?> </li>
<li><i class="icon-user pad-rht"></i><?php
echo
$custom_fields['wpcf-from'][0]."-".$custom_fields['wpcf-to'][0];
?> </li>
</ul>
</div>
<div class="span3">
<div class="price-box clearfix">
<h4>Price Range</h4>
<ul class="inline clearfix">
<!-- <li>From</li>-->
<li><?php echo
$em_ticket_price[0]->ticket_price;
?>€</li>
<br />
<!-- <li>To </li>
<li>100€</li>-->
</ul>
</div>
</div>
</div>
</div>
</div>
<?php endwhile; } ?>
and my jquery is follows
<script type="text/javascript">
var $j = jQuery.noConflict();
$j(function(){
var offset = 0;
// $j("#postContainer").load("<?php echo get_site_url();
?>/additional-posts/?offset="+offset);
$j("#another").click(function(){
offset = offset+3;
$j("#postContainer")
// .slideUp()
.load("<?php echo get_site_url();
?>/additional-posts/?offset="+offset, function() {
$j(this).slideDown();
});
return false;
});
});
</script>
it is working, but while click the get more link, am again getting the
same posts as well as in the my original loop here in my page , i know
that paged query is missing, or else what am missing ?
i need to get the wordpress posts while click the load more button or
something else, so i have followed the tutorial by Here
<?php
/*
Template Name: Additional Posts
*/
$offset = htmlspecialchars(trim($_GET['offset']));
if ($offset == '') {
$offset = 5;
}
$args = 'post_type=event&posts_per_page=3&offset=$offset';
$my_query = new WP_Query($args);
if ( $my_query->have_posts() ) {
while ($my_query->have_posts()) : $my_query->the_post();
$event_id = get_post_meta( get_the_ID(), '_event_id', true );
$location_id = get_post_meta( get_the_ID(),
'_location_id', true );
$custom_fields = get_post_custom(get_the_ID());
global $wpdb;
$em_states = $wpdb->get_results("SELECT *from
".EM_LOCATIONS_TABLE." WHERE location_id = '$location_id'
");
$em_ticket_price = $wpdb->get_results("SELECT *from
".EM_TICKETS_TABLE." WHERE event_id = '$event_id' ");
?>
<div class="filter-box clearfix post">
<div class="row-fluid">
<div class="span4"><?php echo
get_the_post_thumbnail(get_the_ID(),
array(269,168) ); ?> </div>
<div class="span5">
<h5><span class="switch_rest"><?php echo
$em_states[0]->location_town;?> -</span> <?php
the_title(); ?></h5>
<ul class="clearfix">
<li><i class="icon-time pad-rht"></i><?php
$star_time = get_post_meta( get_the_ID(),
'_start_ts', true ); echo date('g:i:s a
',$star_time);?>-<?php $end_time =
get_post_meta( get_the_ID(), '_end_ts', true
); echo date('g:i:s a ',$end_time); ?> </li>
<li> <i class="icon-folder-open
pad-rht"></i><?php
$terms = get_the_terms(get_the_ID(),
'event-categories' );
if ($terms && ! is_wp_error($terms)) :
$term_slugs_arr = array();
foreach ($terms as $term) {
$term_slugs_arr[] = $term->name;
}
$terms_slug_str = join( " | ", $term_slugs_arr);
endif;
echo $terms_slug_str;?> </li>
<li><i class="icon-user pad-rht"></i><?php
echo
$custom_fields['wpcf-from'][0]."-".$custom_fields['wpcf-to'][0];
?> </li>
</ul>
</div>
<div class="span3">
<div class="price-box clearfix">
<h4>Price Range</h4>
<ul class="inline clearfix">
<!-- <li>From</li>-->
<li><?php echo
$em_ticket_price[0]->ticket_price;
?>€</li>
<br />
<!-- <li>To </li>
<li>100€</li>-->
</ul>
</div>
</div>
</div>
</div>
</div>
<?php endwhile; } ?>
and my jquery is follows
<script type="text/javascript">
var $j = jQuery.noConflict();
$j(function(){
var offset = 0;
// $j("#postContainer").load("<?php echo get_site_url();
?>/additional-posts/?offset="+offset);
$j("#another").click(function(){
offset = offset+3;
$j("#postContainer")
// .slideUp()
.load("<?php echo get_site_url();
?>/additional-posts/?offset="+offset, function() {
$j(this).slideDown();
});
return false;
});
});
</script>
it is working, but while click the get more link, am again getting the
same posts as well as in the my original loop here in my page , i know
that paged query is missing, or else what am missing ?
Thursday, 26 September 2013
PHPMYADMIN not loading in Ubuntu12.04
PHPMYADMIN not loading in Ubuntu12.04
I have installed phyMyAdmin on my Ubuntu 12.04 using sudo apt-get.. I
configured the Apache2 Server as it was given in the Documentation The
problem I am facing is that when i take "http://localhost/phyMyAdmin"
nothing is displayed in the browser,instead it downloads a php file. Why
is this occuring?How can I resolve this problem?
I have installed phyMyAdmin on my Ubuntu 12.04 using sudo apt-get.. I
configured the Apache2 Server as it was given in the Documentation The
problem I am facing is that when i take "http://localhost/phyMyAdmin"
nothing is displayed in the browser,instead it downloads a php file. Why
is this occuring?How can I resolve this problem?
Wednesday, 25 September 2013
SQL Update values in table A with multiple values from table B
SQL Update values in table A with multiple values from table B
I'm trying to update products' prices in table A with prices from table B
based on their product code.
There are about 50,000 products in table A but only 200 in table B. So I
want those 200 prices in table B to replace the prices of those products
in table A by matching the product code in both tables.
Can anyone advise me on how to go about doing it?
I'm trying to update products' prices in table A with prices from table B
based on their product code.
There are about 50,000 products in table A but only 200 in table B. So I
want those 200 prices in table B to replace the prices of those products
in table A by matching the product code in both tables.
Can anyone advise me on how to go about doing it?
Thursday, 19 September 2013
Trouble removing extra hyphens from string in python?
Trouble removing extra hyphens from string in python?
def checkio(line):
list.remove(max("---"))
list.remove(min("--"))
return line
if __name__ == '__main__':
assert checkio('I---like--python') == "I-like-python", 'Example'
$ I am trying to remove the "---" and the "--" from the string I like
python and it does nto seem to be working. Any help?
def checkio(line):
list.remove(max("---"))
list.remove(min("--"))
return line
if __name__ == '__main__':
assert checkio('I---like--python') == "I-like-python", 'Example'
$ I am trying to remove the "---" and the "--" from the string I like
python and it does nto seem to be working. Any help?
Symfony 1 trim all spaces of input fields
Symfony 1 trim all spaces of input fields
I'm running an application with Symfony1/ Doctrine1. Is there a simple way
to trim all spaces either end of single line input fields? I'm using
largely default fields and default admin modules.
I'm running an application with Symfony1/ Doctrine1. Is there a simple way
to trim all spaces either end of single line input fields? I'm using
largely default fields and default admin modules.
Encounter Error for generating Radio button from Model
Encounter Error for generating Radio button from Model
i am trying to generate radio button from model but getting object
reference error. i just can not understand where i am making mistake in
MVC because i am just learning it. here is my full code. please have a
look and tell me where is the mistake. thanks
model class
public class StudentModel
{
[Required(ErrorMessage = "First Name Required")] // textboxes will
show
[Display(Name = "First Name :")]
[StringLength(5, ErrorMessage = "First Name cannot be longer than
5 characters.")]
public string FirstName { get; set; }
[Required(ErrorMessage = "Last Name Required")] // textboxes will
show
[Display(Name = "Last Name :")]
[StringLength(5, ErrorMessage = "Last Name cannot be longer than 5
characters.")]
public string LastName { get; set; }
[Required(ErrorMessage = "Sex Required")]
[Display(Name = "Sex :")]
public int SexID { get; set; }
public List<Sex> Sex { get; set; }
}
public class Sex
{
public string ID { get; set; }
public string Type { get; set; }
}
controller class
public class HomeController : Controller
{
[HttpGet]
public ActionResult Index()
{
ViewBag.Message = "Welcome to ASP.NET MVC!";
var student = new StudentModel
{
FirstName = "Rion",
LastName = "Gomes",
//I think the best way to populate this list is to call a
service here.
Sex = new List<Sex>
{
new Sex{ID="1" , Type = "Male"},
new Sex{ID="2" , Type = "Female"}
}
};
return View();
}
[HttpPost]
public ActionResult Index(StudentModel model)
{
if (ModelState.IsValid)
{
//TODO: Save your model and redirect
}
//Call the same service to initialize your model again (cause
we didn't post the list of sexs)
return View(model);
}
}
view code
@model MvcRadioButton.Models.StudentModel
@Html.BeginForm()
{
<div>
@Html.LabelFor(model => model.FirstName)
@Html.EditorFor(model => model.FirstName)
@Html.ValidationMessageFor(model => model.FirstName)
</div>
<div>
@Html.LabelFor(model => model.LastName)
@Html.EditorFor(model => model.LastName)
@Html.ValidationMessageFor(model => model.LastName)
</div>
@{
foreach (var sex in Model.Sex)
{
<div>
@Html.RadioButtonFor(model => model.Sex, new { id = "sex"
+ sex.ID })
@Html.Label("sex" + sex.ID, sex.Type)
</div>
}
}
<input type="submit" value="Submit" />
}
this line throwing error
foreach (var sex in Model.Sex) saying model null or object reference error
i am trying to generate radio button from model but getting object
reference error. i just can not understand where i am making mistake in
MVC because i am just learning it. here is my full code. please have a
look and tell me where is the mistake. thanks
model class
public class StudentModel
{
[Required(ErrorMessage = "First Name Required")] // textboxes will
show
[Display(Name = "First Name :")]
[StringLength(5, ErrorMessage = "First Name cannot be longer than
5 characters.")]
public string FirstName { get; set; }
[Required(ErrorMessage = "Last Name Required")] // textboxes will
show
[Display(Name = "Last Name :")]
[StringLength(5, ErrorMessage = "Last Name cannot be longer than 5
characters.")]
public string LastName { get; set; }
[Required(ErrorMessage = "Sex Required")]
[Display(Name = "Sex :")]
public int SexID { get; set; }
public List<Sex> Sex { get; set; }
}
public class Sex
{
public string ID { get; set; }
public string Type { get; set; }
}
controller class
public class HomeController : Controller
{
[HttpGet]
public ActionResult Index()
{
ViewBag.Message = "Welcome to ASP.NET MVC!";
var student = new StudentModel
{
FirstName = "Rion",
LastName = "Gomes",
//I think the best way to populate this list is to call a
service here.
Sex = new List<Sex>
{
new Sex{ID="1" , Type = "Male"},
new Sex{ID="2" , Type = "Female"}
}
};
return View();
}
[HttpPost]
public ActionResult Index(StudentModel model)
{
if (ModelState.IsValid)
{
//TODO: Save your model and redirect
}
//Call the same service to initialize your model again (cause
we didn't post the list of sexs)
return View(model);
}
}
view code
@model MvcRadioButton.Models.StudentModel
@Html.BeginForm()
{
<div>
@Html.LabelFor(model => model.FirstName)
@Html.EditorFor(model => model.FirstName)
@Html.ValidationMessageFor(model => model.FirstName)
</div>
<div>
@Html.LabelFor(model => model.LastName)
@Html.EditorFor(model => model.LastName)
@Html.ValidationMessageFor(model => model.LastName)
</div>
@{
foreach (var sex in Model.Sex)
{
<div>
@Html.RadioButtonFor(model => model.Sex, new { id = "sex"
+ sex.ID })
@Html.Label("sex" + sex.ID, sex.Type)
</div>
}
}
<input type="submit" value="Submit" />
}
this line throwing error
foreach (var sex in Model.Sex) saying model null or object reference error
How to initialise a pointer to a pointer when the final address isn't known?
How to initialise a pointer to a pointer when the final address isn't known?
In this example, I'd like to pass a pointer pointer to the future,
not-yet-allocated someObject to a function. (Please don't ask why.)
int main(void) {
functionThatNeedsSomeObject();
SomeClass someObject(0);
}
I'm trying to do that using a pointer to a pointer. This is my attempt:
int main(void) {
SomeClass** ppSomeObject;
functionThatNeedsSomeObject( ppSomeObject);
SomeClass someObject(0);
*ppSomeObject = &someObject;
}
But in my code, ppSomeObject is uninitialized when it is passed. Of course
the second-layer pointer can't point to the object, but how can I make the
first-layer pointer point somewhere that I can change later, when
someObject is created?
Should I do something like this? Even if it works, creating an
intermediate pointer feels unnecessary.
SomeClass* pSomeObject = 0;
SomeClass** ppSomeObject = &pSomeObject
In this example, I'd like to pass a pointer pointer to the future,
not-yet-allocated someObject to a function. (Please don't ask why.)
int main(void) {
functionThatNeedsSomeObject();
SomeClass someObject(0);
}
I'm trying to do that using a pointer to a pointer. This is my attempt:
int main(void) {
SomeClass** ppSomeObject;
functionThatNeedsSomeObject( ppSomeObject);
SomeClass someObject(0);
*ppSomeObject = &someObject;
}
But in my code, ppSomeObject is uninitialized when it is passed. Of course
the second-layer pointer can't point to the object, but how can I make the
first-layer pointer point somewhere that I can change later, when
someObject is created?
Should I do something like this? Even if it works, creating an
intermediate pointer feels unnecessary.
SomeClass* pSomeObject = 0;
SomeClass** ppSomeObject = &pSomeObject
changing the position of the search icon
changing the position of the search icon
I use SearchView in OptionsMenu:
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/action_search"
android:title="Search"
android:icon="@drawable/icon_search"
android:showAsAction="always"
android:actionViewClass="android.widget.SearchView" />
</menu>
In main activity:
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_search, menu);
View inflatedView = getLayoutInflater().inflate(R.layout.arrow,
null);
MenuItem searchItem = menu.findItem(R.id.action_search);
mSearchView = (SearchView) searchItem.getActionView();
setupSearchView(searchItem);
return (super.onCreateOptionsMenu(menu));
}
The search icon located on the right in menu. How to change its position
in my menu? I want that it is located left.
I use SearchView in OptionsMenu:
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/action_search"
android:title="Search"
android:icon="@drawable/icon_search"
android:showAsAction="always"
android:actionViewClass="android.widget.SearchView" />
</menu>
In main activity:
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_search, menu);
View inflatedView = getLayoutInflater().inflate(R.layout.arrow,
null);
MenuItem searchItem = menu.findItem(R.id.action_search);
mSearchView = (SearchView) searchItem.getActionView();
setupSearchView(searchItem);
return (super.onCreateOptionsMenu(menu));
}
The search icon located on the right in menu. How to change its position
in my menu? I want that it is located left.
java.lang.NumberFormatException: For input string: "" when using "2" or "5"
java.lang.NumberFormatException: For input string: "" when using "2" or "5"
I read in a menu choice and typing in any number but 2 & 5 work.
String choice = promptUser(choicePrompt);
try {
outputInfo(String.format("choice=...%s...",choice));
int c = Integer.parseInt(choice);
/* process it */
}catch (NumberFormatException e) {
outputInfo(String.format("choice=%s",choice));
outputInfo(e.toString());
}
public static void outputInfo(String msg)
{
System.out.printf("\t%s\n",msg);
}
Good output:
Enter Option: 1
choice=...1...
Bad Output:
Enter Option: 2
choice=...2...
choice=2
java.lang.NumberFormatException: For input string: ""
Any ideas gratefully received.
Simon
I read in a menu choice and typing in any number but 2 & 5 work.
String choice = promptUser(choicePrompt);
try {
outputInfo(String.format("choice=...%s...",choice));
int c = Integer.parseInt(choice);
/* process it */
}catch (NumberFormatException e) {
outputInfo(String.format("choice=%s",choice));
outputInfo(e.toString());
}
public static void outputInfo(String msg)
{
System.out.printf("\t%s\n",msg);
}
Good output:
Enter Option: 1
choice=...1...
Bad Output:
Enter Option: 2
choice=...2...
choice=2
java.lang.NumberFormatException: For input string: ""
Any ideas gratefully received.
Simon
Apache redirecting absolute url-s
Apache redirecting absolute url-s
I want Apache to redirect links in the page like <a href =
http://site.com/something> to <a href = http://site1.com/something>.
It works with relative URLs using RedirectMatch, but not for absolute.
I want Apache to redirect links in the page like <a href =
http://site.com/something> to <a href = http://site1.com/something>.
It works with relative URLs using RedirectMatch, but not for absolute.
Wednesday, 18 September 2013
How does indirect eval work
How does indirect eval work
I saw on the Internet that people using following construction to get
Global object
(1,eval)(this)
or this
(0||eval)(this)
Could you explain how exactly does it work and the benefit over window,
top, etc.?
I saw on the Internet that people using following construction to get
Global object
(1,eval)(this)
or this
(0||eval)(this)
Could you explain how exactly does it work and the benefit over window,
top, etc.?
Remove Substring in String C#
Remove Substring in String C#
I have some Urls string, such as:
http://www.testproject.com/tokyo/4
http://www.testproject.com/india/11
http://www.testproject.com/singapore/819
How to get the number ("4". "11", "819") in the end of Url?
I have some Urls string, such as:
http://www.testproject.com/tokyo/4
http://www.testproject.com/india/11
http://www.testproject.com/singapore/819
How to get the number ("4". "11", "819") in the end of Url?
How retrieve video tags from a youtube video in API v3 without use OAuth?
How retrieve video tags from a youtube video in API v3 without use OAuth?
I need get tags for filtering videos from a specific channel. Its
implemented in a audiovisual studio web as portfolio. Obviously I want
that this process be transparent for users. Looks impossible achieve what
I need without a OAuth authentication process...I already have tried it in
some ways, failing whole times. Thanks
I need get tags for filtering videos from a specific channel. Its
implemented in a audiovisual studio web as portfolio. Obviously I want
that this process be transparent for users. Looks impossible achieve what
I need without a OAuth authentication process...I already have tried it in
some ways, failing whole times. Thanks
Jcrop Cropbox image preview is different than original cropped image
Jcrop Cropbox image preview is different than original cropped image
I am cropping an image with JCrop. In Preview pane, the image is perfect.
But when cropped, it is getting other co-ordinate and crops a different
area on the image. How can I fix the preview co-ordinate and the crop
co-ordinate?
Cropping preview:
After Crop:
Code where the image is being shown:
<img src="uploads/destination_<?php echo $filename; ?>" id="target"
alt="crop" />
<div id="preview-pane">
<div class="preview-container">
<img src="uploads/destination_<?php echo $filename; ?>"
class="jcrop-preview" alt="Preview" />
</div>
</div><!-- @end #preview-pane -->
<div id="form-container">
<form id="cropimg" name="cropimg" method="post" action="crop.php"
target="_blank">
<input type="hidden" id="x" name="x">
<input type="hidden" id="y" name="y">
<input type="hidden" id="w" name="w">
<input type="hidden" id="h" name="h">
<input type="submit" id="submit" value="Crop Image!">
</form>
</div><!-- @end #form-container -->
Crop.php code:
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$targ_w = 150;
$targ_h = 94;
$jpeg_quality = 90;
if(!isset($_POST['x']) || !is_numeric($_POST['x'])) {
die('Please select a crop area.');
}
$src = 'uploads/'.$fname;
$img_r = imagecreatefromjpeg($src);
$dst_r = ImageCreateTrueColor($targ_w, $targ_h);
imagecopyresampled($dst_r,$img_r,0,0,$_POST['x'],$_POST['y'],
$targ_w,$targ_h,$_POST['w'],$_POST['h']);
header('Content-type: image/jpeg');
imagejpeg($dst_r,"uploads/img_new.jpeg",$jpeg_quality); // NULL will
output the image directly
exit;
}
?>
I am cropping an image with JCrop. In Preview pane, the image is perfect.
But when cropped, it is getting other co-ordinate and crops a different
area on the image. How can I fix the preview co-ordinate and the crop
co-ordinate?
Cropping preview:
After Crop:
Code where the image is being shown:
<img src="uploads/destination_<?php echo $filename; ?>" id="target"
alt="crop" />
<div id="preview-pane">
<div class="preview-container">
<img src="uploads/destination_<?php echo $filename; ?>"
class="jcrop-preview" alt="Preview" />
</div>
</div><!-- @end #preview-pane -->
<div id="form-container">
<form id="cropimg" name="cropimg" method="post" action="crop.php"
target="_blank">
<input type="hidden" id="x" name="x">
<input type="hidden" id="y" name="y">
<input type="hidden" id="w" name="w">
<input type="hidden" id="h" name="h">
<input type="submit" id="submit" value="Crop Image!">
</form>
</div><!-- @end #form-container -->
Crop.php code:
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$targ_w = 150;
$targ_h = 94;
$jpeg_quality = 90;
if(!isset($_POST['x']) || !is_numeric($_POST['x'])) {
die('Please select a crop area.');
}
$src = 'uploads/'.$fname;
$img_r = imagecreatefromjpeg($src);
$dst_r = ImageCreateTrueColor($targ_w, $targ_h);
imagecopyresampled($dst_r,$img_r,0,0,$_POST['x'],$_POST['y'],
$targ_w,$targ_h,$_POST['w'],$_POST['h']);
header('Content-type: image/jpeg');
imagejpeg($dst_r,"uploads/img_new.jpeg",$jpeg_quality); // NULL will
output the image directly
exit;
}
?>
milisectonds to TDateTime - Java
milisectonds to TDateTime - Java
I´m in an android project that requiere save a file with TDateTime type
(Delphi). I have my date in milliseconds and I have not idea how parse
miliseconds to TDateTime. I have something like this:
Date dateInMillis = new Date(System.currentTimeMillis()); double
dateInDouble = ???;
I´ll be glad for any tips that can help me to resolve this.
PD: Sorry for my poor English =)
I´m in an android project that requiere save a file with TDateTime type
(Delphi). I have my date in milliseconds and I have not idea how parse
miliseconds to TDateTime. I have something like this:
Date dateInMillis = new Date(System.currentTimeMillis()); double
dateInDouble = ???;
I´ll be glad for any tips that can help me to resolve this.
PD: Sorry for my poor English =)
tcp::socket::is_open() is true after socket is closed
tcp::socket::is_open() is true after socket is closed
In the following simple code:
tcp::socket socket(ios);
socket.connect(...);
const bool iso1 = socket.is_open();
socket.close();
const bool iso2 = socket.is_open();
I get: iso1 == iso2 == true
Why? Thanks.
P.S. Ubuntu 13.04, boost-1.54.0
In the following simple code:
tcp::socket socket(ios);
socket.connect(...);
const bool iso1 = socket.is_open();
socket.close();
const bool iso2 = socket.is_open();
I get: iso1 == iso2 == true
Why? Thanks.
P.S. Ubuntu 13.04, boost-1.54.0
trouble about setting value of slider in wpf?
trouble about setting value of slider in wpf?
I have a slider in wpf and want the user , set the min and max value of it.
in xaml code :
<Slider x:Name="slider1" Width="34" Minimum="{Binding Path=Minval}"
Value="10" Height="105" Margin="5,5,5,5" Maximum="{Binding
Path=Maxcamdistance}"/>
<TextBox Height="23" HorizontalAlignment="Left" Margin="5,5,5,5"
Name="minvaltxt" VerticalAlignment="Top" Width="120" />
<TextBox Height="23" HorizontalAlignment="Left" Margin="5,5,5,5"
Name="maxvaltxt" VerticalAlignment="Top" Width="120" />
<Button Content="Apply" Name="btn" Height="23"
HorizontalAlignment="Left" Margin="5,5,5,5" VerticalAlignment="Top"
Width="24" Click="btn_Click" />
in code behind :
private double maxval = 80;
public double Maxval
{
get { return maxval; }
set { value = maxval; }
}
private double minval = 5;
public double Minval
{
get { return minval; }
set { value = minval; }
}
private void btn_Click(object sender, RoutedEventArgs e)
{
minval= double.Parse(minvaltxt.Text);
maxval= double.Parse(maxvaltxt.Text);
slider1.Minimum = Minval
slider1.Maximum = Maxval;
}
but it does not update the min and max value of silder ! what is the
problem ? thanks for any help.
sorry for copy-paste mistake. the question now edited. thanks.
I have a slider in wpf and want the user , set the min and max value of it.
in xaml code :
<Slider x:Name="slider1" Width="34" Minimum="{Binding Path=Minval}"
Value="10" Height="105" Margin="5,5,5,5" Maximum="{Binding
Path=Maxcamdistance}"/>
<TextBox Height="23" HorizontalAlignment="Left" Margin="5,5,5,5"
Name="minvaltxt" VerticalAlignment="Top" Width="120" />
<TextBox Height="23" HorizontalAlignment="Left" Margin="5,5,5,5"
Name="maxvaltxt" VerticalAlignment="Top" Width="120" />
<Button Content="Apply" Name="btn" Height="23"
HorizontalAlignment="Left" Margin="5,5,5,5" VerticalAlignment="Top"
Width="24" Click="btn_Click" />
in code behind :
private double maxval = 80;
public double Maxval
{
get { return maxval; }
set { value = maxval; }
}
private double minval = 5;
public double Minval
{
get { return minval; }
set { value = minval; }
}
private void btn_Click(object sender, RoutedEventArgs e)
{
minval= double.Parse(minvaltxt.Text);
maxval= double.Parse(maxvaltxt.Text);
slider1.Minimum = Minval
slider1.Maximum = Maxval;
}
but it does not update the min and max value of silder ! what is the
problem ? thanks for any help.
sorry for copy-paste mistake. the question now edited. thanks.
SQL query regarding date and time
SQL query regarding date and time
I am trying to answer the following question:
Show all engagements in October 2007 that start between noon and 5 P.M
I have tried the following query:
**SELECT EngagementNumber, StartDate, StartTime
FROM Engagements
WHERE StartDate <= CAST('2007-10-31' As DATE)
AND EndDate >= CAST('2007-10-01' AS DATE)
AND StartTime Between CAST('12:00:00' AS TIME) AND CAST('17:00:00' AS TIME)**
However, the following error is occurring:
Msg 402, Level 16, State 1, Line 1 The data types datetime and time are
incompatible in the less than or equal to operator.
I am running this on a SQL Server Database 2008R2 version and wondered if
anyone could tell me why this is happening please?
Thanks
H
I am trying to answer the following question:
Show all engagements in October 2007 that start between noon and 5 P.M
I have tried the following query:
**SELECT EngagementNumber, StartDate, StartTime
FROM Engagements
WHERE StartDate <= CAST('2007-10-31' As DATE)
AND EndDate >= CAST('2007-10-01' AS DATE)
AND StartTime Between CAST('12:00:00' AS TIME) AND CAST('17:00:00' AS TIME)**
However, the following error is occurring:
Msg 402, Level 16, State 1, Line 1 The data types datetime and time are
incompatible in the less than or equal to operator.
I am running this on a SQL Server Database 2008R2 version and wondered if
anyone could tell me why this is happening please?
Thanks
H
Why does array undefined here?
Why does array undefined here?
I have a simple function:
function megaKill(pos, size) {
blasts.push({
pos: pos,
sprite: new Sprite('img/sprites.png', [84, 7], [60, 60], 6, [0, 1])
});
for (var i=0; i<enemies.length; i++) {
if (boxCollides(pos, size, enemies[i].pos, blasts[0].sprite.size)){
enemies.splice(i, 1);
//i--;
explosions.push({
pos: enemies[i].pos,
sprite: new Sprite('img/sprites.png',
[0, 117],
[39, 39],
16,
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],
null,
true)
});
}
}
}
The error message is "Uncaught TypeError: Cannot read property 'sprite' of
undefined" in line "if (boxCollides(pos, size, enemies[i].pos,
blasts[0].sprite.size)){". But I have declared blasts before this
functions as global var blasts = [];!
I came from C# world and I really don't know why that array is undefined
after being declared and pushed couple values into it.
Thank you.
I have a simple function:
function megaKill(pos, size) {
blasts.push({
pos: pos,
sprite: new Sprite('img/sprites.png', [84, 7], [60, 60], 6, [0, 1])
});
for (var i=0; i<enemies.length; i++) {
if (boxCollides(pos, size, enemies[i].pos, blasts[0].sprite.size)){
enemies.splice(i, 1);
//i--;
explosions.push({
pos: enemies[i].pos,
sprite: new Sprite('img/sprites.png',
[0, 117],
[39, 39],
16,
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],
null,
true)
});
}
}
}
The error message is "Uncaught TypeError: Cannot read property 'sprite' of
undefined" in line "if (boxCollides(pos, size, enemies[i].pos,
blasts[0].sprite.size)){". But I have declared blasts before this
functions as global var blasts = [];!
I came from C# world and I really don't know why that array is undefined
after being declared and pushed couple values into it.
Thank you.
Tuesday, 17 September 2013
Dynamic List List [on hold]
Dynamic List List [on hold]
Hi i would like to create a dynamic List in C# my results is not the same
everytime sometimes will be 20 results, 30 results, 34 results and etc.
But i want to retrieve out the results stored is that possbie?
Hi i would like to create a dynamic List in C# my results is not the same
everytime sometimes will be 20 results, 30 results, 34 results and etc.
But i want to retrieve out the results stored is that possbie?
DoCmd.RunCommand acCmdRecordsGoToNext failed after save as ACCDE file
DoCmd.RunCommand acCmdRecordsGoToNext failed after save as ACCDE file
i have DoCmd.RunCommand acCmdRecordsGoToNext command that runs after i
called it from another form. everything works totally fine before i save
it as ACCDE file. those DoCmd.RunCommand acCmdRecordsGoToNext wont works
in the ACCDE file.
Public Sub cmdFindRecord_Click()'i make this button click event public so
i can call it from another form
DoCmd.RunCommand acCmdRecordsGoToFirst
End Sub
Forms("frmEditRecord").cmdFindRecord_Click'calling button click event from
another form
I tried to runs the cmdFindRecord_Click() event on its form (without
calling it from another form) and it runs well. It's like the
DoCmd.RunCommand acCmdRecordsGoToNext command on the cmdFindRecord_Click()
cannot be call from another form in ACCDE filetype. is it suppose to be
references issue or what?hope someone help
i have DoCmd.RunCommand acCmdRecordsGoToNext command that runs after i
called it from another form. everything works totally fine before i save
it as ACCDE file. those DoCmd.RunCommand acCmdRecordsGoToNext wont works
in the ACCDE file.
Public Sub cmdFindRecord_Click()'i make this button click event public so
i can call it from another form
DoCmd.RunCommand acCmdRecordsGoToFirst
End Sub
Forms("frmEditRecord").cmdFindRecord_Click'calling button click event from
another form
I tried to runs the cmdFindRecord_Click() event on its form (without
calling it from another form) and it runs well. It's like the
DoCmd.RunCommand acCmdRecordsGoToNext command on the cmdFindRecord_Click()
cannot be call from another form in ACCDE filetype. is it suppose to be
references issue or what?hope someone help
when do java infinite loops stop?
when do java infinite loops stop?
I read about infinite loops and found out in some languages it will stop
when stack overflows or reached the allotted maximum memory. Others will
loop forever depending on the type of program and language. My question
is, do java infinite loops stop? I'm just curious because java has a
garbage collector, that reuse memory when there's memory leak in case of
reaching allotted maximum memory and stack overflow.
Also,will this kind of infinite loop stop?
for( ; ; ){}
I read about infinite loops and found out in some languages it will stop
when stack overflows or reached the allotted maximum memory. Others will
loop forever depending on the type of program and language. My question
is, do java infinite loops stop? I'm just curious because java has a
garbage collector, that reuse memory when there's memory leak in case of
reaching allotted maximum memory and stack overflow.
Also,will this kind of infinite loop stop?
for( ; ; ){}
Detecting when a hidden form field was changed dynamically
Detecting when a hidden form field was changed dynamically
How can we detect when a hidden form field was changed dynamically? If it
was changed, then display an alert?
A JQuery UI (DatePicker) is used to change the hidden form field.
<input name="textbox" id="alternate" type="hidden" size="30"
onchange="alert('changed')" />
How can we detect when a hidden form field was changed dynamically? If it
was changed, then display an alert?
A JQuery UI (DatePicker) is used to change the hidden form field.
<input name="textbox" id="alternate" type="hidden" size="30"
onchange="alert('changed')" />
Sorting an Array of JavaScript Objects a Specific Order
Sorting an Array of JavaScript Objects a Specific Order
Given an array of objects:
{
key: "a",
value: 42
},
{
key: "d",
value: 28
},
{
key: "c",
value: 92
},
{
key: "b",
value: 87
}
and an array of keys:
["c", "a", "b", "d"]
Is there a ECMAScript function or a 3rd-party JavaScript library that lets
you sort (in one line) the first array of objects, to match the order of
the keys specified in the second array, such that the result is:
{
key: "c",
value: 92
},
{
key: "a",
value: 42
},
{
key: "b",
value: 87
},
{
key: "d",
value: 28
}
Other questions that provide a function or algorithm:
Javascript - sort array based on another array - Stack Overflow
javascript - How do I sort an array of objects based on the ordering of
another array? - Stack Overflow
Similar/related questions:
Sorting an Array of Objects in PHP In a Specific Order
php - Sort array of objects
Given an array of objects:
{
key: "a",
value: 42
},
{
key: "d",
value: 28
},
{
key: "c",
value: 92
},
{
key: "b",
value: 87
}
and an array of keys:
["c", "a", "b", "d"]
Is there a ECMAScript function or a 3rd-party JavaScript library that lets
you sort (in one line) the first array of objects, to match the order of
the keys specified in the second array, such that the result is:
{
key: "c",
value: 92
},
{
key: "a",
value: 42
},
{
key: "b",
value: 87
},
{
key: "d",
value: 28
}
Other questions that provide a function or algorithm:
Javascript - sort array based on another array - Stack Overflow
javascript - How do I sort an array of objects based on the ordering of
another array? - Stack Overflow
Similar/related questions:
Sorting an Array of Objects in PHP In a Specific Order
php - Sort array of objects
How to know if an element, created dynamically, exist?
How to know if an element, created dynamically, exist?
I have this simple function:
var x = document.createTextNode("ERROR");
document.body.appendChild(x);
So then I need to create an IF to verify if this message exist [If this
message has been created]. This is the problem, I don't know how to do
that.
GetElementByID seems to don't work with element created by dynamically.
Any help? Thanks.
I have this simple function:
var x = document.createTextNode("ERROR");
document.body.appendChild(x);
So then I need to create an IF to verify if this message exist [If this
message has been created]. This is the problem, I don't know how to do
that.
GetElementByID seems to don't work with element created by dynamically.
Any help? Thanks.
Sunday, 15 September 2013
how to send keepalives in XMPP in Android app
how to send keepalives in XMPP in Android app
i don't know how to implement a keepalive connection in android
http://xmpp.org/extensions/xep-0304.html . I'm using a service with asmack
in my app. After two hours the connection break. I use a reconnection
function to keep alive but doesnt work
public void reconnect(){
try{
connection = Koneksi.getInstance().getConnection();
}catch(NullPointerException e){
SharedPreferences pref =
getSharedPreferences(PREFS_NAME,MODE_PRIVATE);
String username = pref.getString(PREF_USERNAME, null);
String password = pref.getString(PREF_PASSWORD, null);
System.out.println("FDATOS EN MYSERVICE " + username + " " +
username);
try {
Koneksi.getInstance().init();
Koneksi.getInstance().performLogin(username, password);
Koneksi.getInstance().setStatus(true, "");
//
Koneksi.getInstance().getConnection().getRoster().setSubscriptionMode(SubscriptionMode.manual);
Presence presence = new Presence(Presence.Type.available);
presence.setMode(Presence.Mode.available);
connection.sendPacket(presence);
} catch (Exception e2) {
e2.printStackTrace();
}
}
}
i don't know how to implement a keepalive connection in android
http://xmpp.org/extensions/xep-0304.html . I'm using a service with asmack
in my app. After two hours the connection break. I use a reconnection
function to keep alive but doesnt work
public void reconnect(){
try{
connection = Koneksi.getInstance().getConnection();
}catch(NullPointerException e){
SharedPreferences pref =
getSharedPreferences(PREFS_NAME,MODE_PRIVATE);
String username = pref.getString(PREF_USERNAME, null);
String password = pref.getString(PREF_PASSWORD, null);
System.out.println("FDATOS EN MYSERVICE " + username + " " +
username);
try {
Koneksi.getInstance().init();
Koneksi.getInstance().performLogin(username, password);
Koneksi.getInstance().setStatus(true, "");
//
Koneksi.getInstance().getConnection().getRoster().setSubscriptionMode(SubscriptionMode.manual);
Presence presence = new Presence(Presence.Type.available);
presence.setMode(Presence.Mode.available);
connection.sendPacket(presence);
} catch (Exception e2) {
e2.printStackTrace();
}
}
}
HTTP Basic Auth Rails Admin
HTTP Basic Auth Rails Admin
I'm trying to use basic http authentication on my admin panel. I'm using
Rails Admin.
I want to require http basic auth for the admin login.
In my application controller I'm trying the following:
before_action :basic_auth_admin, if: :admin_url?
private
def admin_url?
request.url.scan(/\/{1}admin.*/).size > 0
end
def basic_auth_admin
authenticate_or_request_with_http_basic do |username, password|
username == "user" && password == "pass"
end
end
In Chrome/Firefox I cannot access the admin login. Chrome continues to
prompt for credentials and Firefox just continues loading.
Please advise. If there's a better way to accomplish my goal please let me
know.
I'm trying to use basic http authentication on my admin panel. I'm using
Rails Admin.
I want to require http basic auth for the admin login.
In my application controller I'm trying the following:
before_action :basic_auth_admin, if: :admin_url?
private
def admin_url?
request.url.scan(/\/{1}admin.*/).size > 0
end
def basic_auth_admin
authenticate_or_request_with_http_basic do |username, password|
username == "user" && password == "pass"
end
end
In Chrome/Firefox I cannot access the admin login. Chrome continues to
prompt for credentials and Firefox just continues loading.
Please advise. If there's a better way to accomplish my goal please let me
know.
Loading parts of the knockout model dinamically from database on demand
Loading parts of the knockout model dinamically from database on demand
I store my data in a relational database table. Each record contains the
fields of a form and the name of the template
(http://knockoutjs.com/documentation/template-binding.html) to use for
them. (There are different record structures for different templates, but
the details are not important here.) I can get one record by ID in a
$.getJSON call, make a ko.mapping.fromJS from it and ko.applyBindings the
result on my HTML page. This works well so far for any given ID.
Now there is an other table with master-detail connections, i.e. I can get
for a master ID the array of ID-s of the child records. I'd like to
display the child records below the master (each child with its own
template, of course, which might be different) like in a tree view, when
the user expands that branch of the tree. I can't load the whole database
into the client browser, only the parts asked by the user should be
loaded.
I was thinking about foreach-binding
(http://knockoutjs.com/documentation/foreach-binding.html) the array of
ID-s somehow (seems to be natural), but there are a number of issues with
it:
KO wants the whole data structure to be present when binded. Now I have
the ID-s only, which refer to the records indirectly. My data will arrive
later, via async AJAX call.
Appending a new child record needs to fetch a new ID from the server (a
database sequence's next value). We must know the template of the new
record too, but it will be given somehow (the master has a default for new
children.)
I have a js object which caches the records already loaded (the key is the
ID, the value is the record), but I can't phrase the connection with
foreach.
Do you know some tricks to bind non-existing data (I mean currently not in
the model), or any method to handle this indirect reference?
Perhaps I could manipulate the DOM manually for the array, but this is
exactly what the foreach-binding does (I think), so I'd prefer the builtin
way, if possible.
Or, could I use KO's foreach to build empty slots for the children, and
bind to the slots later, when the AJAX succeeds? But how can I reference
these parts of the DOM?
Thanks.
I store my data in a relational database table. Each record contains the
fields of a form and the name of the template
(http://knockoutjs.com/documentation/template-binding.html) to use for
them. (There are different record structures for different templates, but
the details are not important here.) I can get one record by ID in a
$.getJSON call, make a ko.mapping.fromJS from it and ko.applyBindings the
result on my HTML page. This works well so far for any given ID.
Now there is an other table with master-detail connections, i.e. I can get
for a master ID the array of ID-s of the child records. I'd like to
display the child records below the master (each child with its own
template, of course, which might be different) like in a tree view, when
the user expands that branch of the tree. I can't load the whole database
into the client browser, only the parts asked by the user should be
loaded.
I was thinking about foreach-binding
(http://knockoutjs.com/documentation/foreach-binding.html) the array of
ID-s somehow (seems to be natural), but there are a number of issues with
it:
KO wants the whole data structure to be present when binded. Now I have
the ID-s only, which refer to the records indirectly. My data will arrive
later, via async AJAX call.
Appending a new child record needs to fetch a new ID from the server (a
database sequence's next value). We must know the template of the new
record too, but it will be given somehow (the master has a default for new
children.)
I have a js object which caches the records already loaded (the key is the
ID, the value is the record), but I can't phrase the connection with
foreach.
Do you know some tricks to bind non-existing data (I mean currently not in
the model), or any method to handle this indirect reference?
Perhaps I could manipulate the DOM manually for the array, but this is
exactly what the foreach-binding does (I think), so I'd prefer the builtin
way, if possible.
Or, could I use KO's foreach to build empty slots for the children, and
bind to the slots later, when the AJAX succeeds? But how can I reference
these parts of the DOM?
Thanks.
Event handling on jQuery this
Event handling on jQuery this
function Car(id) {
var $this = this;
this.init = function() {
this.el = document.getElementById(id);
$(this).on('keypress', function(e){
alert(e.target);
});
}
}
The alert never happens. If I change $(this) to #hero. It works. I can't
see why.
$(document).ready(function(){
var hero = new Car("hero");
hero.init();
});
function Car(id) {
var $this = this;
this.init = function() {
this.el = document.getElementById(id);
$(this).on('keypress', function(e){
alert(e.target);
});
}
}
The alert never happens. If I change $(this) to #hero. It works. I can't
see why.
$(document).ready(function(){
var hero = new Car("hero");
hero.init();
});
Rails, nested attributes, created in new action,
Rails, nested attributes, created in new action,
I have a order system where a user selects products that's being saved in
a cookie. It is then retrieved by the system when continued to the order
page.
@order = Order.new
unless @cart.nil?
@cart.each do | product |
@order.quantities.new :product => product, :quantity => 1
end
However I want the user to be able to update the quantity which is a field
in the quantity model that belongs to product and order.
How can I access this newly made "@order.quantities" in my form view?
<%= simple_form_for(@order) do |f| %>
<%= f.error_notification %>
....
I have a order system where a user selects products that's being saved in
a cookie. It is then retrieved by the system when continued to the order
page.
@order = Order.new
unless @cart.nil?
@cart.each do | product |
@order.quantities.new :product => product, :quantity => 1
end
However I want the user to be able to update the quantity which is a field
in the quantity model that belongs to product and order.
How can I access this newly made "@order.quantities" in my form view?
<%= simple_form_for(@order) do |f| %>
<%= f.error_notification %>
....
finding the first occurence in a list
finding the first occurence in a list
I want to find the first occurence of a digit in a list :
let pos_list = function (list , x) ->
let rec pos = function
|([] , x , i) -> i
|([y] , x , i) -> if y == x then i
|(s::t , x , i) -> if s == x then i else pos(t , x , i + 1) in
pos(list , x , 0) ;;
but the compiler complain that the expression is a "uint" type , and was
used instead with a "int" type .
I want to find the first occurence of a digit in a list :
let pos_list = function (list , x) ->
let rec pos = function
|([] , x , i) -> i
|([y] , x , i) -> if y == x then i
|(s::t , x , i) -> if s == x then i else pos(t , x , i + 1) in
pos(list , x , 0) ;;
but the compiler complain that the expression is a "uint" type , and was
used instead with a "int" type .
why doesn't this php foreach return the value?
why doesn't this php foreach return the value?
If you look at the code below, it doesn't echo anything out when the
return is in the if statement. When I take the return out, it echoes out
the correct value. Why is this?
$images= Array(
[0] => Array
(
[id] => 131],
[width] => 400]
),
[1] => Array
(
[id] => 140],
[width] => 900]
)
)
$array_key=0;
foreach($images as $key => $image){
if($image['id'] == $image_id){
$array_key= $key;
return;
}
}
echo $array_key;
If you look at the code below, it doesn't echo anything out when the
return is in the if statement. When I take the return out, it echoes out
the correct value. Why is this?
$images= Array(
[0] => Array
(
[id] => 131],
[width] => 400]
),
[1] => Array
(
[id] => 140],
[width] => 900]
)
)
$array_key=0;
foreach($images as $key => $image){
if($image['id'] == $image_id){
$array_key= $key;
return;
}
}
echo $array_key;
Saturday, 14 September 2013
Regex how to move all matched char to the end of string
Regex how to move all matched char to the end of string
I want to move all matched char in a string to the end of it.
For example:
chafo -> chaof
sasc -> sacs
chafof -> chaoff
I tried with this:
Pattern: "/(.+)([f|z|x|r|s])+(.*)/"
Replacement: "$1$3$2"
But it just make: chafo -> chaof, not chafof -> chaoff
Can anyone help me out?
I want to move all matched char in a string to the end of it.
For example:
chafo -> chaof
sasc -> sacs
chafof -> chaoff
I tried with this:
Pattern: "/(.+)([f|z|x|r|s])+(.*)/"
Replacement: "$1$3$2"
But it just make: chafo -> chaof, not chafof -> chaoff
Can anyone help me out?
Create Exception on Mime filtering on squid
Create Exception on Mime filtering on squid
I have a server with the operating system Ubuntu 12:04 LTS version. I also
paired the squid version 3.1.19 on my server. with the client about 30
units.
to prevent my clients to download any files and streaming, I use acl xxx
rep_mime_type application/octet-stream during limited hours. Of course
with http_reply_access deny xxx.
But I see that the anti-virus update (average client using avast) on squid
logs to participate blocked. the question is, how is that files of a
particular site made ​​an exception.
Thanks for the advice
I have a server with the operating system Ubuntu 12:04 LTS version. I also
paired the squid version 3.1.19 on my server. with the client about 30
units.
to prevent my clients to download any files and streaming, I use acl xxx
rep_mime_type application/octet-stream during limited hours. Of course
with http_reply_access deny xxx.
But I see that the anti-virus update (average client using avast) on squid
logs to participate blocked. the question is, how is that files of a
particular site made ​​an exception.
Thanks for the advice
Methods to generate image based on Perlin Noise array
Methods to generate image based on Perlin Noise array
I'm trying to begin learning to use Perlin Noise to create a tile map. I'm
just beginning so I found some source code online to create an array based
on Perlin Noise. So I have an array of good data right now (as far as I
know) but I don't understand what kinds of methods can be used to convert
this from an array into a tile map.
Does anybody have any examples or sources of any methods to do this?
Here is the code I'm using the generate the array.
package perlin1;
import java.util.Random;
public class ImageWriter {
/** Source of entropy */
private Random rand_;
/** Amount of roughness */
float roughness_;
/** Plasma fractal grid */
private float[][] grid_;
/** Generate a noise source based upon the midpoint displacement fractal.
*
* @param rand The random number generator
* @param roughness a roughness parameter
* @param width the width of the grid
* @param height the height of the grid
*/
public ImageWriter(Random rand, float roughness, int width, int height) {
roughness_ = roughness / width;
grid_ = new float[width][height];
rand_ = (rand == null) ? new Random() : rand;
}
public void initialise() {
int xh = grid_.length - 1;
int yh = grid_[0].length - 1;
// set the corner points
grid_[0][0] = rand_.nextFloat() - 0.5f;
grid_[0][yh] = rand_.nextFloat() - 0.5f;
grid_[xh][0] = rand_.nextFloat() - 0.5f;
grid_[xh][yh] = rand_.nextFloat() - 0.5f;
// generate the fractal
generate(0, 0, xh, yh);
}
// Add a suitable amount of random displacement to a point
private float roughen(float v, int l, int h) {
return v + roughness_ * (float) (rand_.nextGaussian() * (h - l));
}
// generate the fractal
private void generate(int xl, int yl, int xh, int yh) {
int xm = (xl + xh) / 2;
int ym = (yl + yh) / 2;
if ((xl == xm) && (yl == ym)) return;
grid_[xm][yl] = 0.5f * (grid_[xl][yl] + grid_[xh][yl]);
grid_[xm][yh] = 0.5f * (grid_[xl][yh] + grid_[xh][yh]);
grid_[xl][ym] = 0.5f * (grid_[xl][yl] + grid_[xl][yh]);
grid_[xh][ym] = 0.5f * (grid_[xh][yl] + grid_[xh][yh]);
float v = roughen(0.5f * (grid_[xm][yl] + grid_[xm][yh]), xl + yl, yh
+ xh);
grid_[xm][ym] = v;
grid_[xm][yl] = roughen(grid_[xm][yl], xl, xh);
grid_[xm][yh] = roughen(grid_[xm][yh], xl, xh);
grid_[xl][ym] = roughen(grid_[xl][ym], yl, yh);
grid_[xh][ym] = roughen(grid_[xh][ym], yl, yh);
generate(xl, yl, xm, ym);
generate(xm, yl, xh, ym);
generate(xl, ym, xm, yh);
generate(xm, ym, xh, yh);
}
/**
* Dump out as a CSV
*/
public void printAsCSV() {
for(int i = 0;i < grid_.length;i++) {
for(int j = 0;j < grid_[0].length;j++) {
System.out.print(grid_[i][j]);
System.out.print(",");
}
System.out.println();
}
}
/**
* Convert to a Boolean array
* @return the boolean array
*/
public boolean[][] toBooleans() {
int w = grid_.length;
int h = grid_[0].length;
boolean[][] ret = new boolean[w][h];
for(int i = 0;i < w;i++) {
for(int j = 0;j < h;j++) {
ret[i][j] = grid_[i][j] < 0;
}
}
return ret;
}
/** For testing */
public static void main(String[] args) {
ImageWriter n = new ImageWriter(null, 1.0f, 250, 250);
n.initialise();
n.printAsCSV();
}
}
The resulting array is all amounts between 0 and 1.
Again, I'm just looking for how this array can be converted into a tile
map. Any help is appreciated. Thanks
I'm trying to begin learning to use Perlin Noise to create a tile map. I'm
just beginning so I found some source code online to create an array based
on Perlin Noise. So I have an array of good data right now (as far as I
know) but I don't understand what kinds of methods can be used to convert
this from an array into a tile map.
Does anybody have any examples or sources of any methods to do this?
Here is the code I'm using the generate the array.
package perlin1;
import java.util.Random;
public class ImageWriter {
/** Source of entropy */
private Random rand_;
/** Amount of roughness */
float roughness_;
/** Plasma fractal grid */
private float[][] grid_;
/** Generate a noise source based upon the midpoint displacement fractal.
*
* @param rand The random number generator
* @param roughness a roughness parameter
* @param width the width of the grid
* @param height the height of the grid
*/
public ImageWriter(Random rand, float roughness, int width, int height) {
roughness_ = roughness / width;
grid_ = new float[width][height];
rand_ = (rand == null) ? new Random() : rand;
}
public void initialise() {
int xh = grid_.length - 1;
int yh = grid_[0].length - 1;
// set the corner points
grid_[0][0] = rand_.nextFloat() - 0.5f;
grid_[0][yh] = rand_.nextFloat() - 0.5f;
grid_[xh][0] = rand_.nextFloat() - 0.5f;
grid_[xh][yh] = rand_.nextFloat() - 0.5f;
// generate the fractal
generate(0, 0, xh, yh);
}
// Add a suitable amount of random displacement to a point
private float roughen(float v, int l, int h) {
return v + roughness_ * (float) (rand_.nextGaussian() * (h - l));
}
// generate the fractal
private void generate(int xl, int yl, int xh, int yh) {
int xm = (xl + xh) / 2;
int ym = (yl + yh) / 2;
if ((xl == xm) && (yl == ym)) return;
grid_[xm][yl] = 0.5f * (grid_[xl][yl] + grid_[xh][yl]);
grid_[xm][yh] = 0.5f * (grid_[xl][yh] + grid_[xh][yh]);
grid_[xl][ym] = 0.5f * (grid_[xl][yl] + grid_[xl][yh]);
grid_[xh][ym] = 0.5f * (grid_[xh][yl] + grid_[xh][yh]);
float v = roughen(0.5f * (grid_[xm][yl] + grid_[xm][yh]), xl + yl, yh
+ xh);
grid_[xm][ym] = v;
grid_[xm][yl] = roughen(grid_[xm][yl], xl, xh);
grid_[xm][yh] = roughen(grid_[xm][yh], xl, xh);
grid_[xl][ym] = roughen(grid_[xl][ym], yl, yh);
grid_[xh][ym] = roughen(grid_[xh][ym], yl, yh);
generate(xl, yl, xm, ym);
generate(xm, yl, xh, ym);
generate(xl, ym, xm, yh);
generate(xm, ym, xh, yh);
}
/**
* Dump out as a CSV
*/
public void printAsCSV() {
for(int i = 0;i < grid_.length;i++) {
for(int j = 0;j < grid_[0].length;j++) {
System.out.print(grid_[i][j]);
System.out.print(",");
}
System.out.println();
}
}
/**
* Convert to a Boolean array
* @return the boolean array
*/
public boolean[][] toBooleans() {
int w = grid_.length;
int h = grid_[0].length;
boolean[][] ret = new boolean[w][h];
for(int i = 0;i < w;i++) {
for(int j = 0;j < h;j++) {
ret[i][j] = grid_[i][j] < 0;
}
}
return ret;
}
/** For testing */
public static void main(String[] args) {
ImageWriter n = new ImageWriter(null, 1.0f, 250, 250);
n.initialise();
n.printAsCSV();
}
}
The resulting array is all amounts between 0 and 1.
Again, I'm just looking for how this array can be converted into a tile
map. Any help is appreciated. Thanks
execute code in java fields
execute code in java fields
I'm in a position where I have referenced a static field variable to a
custom class. I need to make alterations to the variable with methods from
the class it references. I can not instantiate the class under
construction. Simplified example:
public class House {
private static MaterialsRequired matsReq = new MaterialsRequired();
private String size;
private House(String size) {
this.size = size;
}
public static MaterialsRequired getMaterialsRequired() {
}
public static void Build(String size) {
new House(size); //Do I need to put 'this(size)' here?
//some code here to expend the materials required factored based on size.
}
To construct the house I need to know the materials required (for standard
size). To know the materials required I need to call the addMaterial()
method of MaterialsRequired. What do I do?
EDIT: I need to call the addMaterial() method repeatedly on matsReq. Maybe
ten times. When I call House.build() I want the matsReq to have been
altered by method calls (if my question was unspecific). Also it doesn't
satisfy me to just set the materials required every time the build() or
getMaterialsRequired() methods are called.
I'm in a position where I have referenced a static field variable to a
custom class. I need to make alterations to the variable with methods from
the class it references. I can not instantiate the class under
construction. Simplified example:
public class House {
private static MaterialsRequired matsReq = new MaterialsRequired();
private String size;
private House(String size) {
this.size = size;
}
public static MaterialsRequired getMaterialsRequired() {
}
public static void Build(String size) {
new House(size); //Do I need to put 'this(size)' here?
//some code here to expend the materials required factored based on size.
}
To construct the house I need to know the materials required (for standard
size). To know the materials required I need to call the addMaterial()
method of MaterialsRequired. What do I do?
EDIT: I need to call the addMaterial() method repeatedly on matsReq. Maybe
ten times. When I call House.build() I want the matsReq to have been
altered by method calls (if my question was unspecific). Also it doesn't
satisfy me to just set the materials required every time the build() or
getMaterialsRequired() methods are called.
Add a method to existing C++ class in other file
Add a method to existing C++ class in other file
Is it possible in C++ to extend a class(add a method) in different source
file without editing the original source file where the class is written?
In obj-c it is possible by writing another @interface AbcClass
(ExtCategory) ... @end
I got compile-time error when I tried these:
//Abc.h
class Abc {
void methodOne();
void methodTwo();
}
//Abc+Ext.h
class Abc { // ERROR: Redefinition of 'Abc'
void methodAdded();
}
Is it possible in C++ to extend a class(add a method) in different source
file without editing the original source file where the class is written?
In obj-c it is possible by writing another @interface AbcClass
(ExtCategory) ... @end
I got compile-time error when I tried these:
//Abc.h
class Abc {
void methodOne();
void methodTwo();
}
//Abc+Ext.h
class Abc { // ERROR: Redefinition of 'Abc'
void methodAdded();
}
Showing null pointer exception in activity Android
Showing null pointer exception in activity Android
I have two java class where in the first activity i have created a
database and stored some data in the sqlite DB. And in the second java
class the data will be retrieved checking current date and time. but the
second class is not starting. its showing a null pointer exception in the
logcat. The first class is :
package com.example.eventmanager;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;
import com.example.eventmanager.R;
import android.app.Activity;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TimePicker;
import android.widget.Toast;
public class MainActivity extends Activity {
MediaPlayer mp;
EditText name;
EditText venue;
public SQLiteDatabase eventsDB;
private ScheduleClient scheduleClient;
private DatePicker picker;
private TimePicker timePic;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
scheduleClient = new ScheduleClient(this);
scheduleClient.doBindService();
picker = (DatePicker) findViewById(R.id.scheduleTimePicker);
timePic = (TimePicker) findViewById(R.id.timePicer);
name = (EditText) findViewById(R.id.ename);
venue = (EditText) findViewById(R.id.venue);
}
public void onDateSelectedButtonClick(View v){
eventsDB = this.openOrCreateDatabase("eventsDB", 0, null);
eventsDB.setVersion(2);
eventsDB.setLocale(Locale.getDefault());
eventsDB.execSQL("CREATE TABLE IF NOT EXISTS " +
" events " +
" (name VARCHAR, date VARCHAR,time VARCHAR, venue
VARCHAR);");
int day = picker.getDayOfMonth();
int month = picker.getMonth();
int year = picker.getYear();
Calendar c = Calendar.getInstance();
c.set(year, month, day);
c.set(Calendar.HOUR_OF_DAY, timePic.getCurrentHour());
c.set(Calendar.MINUTE, timePic.getCurrentMinute());
c.set(Calendar.SECOND, 0);
String eday = String.valueOf(day);
SimpleDateFormat month_date = new SimpleDateFormat("MMM"); // or
"MMM" for short month name
String emonth = month_date.format(c.getTime());
// String emonth = String.valueOf(month);
String eyear = String.valueOf(year);
String edate = eday+","+emonth+" "+eyear;
String ehour = String.valueOf(timePic.getCurrentHour());
String eminute = String.valueOf(timePic.getCurrentMinute());
String etime = ehour+" : "+eminute;
eventsDB.execSQL("INSERT INTO " +
"events" +
" Values ('"+name+"','"+edate+"','"+etime+"','"+venue+"');");
scheduleClient.setAlarmForNotification(c);
Toast.makeText(this, "The event for: "+ day +"/"+ (month+1) +"/"+
year+" Has been set", Toast.LENGTH_SHORT).show();
}
@Override
protected void onStop() {
if(scheduleClient != null)
scheduleClient.doUnbindService();
super.onStop();
}
}
and the second class is:
package com.example.eventmanager;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import android.app.Activity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.widget.DatePicker;
import android.widget.TextView;
import android.widget.TimePicker;
public class AlertActivity extends Activity {
TextView test;
public SQLiteDatabase eventsDB;
private DatePicker picker;
private TimePicker timePic;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.alert);
test = (TextView) findViewById(R.id.textView1);
Calendar c = Calendar.getInstance();
int day = c.get(Calendar.DAY_OF_MONTH);
//int month = c.get(Calendar.MONTH);
SimpleDateFormat month_date = new SimpleDateFormat("MMM"); // or
"MMM" for short month name
String month = month_date.format(c.getTime());
int year = c.get(Calendar.YEAR);
String eday = String.valueOf(day);
String emonth = String.valueOf(month);
String eyear = String.valueOf(year);
String edate = eday+","+emonth+" "+eyear;
String ehour = String.valueOf(timePic.getCurrentHour());
String eminute = String.valueOf(timePic.getCurrentMinute());
String etime = ehour+" : "+eminute;
String q="Select * from events where date='" + edate + "' and
time='" + etime+ "'";
Cursor m = eventsDB.rawQuery(q, null);
if(edate.matches("") || etime.matches("") ){
//Toast.makeText(getApplicationContext(), "Please insert a
student ID", Toast.LENGTH_LONG).show();
}
else {
if(m.moveToFirst() )
{
String curevent = m.getString(m.getColumnIndex("name"));
String curdate = m.getString(m.getColumnIndex("edate"));
test.setText(curevent);
}
else {
test.setText("Not found");
}
}
}
}
The logcat is here :
09-14 19:55:29.954: D/GalleryCacheReady(2754): Receive
action.ACTION_MEDIA_SCANNER_FINISHED
09-14 19:55:29.959: E/AndroidRuntime(1266): FATAL EXCEPTION: main
09-14 19:55:29.959: E/AndroidRuntime(1266): java.lang.RuntimeException:
Unable to start activity
ComponentInfo{com.example.eventmanager/com.example.eventmanager.AlertActivity}:
java.lang.NullPointerException
09-14 19:55:29.959: E/AndroidRuntime(1266): at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2100)
09-14 19:55:29.959: E/AndroidRuntime(1266): at
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2125)
09-14 19:55:29.959: E/AndroidRuntime(1266): at
android.app.ActivityThread.access$600(ActivityThread.java:140)
09-14 19:55:29.959: E/AndroidRuntime(1266): at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1227)
09-14 19:55:29.959: E/AndroidRuntime(1266): at
android.os.Handler.dispatchMessage(Handler.java:99)
09-14 19:55:29.959: E/AndroidRuntime(1266): at
android.os.Looper.loop(Looper.java:137)
09-14 19:55:29.959: E/AndroidRuntime(1266): at
android.app.ActivityThread.main(ActivityThread.java:4898)
09-14 19:55:29.959: E/AndroidRuntime(1266): at
java.lang.reflect.Method.invokeNative(Native Method)
09-14 19:55:29.959: E/AndroidRuntime(1266): at
java.lang.reflect.Method.invoke(Method.java:511)
09-14 19:55:29.959: E/AndroidRuntime(1266): at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1006)
09-14 19:55:29.959: E/AndroidRuntime(1266): at
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:773)
09-14 19:55:29.959: E/AndroidRuntime(1266): at
dalvik.system.NativeStart.main(Native Method)
09-14 19:55:29.959: E/AndroidRuntime(1266): Caused by:
java.lang.NullPointerException
09-14 19:55:29.959: E/AndroidRuntime(1266): at
com.example.eventmanager.AlertActivity.onCreate(AlertActivity.java:47)
09-14 19:55:29.959: E/AndroidRuntime(1266): at
android.app.Activity.performCreate(Activity.java:5206)
09-14 19:55:29.959: E/AndroidRuntime(1266): at
android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1083)
09-14 19:55:29.959: E/AndroidRuntime(1266): at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2064)
09-14 19:55:29.959: E/AndroidRuntime(1266): ... 11 more
09-14 19:55:30.009: D/dalvikvm(1266): GC_CONCURRENT freed 204K, 6% free
13512K/14343K, paused 17ms+5ms, total 37ms
Please help me to find out the error as i am novice in android application
development.
I have two java class where in the first activity i have created a
database and stored some data in the sqlite DB. And in the second java
class the data will be retrieved checking current date and time. but the
second class is not starting. its showing a null pointer exception in the
logcat. The first class is :
package com.example.eventmanager;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;
import com.example.eventmanager.R;
import android.app.Activity;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TimePicker;
import android.widget.Toast;
public class MainActivity extends Activity {
MediaPlayer mp;
EditText name;
EditText venue;
public SQLiteDatabase eventsDB;
private ScheduleClient scheduleClient;
private DatePicker picker;
private TimePicker timePic;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
scheduleClient = new ScheduleClient(this);
scheduleClient.doBindService();
picker = (DatePicker) findViewById(R.id.scheduleTimePicker);
timePic = (TimePicker) findViewById(R.id.timePicer);
name = (EditText) findViewById(R.id.ename);
venue = (EditText) findViewById(R.id.venue);
}
public void onDateSelectedButtonClick(View v){
eventsDB = this.openOrCreateDatabase("eventsDB", 0, null);
eventsDB.setVersion(2);
eventsDB.setLocale(Locale.getDefault());
eventsDB.execSQL("CREATE TABLE IF NOT EXISTS " +
" events " +
" (name VARCHAR, date VARCHAR,time VARCHAR, venue
VARCHAR);");
int day = picker.getDayOfMonth();
int month = picker.getMonth();
int year = picker.getYear();
Calendar c = Calendar.getInstance();
c.set(year, month, day);
c.set(Calendar.HOUR_OF_DAY, timePic.getCurrentHour());
c.set(Calendar.MINUTE, timePic.getCurrentMinute());
c.set(Calendar.SECOND, 0);
String eday = String.valueOf(day);
SimpleDateFormat month_date = new SimpleDateFormat("MMM"); // or
"MMM" for short month name
String emonth = month_date.format(c.getTime());
// String emonth = String.valueOf(month);
String eyear = String.valueOf(year);
String edate = eday+","+emonth+" "+eyear;
String ehour = String.valueOf(timePic.getCurrentHour());
String eminute = String.valueOf(timePic.getCurrentMinute());
String etime = ehour+" : "+eminute;
eventsDB.execSQL("INSERT INTO " +
"events" +
" Values ('"+name+"','"+edate+"','"+etime+"','"+venue+"');");
scheduleClient.setAlarmForNotification(c);
Toast.makeText(this, "The event for: "+ day +"/"+ (month+1) +"/"+
year+" Has been set", Toast.LENGTH_SHORT).show();
}
@Override
protected void onStop() {
if(scheduleClient != null)
scheduleClient.doUnbindService();
super.onStop();
}
}
and the second class is:
package com.example.eventmanager;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import android.app.Activity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.widget.DatePicker;
import android.widget.TextView;
import android.widget.TimePicker;
public class AlertActivity extends Activity {
TextView test;
public SQLiteDatabase eventsDB;
private DatePicker picker;
private TimePicker timePic;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.alert);
test = (TextView) findViewById(R.id.textView1);
Calendar c = Calendar.getInstance();
int day = c.get(Calendar.DAY_OF_MONTH);
//int month = c.get(Calendar.MONTH);
SimpleDateFormat month_date = new SimpleDateFormat("MMM"); // or
"MMM" for short month name
String month = month_date.format(c.getTime());
int year = c.get(Calendar.YEAR);
String eday = String.valueOf(day);
String emonth = String.valueOf(month);
String eyear = String.valueOf(year);
String edate = eday+","+emonth+" "+eyear;
String ehour = String.valueOf(timePic.getCurrentHour());
String eminute = String.valueOf(timePic.getCurrentMinute());
String etime = ehour+" : "+eminute;
String q="Select * from events where date='" + edate + "' and
time='" + etime+ "'";
Cursor m = eventsDB.rawQuery(q, null);
if(edate.matches("") || etime.matches("") ){
//Toast.makeText(getApplicationContext(), "Please insert a
student ID", Toast.LENGTH_LONG).show();
}
else {
if(m.moveToFirst() )
{
String curevent = m.getString(m.getColumnIndex("name"));
String curdate = m.getString(m.getColumnIndex("edate"));
test.setText(curevent);
}
else {
test.setText("Not found");
}
}
}
}
The logcat is here :
09-14 19:55:29.954: D/GalleryCacheReady(2754): Receive
action.ACTION_MEDIA_SCANNER_FINISHED
09-14 19:55:29.959: E/AndroidRuntime(1266): FATAL EXCEPTION: main
09-14 19:55:29.959: E/AndroidRuntime(1266): java.lang.RuntimeException:
Unable to start activity
ComponentInfo{com.example.eventmanager/com.example.eventmanager.AlertActivity}:
java.lang.NullPointerException
09-14 19:55:29.959: E/AndroidRuntime(1266): at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2100)
09-14 19:55:29.959: E/AndroidRuntime(1266): at
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2125)
09-14 19:55:29.959: E/AndroidRuntime(1266): at
android.app.ActivityThread.access$600(ActivityThread.java:140)
09-14 19:55:29.959: E/AndroidRuntime(1266): at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1227)
09-14 19:55:29.959: E/AndroidRuntime(1266): at
android.os.Handler.dispatchMessage(Handler.java:99)
09-14 19:55:29.959: E/AndroidRuntime(1266): at
android.os.Looper.loop(Looper.java:137)
09-14 19:55:29.959: E/AndroidRuntime(1266): at
android.app.ActivityThread.main(ActivityThread.java:4898)
09-14 19:55:29.959: E/AndroidRuntime(1266): at
java.lang.reflect.Method.invokeNative(Native Method)
09-14 19:55:29.959: E/AndroidRuntime(1266): at
java.lang.reflect.Method.invoke(Method.java:511)
09-14 19:55:29.959: E/AndroidRuntime(1266): at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1006)
09-14 19:55:29.959: E/AndroidRuntime(1266): at
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:773)
09-14 19:55:29.959: E/AndroidRuntime(1266): at
dalvik.system.NativeStart.main(Native Method)
09-14 19:55:29.959: E/AndroidRuntime(1266): Caused by:
java.lang.NullPointerException
09-14 19:55:29.959: E/AndroidRuntime(1266): at
com.example.eventmanager.AlertActivity.onCreate(AlertActivity.java:47)
09-14 19:55:29.959: E/AndroidRuntime(1266): at
android.app.Activity.performCreate(Activity.java:5206)
09-14 19:55:29.959: E/AndroidRuntime(1266): at
android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1083)
09-14 19:55:29.959: E/AndroidRuntime(1266): at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2064)
09-14 19:55:29.959: E/AndroidRuntime(1266): ... 11 more
09-14 19:55:30.009: D/dalvikvm(1266): GC_CONCURRENT freed 204K, 6% free
13512K/14343K, paused 17ms+5ms, total 37ms
Please help me to find out the error as i am novice in android application
development.
What does -g option do in gcc
What does -g option do in gcc
I see many tutorials on gdb asking to use -g option while compiling c
program. I fail to understand what does the -g option actually do.
I see many tutorials on gdb asking to use -g option while compiling c
program. I fail to understand what does the -g option actually do.
Is it possible to set the the value of the name in wufoo form fields?
Is it possible to set the the value of the name in wufoo form fields?
I have a Wufoo form am I am trying to save the data captured from the form
to Solve360.
I have been trying to look for a way on how to change the value of the
name attribute of the input tag but I can't seem to find a way how to do
it.
Here is the code of the form looks like:
<input id="Field3" name="Field3" type="text" class="field text medium"
value="" maxlength="255" tabindex="1" onkeyup="handleInput(this); "
onchange="handleInput(this);" required="">
I've been looking at the wufoo backend for the option to change the value
in the name field from Field3 to something more correct like name, age,
etc.
Is it possible in Wufoo?
I have a Wufoo form am I am trying to save the data captured from the form
to Solve360.
I have been trying to look for a way on how to change the value of the
name attribute of the input tag but I can't seem to find a way how to do
it.
Here is the code of the form looks like:
<input id="Field3" name="Field3" type="text" class="field text medium"
value="" maxlength="255" tabindex="1" onkeyup="handleInput(this); "
onchange="handleInput(this);" required="">
I've been looking at the wufoo backend for the option to change the value
in the name field from Field3 to something more correct like name, age,
etc.
Is it possible in Wufoo?
Friday, 13 September 2013
how to convert preg_replace http:// & www
how to convert preg_replace http:// & www
Here i have 3 type of links users gives in their $description.
www.Apple.com
http://www.Apple.com
http://apple.com
First i'm using this to make $description safe
$description = preg_replace('<[^A-Za-z0-9-.?#%=_&():/]>', '',
"$description");
Second I did this but here i got stuck.
$description = preg_replace('/(www.[^\s]*)/i', '<a href="//$1"
target="_blank">$1</a>', $description); //This converts www.apple.com
$description = preg_replace('/(http[s]?:\/\/[^\s]*)/i', '<a href="$1"
target="_blank">$1</a>', $description); // This converts http://apple.com
www. works and http:// doesn't works because they both combine together so
is there any process by which this can be undone Also Please tell me if
there is something wrong i have coded which can be harmful or better way
to do this.
Here i have 3 type of links users gives in their $description.
www.Apple.com
http://www.Apple.com
http://apple.com
First i'm using this to make $description safe
$description = preg_replace('<[^A-Za-z0-9-.?#%=_&():/]>', '',
"$description");
Second I did this but here i got stuck.
$description = preg_replace('/(www.[^\s]*)/i', '<a href="//$1"
target="_blank">$1</a>', $description); //This converts www.apple.com
$description = preg_replace('/(http[s]?:\/\/[^\s]*)/i', '<a href="$1"
target="_blank">$1</a>', $description); // This converts http://apple.com
www. works and http:// doesn't works because they both combine together so
is there any process by which this can be undone Also Please tell me if
there is something wrong i have coded which can be harmful or better way
to do this.
Tablesorter becomes non-functional after jquery page load
Tablesorter becomes non-functional after jquery page load
I have page that has a variable refresh rate, and displays a couple of
tables. The tablesorter.js code works fine initially, but after the first
refresh its non-functional.
I've tried placing the tablesorter function inside the click function for
each branch, or at the end of the whole click function or inside the load
function -and- After looking at the docs for tablesorter, I have tried
calling $("#workstation-table").trigger("update", true) in all the
forementioned scenarios. Everytime it's the same. Doesn't work after first
refresh. Any advice would be great.
HAML code (HTML at bottom if necessary):
.whole-page
.container
%h1#application-title.hero-unit
.row-fluid
.span1
= image_tag "cog_logo.png"
= image_tag "crs.png"
Replication Server
.span1.pull-right#refresh-label
Refresh Rate:
.btn-group#refresh-buttons
%button.btn.btn-default#refresh-5-sec 5 sec
%button.btn.btn-default#refresh-30-sec 30 sec
%button.btn.btn-default#refresh-60-sec 60 sec
%h2
%small Status Dashboard
#status-tables
.col-md-4
%h3 Reports
#report-table-panel.panel
%a.accordion-toggle{ :data => { :toggle => "collapse", :target
=> "#collapse-cidne"} } CIDNE
#collapse-cidne.uncollapse.in
%table#report-table.table.table-striped.table-hover.table-bordered
%thead
%tr
%th#table-header Source
%th#table-header Type
%th#table-header Count
%tbody
- @reports.each do |report|
- if report[:source] == "CIDNE"
%tr
%td
= report[:source]
%td
= report[:type]
%td
= report[:count]
#report-table-panel.panel
%a.accordion-toggle{ :data => { :toggle => "collapse", :target
=> "#collapse-dcgs"} } DCGS
#collapse-dcgs.uncollapse.in
%table#report-table.table.table-striped.table-hover.table-bordered
%thead
%tr
%th#table-header Source
%th#table-header Type
%th#table-header Count
%tbody
- @reports.each do |report|
- if report[:source].blank?
- elsif report[:source] == "DCGS"
%tr
%td
= report[:source]
%td
= report[:type]
%td
= report[:count]
.col-md-5
%h3#workstation-title Workstations
.span-1
#sort-instructions (click column name to sort)
%table#workstation-table.table.table-striped.table-hover.table-bordered
%thead
%tr
%th#table-header Name
%th#table-header Downloaded
%th#table-header Available
%th#table-header Last Connect
%tbody
- @workstations.each do |workstation|
%tr
%td
= workstation[:name]
%td
= workstation[:downloaded]
%td
= workstation[:available]
%td
= workstation[:last_connect]
.col-md-3
%h3 Source
%table.table.table-striped.table-hover.table-bordered
%tr
%th#table-header Type
%th#table-header Name
%th#table-header Status
- @data_sources.each do |data_source|
%tr
%td
= data_source[:type]
%td
= data_source[:name]
%td
- if data_source[:status] == "UP"
#service-up
- else
#service-down
JS code:
$(document).ready(function() {
var intervalId = window.setInterval(function(){
$('.container').load('/dashboard/index .container');
}, 60000);
$("#refresh-60-sec").addClass("pressed-button");
$("#application-title").on("click", "#refresh-buttons button",
function(event) {
var interval = 0;
switch(event.target.id) {
case "refresh-5-sec" :
interval = 5000;
$(this).parent().children().removeClass("pressed-button");
$(this).addClass("pressed-button");
break;
case "refresh-30-sec" :
interval = 30000;
$(this).parent().children().removeClass("pressed-button");
$(this).addClass("pressed-button");
break;
case "refresh-60-sec" :
interval = 60000;
$(this).parent().children().removeClass("pressed-button");
$(this).addClass("pressed-button");
break;
}
if (interval != 0)
{
clearInterval(intervalId);
intervalId = setInterval(function(){
$('#status-tables').load('/dashboard/index #status-tables',
function() {
$("#workstation-table").trigger("update", true)
});
}, interval);
}
});
$("#workstation-table").tablesorter();
});
HTML:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta name="generator" content=
"HTML Tidy for Linux/x86 (vers 25 March 2009), see www.w3.org" />
<title>Webui</title>
<link data-turbolinks-track="true" href="/assets/application.css"
media="all" rel=
"stylesheet" type="text/css" />
<script data-turbolinks-track="true" src="/assets/application.js" type=
"text/javascript">
</script>
<meta content="authenticity_token" name="csrf-param" />
<meta content="D/VkaPDSNH5HHMazYu8dS8hcgGSIMl5rl5QS+eBnDyQ="
name="csrf-token" />
</head>
<body>
<div class='whole-page'>
<div class='container'>
<h1 class='hero-unit' id='application-title'></h1>
<div class='row-fluid'>
<h1 class='hero-unit' id='application-title'></h1>
<div class='span1'>
<h1 class='hero-unit' id='application-title'><img alt="Cog logo"
src=
"/assets/cog_logo.png" /> <img alt="Crs" src="/assets/crs.png"
/> Replication
Server</h1>
<div class='span1 pull-right' id='refresh-label'>
<h1 class='hero-unit' id='application-title'>Refresh Rate:</h1>
<div class='btn-group' id='refresh-buttons'>
<h1 class='hero-unit' id='application-title'><button class=
'btn btn-default' id='refresh-5-sec'>5 sec</button> <button
class=
'btn btn-default' id='refresh-30-sec'>30 sec</button>
<button class=
'btn btn-default' id='refresh-60-sec'>60 sec</button></h1>
</div>
</div>
</div>
</div>
<h2><small>Status Dashboard</small></h2>
<div id='status-tables'>
<div class='col-md-4'>
<h3>Reports</h3>
<div class='panel' id='report-table-panel'>
<a class='accordion-toggle' data-target='#collapse-cidne'
data-toggle=
'collapse'>CIDNE</a>
</div>
<div class='uncollapse in' id='collapse-cidne'>
<table class='table table-striped table-hover table-bordered' id=
'report-table'>
<thead>
<tr>
<th id='table-header'>Source</th>
<th id='table-header'>Type</th>
<th id='table-header'>Count</th>
</tr>
</thead>
<tr>
<td>CIDNE</td>
<td>et</td>
<td>5,070,127</td>
</tr>
<tr>
<td>CIDNE</td>
<td>laborum</td>
<td>8,674,267</td>
</tr>
<tr>
<td>CIDNE</td>
<td>sed</td>
<td>1,239,300</td>
</tr>
<tr>
<td>CIDNE</td>
<td>quos</td>
<td>826,247</td>
</tr>
<tr>
<td>CIDNE</td>
<td>dolorem</td>
<td>4,375,838</td>
</tr>
<tr>
<td>CIDNE</td>
<td>quos</td>
<td>8,932,341</td>
</tr>
<tr>
<td>CIDNE</td>
<td>ullam</td>
<td>2,504,480</td>
</tr>
<tr>
<td>CIDNE</td>
<td>et</td>
<td>4,178,823</td>
</tr>
<tr>
<td>CIDNE</td>
<td>vitae</td>
<td>3,945,054</td>
</tr>
<tr>
<td>CIDNE</td>
<td>vitae</td>
<td>1,158,563</td>
</tr>
<tr>
<td>CIDNE</td>
<td>ipsa</td>
<td>5,673,954</td>
</tr>
<tr>
<td>CIDNE</td>
<td>et</td>
<td>8,947,587</td>
</tr>
</table>
</div>
<div class='panel' id='report-table-panel'>
<a class='accordion-toggle' data-target='#collapse-dcgs'
data-toggle=
'collapse'>DCGS</a>
</div>
<div class='uncollapse in' id='collapse-dcgs'>
<table class='table table-striped table-hover table-bordered' id=
'report-table'>
<thead>
<tr>
<th id='table-header'>Source</th>
<th id='table-header'>Type</th>
<th id='table-header'>Count</th>
</tr>
</thead>
<tbody>
<tr>
<td>DCGS</td>
<td>Voluptates</td>
<td>8,549,353</td>
</tr>
<tr>
<td>DCGS</td>
<td>Tempore</td>
<td>8,611,361</td>
</tr>
<tr>
<td>DCGS</td>
<td>Provident</td>
<td>1,461,613</td>
</tr>
<tr>
<td>DCGS</td>
<td>Velit</td>
<td>3,823,704</td>
</tr>
<tr>
<td>DCGS</td>
<td>Velit</td>
<td>2,079,617</td>
</tr>
<tr>
<td>DCGS</td>
<td>Tempore</td>
<td>2,004,062</td>
</tr>
<tr>
<td>DCGS</td>
<td>Velit</td>
<td>7,906,194</td>
</tr>
<tr>
<td>DCGS</td>
<td>Tempore</td>
<td>4,367,449</td>
</tr>
<tr>
<td>DCGS</td>
<td>Voluptates</td>
<td>4,405,687</td>
</tr>
<tr>
<td>DCGS</td>
<td>Voluptates</td>
<td>6,369,859</td>
</tr>
</tbody>
</table>
</div>
</div>
<div class='col-md-5'>
<h3 id='workstation-title'>Workstations</h3>
<div class='span-1'>
<div id='sort-instructions'>
(click column name to sort)
</div>
</div>
<table class='table table-striped table-hover table-bordered' id=
'workstation-table'>
<thead>
<tr>
<th id='table-header'>Name</th>
<th id='table-header'>Downloaded</th>
<th id='table-header'>Available</th>
<th id='table-header'>Last Connect</th>
</tr>
</thead>
<tbody>
<tr>
<td>repellat</td>
<td>16,957</td>
<td>9,681,569</td>
<td>2013-08-25 01:59:43</td>
</tr>
<tr>
<td>qui</td>
<td>40,374</td>
<td>4,768,666</td>
<td>2013-07-06 02:45:04</td>
</tr>
<tr>
<td>consequatur</td>
<td>4,067</td>
<td>4,201,935</td>
<td>2013-07-26 21:42:00</td>
</tr>
<tr>
<td>sunt</td>
<td>11,049</td>
<td>5,605,974</td>
<td>2013-08-25 21:37:52</td>
</tr>
<tr>
<td>accusamus</td>
<td>1,870</td>
<td>6,209,493</td>
<td>2013-07-09 02:45:25</td>
</tr>
<tr>
<td>voluptate</td>
<td>40,900</td>
<td>9,647,011</td>
<td>2013-07-22 03:29:08</td>
</tr>
<tr>
<td>sint</td>
<td>33,815</td>
<td>6,141,657</td>
<td>2013-08-09 16:48:21</td>
</tr>
<tr>
<td>optio</td>
<td>22,849</td>
<td>6,901,660</td>
<td>2013-07-19 20:37:10</td>
</tr>
</tbody>
</table>
</div>
<div class='col-md-3'>
<h3>Source</h3>
<table class='table table-striped table-hover table-bordered'>
<tr>
<th id='table-header'>Type</th>
<th id='table-header'>Name</th>
<th id='table-header'>Status</th>
</tr>
<tr>
<td>CIDNE</td>
<td>http://gaylord.biz/kayla.mraz</td>
<td>
<div id='service-up'></div>
</td>
</tr>
<tr>
<td>DCGS</td>
<td>http://jenkins.org/ernest_gleichner</td>
<td>
<div id='service-down'></div>
</td>
</tr>
</table>
</div>
</div>
</div>
</div>
</body>
</html>
I have page that has a variable refresh rate, and displays a couple of
tables. The tablesorter.js code works fine initially, but after the first
refresh its non-functional.
I've tried placing the tablesorter function inside the click function for
each branch, or at the end of the whole click function or inside the load
function -and- After looking at the docs for tablesorter, I have tried
calling $("#workstation-table").trigger("update", true) in all the
forementioned scenarios. Everytime it's the same. Doesn't work after first
refresh. Any advice would be great.
HAML code (HTML at bottom if necessary):
.whole-page
.container
%h1#application-title.hero-unit
.row-fluid
.span1
= image_tag "cog_logo.png"
= image_tag "crs.png"
Replication Server
.span1.pull-right#refresh-label
Refresh Rate:
.btn-group#refresh-buttons
%button.btn.btn-default#refresh-5-sec 5 sec
%button.btn.btn-default#refresh-30-sec 30 sec
%button.btn.btn-default#refresh-60-sec 60 sec
%h2
%small Status Dashboard
#status-tables
.col-md-4
%h3 Reports
#report-table-panel.panel
%a.accordion-toggle{ :data => { :toggle => "collapse", :target
=> "#collapse-cidne"} } CIDNE
#collapse-cidne.uncollapse.in
%table#report-table.table.table-striped.table-hover.table-bordered
%thead
%tr
%th#table-header Source
%th#table-header Type
%th#table-header Count
%tbody
- @reports.each do |report|
- if report[:source] == "CIDNE"
%tr
%td
= report[:source]
%td
= report[:type]
%td
= report[:count]
#report-table-panel.panel
%a.accordion-toggle{ :data => { :toggle => "collapse", :target
=> "#collapse-dcgs"} } DCGS
#collapse-dcgs.uncollapse.in
%table#report-table.table.table-striped.table-hover.table-bordered
%thead
%tr
%th#table-header Source
%th#table-header Type
%th#table-header Count
%tbody
- @reports.each do |report|
- if report[:source].blank?
- elsif report[:source] == "DCGS"
%tr
%td
= report[:source]
%td
= report[:type]
%td
= report[:count]
.col-md-5
%h3#workstation-title Workstations
.span-1
#sort-instructions (click column name to sort)
%table#workstation-table.table.table-striped.table-hover.table-bordered
%thead
%tr
%th#table-header Name
%th#table-header Downloaded
%th#table-header Available
%th#table-header Last Connect
%tbody
- @workstations.each do |workstation|
%tr
%td
= workstation[:name]
%td
= workstation[:downloaded]
%td
= workstation[:available]
%td
= workstation[:last_connect]
.col-md-3
%h3 Source
%table.table.table-striped.table-hover.table-bordered
%tr
%th#table-header Type
%th#table-header Name
%th#table-header Status
- @data_sources.each do |data_source|
%tr
%td
= data_source[:type]
%td
= data_source[:name]
%td
- if data_source[:status] == "UP"
#service-up
- else
#service-down
JS code:
$(document).ready(function() {
var intervalId = window.setInterval(function(){
$('.container').load('/dashboard/index .container');
}, 60000);
$("#refresh-60-sec").addClass("pressed-button");
$("#application-title").on("click", "#refresh-buttons button",
function(event) {
var interval = 0;
switch(event.target.id) {
case "refresh-5-sec" :
interval = 5000;
$(this).parent().children().removeClass("pressed-button");
$(this).addClass("pressed-button");
break;
case "refresh-30-sec" :
interval = 30000;
$(this).parent().children().removeClass("pressed-button");
$(this).addClass("pressed-button");
break;
case "refresh-60-sec" :
interval = 60000;
$(this).parent().children().removeClass("pressed-button");
$(this).addClass("pressed-button");
break;
}
if (interval != 0)
{
clearInterval(intervalId);
intervalId = setInterval(function(){
$('#status-tables').load('/dashboard/index #status-tables',
function() {
$("#workstation-table").trigger("update", true)
});
}, interval);
}
});
$("#workstation-table").tablesorter();
});
HTML:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta name="generator" content=
"HTML Tidy for Linux/x86 (vers 25 March 2009), see www.w3.org" />
<title>Webui</title>
<link data-turbolinks-track="true" href="/assets/application.css"
media="all" rel=
"stylesheet" type="text/css" />
<script data-turbolinks-track="true" src="/assets/application.js" type=
"text/javascript">
</script>
<meta content="authenticity_token" name="csrf-param" />
<meta content="D/VkaPDSNH5HHMazYu8dS8hcgGSIMl5rl5QS+eBnDyQ="
name="csrf-token" />
</head>
<body>
<div class='whole-page'>
<div class='container'>
<h1 class='hero-unit' id='application-title'></h1>
<div class='row-fluid'>
<h1 class='hero-unit' id='application-title'></h1>
<div class='span1'>
<h1 class='hero-unit' id='application-title'><img alt="Cog logo"
src=
"/assets/cog_logo.png" /> <img alt="Crs" src="/assets/crs.png"
/> Replication
Server</h1>
<div class='span1 pull-right' id='refresh-label'>
<h1 class='hero-unit' id='application-title'>Refresh Rate:</h1>
<div class='btn-group' id='refresh-buttons'>
<h1 class='hero-unit' id='application-title'><button class=
'btn btn-default' id='refresh-5-sec'>5 sec</button> <button
class=
'btn btn-default' id='refresh-30-sec'>30 sec</button>
<button class=
'btn btn-default' id='refresh-60-sec'>60 sec</button></h1>
</div>
</div>
</div>
</div>
<h2><small>Status Dashboard</small></h2>
<div id='status-tables'>
<div class='col-md-4'>
<h3>Reports</h3>
<div class='panel' id='report-table-panel'>
<a class='accordion-toggle' data-target='#collapse-cidne'
data-toggle=
'collapse'>CIDNE</a>
</div>
<div class='uncollapse in' id='collapse-cidne'>
<table class='table table-striped table-hover table-bordered' id=
'report-table'>
<thead>
<tr>
<th id='table-header'>Source</th>
<th id='table-header'>Type</th>
<th id='table-header'>Count</th>
</tr>
</thead>
<tr>
<td>CIDNE</td>
<td>et</td>
<td>5,070,127</td>
</tr>
<tr>
<td>CIDNE</td>
<td>laborum</td>
<td>8,674,267</td>
</tr>
<tr>
<td>CIDNE</td>
<td>sed</td>
<td>1,239,300</td>
</tr>
<tr>
<td>CIDNE</td>
<td>quos</td>
<td>826,247</td>
</tr>
<tr>
<td>CIDNE</td>
<td>dolorem</td>
<td>4,375,838</td>
</tr>
<tr>
<td>CIDNE</td>
<td>quos</td>
<td>8,932,341</td>
</tr>
<tr>
<td>CIDNE</td>
<td>ullam</td>
<td>2,504,480</td>
</tr>
<tr>
<td>CIDNE</td>
<td>et</td>
<td>4,178,823</td>
</tr>
<tr>
<td>CIDNE</td>
<td>vitae</td>
<td>3,945,054</td>
</tr>
<tr>
<td>CIDNE</td>
<td>vitae</td>
<td>1,158,563</td>
</tr>
<tr>
<td>CIDNE</td>
<td>ipsa</td>
<td>5,673,954</td>
</tr>
<tr>
<td>CIDNE</td>
<td>et</td>
<td>8,947,587</td>
</tr>
</table>
</div>
<div class='panel' id='report-table-panel'>
<a class='accordion-toggle' data-target='#collapse-dcgs'
data-toggle=
'collapse'>DCGS</a>
</div>
<div class='uncollapse in' id='collapse-dcgs'>
<table class='table table-striped table-hover table-bordered' id=
'report-table'>
<thead>
<tr>
<th id='table-header'>Source</th>
<th id='table-header'>Type</th>
<th id='table-header'>Count</th>
</tr>
</thead>
<tbody>
<tr>
<td>DCGS</td>
<td>Voluptates</td>
<td>8,549,353</td>
</tr>
<tr>
<td>DCGS</td>
<td>Tempore</td>
<td>8,611,361</td>
</tr>
<tr>
<td>DCGS</td>
<td>Provident</td>
<td>1,461,613</td>
</tr>
<tr>
<td>DCGS</td>
<td>Velit</td>
<td>3,823,704</td>
</tr>
<tr>
<td>DCGS</td>
<td>Velit</td>
<td>2,079,617</td>
</tr>
<tr>
<td>DCGS</td>
<td>Tempore</td>
<td>2,004,062</td>
</tr>
<tr>
<td>DCGS</td>
<td>Velit</td>
<td>7,906,194</td>
</tr>
<tr>
<td>DCGS</td>
<td>Tempore</td>
<td>4,367,449</td>
</tr>
<tr>
<td>DCGS</td>
<td>Voluptates</td>
<td>4,405,687</td>
</tr>
<tr>
<td>DCGS</td>
<td>Voluptates</td>
<td>6,369,859</td>
</tr>
</tbody>
</table>
</div>
</div>
<div class='col-md-5'>
<h3 id='workstation-title'>Workstations</h3>
<div class='span-1'>
<div id='sort-instructions'>
(click column name to sort)
</div>
</div>
<table class='table table-striped table-hover table-bordered' id=
'workstation-table'>
<thead>
<tr>
<th id='table-header'>Name</th>
<th id='table-header'>Downloaded</th>
<th id='table-header'>Available</th>
<th id='table-header'>Last Connect</th>
</tr>
</thead>
<tbody>
<tr>
<td>repellat</td>
<td>16,957</td>
<td>9,681,569</td>
<td>2013-08-25 01:59:43</td>
</tr>
<tr>
<td>qui</td>
<td>40,374</td>
<td>4,768,666</td>
<td>2013-07-06 02:45:04</td>
</tr>
<tr>
<td>consequatur</td>
<td>4,067</td>
<td>4,201,935</td>
<td>2013-07-26 21:42:00</td>
</tr>
<tr>
<td>sunt</td>
<td>11,049</td>
<td>5,605,974</td>
<td>2013-08-25 21:37:52</td>
</tr>
<tr>
<td>accusamus</td>
<td>1,870</td>
<td>6,209,493</td>
<td>2013-07-09 02:45:25</td>
</tr>
<tr>
<td>voluptate</td>
<td>40,900</td>
<td>9,647,011</td>
<td>2013-07-22 03:29:08</td>
</tr>
<tr>
<td>sint</td>
<td>33,815</td>
<td>6,141,657</td>
<td>2013-08-09 16:48:21</td>
</tr>
<tr>
<td>optio</td>
<td>22,849</td>
<td>6,901,660</td>
<td>2013-07-19 20:37:10</td>
</tr>
</tbody>
</table>
</div>
<div class='col-md-3'>
<h3>Source</h3>
<table class='table table-striped table-hover table-bordered'>
<tr>
<th id='table-header'>Type</th>
<th id='table-header'>Name</th>
<th id='table-header'>Status</th>
</tr>
<tr>
<td>CIDNE</td>
<td>http://gaylord.biz/kayla.mraz</td>
<td>
<div id='service-up'></div>
</td>
</tr>
<tr>
<td>DCGS</td>
<td>http://jenkins.org/ernest_gleichner</td>
<td>
<div id='service-down'></div>
</td>
</tr>
</table>
</div>
</div>
</div>
</div>
</body>
</html>
How to get authors name's posts?
How to get authors name's posts?
I have a site where users are not logged in and they can post, I am using
a plugin called http://wordpress.org/plugins/user-submitted-posts/. Their
posts are considered as posted by Admin, however, since in the form when
they submit they can insert their name, wordpress shows in the admin panel
their name.
By doing this i can get a list of the names:
<ul>
<?php
$args= array(
'posts_per_page' => -1
);
query_posts($args);
?>
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
<li>
<?php echo get_the_author(); ?>
</li>
<?php endwhile; ?> <?php endif; ?>
</ul>
But if I add this:
<?php echo get_the_author_posts(); ?>
I get a list of the different names but each of them shows me the same
number of posts, e.g.:
Name1 22
Name2 22
Name3 22
Name4 22
This happens because these are not actual users and their are posting on
the behalf of the admin.
So how can I get the posts number based on the authors names as they
display on the admin panel and not by registered users?
I have a site where users are not logged in and they can post, I am using
a plugin called http://wordpress.org/plugins/user-submitted-posts/. Their
posts are considered as posted by Admin, however, since in the form when
they submit they can insert their name, wordpress shows in the admin panel
their name.
By doing this i can get a list of the names:
<ul>
<?php
$args= array(
'posts_per_page' => -1
);
query_posts($args);
?>
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
<li>
<?php echo get_the_author(); ?>
</li>
<?php endwhile; ?> <?php endif; ?>
</ul>
But if I add this:
<?php echo get_the_author_posts(); ?>
I get a list of the different names but each of them shows me the same
number of posts, e.g.:
Name1 22
Name2 22
Name3 22
Name4 22
This happens because these are not actual users and their are posting on
the behalf of the admin.
So how can I get the posts number based on the authors names as they
display on the admin panel and not by registered users?
Passing F keys to Emulated Telnet session in Powershell (TCP)
Passing F keys to Emulated Telnet session in Powershell (TCP)
I have figured out a way to connect to a telnet server using powershell.
The script allows to create a tcp socket type connections and pass
commands.
Basically, I use System.Net.Sockets.TcpClient System.IO.StreamWriter and
then a sequence of WriteLine and Flush methods.
I have no problem passing regular ascii type lines using WriteLine. But
how do I pass on the F3 key.
F3 has no ASCII code, and I don't know what byte sequence is sent to
telnet when I hit F3. I need F3 to do certain tasks in the telnet session.
Any assistance is highly appreciated. Here is an example of my code:
$x = [char]114 + [char]189 <-- F3 key ???????????????????
Function Get-Telnet
{ Param (
[Parameter(ValueFromPipeline=$true)],
[string]$RemoteHost = "HostnameOrIPAddress",
[string]$Port = "23",
[int]$WaitTime = 6000,
[string]$OutputPath = ""
)
#Attach to the remote device, setup streaming requirements
$Socket = New-Object System.Net.Sockets.TcpClient($RemoteHost, $Port)
If ($Socket)
{ $Stream = $Socket.GetStream()
$Writer = New-Object System.IO.StreamWriter($Stream)
$Buffer = New-Object System.Byte[] 1024
$Encoding = New-Object System.Text.AsciiEncoding
#Now start issuing the commands
$Writer.WriteLine([char]08)
$Writer.Flush()
Start-Sleep -Milliseconds $WaitTime
$Writer.WriteLine("TA")
$Writer.Flush()
Start-Sleep -Milliseconds $WaitTime
$Writer.WriteLine("12345")
$Writer.Flush()
Start-Sleep -Milliseconds $WaitTime
$Writer.Write($x)
$Writer.Flush()
Start-Sleep -Milliseconds ($WaitTime * 4)
$Result = ""
#Save all the results
While($Stream.DataAvailable)
{ $Read = $Stream.Read($Buffer, 0, 1024)
$Result += ($Encoding.GetString($Buffer, 0, $Read))
}
}
Else
{ $Result = "Unable to connect to host: $($RemoteHost):$Port"
}
#Done, now save the results to a file
$Result | Out-File $OutputPath
}
Get-Telnet -RemoteHost "localhost" -OutputPath c:\windows\temp\telnetlog.imp
I have figured out a way to connect to a telnet server using powershell.
The script allows to create a tcp socket type connections and pass
commands.
Basically, I use System.Net.Sockets.TcpClient System.IO.StreamWriter and
then a sequence of WriteLine and Flush methods.
I have no problem passing regular ascii type lines using WriteLine. But
how do I pass on the F3 key.
F3 has no ASCII code, and I don't know what byte sequence is sent to
telnet when I hit F3. I need F3 to do certain tasks in the telnet session.
Any assistance is highly appreciated. Here is an example of my code:
$x = [char]114 + [char]189 <-- F3 key ???????????????????
Function Get-Telnet
{ Param (
[Parameter(ValueFromPipeline=$true)],
[string]$RemoteHost = "HostnameOrIPAddress",
[string]$Port = "23",
[int]$WaitTime = 6000,
[string]$OutputPath = ""
)
#Attach to the remote device, setup streaming requirements
$Socket = New-Object System.Net.Sockets.TcpClient($RemoteHost, $Port)
If ($Socket)
{ $Stream = $Socket.GetStream()
$Writer = New-Object System.IO.StreamWriter($Stream)
$Buffer = New-Object System.Byte[] 1024
$Encoding = New-Object System.Text.AsciiEncoding
#Now start issuing the commands
$Writer.WriteLine([char]08)
$Writer.Flush()
Start-Sleep -Milliseconds $WaitTime
$Writer.WriteLine("TA")
$Writer.Flush()
Start-Sleep -Milliseconds $WaitTime
$Writer.WriteLine("12345")
$Writer.Flush()
Start-Sleep -Milliseconds $WaitTime
$Writer.Write($x)
$Writer.Flush()
Start-Sleep -Milliseconds ($WaitTime * 4)
$Result = ""
#Save all the results
While($Stream.DataAvailable)
{ $Read = $Stream.Read($Buffer, 0, 1024)
$Result += ($Encoding.GetString($Buffer, 0, $Read))
}
}
Else
{ $Result = "Unable to connect to host: $($RemoteHost):$Port"
}
#Done, now save the results to a file
$Result | Out-File $OutputPath
}
Get-Telnet -RemoteHost "localhost" -OutputPath c:\windows\temp\telnetlog.imp
Add row to dataframe based on presence criteria
Add row to dataframe based on presence criteria
I am trying to find a way to add rows based on criteria in a data frame. I
essentially want to take a data frame and insert values that are missing.
Here is what I start with:
Plot Species Status
1A ABBI L
1A PIEN D
1B ABBI D
1B PIEN L
2A ABBI L
I would like the ability to search the Plot column for 1A, 2B and 3A.
Since 1A is present, there would be no action, but 2B and 2B would be
added to the data frame. For missing values, I will always want to enter
the Plot number and 0 for everything else. The end result looking like
this:
Plot Species Status
1A ABBI L
1A PIEN D
1B ABBI D
1B PIEN L
2A ABBI L
2B 0 0
3A 0 0
Thanks for your help!
I am trying to find a way to add rows based on criteria in a data frame. I
essentially want to take a data frame and insert values that are missing.
Here is what I start with:
Plot Species Status
1A ABBI L
1A PIEN D
1B ABBI D
1B PIEN L
2A ABBI L
I would like the ability to search the Plot column for 1A, 2B and 3A.
Since 1A is present, there would be no action, but 2B and 2B would be
added to the data frame. For missing values, I will always want to enter
the Plot number and 0 for everything else. The end result looking like
this:
Plot Species Status
1A ABBI L
1A PIEN D
1B ABBI D
1B PIEN L
2A ABBI L
2B 0 0
3A 0 0
Thanks for your help!
Thursday, 12 September 2013
how to start placement of action buttons from the left in action bar
how to start placement of action buttons from the left in action bar
I am new to android development. Hence, I'm still in the
getting-the-hang-of-it mode. I have started off my app by creating an xml
file in the res/menu folder, the code for which is shown below. What I
need help with is placing the first (add) button in the left hand corner,
where the title bar is supposed to be located, followed by the remove
button in the centre, and finally the overflow menu in the last third. I
want these three entities to be evenly spaced out. Additionally, I have
managed to get rid of the app name and icon from the left hand corner.
Any help will me much appreciated.
Thanks in advance
<?xml version="1.0" encoding="utf-8"?>
<item android:id="@+id/setting"
android:title="@string/action_settings"
android:orderInCategory="100"
android:showAsAction="never" />
<item android:id="@+id/add_contact"
android:title="@string/action_add"
android:orderInCategory="1"
android:showAsAction="ifRoom" />
<item android:id="@+id/remove_contact"
android:title="@string/action_remove"
android:orderInCategory="2"
android:showAsAction="ifRoom" />
This is what I want it to look like. It is a screen shot of the Nexus 4
contacts manager. However, I want buttons not tabs:
http://i.imgur.com/iDwUCJl.png
Current output: http://i.imgur.com/sQU3Jjq.png
I am new to android development. Hence, I'm still in the
getting-the-hang-of-it mode. I have started off my app by creating an xml
file in the res/menu folder, the code for which is shown below. What I
need help with is placing the first (add) button in the left hand corner,
where the title bar is supposed to be located, followed by the remove
button in the centre, and finally the overflow menu in the last third. I
want these three entities to be evenly spaced out. Additionally, I have
managed to get rid of the app name and icon from the left hand corner.
Any help will me much appreciated.
Thanks in advance
<?xml version="1.0" encoding="utf-8"?>
<item android:id="@+id/setting"
android:title="@string/action_settings"
android:orderInCategory="100"
android:showAsAction="never" />
<item android:id="@+id/add_contact"
android:title="@string/action_add"
android:orderInCategory="1"
android:showAsAction="ifRoom" />
<item android:id="@+id/remove_contact"
android:title="@string/action_remove"
android:orderInCategory="2"
android:showAsAction="ifRoom" />
This is what I want it to look like. It is a screen shot of the Nexus 4
contacts manager. However, I want buttons not tabs:
http://i.imgur.com/iDwUCJl.png
Current output: http://i.imgur.com/sQU3Jjq.png
Weird back button (Alt-Left) behavior in Eclipse
Weird back button (Alt-Left) behavior in Eclipse
Not exactly a programming question, but I figured I'd get more response
here than in SU. Tag 'java' added because I'm programming in Java. Feel
free to edit/move question as appropriate.
I'm using Eclipse Kepler IDE, and I'm having this annoying weird behavior
from the Back function. I can't remember if I had this behavior in Juno
version but I think not - that's what I'm here to confirm, if this is a
bug or I need to adjust some setting in Eclipse.
Imagine the following code points:
Point A
Point B
Point C
When my editing cursor is at point A and I hit F3 (Open Declaration),
Eclipse takes me to B. If I hit F3 again, Eclipse takes me to C.
All that is well, but when I hit the Back button or press Alt+Left from C,
I'm being taken back to A. If I then hit Forward (Alt+Right), I'm taken to
B and the Forward button is disabled! (I can't go forward to C).
Current Behavior:
F3: A -> B -> C
Back: C ------> A
Forward: A -> B
This doesn't seem right at all, because I would expect going back from C,
I should reach B, and then to A. Following that, going forward from A, I
should go to B, and then to C.
Expected Behavior:
F3: A -> B -> C
Back: C -> B -> A
Forward: A -> B -> C
Not exactly a programming question, but I figured I'd get more response
here than in SU. Tag 'java' added because I'm programming in Java. Feel
free to edit/move question as appropriate.
I'm using Eclipse Kepler IDE, and I'm having this annoying weird behavior
from the Back function. I can't remember if I had this behavior in Juno
version but I think not - that's what I'm here to confirm, if this is a
bug or I need to adjust some setting in Eclipse.
Imagine the following code points:
Point A
Point B
Point C
When my editing cursor is at point A and I hit F3 (Open Declaration),
Eclipse takes me to B. If I hit F3 again, Eclipse takes me to C.
All that is well, but when I hit the Back button or press Alt+Left from C,
I'm being taken back to A. If I then hit Forward (Alt+Right), I'm taken to
B and the Forward button is disabled! (I can't go forward to C).
Current Behavior:
F3: A -> B -> C
Back: C ------> A
Forward: A -> B
This doesn't seem right at all, because I would expect going back from C,
I should reach B, and then to A. Following that, going forward from A, I
should go to B, and then to C.
Expected Behavior:
F3: A -> B -> C
Back: C -> B -> A
Forward: A -> B -> C
Unable to let ajax calendar appear twice from the textbox
Unable to let ajax calendar appear twice from the textbox
I have created a search function where the user will be able to select the
search field from the dropdownlist. For example, the field can contain
data such as default value "---Select---", "incidentdate", "memberid". In
my condition, i have put this
if (ddlCategory.SelectedItem.Text.Equals("incidentdate"))
{
CalendarExtender myCalExt = new CalendarExtender();
myCalExt.TargetControlID = "txtData";
myCalExt.Enabled = true;
Place1.Controls.Add(myCalExt);
}
if (!ddlCategory.SelectedItem.Text.Equals("--- Select ---"))
{
txtData.ReadOnly = false;
}
else
{
txtData.ReadOnly = true;
}
This basically allow the ajax calendar to appear whenever the user select
the ddl text incident date. The user will then have to click the search
button before the webapp will display any data. However, if the user
failed to search a data from the date he select from the calendar, the
user will not be able to re-select the date as the ajax calendar will not
appear again. In fact, tt will only re-appear if the user re-select the
"incidentdate".
Why is this so? My condition has already mentioned that if the Text equals
to incidentdate, the calendar will appear.
Regards.
I have created a search function where the user will be able to select the
search field from the dropdownlist. For example, the field can contain
data such as default value "---Select---", "incidentdate", "memberid". In
my condition, i have put this
if (ddlCategory.SelectedItem.Text.Equals("incidentdate"))
{
CalendarExtender myCalExt = new CalendarExtender();
myCalExt.TargetControlID = "txtData";
myCalExt.Enabled = true;
Place1.Controls.Add(myCalExt);
}
if (!ddlCategory.SelectedItem.Text.Equals("--- Select ---"))
{
txtData.ReadOnly = false;
}
else
{
txtData.ReadOnly = true;
}
This basically allow the ajax calendar to appear whenever the user select
the ddl text incident date. The user will then have to click the search
button before the webapp will display any data. However, if the user
failed to search a data from the date he select from the calendar, the
user will not be able to re-select the date as the ajax calendar will not
appear again. In fact, tt will only re-appear if the user re-select the
"incidentdate".
Why is this so? My condition has already mentioned that if the Text equals
to incidentdate, the calendar will appear.
Regards.
Java copy multi-d array, random errors
Java copy multi-d array, random errors
I have been debugging my implementation of Game of Life, and my main
problem looks like its coming from how I use arrays.
public boolean[][] oldState;
public boolean[][] newState;
private boolean gameState = true;
public LifeBoard(Seed seed) {
oldState = seed.getSeed();
newState = new boolean[oldState.length][oldState[0].length];
run();
}
public void run() {
//debug code to run for x generations
for (int i = 0; i < 5; i++) {
BoardPrinter.print(oldState);
evaluateCells();
oldState = newState;
}
BoardPrinter.print(oldState);
System.out.println("game over");
}
the boolean[][] from Seed is a 5x5 grid, all false (dead) except the 3
horizontal middle cells in the middle row
00000
00000
0+++0
00000
00000
evaluateCells() looks at each cell in the grid, looks at the 8 cells
around it, counts them, and based on the number of neighbors it writes a
new value to newState.
What should happen: use oldState to calculate newState, copy newState to
oldState, then go back through newState, writing each cell again based on
the new oldState.
What really happens: the first generation works correctly, but after that
the results are increasingly weird, it evaluates cells to be false that I
know to be true, etc. The problem seems to be in the way I am copying the
arrays.
If I initialize a 3rd blank array blankState[][] = new boolean[5][5]; and
during the loop in run say:
public void run() {
//debug code to run for x generations
for (int i = 0; i < 5; i++) {
BoardPrinter.print(oldState);
evaluateCells();
oldState = newState;
newState = blankState;
}
BoardPrinter.print(oldState);
System.out.println("game over");
}
...then the game works correctly for an additional 1 generation, then the
weird garbage returns.
I have 2 questions: first, it looks like I have to use System.arraycopy(),
but unless someone tells me about a version for multidimensional arrays, I
will have to write a simple loop.
My real question: why do you have to use this special System method to
copy an array? Why can't you use the = operator?
I have been debugging my implementation of Game of Life, and my main
problem looks like its coming from how I use arrays.
public boolean[][] oldState;
public boolean[][] newState;
private boolean gameState = true;
public LifeBoard(Seed seed) {
oldState = seed.getSeed();
newState = new boolean[oldState.length][oldState[0].length];
run();
}
public void run() {
//debug code to run for x generations
for (int i = 0; i < 5; i++) {
BoardPrinter.print(oldState);
evaluateCells();
oldState = newState;
}
BoardPrinter.print(oldState);
System.out.println("game over");
}
the boolean[][] from Seed is a 5x5 grid, all false (dead) except the 3
horizontal middle cells in the middle row
00000
00000
0+++0
00000
00000
evaluateCells() looks at each cell in the grid, looks at the 8 cells
around it, counts them, and based on the number of neighbors it writes a
new value to newState.
What should happen: use oldState to calculate newState, copy newState to
oldState, then go back through newState, writing each cell again based on
the new oldState.
What really happens: the first generation works correctly, but after that
the results are increasingly weird, it evaluates cells to be false that I
know to be true, etc. The problem seems to be in the way I am copying the
arrays.
If I initialize a 3rd blank array blankState[][] = new boolean[5][5]; and
during the loop in run say:
public void run() {
//debug code to run for x generations
for (int i = 0; i < 5; i++) {
BoardPrinter.print(oldState);
evaluateCells();
oldState = newState;
newState = blankState;
}
BoardPrinter.print(oldState);
System.out.println("game over");
}
...then the game works correctly for an additional 1 generation, then the
weird garbage returns.
I have 2 questions: first, it looks like I have to use System.arraycopy(),
but unless someone tells me about a version for multidimensional arrays, I
will have to write a simple loop.
My real question: why do you have to use this special System method to
copy an array? Why can't you use the = operator?
Is There Better Way to Validate SqlXml in CLR?
Is There Better Way to Validate SqlXml in CLR?
I need to validate xml in sql server against an xsd. The xsd is too
complex to use with XML SCHEMA COLLECTION, so I am writing a SQL CLR
function to do it. I have two issue with how I have "had" to write the
code. Code is VB.NET targeting 2.0, btw, thought I think I run into the
same issue in C#. If not happy to switch.
[1] I cannot seem to attach setting to the reader created by
SqlXml.CreateReader so I have to load into an XmlDocument to perform the
validation. I also cannot just load the SqlXml straight to XmlDocument--I
would have to do extra type conversions.
Am I missing something or is that just the way it is?
[2] I hate that I am using a shared member to pass the validation result
from the event handler and then back to the caller. This is fine in my
first specific usage where I no there is a sequence of individual calls.
But if I ever tried using this with multiple callers or in set operation I
fear the results would be suspect.
Is there a way around this?
Imports System.Data.SqlTypes
Imports Microsoft.SqlServer.Server
Imports System.Xml
Imports System.Xml.Schema
Partial Public Class UserDefinedFunctions
'this is from an ms sample
Const TARGET_NAMESPACE As String = "http://www.contoso.com/books"
Const SCHEMA_URI As String = "D:\temp\temp.xsd"
Shared schemaSet As XmlSchemaSet
Shared schemaValidationEventHandler As ValidationEventHandler
Shared isValid As Boolean
Shared doc As XmlDocument
Shared Sub New()
schemaSet = New XmlSchemaSet
schemaSet.Add(TARGET_NAMESPACE, SCHEMA_URI)
schemaSet.Compile()
doc = New XmlDocument
doc.Schemas = schemaSet
schemaValidationEventHandler = New ValidationEventHandler(
AddressOf ValidationCallBack)
End Sub
<SqlFunction()> _
Public Shared Function ValidateWithContosoXsd(ByVal xml As SqlXml) _
As SqlBoolean
isValid = True
Dim reader As XmlReader = xml.CreateReader
reader.Settings.ValidationType = ValidationType.Schema
doc.Load(reader)
doc.Validate(schemaValidationEventHandler)
ValidateWithContosoXsd = isValid
End Function
Private Shared Sub ValidationCallBack(ByVal sender As Object,
ByVal args As ValidationEventArgs)
isValid = False
End Sub
End Class
I did follow a clue to try using the initial reader as the basis a for a
second reader, which works in a roughly equivalent console app. The
difference in the console app is that the first ready is from a file uri
instead of from SqlXml. Sadly, this always shows valid when done in the
clr.
Partial Public Class UserDefinedFunctions
Const TARGET_NAMESPACE As String = "http://www.contoso.com/books"
Const SCHEMA_URI As String = "D:\temp\temp.xsd"
Shared settings As XmlReaderSettings
Shared schemaSet As XmlSchemaSet
Shared schemaValidationEventHandler As ValidationEventHandler
Shared isValid As Boolean
Shared Sub New()
schemaSet = New XmlSchemaSet
schemaSet.Add(TARGET_NAMESPACE, SCHEMA_URI)
schemaSet.Compile()
schemaValidationEventHandler = New
ValidationEventHandler(AddressOf ValidationCallBack)
settings = New XmlReaderSettings
settings.Schemas = schemaSet
settings.ValidationType = ValidationType.Schema
AddHandler settings.ValidationEventHandler,
schemaValidationEventHandler
End Sub
<SqlFunction()> _
Public Shared Function ValidateWithContosoXsd(ByVal xml As SqlXml) As
SqlBoolean
isValid = True
Dim baseReader As XmlReader = xml.CreateReader
Dim reader As XmlReader = XmlReader.Create(baseReader, settings)
While reader.Read()
End While
ValidateWithContosoXsd = isValid
End Function
Private Shared Sub ValidationCallBack(ByVal sender As Object, ByVal
args As ValidationEventArgs)
isValid = False
End Sub
End Class
I need to validate xml in sql server against an xsd. The xsd is too
complex to use with XML SCHEMA COLLECTION, so I am writing a SQL CLR
function to do it. I have two issue with how I have "had" to write the
code. Code is VB.NET targeting 2.0, btw, thought I think I run into the
same issue in C#. If not happy to switch.
[1] I cannot seem to attach setting to the reader created by
SqlXml.CreateReader so I have to load into an XmlDocument to perform the
validation. I also cannot just load the SqlXml straight to XmlDocument--I
would have to do extra type conversions.
Am I missing something or is that just the way it is?
[2] I hate that I am using a shared member to pass the validation result
from the event handler and then back to the caller. This is fine in my
first specific usage where I no there is a sequence of individual calls.
But if I ever tried using this with multiple callers or in set operation I
fear the results would be suspect.
Is there a way around this?
Imports System.Data.SqlTypes
Imports Microsoft.SqlServer.Server
Imports System.Xml
Imports System.Xml.Schema
Partial Public Class UserDefinedFunctions
'this is from an ms sample
Const TARGET_NAMESPACE As String = "http://www.contoso.com/books"
Const SCHEMA_URI As String = "D:\temp\temp.xsd"
Shared schemaSet As XmlSchemaSet
Shared schemaValidationEventHandler As ValidationEventHandler
Shared isValid As Boolean
Shared doc As XmlDocument
Shared Sub New()
schemaSet = New XmlSchemaSet
schemaSet.Add(TARGET_NAMESPACE, SCHEMA_URI)
schemaSet.Compile()
doc = New XmlDocument
doc.Schemas = schemaSet
schemaValidationEventHandler = New ValidationEventHandler(
AddressOf ValidationCallBack)
End Sub
<SqlFunction()> _
Public Shared Function ValidateWithContosoXsd(ByVal xml As SqlXml) _
As SqlBoolean
isValid = True
Dim reader As XmlReader = xml.CreateReader
reader.Settings.ValidationType = ValidationType.Schema
doc.Load(reader)
doc.Validate(schemaValidationEventHandler)
ValidateWithContosoXsd = isValid
End Function
Private Shared Sub ValidationCallBack(ByVal sender As Object,
ByVal args As ValidationEventArgs)
isValid = False
End Sub
End Class
I did follow a clue to try using the initial reader as the basis a for a
second reader, which works in a roughly equivalent console app. The
difference in the console app is that the first ready is from a file uri
instead of from SqlXml. Sadly, this always shows valid when done in the
clr.
Partial Public Class UserDefinedFunctions
Const TARGET_NAMESPACE As String = "http://www.contoso.com/books"
Const SCHEMA_URI As String = "D:\temp\temp.xsd"
Shared settings As XmlReaderSettings
Shared schemaSet As XmlSchemaSet
Shared schemaValidationEventHandler As ValidationEventHandler
Shared isValid As Boolean
Shared Sub New()
schemaSet = New XmlSchemaSet
schemaSet.Add(TARGET_NAMESPACE, SCHEMA_URI)
schemaSet.Compile()
schemaValidationEventHandler = New
ValidationEventHandler(AddressOf ValidationCallBack)
settings = New XmlReaderSettings
settings.Schemas = schemaSet
settings.ValidationType = ValidationType.Schema
AddHandler settings.ValidationEventHandler,
schemaValidationEventHandler
End Sub
<SqlFunction()> _
Public Shared Function ValidateWithContosoXsd(ByVal xml As SqlXml) As
SqlBoolean
isValid = True
Dim baseReader As XmlReader = xml.CreateReader
Dim reader As XmlReader = XmlReader.Create(baseReader, settings)
While reader.Read()
End While
ValidateWithContosoXsd = isValid
End Function
Private Shared Sub ValidationCallBack(ByVal sender As Object, ByVal
args As ValidationEventArgs)
isValid = False
End Sub
End Class
Subscribe to:
Comments (Atom)