Joining different tables based on column value
I have a table called notifications:
CREATE TABLE `notifications` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`user_id` int(11) DEFAULT NULL,
`type` varchar(20) NOT NULL DEFAULT '',
`parent_id` int(11) DEFAULT NULL,
`parent_type` varchar(15) DEFAULT NULL,
`type_id` int(11) DEFAULT NULL,
`etc` NULL
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=25 DEFAULT CHARSET=utf8;
Each notification is related to a different table, the value parent_type
field specifies the name of the table that I want to * join the table
with. All target tables have several similar columns:
CREATE TABLE `tablename` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`is_visible` tinyint(1) NOT NULL,
`etc` NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
Currently I'm using this query for selecting notifcations that their
related row in the target table exist and their is_visible field is 1:
SELECT n.id,
FROM notifications n
LEFT JOIN books b ON n.parent_id = b.id AND n.parent_type = 'book' AND
b.is_visible = 1
LEFT JOIN interviews i ON n.parent_id = i.id AND n.parent_type =
'interview' AND i.is_visible = 1
LEFT JOIN other tables...
WHERE n.user_id = 1
GROUP BY n.id
which since it is a left join it returns the notification if it matches
any table or not, how can I rewrite it so it doesn't return notifications
that don't match with any row in the target table? I have also tried the
CASE statement unsuccessfully.
Saturday, 31 August 2013
Python 101 and Math Logic - Listing square root numbers less than n
Python 101 and Math Logic - Listing square root numbers less than n
I'm stuck on a Python 101 type problem involving loops. Here are the
directions:
The square numbers are the integers of the form K × K, e.g. 9 is a square
number since 3 × 3 = 9. Write a program that reads an integer n from input
and outputs all the positive square numbers less than n, one per line in
increasing order. For example, if the input is 16, then the correct output
would be
1
4
9
This is what I have so far but it sort of works but runs on forever. My
code never reaches the if statement so it breaks(stops) before it gets to
17.
Suppose n = 17.
n=int(input())
counter = 1
while counter * counter < n:
for counter in range(1,n):
a = counter*counter
print(a)
if a < n:
break
Results:
1
4
9
16
25
36
49
64
81
I'm stuck on a Python 101 type problem involving loops. Here are the
directions:
The square numbers are the integers of the form K × K, e.g. 9 is a square
number since 3 × 3 = 9. Write a program that reads an integer n from input
and outputs all the positive square numbers less than n, one per line in
increasing order. For example, if the input is 16, then the correct output
would be
1
4
9
This is what I have so far but it sort of works but runs on forever. My
code never reaches the if statement so it breaks(stops) before it gets to
17.
Suppose n = 17.
n=int(input())
counter = 1
while counter * counter < n:
for counter in range(1,n):
a = counter*counter
print(a)
if a < n:
break
Results:
1
4
9
16
25
36
49
64
81
Same column for two different relational entities with doctrine
Same column for two different relational entities with doctrine
Well, I have these three tables:
likes
id_like | post | post_type
post: it has the post id where the "like button" was triggered.
post_type: it has the type of the post, it could "article" or "comment".
Comment
id_comment | body
Article
id_article | body
I am trying to create the models "Article" and "Comment" where each one
can has an array of its likes. For example, I have tried this with:
Model Like
/**
* @Entity
* @Table(name="likes")
*/
class Like
{
/**
* @Id @Column(type="integer", nullable=false, name="id_like")
* @GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* @Column(type="integer", nullable=false, name="like_type")
*/
protected $type;
Model Article
namespace models;
use \Doctrine\Common\Collections\ArrayCollection;
/** * @Entity * @Table(name="article") */ class Article {
/**
* @Id @Column(type="integer", nullable=false, name="id_article")
* @GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* @OneToMany(targetEntity="Vote", mappedBy="article")
* @JoinColumn(name="id_article", referencedColumnName="post")
*/
protected $likes;
My first problem comes when I try to get the "likes" from the article. If
I do:
$likes = $article->getLikes();
I get this error:
Severity: Notice
Message: Undefined index: article
Filename: Persisters/BasicEntityPersister.php
Line Number: 1574
Now, the second problem (or question) that eventually will come is about
the "Comment" model. Is be possible do a OneToMany from Comment to Likes
using as the same way as Article do?
Well, I have these three tables:
likes
id_like | post | post_type
post: it has the post id where the "like button" was triggered.
post_type: it has the type of the post, it could "article" or "comment".
Comment
id_comment | body
Article
id_article | body
I am trying to create the models "Article" and "Comment" where each one
can has an array of its likes. For example, I have tried this with:
Model Like
/**
* @Entity
* @Table(name="likes")
*/
class Like
{
/**
* @Id @Column(type="integer", nullable=false, name="id_like")
* @GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* @Column(type="integer", nullable=false, name="like_type")
*/
protected $type;
Model Article
namespace models;
use \Doctrine\Common\Collections\ArrayCollection;
/** * @Entity * @Table(name="article") */ class Article {
/**
* @Id @Column(type="integer", nullable=false, name="id_article")
* @GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* @OneToMany(targetEntity="Vote", mappedBy="article")
* @JoinColumn(name="id_article", referencedColumnName="post")
*/
protected $likes;
My first problem comes when I try to get the "likes" from the article. If
I do:
$likes = $article->getLikes();
I get this error:
Severity: Notice
Message: Undefined index: article
Filename: Persisters/BasicEntityPersister.php
Line Number: 1574
Now, the second problem (or question) that eventually will come is about
the "Comment" model. Is be possible do a OneToMany from Comment to Likes
using as the same way as Article do?
Trying to INSERT in db but keep getting Keyword not supported: 'metadata'
Trying to INSERT in db but keep getting Keyword not supported: 'metadata'
I've read all the postings that have to do with this but can't figure it
out. I imagine my problem is in the web.config. Any help would really be
appreciated. Still getting the hang of .NET
Here's the error:
Description: An unhandled exception occurred during the execution of the
current web request. Please review the stack trace for more information
about the error and where it originated in the code.
Exception Details: System.ArgumentException: Keyword not supported:
'metadata'.
Source Error:
Line 20: {
Line 21: string connString =
System.Configuration.ConfigurationManager.ConnectionStrings["CateringAuthorizationEntities"].ConnectionString;
Line 22: SqlConnection conn = new SqlConnection(connString);
Line 23: string sql = "INSERT INTO tbBooking (BookingName) VALUES "
Line 24: + " (@BookingName)";
C# Code:
private void ExecuteInsert(string name)
{
string connString =
System.Configuration.ConfigurationManager.ConnectionStrings["CateringAuthorizationEntities"].ConnectionString;
SqlConnection conn = new SqlConnection(connString);
string sql = "INSERT INTO tbBooking (BookingName) VALUES "
+ " (@BookingName)";
try
{
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
SqlParameter[] param = new SqlParameter[1];
//param[0] = new SqlParameter("@id", SqlDbType.Int, 20);
param[0] = new SqlParameter("@BookingName",
System.Data.SqlDbType.VarChar, 50);
param[0].Value = name;
for (int i = 0; i < param.Length; i++)
{
cmd.Parameters.Add(param[i]);
}
cmd.CommandType = System.Data.CommandType.Text;
cmd.ExecuteNonQuery();
}
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Insert Error:";
msg += ex.Message;
throw new Exception(msg);
}
finally
{
conn.Close();
}
}
protected void BtnCatering_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
//call the method to execute insert to the database
ExecuteInsert(BookingName.Text);
Response.Write("Record was successfully added!");
}
}
Web.Config:
<connectionStrings>
<add name="ApplicationServices" connectionString="data
source=.\SQLEXPRESS;Integrated
Security=SSPI;AttachDBFilename=|DataDirectory|\aspnetdb.mdf;User
Instance=true" providerName="System.Data.SqlClient"/>
<add name="CateringAuthorizationEntities"
connectionString="metadata=res://*/App_Code.CateringAuthorization.csdl|res://*/App_Code.CateringAuthorization.ssdl|res://*/App_Code.CateringAuthorization.msl;provider=System.Data.SqlClient;provider
connection string="data source=xxxxxx;initial
catalog=CateringAuthorization;integrated
security=True;multipleactiveresultsets=True;App=EntityFramework""
providerName="System.Data.EntityClient"/>
I've read all the postings that have to do with this but can't figure it
out. I imagine my problem is in the web.config. Any help would really be
appreciated. Still getting the hang of .NET
Here's the error:
Description: An unhandled exception occurred during the execution of the
current web request. Please review the stack trace for more information
about the error and where it originated in the code.
Exception Details: System.ArgumentException: Keyword not supported:
'metadata'.
Source Error:
Line 20: {
Line 21: string connString =
System.Configuration.ConfigurationManager.ConnectionStrings["CateringAuthorizationEntities"].ConnectionString;
Line 22: SqlConnection conn = new SqlConnection(connString);
Line 23: string sql = "INSERT INTO tbBooking (BookingName) VALUES "
Line 24: + " (@BookingName)";
C# Code:
private void ExecuteInsert(string name)
{
string connString =
System.Configuration.ConfigurationManager.ConnectionStrings["CateringAuthorizationEntities"].ConnectionString;
SqlConnection conn = new SqlConnection(connString);
string sql = "INSERT INTO tbBooking (BookingName) VALUES "
+ " (@BookingName)";
try
{
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
SqlParameter[] param = new SqlParameter[1];
//param[0] = new SqlParameter("@id", SqlDbType.Int, 20);
param[0] = new SqlParameter("@BookingName",
System.Data.SqlDbType.VarChar, 50);
param[0].Value = name;
for (int i = 0; i < param.Length; i++)
{
cmd.Parameters.Add(param[i]);
}
cmd.CommandType = System.Data.CommandType.Text;
cmd.ExecuteNonQuery();
}
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Insert Error:";
msg += ex.Message;
throw new Exception(msg);
}
finally
{
conn.Close();
}
}
protected void BtnCatering_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
//call the method to execute insert to the database
ExecuteInsert(BookingName.Text);
Response.Write("Record was successfully added!");
}
}
Web.Config:
<connectionStrings>
<add name="ApplicationServices" connectionString="data
source=.\SQLEXPRESS;Integrated
Security=SSPI;AttachDBFilename=|DataDirectory|\aspnetdb.mdf;User
Instance=true" providerName="System.Data.SqlClient"/>
<add name="CateringAuthorizationEntities"
connectionString="metadata=res://*/App_Code.CateringAuthorization.csdl|res://*/App_Code.CateringAuthorization.ssdl|res://*/App_Code.CateringAuthorization.msl;provider=System.Data.SqlClient;provider
connection string="data source=xxxxxx;initial
catalog=CateringAuthorization;integrated
security=True;multipleactiveresultsets=True;App=EntityFramework""
providerName="System.Data.EntityClient"/>
PHP gettext translate in wrong language when running from shell
PHP gettext translate in wrong language when running from shell
I have a complete PHP app, with MySQL.
All strings are using gettext, and I have 2 translations, Spanish and
English.
Original strings are written in Spanish.
it is working perfect, but, when I run a cron job, to send a report email,
it is sent using English, when it should send in spanish.
The problem isn't related to the mail code, since it works ok when I run
the cron file on the browser, plus, my email system first save it to the
DB then it sends them, and the message is already stored in English on the
DB.
So, I know my problem is the cron file is not using the correct language.
I use this code to set the language in a config file, included in ALL
files.
$language = "ES_AR.utf8"; //this is the locale name on the linux machine.
putenv("LANG=$language");
setlocale(LC_ALL, $language);
$domain = 'messages';
bindtextdomain($domain, APP_PATH . "/locale");
textdomain($domain);
As I said it works good.
I put this code at the top of the cron file, and the problem persists.
So the question is, is there something I can do to force a language when
running the cron file from shell??
Thanks!!!
I have a complete PHP app, with MySQL.
All strings are using gettext, and I have 2 translations, Spanish and
English.
Original strings are written in Spanish.
it is working perfect, but, when I run a cron job, to send a report email,
it is sent using English, when it should send in spanish.
The problem isn't related to the mail code, since it works ok when I run
the cron file on the browser, plus, my email system first save it to the
DB then it sends them, and the message is already stored in English on the
DB.
So, I know my problem is the cron file is not using the correct language.
I use this code to set the language in a config file, included in ALL
files.
$language = "ES_AR.utf8"; //this is the locale name on the linux machine.
putenv("LANG=$language");
setlocale(LC_ALL, $language);
$domain = 'messages';
bindtextdomain($domain, APP_PATH . "/locale");
textdomain($domain);
As I said it works good.
I put this code at the top of the cron file, and the problem persists.
So the question is, is there something I can do to force a language when
running the cron file from shell??
Thanks!!!
IOS Uploading App to appStore errors
IOS Uploading App to appStore errors
I am trying to upload an iOS application to the App Store on Xcode, but
for some reason after it passes validation the application is stuck on
"Your Application is Being Uploaded". and when i have tried to edit schema
-> build configuration change it to release then get the .app and compress
it to upload it with application loader it gives me an error when i run
the code in release "A valid provisioning profile for this executable was
not found." (although its working on debug perfectly) iam sure that code
signing working 100% i have put the developer profile under debug and
distribution profile under release NOTE:my project contains two projects
and i have read to change the dependent project to skip install YES and i
have done this to avoid errors, any thoughts ?
I am trying to upload an iOS application to the App Store on Xcode, but
for some reason after it passes validation the application is stuck on
"Your Application is Being Uploaded". and when i have tried to edit schema
-> build configuration change it to release then get the .app and compress
it to upload it with application loader it gives me an error when i run
the code in release "A valid provisioning profile for this executable was
not found." (although its working on debug perfectly) iam sure that code
signing working 100% i have put the developer profile under debug and
distribution profile under release NOTE:my project contains two projects
and i have read to change the dependent project to skip install YES and i
have done this to avoid errors, any thoughts ?
Database login doesn't seem to be working when password is correct
Database login doesn't seem to be working when password is correct
just wondering if someone can look at this code and tell me where I am
making my mistake. What the code is supposed to do is check username and
password with a database and then run an if statement to either allow the
user to view the page or just show them a "Please login" message. At this
point it is only returning the false values even if the passwords are ==.
I know I can pick up code for this on the internet, but I want to figure
out where my logic (only in my head) is going wrong. I also know I haven't
sanitized the data, but this is just a tutorial for grade 10 students just
learning HTML and CSS with a little bit of PHP. I will get to that
protecting data later. (one concept at a time)
Thanks for the help!
<?php
// connects to server
include('includes/connect2.php');
// sets post to variables, don't know if this is needed
$user=$_POST[username];
$pass=$_POST[password];
?>
<?php
// query to find information in database
$result = mysqli_query($con, "SELECT * FROM social_register WHERE
Login='$user'" );
if ($pass == $result['Password']){?>
<div id="container">
<div id="banner">
The social Site
<div id="site_logo">
<img src="images/logo_thumb.gif" />
<?php
while($row = mysqli_fetch_array($result))
{
echo $row['First_Name'] . " " . $row['Last_Name'];
echo "<br>";
}
mysqli_close($con);
?>
</div>
</div>
<div id="person">
<h1>Welcome to your test web site</h1>
</div>
</div>
<?php
}
// else part of code to display result if user is not logged in
else
{
?>
<div id="container">
<div id="banner">
The social Site
<div id="site_logo">
<img src="images/logo_thumb.gif" />
</div>
</div>
<div id="person">
<h1>You have not loged into the site, please login.</h1>
</div>
<?php
}
?>
just wondering if someone can look at this code and tell me where I am
making my mistake. What the code is supposed to do is check username and
password with a database and then run an if statement to either allow the
user to view the page or just show them a "Please login" message. At this
point it is only returning the false values even if the passwords are ==.
I know I can pick up code for this on the internet, but I want to figure
out where my logic (only in my head) is going wrong. I also know I haven't
sanitized the data, but this is just a tutorial for grade 10 students just
learning HTML and CSS with a little bit of PHP. I will get to that
protecting data later. (one concept at a time)
Thanks for the help!
<?php
// connects to server
include('includes/connect2.php');
// sets post to variables, don't know if this is needed
$user=$_POST[username];
$pass=$_POST[password];
?>
<?php
// query to find information in database
$result = mysqli_query($con, "SELECT * FROM social_register WHERE
Login='$user'" );
if ($pass == $result['Password']){?>
<div id="container">
<div id="banner">
The social Site
<div id="site_logo">
<img src="images/logo_thumb.gif" />
<?php
while($row = mysqli_fetch_array($result))
{
echo $row['First_Name'] . " " . $row['Last_Name'];
echo "<br>";
}
mysqli_close($con);
?>
</div>
</div>
<div id="person">
<h1>Welcome to your test web site</h1>
</div>
</div>
<?php
}
// else part of code to display result if user is not logged in
else
{
?>
<div id="container">
<div id="banner">
The social Site
<div id="site_logo">
<img src="images/logo_thumb.gif" />
</div>
</div>
<div id="person">
<h1>You have not loged into the site, please login.</h1>
</div>
<?php
}
?>
Overriding of Profile2 form template not working
Overriding of Profile2 form template not working
I am attempting to generate template files for user login, user register,
and now the edit profile pages on my site. The user login and user
register templates are working effectively. However, the edit profile
template doesn't seem to work. I am utilizing the Profile2 module, and the
form I'd like to theme is located at profile-main/#/edit.
function project_near_theme() {
$items = array();
// create custom user-login.tpl.php
$items['user_login'] = array(
'render element' => 'form',
'path' => drupal_get_path('theme', 'project_near') . '/templates',
'template' => 'user-login',
'preprocess functions' => array(
'project_near_preprocess_user_login'
),
);
// create custom user-register.tpl.php
$items['user_register_form'] = array(
'render element' => 'form',
'path' => drupal_get_path('theme','project_near') . '/templates',
'template' => 'user-register',
'preprocess functions' => array(
'project_near_preprocess_user_register_form'
),
);
// create custom user-profile-form.tpl.php
$items['user_profile_form'] = array(
'render element' => 'form',
'path' => drupal_get_path('theme','project_near') . '/templates',
'template' => 'user-profile-form',
'preprocess functions' => array(
'project_near_preprocess_user_profile_form'
),
);
return $items;
}
I am attempting to generate template files for user login, user register,
and now the edit profile pages on my site. The user login and user
register templates are working effectively. However, the edit profile
template doesn't seem to work. I am utilizing the Profile2 module, and the
form I'd like to theme is located at profile-main/#/edit.
function project_near_theme() {
$items = array();
// create custom user-login.tpl.php
$items['user_login'] = array(
'render element' => 'form',
'path' => drupal_get_path('theme', 'project_near') . '/templates',
'template' => 'user-login',
'preprocess functions' => array(
'project_near_preprocess_user_login'
),
);
// create custom user-register.tpl.php
$items['user_register_form'] = array(
'render element' => 'form',
'path' => drupal_get_path('theme','project_near') . '/templates',
'template' => 'user-register',
'preprocess functions' => array(
'project_near_preprocess_user_register_form'
),
);
// create custom user-profile-form.tpl.php
$items['user_profile_form'] = array(
'render element' => 'form',
'path' => drupal_get_path('theme','project_near') . '/templates',
'template' => 'user-profile-form',
'preprocess functions' => array(
'project_near_preprocess_user_profile_form'
),
);
return $items;
}
Friday, 30 August 2013
Is it possible to update a variable using a form in Rails?
Is it possible to update a variable using a form in Rails?
I'm working on a form that should allow users to update a session variable
called session[:city] that tracks their location. The variable doesn't
need to be saved in the database cause it's kind of a throwaway; it only
needs to exist while the user is on the site.
session[:city] is used in several places throughout the site, so I've
placed the following method in the Application Controller:
class ApplicationController < ActionController::Base
before_filter :set_city
def set_city
unless session[:city].present?
session[:city] = request.location.city
end
end
end
That part works correctly, and I'm able to call the variable throughout
the site.
The issue I'm having is in updating the variable by a form. The only
action I need it to do is update the variable, but it's not responding. I
know I'm missing something here, but after trying a bunch of things I'm a
bit stumped. This is my basic form currently:
<%= form_tag do %>
<%= text_field_tag session[:city] %>
<%= submit_tag %>
<% end %>
I'm working on a form that should allow users to update a session variable
called session[:city] that tracks their location. The variable doesn't
need to be saved in the database cause it's kind of a throwaway; it only
needs to exist while the user is on the site.
session[:city] is used in several places throughout the site, so I've
placed the following method in the Application Controller:
class ApplicationController < ActionController::Base
before_filter :set_city
def set_city
unless session[:city].present?
session[:city] = request.location.city
end
end
end
That part works correctly, and I'm able to call the variable throughout
the site.
The issue I'm having is in updating the variable by a form. The only
action I need it to do is update the variable, but it's not responding. I
know I'm missing something here, but after trying a bunch of things I'm a
bit stumped. This is my basic form currently:
<%= form_tag do %>
<%= text_field_tag session[:city] %>
<%= submit_tag %>
<% end %>
Thursday, 29 August 2013
Redirect POST Request in RESTful Controller - Zend Framework2
Redirect POST Request in RESTful Controller - Zend Framework2
After getting used to the RESTful Web Services in Zend Framework2, I
encountering a typical redirect problem when dealing with POST Request.
The problem is that I have furnished an extra action in my indexController
which extends AbstractRestfulController for the POST Request. But when
testing the URI in Simple Restful Client, I found out that the request is
automatically routed to the create method in the indexController.
Is there a way how I can forcefully redirect the POST Request to one of
the actions which I wanted to that is set in the routes in
module.config.php file
Well here is my indexController:
<?php
namespace Project\Controller;
use Zend\Mvc\Controller\AbstractRestfulController;
use Zend\Mvc\MvcEvent as Event;
use Zend\View\Model\JsonModel as Json;
use XmlStrategy\View\Model\XmlModel as Xml;
class IndexController extends AbstractRestfulController
{
public function getList ()
{
;
}
public function get ($id)
{
;
}
public function addAction ()
{
return $this->create(array(
'test' => "Test",
));
}
public function update ($id, $data)
{
;
}
public function create ($data)
{
;
}
public function delete ($id)
{
;
}
}
This is how im furnishing the routes
<?php
namespace Project;
return array(
'router' => array(
'routes' => array(
'home' => array(
'child_routes' => array(
'project' => array(
'type' => "Segment",
'options' => array(
'route' => "/project",
'defaults' => array(
'controller' =>
"Project\Controller\Index",
),
),
'may_terminate' => true,
'child_routes' => array(
'add' => array(
'type' => "Segment",
'options' => array(
'route' => "/add",
'defalults' => array(
'contoller' =>
"Project\Controller\Index",
'action' => "add",
),
),
'may_terminate' => true,
),
),
),
),
),
),
),
'view_manager' => array(
'strategies' => array(
"ViewJsonStrategy",
"ViewXMLStrategy",
),
),
);
But as described, when the URI with POST Request
www.myproject.com/project/add, i can see that it is redirected to the
create action in my controller
This is the error "Zend\View\Renderer\PhpRenderer::render: Unable to
render template "project/index/create"; resolver could not resolve to a
file"
Any help would be appreciated.
Thanks
After getting used to the RESTful Web Services in Zend Framework2, I
encountering a typical redirect problem when dealing with POST Request.
The problem is that I have furnished an extra action in my indexController
which extends AbstractRestfulController for the POST Request. But when
testing the URI in Simple Restful Client, I found out that the request is
automatically routed to the create method in the indexController.
Is there a way how I can forcefully redirect the POST Request to one of
the actions which I wanted to that is set in the routes in
module.config.php file
Well here is my indexController:
<?php
namespace Project\Controller;
use Zend\Mvc\Controller\AbstractRestfulController;
use Zend\Mvc\MvcEvent as Event;
use Zend\View\Model\JsonModel as Json;
use XmlStrategy\View\Model\XmlModel as Xml;
class IndexController extends AbstractRestfulController
{
public function getList ()
{
;
}
public function get ($id)
{
;
}
public function addAction ()
{
return $this->create(array(
'test' => "Test",
));
}
public function update ($id, $data)
{
;
}
public function create ($data)
{
;
}
public function delete ($id)
{
;
}
}
This is how im furnishing the routes
<?php
namespace Project;
return array(
'router' => array(
'routes' => array(
'home' => array(
'child_routes' => array(
'project' => array(
'type' => "Segment",
'options' => array(
'route' => "/project",
'defaults' => array(
'controller' =>
"Project\Controller\Index",
),
),
'may_terminate' => true,
'child_routes' => array(
'add' => array(
'type' => "Segment",
'options' => array(
'route' => "/add",
'defalults' => array(
'contoller' =>
"Project\Controller\Index",
'action' => "add",
),
),
'may_terminate' => true,
),
),
),
),
),
),
),
'view_manager' => array(
'strategies' => array(
"ViewJsonStrategy",
"ViewXMLStrategy",
),
),
);
But as described, when the URI with POST Request
www.myproject.com/project/add, i can see that it is redirected to the
create action in my controller
This is the error "Zend\View\Renderer\PhpRenderer::render: Unable to
render template "project/index/create"; resolver could not resolve to a
file"
Any help would be appreciated.
Thanks
Wednesday, 28 August 2013
Run function when another function finishes jQuery
Run function when another function finishes jQuery
When a page is done refreshing, jQuery event is launched:
$(#id).trigger('reloaded');
'reloaded' is a custom event;
How do i set up a listener , such that, when it is done 'reloading' , i
run another function:
I was thinking about this:
$(#id).on('reloaded',function(ev) {
alert("LAUNCH function");
});
But this doesnt work
When a page is done refreshing, jQuery event is launched:
$(#id).trigger('reloaded');
'reloaded' is a custom event;
How do i set up a listener , such that, when it is done 'reloading' , i
run another function:
I was thinking about this:
$(#id).on('reloaded',function(ev) {
alert("LAUNCH function");
});
But this doesnt work
Copy query output data from SQL SERVER 2012 and paste to Excel
Copy query output data from SQL SERVER 2012 and paste to Excel
I have a column that has data type varchar(max). Some rows in that column
have long text data. When I copy the SQL result set from that column and
paste to excel, the row gets split into multiple rows. I want to past in
sunch a way that single cell data from SQL server go to single cell in
excel. I am not sure how to fix that problem. Any suggestion would be
appreciated. Thank you
I have a column that has data type varchar(max). Some rows in that column
have long text data. When I copy the SQL result set from that column and
paste to excel, the row gets split into multiple rows. I want to past in
sunch a way that single cell data from SQL server go to single cell in
excel. I am not sure how to fix that problem. Any suggestion would be
appreciated. Thank you
Excel Counting non blank cells
Excel Counting non blank cells
I am having no luck trying to count my non blank cells in excel. I have
tried multiple formulas and I keep getting inaccurate data. Here is the
situation:
I am creating a Preventative Care list for my physicians (I have 4) I
created a list of all their patients that have received a letter re: Prev.
Care and I am inputting who needs a second letter and who has results.
Some results are negative, some are positive. I have the list set up in
alphabetical order on patients last name and then I have their physician
initials in the other column. I want to check to see what percentage of
each doctors patients have done their prev. care. I want to calculate this
separately. Unfortunately, the cells are no in order. I have tried
everything to my knowledge.
Help!
I am having no luck trying to count my non blank cells in excel. I have
tried multiple formulas and I keep getting inaccurate data. Here is the
situation:
I am creating a Preventative Care list for my physicians (I have 4) I
created a list of all their patients that have received a letter re: Prev.
Care and I am inputting who needs a second letter and who has results.
Some results are negative, some are positive. I have the list set up in
alphabetical order on patients last name and then I have their physician
initials in the other column. I want to check to see what percentage of
each doctors patients have done their prev. care. I want to calculate this
separately. Unfortunately, the cells are no in order. I have tried
everything to my knowledge.
Help!
add +1 or -1 value with like
add +1 or -1 value with like
hi every one i am working on socila website project now i am at end of
this but geting 1 problem i want to setup when click like button then its
show +1 with existing likes value . if already 10 likes then after click
on like its change into 11. but i did not find any solutin . i fin eaiest
script . below my working script like and unlike,
<script type="text/javascript">
$(document).ready(function () {
$(".like").click(function () {
var ID = $(this).attr("id");
var REL = $(this).attr("rel");
var URL = 'box_like.php';
var dataString = 'msg_id=' + ID + '&rel=' + REL;
$.ajax({
type: "POST",
url: URL,
data: dataString,
cache: false,
success: function (html) {
if (REL == 'Like') {
$('#' + ID).html('Unlike').attr('rel',
'Unlike').attr('title', 'Unlike');
} else {
$('#' + ID).attr('rel', 'Like').attr('title',
'Like').html('Like');
}
}
});
});
});
</script>
if somone add this script into likes counter i wil be thank full
hi every one i am working on socila website project now i am at end of
this but geting 1 problem i want to setup when click like button then its
show +1 with existing likes value . if already 10 likes then after click
on like its change into 11. but i did not find any solutin . i fin eaiest
script . below my working script like and unlike,
<script type="text/javascript">
$(document).ready(function () {
$(".like").click(function () {
var ID = $(this).attr("id");
var REL = $(this).attr("rel");
var URL = 'box_like.php';
var dataString = 'msg_id=' + ID + '&rel=' + REL;
$.ajax({
type: "POST",
url: URL,
data: dataString,
cache: false,
success: function (html) {
if (REL == 'Like') {
$('#' + ID).html('Unlike').attr('rel',
'Unlike').attr('title', 'Unlike');
} else {
$('#' + ID).attr('rel', 'Like').attr('title',
'Like').html('Like');
}
}
});
});
});
</script>
if somone add this script into likes counter i wil be thank full
Tuesday, 27 August 2013
Inserting list element in next to last position
Inserting list element in next to last position
Given a HTML unordered list
<ul id = "master_key_list">
<li id="master_key_23" class="available_element">Fix the Peanut Butter</li>
<li id="master_key_24" class="available_element">Focus on Price
Sensitivity</li>
<li id="master_key_25" class="available_element" >Focus on Messaging</li>
<li id="master_key_26" class="available_element">Create Growth and
Retention Funnels</li>
<li id="new_bp_element_element" class="available_element">Additional
Best Practice?</li>
</ul>
how can I add another list element before the last list element?
I've tried
$("#master_key_list li:last").before("<li />").append(appendString);
where appendString is a valid concatenated HTML text. However, all this is
doing is overwriting the last list element text, rather than actually
inserting it.
Given a HTML unordered list
<ul id = "master_key_list">
<li id="master_key_23" class="available_element">Fix the Peanut Butter</li>
<li id="master_key_24" class="available_element">Focus on Price
Sensitivity</li>
<li id="master_key_25" class="available_element" >Focus on Messaging</li>
<li id="master_key_26" class="available_element">Create Growth and
Retention Funnels</li>
<li id="new_bp_element_element" class="available_element">Additional
Best Practice?</li>
</ul>
how can I add another list element before the last list element?
I've tried
$("#master_key_list li:last").before("<li />").append(appendString);
where appendString is a valid concatenated HTML text. However, all this is
doing is overwriting the last list element text, rather than actually
inserting it.
How can I set height for Twitter bootstrap thumbnails?
How can I set height for Twitter bootstrap thumbnails?
I'm novice here :) I use twitter bootstrap (3.0) for my project and i'm
having trouble setting up thumbnail module.
The width is ok but i can't set up height of thumbnails (i can't align all
thumbnails at the same height).
How i can set one (standard) height for all the thumbnails and zoom/scale
image to center so they can fill all space without stretching the image?
Thank you!
<div class="row">
<!-- Thumbnail 0 -->
<div class="col-sm-6 col-md-3">
<a href="#" class="thumbnail">
<img src="img.png" alt="...">
</a>
<div class="caption">
<h4>Arctic MX-2, 8g</h4>
</div>
</div><!-- /thumbnail 0 -->
<!-- Thumbnail 1 -->
<div class="col-sm-6 col-md-3">
<a href="#" class="thumbnail">
<img src="blue.png" alt="...">
</a>
<div class="caption">
<h4>Arctic MX-2, 8g</h4>
</div>
</div><!-- /thumbnail 1 -->
</div><!-- /thumbnail -->
I'm novice here :) I use twitter bootstrap (3.0) for my project and i'm
having trouble setting up thumbnail module.
The width is ok but i can't set up height of thumbnails (i can't align all
thumbnails at the same height).
How i can set one (standard) height for all the thumbnails and zoom/scale
image to center so they can fill all space without stretching the image?
Thank you!
<div class="row">
<!-- Thumbnail 0 -->
<div class="col-sm-6 col-md-3">
<a href="#" class="thumbnail">
<img src="img.png" alt="...">
</a>
<div class="caption">
<h4>Arctic MX-2, 8g</h4>
</div>
</div><!-- /thumbnail 0 -->
<!-- Thumbnail 1 -->
<div class="col-sm-6 col-md-3">
<a href="#" class="thumbnail">
<img src="blue.png" alt="...">
</a>
<div class="caption">
<h4>Arctic MX-2, 8g</h4>
</div>
</div><!-- /thumbnail 1 -->
</div><!-- /thumbnail -->
Google Cloud Messaging for Android library vs. Google Play Services
Google Cloud Messaging for Android library vs. Google Play Services
Current Google GCM documentation requires you to install Google Play
Services and to use them for GCM (Google Cloud Messaging). The library is
1.1MB, yet my current .apk is half that size. My app is intended to
receive GCM and display some data on the screen, so I don't need Google
Play Services' Maps API, G+ login, etc. Nor I need to be able to respond
back to the server after getting GCM.
SDK Manager allows download and installation of standalone Google Cloud
Messaging for Android package. It is the one that was used before Google
I/O 2013, where Play Services were announced.
My question is: what is the difference in performance between GPS's GCM
and standalone GCM for Android? Do I really have to switch to GPS? Is
standalone GCM depricated? Can I still receive data (up to 4K) with
standalone GCM?
Current Google GCM documentation requires you to install Google Play
Services and to use them for GCM (Google Cloud Messaging). The library is
1.1MB, yet my current .apk is half that size. My app is intended to
receive GCM and display some data on the screen, so I don't need Google
Play Services' Maps API, G+ login, etc. Nor I need to be able to respond
back to the server after getting GCM.
SDK Manager allows download and installation of standalone Google Cloud
Messaging for Android package. It is the one that was used before Google
I/O 2013, where Play Services were announced.
My question is: what is the difference in performance between GPS's GCM
and standalone GCM for Android? Do I really have to switch to GPS? Is
standalone GCM depricated? Can I still receive data (up to 4K) with
standalone GCM?
Shadows on Google Maps visualRefresh
Shadows on Google Maps visualRefresh
In the Google Maps docs
(https://developers.google.com/maps/documentation/javascript/reference#MarkerOptions)
it says:
"Shadows are not rendered when google.maps.visualRefresh is set to true."
Is it possible to over-ride this and get the shadows to show up while
using the visualRefresh?
In the Google Maps docs
(https://developers.google.com/maps/documentation/javascript/reference#MarkerOptions)
it says:
"Shadows are not rendered when google.maps.visualRefresh is set to true."
Is it possible to over-ride this and get the shadows to show up while
using the visualRefresh?
Having content URL as an entry point for events at Google Analytincs Events Flow report
Having content URL as an entry point for events at Google Analytincs
Events Flow report
We are using Google Analytics Events Tracking to monitor the user
behaviour on a set of iFrames that are embedded into pages that we do not
own. I would like to use the Events Flow feature to see the flow of user
actions within the iFrames, but I cannot find a way to split the flow
according to the URL of the iFrames. I see that it is possible to use
Landing Page as events entry point, but since we are tracking iFrames, for
obvious reasons the Landing Page is set to "(not set)". Is it possible to
have the URL of the iFrame instead?
Events Flow report
We are using Google Analytics Events Tracking to monitor the user
behaviour on a set of iFrames that are embedded into pages that we do not
own. I would like to use the Events Flow feature to see the flow of user
actions within the iFrames, but I cannot find a way to split the flow
according to the URL of the iFrames. I see that it is possible to use
Landing Page as events entry point, but since we are tracking iFrames, for
obvious reasons the Landing Page is set to "(not set)". Is it possible to
have the URL of the iFrame instead?
How to install a new keyboard for my laptop
How to install a new keyboard for my laptop
i have Dell vostro laptop , and my keyboard is no more responding after i
drop a cup of coffee over it. i am thinking of buying a new keyboard and
attach it. but i have the following questions:-
will the new keyboard work well automatically without having to configure
it ?
in case the keyboard need some configuration , will i be able to install
it without having to type anything , while installting the new keyboard ,
Or i should have external keyboard while installing the new keyboard?
last question, after i drop the cofee over the keyboard , i have remove it
and i clean it using pure water ? could this have harmed the keyboard ?
i have Dell vostro laptop , and my keyboard is no more responding after i
drop a cup of coffee over it. i am thinking of buying a new keyboard and
attach it. but i have the following questions:-
will the new keyboard work well automatically without having to configure
it ?
in case the keyboard need some configuration , will i be able to install
it without having to type anything , while installting the new keyboard ,
Or i should have external keyboard while installing the new keyboard?
last question, after i drop the cofee over the keyboard , i have remove it
and i clean it using pure water ? could this have harmed the keyboard ?
"this" keyword in a javascript module
"this" keyword in a javascript module
I have defined the following module globally:
var module = (function () {
console.log(this);
this.fn = function () {
console.log(this);
}
return this;
})();
http://www.quirksmode.org/js/this.html :
In JavaScript |this| always refers to the "owner" of the function we're
executing, or rather, to the object that a function is a method of.
The first call to console.log logs Window as the value of this, and that I
understand. But, so does also the second call to console.log.
Since this refers to the owner of the function, why does module.fn log
Window and not module?
When I call fn I still have to write module.fn, I can't write Window.fn.
Since this refers to Window I find this confusing.
EDIT: I forgot to return this in my example.
I have defined the following module globally:
var module = (function () {
console.log(this);
this.fn = function () {
console.log(this);
}
return this;
})();
http://www.quirksmode.org/js/this.html :
In JavaScript |this| always refers to the "owner" of the function we're
executing, or rather, to the object that a function is a method of.
The first call to console.log logs Window as the value of this, and that I
understand. But, so does also the second call to console.log.
Since this refers to the owner of the function, why does module.fn log
Window and not module?
When I call fn I still have to write module.fn, I can't write Window.fn.
Since this refers to Window I find this confusing.
EDIT: I forgot to return this in my example.
Monday, 26 August 2013
import module or any component in python
import module or any component in python
during code implementation, I got suggestion we should import only
specific feature which will reduce time but I got some different result.
Am I doing some thing wrong.
python -m timeit "from subprocess import call" (suggested method which is
taking more time)
1000000 loops, best of 3: 1.01 usec per loop
python -m timeit "import subprocess"
1000000 loops, best of 3: 0.525 usec per loop
during code implementation, I got suggestion we should import only
specific feature which will reduce time but I got some different result.
Am I doing some thing wrong.
python -m timeit "from subprocess import call" (suggested method which is
taking more time)
1000000 loops, best of 3: 1.01 usec per loop
python -m timeit "import subprocess"
1000000 loops, best of 3: 0.525 usec per loop
Preventing implicit conversion in C++
Preventing implicit conversion in C++
I ask the user for an integer input and I do not want to execute code
unless it is strictly an integer.
int x;
if(cin >> x)
For instance if the user inputs a double above, the if statement will
execute with implicit conversion to an integer. Instead I don't want the
code to execute at all.
How can I prevent this?
I ask the user for an integer input and I do not want to execute code
unless it is strictly an integer.
int x;
if(cin >> x)
For instance if the user inputs a double above, the if statement will
execute with implicit conversion to an integer. Instead I don't want the
code to execute at all.
How can I prevent this?
CppUTest example doesn't work
CppUTest example doesn't work
I just installed CppUTest on my MAC using brew as indicated by the guide.
It failed when I tried to build the example cpp.
TEST_GROUP(FirstTestGroup)
{
};
TEST(FirstTestGroup, FirstTest)
{
FAIL("Fail me!");
}
I guess it is because the header file which define those macros are not
included. So I add include as below:
#include "CppUTest/TestHarness.h"
#include "CppUTest/TestOutput.h"
TEST_GROUP(FirstTestGroup)
{
};
TEST(FirstTestGroup, FirstTest)
{
FAIL("Fail me!");
}
Now I get bunch of errors.
Undefined symbols for architecture x86_64: "UtestShell::assertTrue(bool,
char const*, char const*, char const*, int)", referenced from: vtable for
TEST_FirstTestGroup_FirstTest_TestShellin ccNDwnbv.o
I just installed CppUTest on my MAC using brew as indicated by the guide.
It failed when I tried to build the example cpp.
TEST_GROUP(FirstTestGroup)
{
};
TEST(FirstTestGroup, FirstTest)
{
FAIL("Fail me!");
}
I guess it is because the header file which define those macros are not
included. So I add include as below:
#include "CppUTest/TestHarness.h"
#include "CppUTest/TestOutput.h"
TEST_GROUP(FirstTestGroup)
{
};
TEST(FirstTestGroup, FirstTest)
{
FAIL("Fail me!");
}
Now I get bunch of errors.
Undefined symbols for architecture x86_64: "UtestShell::assertTrue(bool,
char const*, char const*, char const*, int)", referenced from: vtable for
TEST_FirstTestGroup_FirstTest_TestShellin ccNDwnbv.o
How to change picture size
How to change picture size
I am afraid my pictures are too large. How do you convert pixels to inches
and what is the best size for sharing your pictures?
Thanks for your help - Bron
I am afraid my pictures are too large. How do you convert pixels to inches
and what is the best size for sharing your pictures?
Thanks for your help - Bron
List index out of Bounds error. Anyway to ensure that Query absolutely returns a QuoteLineItem=?iso-8859-1?Q?=3F_=96_salesforce.stackexchange.com?=
List index out of Bounds error. Anyway to ensure that Query absolutely
returns a QuoteLineItem? – salesforce.stackexchange.com
My test class requires a quote as an input. Thus, I am creating a quote
this way with SeeAllData=true. I'm limiting this by only selecting 1 quote
from all my production data. However, it seems that I …
returns a QuoteLineItem? – salesforce.stackexchange.com
My test class requires a quote as an input. Thus, I am creating a quote
this way with SeeAllData=true. I'm limiting this by only selecting 1 quote
from all my production data. However, it seems that I …
brute force on my wireless network
brute force on my wireless network
I was trying to hack my own wireless network. I could write a code that
could generate all possible combinations of characters and numbers.
However, I don't know how to make my PC to implement the generated keys to
the wireless network. (I have no knowledge of network, wireless, etc.) How
am I supposed to connect to wireless and match each generated password??
Here's the code below:
def createAllPossibleCharacterList():
list = []
# append upper-case letters
for i in range(65,91):
list.append(chr(i))
# append lower-case letters
for i in range(97,123):
list.append(chr(i))
# append numbers
for i in range(10):
i = str(i)
list.append(i)
#return the list
return list
def recursivelyFindKeys(list, key, keyLength):
if keyLength == 0:
print key
# in this stage, a key has to be inserted to see if it matches the
real password
else:
for i in range(len(list)):
recursivelyFindKeys(list, key + list[i], keyLength-1)
def main():
# call create... function to get all possible characters
list = []
list = createAllPossibleCharacterList()
key = ""
n = raw_input("upto what length of passwords?")
n = int(n)
# get keys
for i in range(n, 0, -1):
recursivelyFindKeys(list, key, i)
if __name__ == "__main__":
main()
I was trying to hack my own wireless network. I could write a code that
could generate all possible combinations of characters and numbers.
However, I don't know how to make my PC to implement the generated keys to
the wireless network. (I have no knowledge of network, wireless, etc.) How
am I supposed to connect to wireless and match each generated password??
Here's the code below:
def createAllPossibleCharacterList():
list = []
# append upper-case letters
for i in range(65,91):
list.append(chr(i))
# append lower-case letters
for i in range(97,123):
list.append(chr(i))
# append numbers
for i in range(10):
i = str(i)
list.append(i)
#return the list
return list
def recursivelyFindKeys(list, key, keyLength):
if keyLength == 0:
print key
# in this stage, a key has to be inserted to see if it matches the
real password
else:
for i in range(len(list)):
recursivelyFindKeys(list, key + list[i], keyLength-1)
def main():
# call create... function to get all possible characters
list = []
list = createAllPossibleCharacterList()
key = ""
n = raw_input("upto what length of passwords?")
n = int(n)
# get keys
for i in range(n, 0, -1):
recursivelyFindKeys(list, key, i)
if __name__ == "__main__":
main()
Plugin admin page stylesheet doesn't work
Plugin admin page stylesheet doesn't work
I am trying to style my plugin's admin page. Below is the code is use, but
neither the stylesheet nor the script shows up on my page.
add_action( 'admin_init', 'myplugin_admin_init' );
add_action( 'admin_menu', 'myplugin_custom_menu_page' );
function myplugin_custom_menu_page(){
$page = add_menu_page( 'My Plugin', 'My Plugin', 'manage_options',
'myplugin/myplugin-admin.php', '', plugins_url(
'myplugin/images/icon.png' ), 33 );
add_action( 'admin_enqueue_scripts' . $page, 'myplugin_admin_styles' );
add_action( 'admin_enqueue_scripts' . $page, 'myplugin_admin_scripts' );
}
function myplugin_admin_init() {
wp_register_script( 'myplugin-script', plugins_url(
'myplugin/script.js') );
wp_register_style( 'myplugin-style',
plugins_url('myplugin/stylesheet.css') );
}
function myplugin_admin_styles() {
wp_enqueue_style( 'myplugin-style' );
}
function myplugin_admin_scripts() {
wp_enqueue_script( 'myplugin-script' );
}
Any hints would be much appreciated!
I am trying to style my plugin's admin page. Below is the code is use, but
neither the stylesheet nor the script shows up on my page.
add_action( 'admin_init', 'myplugin_admin_init' );
add_action( 'admin_menu', 'myplugin_custom_menu_page' );
function myplugin_custom_menu_page(){
$page = add_menu_page( 'My Plugin', 'My Plugin', 'manage_options',
'myplugin/myplugin-admin.php', '', plugins_url(
'myplugin/images/icon.png' ), 33 );
add_action( 'admin_enqueue_scripts' . $page, 'myplugin_admin_styles' );
add_action( 'admin_enqueue_scripts' . $page, 'myplugin_admin_scripts' );
}
function myplugin_admin_init() {
wp_register_script( 'myplugin-script', plugins_url(
'myplugin/script.js') );
wp_register_style( 'myplugin-style',
plugins_url('myplugin/stylesheet.css') );
}
function myplugin_admin_styles() {
wp_enqueue_style( 'myplugin-style' );
}
function myplugin_admin_scripts() {
wp_enqueue_script( 'myplugin-script' );
}
Any hints would be much appreciated!
Android when using Downloadmanager how to get or calculate current speed?
Android when using Downloadmanager how to get or calculate current speed?
Android when using Downloadmanager how to get or calculate current speed ?
Do u have any good idea or some nice way to get it? thanks
Android when using Downloadmanager how to get or calculate current speed ?
Do u have any good idea or some nice way to get it? thanks
Sunday, 25 August 2013
Java Command Line Compilation Not Updating
Java Command Line Compilation Not Updating
I am using eclipse for writing some code, but using the command prompt to
compile it because I'm redirecting a file to the input, so initially I
compiled the java file and everything went fine, but I then made some
changes and when I recompiled the java file it just showed the previous
results (not the new results I should have received after compiling), why
is this happening? Any help would be greatly appreciated. Please note that
I have tried restarting and deleting the files (both .class and .java) and
copying the same code to a new java file with the same name, this did not
help, but creating a new file with a new name did work....but creating a
new file everytime I want to run/test a program is obviously not a
solution...
I am using eclipse for writing some code, but using the command prompt to
compile it because I'm redirecting a file to the input, so initially I
compiled the java file and everything went fine, but I then made some
changes and when I recompiled the java file it just showed the previous
results (not the new results I should have received after compiling), why
is this happening? Any help would be greatly appreciated. Please note that
I have tried restarting and deleting the files (both .class and .java) and
copying the same code to a new java file with the same name, this did not
help, but creating a new file with a new name did work....but creating a
new file everytime I want to run/test a program is obviously not a
solution...
Is there some elementary proof of invariance of domain?
Is there some elementary proof of invariance of domain?
Invariance of domain at least in statement seems a simple result. I mean,
the first time I saw the statement I thought: "the proof can't be that
bad", but when I searched for it I saw that it needs even algebraic
topology to prove this result.
My doubt is: isn't there any other proof of invariance of domain that
don't need to use algebraic topology? Is there some more elementary proof
of this result?
Thanks very much in advance!
Invariance of domain at least in statement seems a simple result. I mean,
the first time I saw the statement I thought: "the proof can't be that
bad", but when I searched for it I saw that it needs even algebraic
topology to prove this result.
My doubt is: isn't there any other proof of invariance of domain that
don't need to use algebraic topology? Is there some more elementary proof
of this result?
Thanks very much in advance!
Algorithm to represent a serie of number
Algorithm to represent a serie of number
It's simple: I have a serie of numbers and I want to put write that using
a algorithm (iterative or recursive, doesn't matter... but the best answer
could be iterative).
Contextualizing: This numbers are indexes to iterative over a list of
lists. I need to do a permutation (combination, comutation, i don't know
exactly), but I need to generate all combinations of all positions of that
list of lists.
The serie is:
1 1
2 1
3 1
4 1
5 1
1 2
2 1
3 1
4 1
5 1
1 3
2 1
3 1
4 1
5 1
1 4
2 1
3 1
4 1
5 1
1 5
2 1
3 1
4 1
5 1
1 1
2 2
3 1
4 1
5 1
1 2
2 2
3 1
4 1
5 1
1 3
2 2
3 1
4 1
5 1
1 4
2 2
3 1
4 1
5 1
1 5
2 2
3 1
4 1
5 1
1 1
2 3
3 1
4 1
5 1
1 2
2 3
3 1
4 1
5 1
1 3
2 3
3 1
4 1
5 1
1 4
2 3
3 1
4 1
5 1
1 5
2 3
3 1
4 1
5 1
1 1
2 4
3 1
4 1
5 1
and so on... the last state is:
1 5
2 5
3 5
4 5
5 5
Note that at each line break is a step of iteration or recursion.
I hope that you can help me ! (:
It's simple: I have a serie of numbers and I want to put write that using
a algorithm (iterative or recursive, doesn't matter... but the best answer
could be iterative).
Contextualizing: This numbers are indexes to iterative over a list of
lists. I need to do a permutation (combination, comutation, i don't know
exactly), but I need to generate all combinations of all positions of that
list of lists.
The serie is:
1 1
2 1
3 1
4 1
5 1
1 2
2 1
3 1
4 1
5 1
1 3
2 1
3 1
4 1
5 1
1 4
2 1
3 1
4 1
5 1
1 5
2 1
3 1
4 1
5 1
1 1
2 2
3 1
4 1
5 1
1 2
2 2
3 1
4 1
5 1
1 3
2 2
3 1
4 1
5 1
1 4
2 2
3 1
4 1
5 1
1 5
2 2
3 1
4 1
5 1
1 1
2 3
3 1
4 1
5 1
1 2
2 3
3 1
4 1
5 1
1 3
2 3
3 1
4 1
5 1
1 4
2 3
3 1
4 1
5 1
1 5
2 3
3 1
4 1
5 1
1 1
2 4
3 1
4 1
5 1
and so on... the last state is:
1 5
2 5
3 5
4 5
5 5
Note that at each line break is a step of iteration or recursion.
I hope that you can help me ! (:
Saturday, 24 August 2013
Eager Loading issue with Bullet Gem
Eager Loading issue with Bullet Gem
I have installed the bullet gem to check for N+1 query issues, but I think
it is incorrectly giving me an N+1 query found notice:
User has_one profile
User has_many posts
In my Users Index action, I have:
User.includes(:profile, :post).where("profiles.city IS NOT
NULL").where("posts IS NOT NULL")
I checked my log and Profile and Posts are being loaded in memory, But I
still get a warning from the gem every time I go to the index gem:
N+1 Query detected
User => [:posts, :profile]
Add to your finder: :include => [:posts, :profile]
I have installed the bullet gem to check for N+1 query issues, but I think
it is incorrectly giving me an N+1 query found notice:
User has_one profile
User has_many posts
In my Users Index action, I have:
User.includes(:profile, :post).where("profiles.city IS NOT
NULL").where("posts IS NOT NULL")
I checked my log and Profile and Posts are being loaded in memory, But I
still get a warning from the gem every time I go to the index gem:
N+1 Query detected
User => [:posts, :profile]
Add to your finder: :include => [:posts, :profile]
Change label of current panel in tabbed pane
Change label of current panel in tabbed pane
Hello I need to change the label of the currently selected tab in tabbed
pane. It is for when the user saves the file the change must be reflected
in the label of the current panel in the tabbed pane.
Hello I need to change the label of the currently selected tab in tabbed
pane. It is for when the user saves the file the change must be reflected
in the label of the current panel in the tabbed pane.
Do Apps using iOS Social Framework get affected by Rate Limits?
Do Apps using iOS Social Framework get affected by Rate Limits?
I'm making an app that utilizes Apple's Social Framework to access
Twitter. I plan on eventually releasing it on the app store. I know
twitter has rate limits such as 15 requests/15 mins per endpoint per user.
I am also aware that twitter has 100,000 user limit for apps, however I
don't know how this works with Apple Social Framework. I don't explicitly
create an app on twitter's site, and don't have a client id. Since there
is no application id when using Social Framework, do these limits still
apply?
I'm making an app that utilizes Apple's Social Framework to access
Twitter. I plan on eventually releasing it on the app store. I know
twitter has rate limits such as 15 requests/15 mins per endpoint per user.
I am also aware that twitter has 100,000 user limit for apps, however I
don't know how this works with Apple Social Framework. I don't explicitly
create an app on twitter's site, and don't have a client id. Since there
is no application id when using Social Framework, do these limits still
apply?
proper way to send ajax json to play framework
proper way to send ajax json to play framework
I've read a couple of posts here regarding how to do this and I can get it
working only half-way.
This works (sending json object as text):
function go(itemid)
{
apiRoutes.controllers.Application.addItem(itemid).ajax({
data: '{"reqid":0,"iid":2,"description":"adsf"}',
dataType: 'text',
contentType:'application/json',
success: function(reply) {
alert(reply)
}
});
}
This does not (sending object as json):
function go(itemid)
{
apiRoutes.controllers.Application.addItem(itemid).ajax({
data: {"reqid":0,"iid":2,"description":"adsf"},
dataType: 'json',
contentType:'application/json',
success: function(reply) {
alert(reply)
}
});
}
And what I really want to do is something like this (I've already set up
the proper combinators):
function go(itemid)
{
apiRoutes.controllers.Application.addItem(itemid).ajax({
data: @Html(Json.stringify(Json.toJson(item))),
dataType: 'text',
contentType:'application/json',
success: function(reply) {
alert(reply)
}
});
}
My controller looks like this:
def addItem(id: Long) = Action (parse.json) { implicit request =>
Logger.info("add item")
request.body.validate(Item.itemReads).map { item =>
thing.addItem(item)
Ok("Succesfully added item.")
}.recoverTotal{
e => BadRequest("Detected error:"+ JsError.toFlatJson(e))
}
}
In the second case, it never gets to the logging code. Instead it returns
a 400 Bad Request immediately (this is likely something triggered in the
Action (parse.json) bit I think).
I'd rather send the object as json because when I convert to string and
description happens to have an apostrophe in it (') that messes things up.
I could probaby escape the apostrophe, but hoping that I'm missing
something simple about how to do this with an object rather than a string.
Thanks
I've read a couple of posts here regarding how to do this and I can get it
working only half-way.
This works (sending json object as text):
function go(itemid)
{
apiRoutes.controllers.Application.addItem(itemid).ajax({
data: '{"reqid":0,"iid":2,"description":"adsf"}',
dataType: 'text',
contentType:'application/json',
success: function(reply) {
alert(reply)
}
});
}
This does not (sending object as json):
function go(itemid)
{
apiRoutes.controllers.Application.addItem(itemid).ajax({
data: {"reqid":0,"iid":2,"description":"adsf"},
dataType: 'json',
contentType:'application/json',
success: function(reply) {
alert(reply)
}
});
}
And what I really want to do is something like this (I've already set up
the proper combinators):
function go(itemid)
{
apiRoutes.controllers.Application.addItem(itemid).ajax({
data: @Html(Json.stringify(Json.toJson(item))),
dataType: 'text',
contentType:'application/json',
success: function(reply) {
alert(reply)
}
});
}
My controller looks like this:
def addItem(id: Long) = Action (parse.json) { implicit request =>
Logger.info("add item")
request.body.validate(Item.itemReads).map { item =>
thing.addItem(item)
Ok("Succesfully added item.")
}.recoverTotal{
e => BadRequest("Detected error:"+ JsError.toFlatJson(e))
}
}
In the second case, it never gets to the logging code. Instead it returns
a 400 Bad Request immediately (this is likely something triggered in the
Action (parse.json) bit I think).
I'd rather send the object as json because when I convert to string and
description happens to have an apostrophe in it (') that messes things up.
I could probaby escape the apostrophe, but hoping that I'm missing
something simple about how to do this with an object rather than a string.
Thanks
Reading a file line by line and splitting the string into tokens in c
Reading a file line by line and splitting the string into tokens in c
I am reading a file line by line and splitting the string into tokens.
int main()
{
FILE* fp;
char line[255];
fp = fopen("file.txt" , "r");
while (fgets(line, sizeof(line), fp) != NULL)
{
char val1[16];
char val2[9];
strcpy(val1, strtok(line, ","));
strcpy(val2, strtok(NULL, ","));
printf("%s|%s\n", val1, val2);
}
}
My input file content (file.txt)
182930101222, KLA1512
182930101223, KLA1513
182930101224, KLA1514
182930101225, KLA1515
When I print get
| KLA1512
Instead of
182930101222| KLA1512
What is the issue ?
I am reading a file line by line and splitting the string into tokens.
int main()
{
FILE* fp;
char line[255];
fp = fopen("file.txt" , "r");
while (fgets(line, sizeof(line), fp) != NULL)
{
char val1[16];
char val2[9];
strcpy(val1, strtok(line, ","));
strcpy(val2, strtok(NULL, ","));
printf("%s|%s\n", val1, val2);
}
}
My input file content (file.txt)
182930101222, KLA1512
182930101223, KLA1513
182930101224, KLA1514
182930101225, KLA1515
When I print get
| KLA1512
Instead of
182930101222| KLA1512
What is the issue ?
How to change path location of image from a folder to another
How to change path location of image from a folder to another
I have some pictures in path/TempFolder after clicking on AddButton I want
to change their locations one by one to path/Images and change their names
any idea?
I have some pictures in path/TempFolder after clicking on AddButton I want
to change their locations one by one to path/Images and change their names
any idea?
Is there a Chrome extension that can replace words that I type with other words I define?
Is there a Chrome extension that can replace words that I type with other
words I define?
Eg: I swear too much online and I want replace "m*** f***" with "my friend".
Maybe "I f*** love cake" to "I flipping love cake".
Or "I'm sick and tired of these monday to friday snakes on this monkey
fighting plane"
You get the idea. :)
words I define?
Eg: I swear too much online and I want replace "m*** f***" with "my friend".
Maybe "I f*** love cake" to "I flipping love cake".
Or "I'm sick and tired of these monday to friday snakes on this monkey
fighting plane"
You get the idea. :)
Friday, 23 August 2013
Scrapy exports invalid json
Scrapy exports invalid json
My parse looks like this:
def parse(self, response):
hxs = HtmlXPathSelector(response)
titles = hxs.select("//tr/td")
items = []
for titles in titles:
item = MyItem()
item['title'] = titles.select('h3/a/text()').extract()
items.append(item)
return items
Why does it output json like this:
[{"title": ["random title #1"]},
{"title": ["random title #2"]}]
My parse looks like this:
def parse(self, response):
hxs = HtmlXPathSelector(response)
titles = hxs.select("//tr/td")
items = []
for titles in titles:
item = MyItem()
item['title'] = titles.select('h3/a/text()').extract()
items.append(item)
return items
Why does it output json like this:
[{"title": ["random title #1"]},
{"title": ["random title #2"]}]
php creating an update function, binding, arrays and PDO
php creating an update function, binding, arrays and PDO
ok so im continuing on my journey of learning to adapt to PDO and also OOP
and at a slow rate.
Here is my issue. im trying to create a function to handle updates to
mysql, it feels so complicated to the point i would be just as well to
type it out manually. I will be doing a lot of handling big updates from
forms so i wanted to make this function reusable but i think i way over
complicated it, is there a more concise way while also keeping the code
easy to review?
this is my update function:
// take data from arrays, loop through and print each out
// concatenate this onto SET and concatenate the where clause
// on the end unless there is no criteria in which case print nothing
public function update_sql($table="users",$update_array,$criteria=""){
$sql = 'UPDATE `'.$table.'` SET ';
$sqlFieldParams = array();
// creating an array with `user_id` = :user_id etc etc
foreach ($update_array as $fieldName => $fieldValue) {
$sqlFieldParams [] = $fieldName . '= :' . $fieldName;
}
// concatenate but don't print where if there is no criteria passed
$sql .= implode(', ', $sqlFieldParams) . ($criteria ? ' WHERE ' .
$criteria : "");
$this->query("$sql");
}
my function to bind and execute which i also use for insert and other
statements that need binding.
public function bind_execute($bind_array){
// bind the values
foreach ($bind_array as $field => $item) {
$this->bind(':'.$field,$item);
}
// execute the update
$this->execute();
}
and a couple more reusable functions that are used in this script just for
reference
// prepare our SQL Queries
public function query($query){
$this->stmt = $this->dbh->prepare($query);
}
// use switch to select the appropriate type for the value been passed
// $param = placeholder name e.g username, $value = myusername
public function bind($param, $value, $type = null){
if (is_null($type)) {
switch (true) {
case is_int($value):
$type = PDO::PARAM_INT;
break;
case is_bool($value):
$type = PDO::PARAM_BOOL;
break;
case is_null($value):
$type = PDO::PARAM_NULL;
break;
default:
$type = PDO::PARAM_STR;
}
}
// run the binding process
$this->stmt->bindValue($param, $value, $type);
}
// execute the prepared statement
public function execute(){
return $this->stmt->execute();
}
And now my monstrous update statement
$this->user_id = $_GET['id'];
$this->user_activation_hash = $_GET['verification_code'];
// create an array to pass these values to be set to the update function
$update_array = array(
'user_active' => '1',
'user_activation_hash' => 'NULL',
);
// create the where clause
$criteria = 'WHERE user_id = :user_id AND user_activation_hash =
:user_activation_hash';
// create the update statement
// pass in values table, array & criteria
$database->update_sql('users',$update_array,$criteria);
// these are other values that need binding from the where clause
$criteria_array = array(
'user_id => $this->user_id
);
// join the set values of the update with the where values
// in the one array to merge then in a for loop next
$bind_array = array_merge($update_array, $criteria_array);
$database->bind_execute($bind_array);
Thoughts, feedback? Better approach? I guess its only 5 lines if you strip
it down but i think i might have over-complicated it?
ok so im continuing on my journey of learning to adapt to PDO and also OOP
and at a slow rate.
Here is my issue. im trying to create a function to handle updates to
mysql, it feels so complicated to the point i would be just as well to
type it out manually. I will be doing a lot of handling big updates from
forms so i wanted to make this function reusable but i think i way over
complicated it, is there a more concise way while also keeping the code
easy to review?
this is my update function:
// take data from arrays, loop through and print each out
// concatenate this onto SET and concatenate the where clause
// on the end unless there is no criteria in which case print nothing
public function update_sql($table="users",$update_array,$criteria=""){
$sql = 'UPDATE `'.$table.'` SET ';
$sqlFieldParams = array();
// creating an array with `user_id` = :user_id etc etc
foreach ($update_array as $fieldName => $fieldValue) {
$sqlFieldParams [] = $fieldName . '= :' . $fieldName;
}
// concatenate but don't print where if there is no criteria passed
$sql .= implode(', ', $sqlFieldParams) . ($criteria ? ' WHERE ' .
$criteria : "");
$this->query("$sql");
}
my function to bind and execute which i also use for insert and other
statements that need binding.
public function bind_execute($bind_array){
// bind the values
foreach ($bind_array as $field => $item) {
$this->bind(':'.$field,$item);
}
// execute the update
$this->execute();
}
and a couple more reusable functions that are used in this script just for
reference
// prepare our SQL Queries
public function query($query){
$this->stmt = $this->dbh->prepare($query);
}
// use switch to select the appropriate type for the value been passed
// $param = placeholder name e.g username, $value = myusername
public function bind($param, $value, $type = null){
if (is_null($type)) {
switch (true) {
case is_int($value):
$type = PDO::PARAM_INT;
break;
case is_bool($value):
$type = PDO::PARAM_BOOL;
break;
case is_null($value):
$type = PDO::PARAM_NULL;
break;
default:
$type = PDO::PARAM_STR;
}
}
// run the binding process
$this->stmt->bindValue($param, $value, $type);
}
// execute the prepared statement
public function execute(){
return $this->stmt->execute();
}
And now my monstrous update statement
$this->user_id = $_GET['id'];
$this->user_activation_hash = $_GET['verification_code'];
// create an array to pass these values to be set to the update function
$update_array = array(
'user_active' => '1',
'user_activation_hash' => 'NULL',
);
// create the where clause
$criteria = 'WHERE user_id = :user_id AND user_activation_hash =
:user_activation_hash';
// create the update statement
// pass in values table, array & criteria
$database->update_sql('users',$update_array,$criteria);
// these are other values that need binding from the where clause
$criteria_array = array(
'user_id => $this->user_id
);
// join the set values of the update with the where values
// in the one array to merge then in a for loop next
$bind_array = array_merge($update_array, $criteria_array);
$database->bind_execute($bind_array);
Thoughts, feedback? Better approach? I guess its only 5 lines if you strip
it down but i think i might have over-complicated it?
CSS box-shadow overlapping navbar
CSS box-shadow overlapping navbar
http://jsfiddle.net/CVFvb/
The right edge of the HANDY DANDY LOGO AREA has a box shadow that overlaps
the navbar section. I would like it to not overlap.
(NOTE: The sharpness of the box-shadow is purely for the purposes of this
example. I have it nice and fuzzy in the actual page)
I've tried:
Changing z-index (which puts the whole logobox behind the navbar)
Putting the logobox inside the navbar div (which only messes up the
positioning of the logobox, which is fixable, but doesn't solve the
dropshadow overlap)
Thanks for any help you can provide.
HTML:
<div id="logobox">HANDY DANDY LOGO AREA</div>
<div id="navbar">
<span class="navbarspan"><a class="tab navbaritem active"
pagetoshow="content_home" href="javascript:void(0);">Home</a></span>
<span class="navbarspan"><a class="tab navbaritem"
pagetoshow="content_services" id="servicesanchor"
href="javascript:void(0)">Section 1</a>
</span>
<span class="navbarspan"><a class="tab navbaritem"
pagetoshow="content_examples" id="examplesanchor"
href="javascript:void(0);">Section 2</a>
</span>
<span class="navbarspan right"><a class="tab navbaritem"
pagetoshow="content_contact" href="javascript:void(0);">Contact
Us</a></span>
</div>
CSS:
#logobox {
background: white;
border: 1px solid #486EAC;
border-bottom-left-radius: 10px;
border-bottom-right-radius: 10px;
border-top: none;
float: left;
margin: 10px;
padding: 5px 10px 10px 10px;
position: relative;
top: -10px;
box-shadow: 5px 5px 10px #CCCCCC;
-webkit-box-shadow: 5px 5px 0px #CCCCCC;
-moz-box-shadow: 5px 5px 0px #CCCCCC;
}
#navbar {
background: #486EAC;
padding: 3px;
box-shadow: 2px 2px 10px #CCCCCC;
-webkit-box-shadow: 5px 5px 0px #CCCCCC;
-moz-box-shadow: 5px 5px 0px #CCCCCC;
}
.navbarspan {
padding: 0px 3px;
}
.navbarspan a:hover {
background-color: #F3D13A;
color: black;
border: none;
}
.navbaritem {
font-weight: bold;
color: white;
text-align: center;
padding: 3px 6px;
text-decoration: none;
}
.right {
float: right;
}
http://jsfiddle.net/CVFvb/
The right edge of the HANDY DANDY LOGO AREA has a box shadow that overlaps
the navbar section. I would like it to not overlap.
(NOTE: The sharpness of the box-shadow is purely for the purposes of this
example. I have it nice and fuzzy in the actual page)
I've tried:
Changing z-index (which puts the whole logobox behind the navbar)
Putting the logobox inside the navbar div (which only messes up the
positioning of the logobox, which is fixable, but doesn't solve the
dropshadow overlap)
Thanks for any help you can provide.
HTML:
<div id="logobox">HANDY DANDY LOGO AREA</div>
<div id="navbar">
<span class="navbarspan"><a class="tab navbaritem active"
pagetoshow="content_home" href="javascript:void(0);">Home</a></span>
<span class="navbarspan"><a class="tab navbaritem"
pagetoshow="content_services" id="servicesanchor"
href="javascript:void(0)">Section 1</a>
</span>
<span class="navbarspan"><a class="tab navbaritem"
pagetoshow="content_examples" id="examplesanchor"
href="javascript:void(0);">Section 2</a>
</span>
<span class="navbarspan right"><a class="tab navbaritem"
pagetoshow="content_contact" href="javascript:void(0);">Contact
Us</a></span>
</div>
CSS:
#logobox {
background: white;
border: 1px solid #486EAC;
border-bottom-left-radius: 10px;
border-bottom-right-radius: 10px;
border-top: none;
float: left;
margin: 10px;
padding: 5px 10px 10px 10px;
position: relative;
top: -10px;
box-shadow: 5px 5px 10px #CCCCCC;
-webkit-box-shadow: 5px 5px 0px #CCCCCC;
-moz-box-shadow: 5px 5px 0px #CCCCCC;
}
#navbar {
background: #486EAC;
padding: 3px;
box-shadow: 2px 2px 10px #CCCCCC;
-webkit-box-shadow: 5px 5px 0px #CCCCCC;
-moz-box-shadow: 5px 5px 0px #CCCCCC;
}
.navbarspan {
padding: 0px 3px;
}
.navbarspan a:hover {
background-color: #F3D13A;
color: black;
border: none;
}
.navbaritem {
font-weight: bold;
color: white;
text-align: center;
padding: 3px 6px;
text-decoration: none;
}
.right {
float: right;
}
How to detect Ambiguous and Invalid DateTime in PHP?
How to detect Ambiguous and Invalid DateTime in PHP?
When dealing with local DateTime values provided by a user, it's quite
possible to have a time that is either invalid or ambiguous, due to
Daylight Saving Time transitions.
In other languages and frameworks, there are often methods such as
isAmbiguous and isValid, on some representation of the time zone. For
example in .NET, there is TimeZoneInfo.IsAmbiguousTime and
TimeZoneInfo.IsInvalidTime. Plenty of other time zone implementations have
similar methods.
PHP has excellent time zone support, but I can't seem to find these. The
closest thing I can find is DateTimeZone::getTransitions. That provides
the raw data, so I can see that some methods could be written on top of
this. But do they exist already somewhere? If not, can anyone provide a
good implementation? I would expect them to work something like this:
$tz = new DateTimeZone('America/New_York');
echo $tz-> isValidTime(new DateTime('2013-03-10 02:00:00')); # false
echo $tz-> isAmbiguousTime(new DateTime('2013-11-03 01:00:00')); # true
When dealing with local DateTime values provided by a user, it's quite
possible to have a time that is either invalid or ambiguous, due to
Daylight Saving Time transitions.
In other languages and frameworks, there are often methods such as
isAmbiguous and isValid, on some representation of the time zone. For
example in .NET, there is TimeZoneInfo.IsAmbiguousTime and
TimeZoneInfo.IsInvalidTime. Plenty of other time zone implementations have
similar methods.
PHP has excellent time zone support, but I can't seem to find these. The
closest thing I can find is DateTimeZone::getTransitions. That provides
the raw data, so I can see that some methods could be written on top of
this. But do they exist already somewhere? If not, can anyone provide a
good implementation? I would expect them to work something like this:
$tz = new DateTimeZone('America/New_York');
echo $tz-> isValidTime(new DateTime('2013-03-10 02:00:00')); # false
echo $tz-> isAmbiguousTime(new DateTime('2013-11-03 01:00:00')); # true
Instantiating an object in PHP
Instantiating an object in PHP
I'm a new OOP programmer in PHP. I would like to know :
What's the order of the instantiation methods are they called?
What should I include before the class definition?
What should I include in the method __autoload()?
Thanks for you help.
I'm a new OOP programmer in PHP. I would like to know :
What's the order of the instantiation methods are they called?
What should I include before the class definition?
What should I include in the method __autoload()?
Thanks for you help.
socket.gaierror: [Errno 11001] getaddrinfo failed
socket.gaierror: [Errno 11001] getaddrinfo failed
I have tried to attached a file to the mail using python. Code:
import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
from smtplib import SMTPException
def send_Email():
file1="abc.txt"
message = "Request for new dump"
msg = MIMEMultipart()
msg.attach(MIMEText(file(file1).read()))
try:
smtpObj = smtplib.SMTP('smtp server name',port)
smtpObj.sendmail(sender, EmailId, message, msg.as_string() )
print "Successfully sent email"
except SMTPException:
print "Error: unable to send email"
Bt I have get the error: socket.gaierror: [Errno 11001] getaddrinfo failed
I have tried to attached a file to the mail using python. Code:
import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
from smtplib import SMTPException
def send_Email():
file1="abc.txt"
message = "Request for new dump"
msg = MIMEMultipart()
msg.attach(MIMEText(file(file1).read()))
try:
smtpObj = smtplib.SMTP('smtp server name',port)
smtpObj.sendmail(sender, EmailId, message, msg.as_string() )
print "Successfully sent email"
except SMTPException:
print "Error: unable to send email"
Bt I have get the error: socket.gaierror: [Errno 11001] getaddrinfo failed
How to read a text file having unicode codes in C++?
How to read a text file having unicode codes in C++?
If I initialize a string:
std::string unicode8String = "\u00C1 M\u00F3ti S\u00F3l";
and print using cout, then output is
Á Móti Sól.
But when I read same same string "\u00C1 M\u00F3ti S\u00F3l" from a text
file using ifstream and store it in a std::string, and print it, output is
\u00C1 M\u00F3ti S\u00F3l
but I want it to print Á Móti Sól. The text file I have : \u00C1 M\u00F3ti
S\u00F3l And I want my program to read it and print Á Móti Sól
Is there any method for the above conversion ?
If I initialize a string:
std::string unicode8String = "\u00C1 M\u00F3ti S\u00F3l";
and print using cout, then output is
Á Móti Sól.
But when I read same same string "\u00C1 M\u00F3ti S\u00F3l" from a text
file using ifstream and store it in a std::string, and print it, output is
\u00C1 M\u00F3ti S\u00F3l
but I want it to print Á Móti Sól. The text file I have : \u00C1 M\u00F3ti
S\u00F3l And I want my program to read it and print Á Móti Sól
Is there any method for the above conversion ?
Thursday, 22 August 2013
Tons of Undefined struct-union type and of incomplete type is not allowed
Tons of Undefined struct-union type and of incomplete type is not allowed
I'm pretty new to C++ and C, and I just integrated a source into a Windows
Phone Runtime Component. When compiling the library it self, everything is
fine, but when trying to instantiate some of the structures and objects,
it stats to display several errors like these one:
13 IntelliSense: incomplete type is not allowed
c:\Users\mouss_000\Documents\Visual Studio
2012\Projects\melo\melo\DecoderTest.c 131 33 melo
16 IntelliSense: argument of type "MLO_FrameData *" is incompatible with
parameter of type "const MLO_Byte *" c:\Users\mouss_000\Documents\Visual
Studio 2012\Projects\melo\melo\DecoderTest.c 141 49 melo
11 IntelliSense: argument of type "MLO_Decoder **" is incompatible with
parameter of type "const MLO_DecoderConfig *"
c:\Users\mouss_000\Documents\Visual Studio
2012\Projects\melo\melo\DecoderTest.c 87 33 melo
This test is based on the library that compiles fine, but it seems I can'
use any of the classes, structs or member without getting these errors. Is
this type of error linked with a common scenario and/or a newbie_C++_coder
pattern?
[Edit]
Code:
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include "Melo.h"
#include "MloUtils.h"
/*----------------------------------------------------------------------
| Macros
+---------------------------------------------------------------------*/
/* Keeps all the frames from the stream */
#define MLO_DECODER_TEST_CONTINUOUS_STREAM
/* Do not display or save anything to get a rough idea of the speed */
#undef MLO_DECODER_TEST_FAST
/*----------------------------------------------------------------------
| ShowFrame
+---------------------------------------------------------------------*/
static void
ShowFrame(MLO_FrameData* frame)
{
#if ! defined (MLO_DECODER_TEST_FAST)
printf("Frame: sf=%lu, ch=%u, len=%u, s=%s, p=%s\n",
frame->info.sampling_frequency,
frame->info.channel_configuration,
frame->info.frame_length,
frame->info.standard == MLO_AAC_STANDARD_MPEG2 ? "MPEG2" : "MPEG4",
frame->info.profile == MLO_AAC_PROFILE_MAIN ? "MAIN" :
frame->info.profile == MLO_AAC_PROFILE_LC ? "LC" :
frame->info.profile == MLO_AAC_PROFILE_SSR ? "SSR" : "?");
I'm pretty new to C++ and C, and I just integrated a source into a Windows
Phone Runtime Component. When compiling the library it self, everything is
fine, but when trying to instantiate some of the structures and objects,
it stats to display several errors like these one:
13 IntelliSense: incomplete type is not allowed
c:\Users\mouss_000\Documents\Visual Studio
2012\Projects\melo\melo\DecoderTest.c 131 33 melo
16 IntelliSense: argument of type "MLO_FrameData *" is incompatible with
parameter of type "const MLO_Byte *" c:\Users\mouss_000\Documents\Visual
Studio 2012\Projects\melo\melo\DecoderTest.c 141 49 melo
11 IntelliSense: argument of type "MLO_Decoder **" is incompatible with
parameter of type "const MLO_DecoderConfig *"
c:\Users\mouss_000\Documents\Visual Studio
2012\Projects\melo\melo\DecoderTest.c 87 33 melo
This test is based on the library that compiles fine, but it seems I can'
use any of the classes, structs or member without getting these errors. Is
this type of error linked with a common scenario and/or a newbie_C++_coder
pattern?
[Edit]
Code:
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include "Melo.h"
#include "MloUtils.h"
/*----------------------------------------------------------------------
| Macros
+---------------------------------------------------------------------*/
/* Keeps all the frames from the stream */
#define MLO_DECODER_TEST_CONTINUOUS_STREAM
/* Do not display or save anything to get a rough idea of the speed */
#undef MLO_DECODER_TEST_FAST
/*----------------------------------------------------------------------
| ShowFrame
+---------------------------------------------------------------------*/
static void
ShowFrame(MLO_FrameData* frame)
{
#if ! defined (MLO_DECODER_TEST_FAST)
printf("Frame: sf=%lu, ch=%u, len=%u, s=%s, p=%s\n",
frame->info.sampling_frequency,
frame->info.channel_configuration,
frame->info.frame_length,
frame->info.standard == MLO_AAC_STANDARD_MPEG2 ? "MPEG2" : "MPEG4",
frame->info.profile == MLO_AAC_PROFILE_MAIN ? "MAIN" :
frame->info.profile == MLO_AAC_PROFILE_LC ? "LC" :
frame->info.profile == MLO_AAC_PROFILE_SSR ? "SSR" : "?");
Generating Uniformly Distributed Pseudo-random Numbers in C++
Generating Uniformly Distributed Pseudo-random Numbers in C++
In cplusplus.com reference it's stated that, using modulo operator when
trying to generate random numbers will make lower numbers more likely:
random_var = rand() % 100 + 1; //this will generate numbers between 1-100
Why are lower numbers more likely? And if they're, why aren't we using
this code below :
random_var = rand()/(RAND_MAX/100) + 1; //also will generate those, more
uniform I guess
In cplusplus.com reference it's stated that, using modulo operator when
trying to generate random numbers will make lower numbers more likely:
random_var = rand() % 100 + 1; //this will generate numbers between 1-100
Why are lower numbers more likely? And if they're, why aren't we using
this code below :
random_var = rand()/(RAND_MAX/100) + 1; //also will generate those, more
uniform I guess
installing non-hp RAM in hp proliant ml310e G8
installing non-hp RAM in hp proliant ml310e G8
i bought the hp proliant ml310e G8 with 8GB of crucial RAM. but when i
plug it in the system initialization hangs on 90%. i read in another post
(HP ProLiant ML310e Gen8 early system initialization hangs on 90%) that
you cant install non-hp memory. but is there really no way to this? isnt
it possible to skip the initialization?
i bought the hp proliant ml310e G8 with 8GB of crucial RAM. but when i
plug it in the system initialization hangs on 90%. i read in another post
(HP ProLiant ML310e Gen8 early system initialization hangs on 90%) that
you cant install non-hp memory. but is there really no way to this? isnt
it possible to skip the initialization?
pass static class's string constant into clientside code
pass static class's string constant into clientside code
Passing a serverside variable into a client isn't anything too rough
var Variable = '<%= ServerVaraible %>'
where ServerVaraible is something accessible publicly in the codebehind,
easy peasy
now lets say I have a Static Class as such
namespace Server.Helpers
{
public static class QueryStringConstants
{
public static string CARID = "carId";
}
}
Why can't I go: var Variable = '<%=
Server.Helpers.QueryStringConstants.CARID %>'
if I do this i get an error saying
'System.Web.HttpServerUtility' does not contain a definition for 'Helpers'
and no extension method 'Helpers' accepting a first argument of type
'System.Web.HttpServerUtility' could be found
I am sure I am ment to be declaring something, but I am not 100% sure
what......
Passing a serverside variable into a client isn't anything too rough
var Variable = '<%= ServerVaraible %>'
where ServerVaraible is something accessible publicly in the codebehind,
easy peasy
now lets say I have a Static Class as such
namespace Server.Helpers
{
public static class QueryStringConstants
{
public static string CARID = "carId";
}
}
Why can't I go: var Variable = '<%=
Server.Helpers.QueryStringConstants.CARID %>'
if I do this i get an error saying
'System.Web.HttpServerUtility' does not contain a definition for 'Helpers'
and no extension method 'Helpers' accepting a first argument of type
'System.Web.HttpServerUtility' could be found
I am sure I am ment to be declaring something, but I am not 100% sure
what......
Android FrameLayout
Android FrameLayout
I need to create a gauge. The first image will be static and holds the
measurements and markings. The second image will slide in from bottom to
top. To simulate a water tank.
What will be the best way to handle this problem?
I have done this in css and jquery but cant seen to find a way around it
in android native.
any ideas?
I need to create a gauge. The first image will be static and holds the
measurements and markings. The second image will slide in from bottom to
top. To simulate a water tank.
What will be the best way to handle this problem?
I have done this in css and jquery but cant seen to find a way around it
in android native.
any ideas?
tcp server client communication read() write() problems. c language
tcp server client communication read() write() problems. c language
I have problem, i write a tcp client in c but problem is that client send
command to server server send response to that command, response is
xxx#.But in client when i read from socket i read 2 response from server
for example xxx#xxx#.know client send response only for first response
form server and one response is delete.this is not the same all the time
for example client may read only 1 response ind will response to that.HOW
TO SEARCH FOR # in char array and to extract commands and client response
to all response from server.Any ideas?
i have idea for one write from client to server to read response in client
is that good idea or i write to server and in one read i read all
response?
example
I have problem, i write a tcp client in c but problem is that client send
command to server server send response to that command, response is
xxx#.But in client when i read from socket i read 2 response from server
for example xxx#xxx#.know client send response only for first response
form server and one response is delete.this is not the same all the time
for example client may read only 1 response ind will response to that.HOW
TO SEARCH FOR # in char array and to extract commands and client response
to all response from server.Any ideas?
i have idea for one write from client to server to read response in client
is that good idea or i write to server and in one read i read all
response?
example
Wednesday, 21 August 2013
Getting a Selected Text In SWT Browser Widgets
Getting a Selected Text In SWT Browser Widgets
I am implementing SWT Browser in my Project for displaying a WebPage.
After displaying a web page into this browser, if a user selects
particular text, how can I get the selected text? please help me with
suitable example
I am implementing SWT Browser in my Project for displaying a WebPage.
After displaying a web page into this browser, if a user selects
particular text, how can I get the selected text? please help me with
suitable example
forms not closing or still show as an open process
forms not closing or still show as an open process
Okay so I have a game launcher written in VB.NET, which includes file
security as a separate form which opens before the launcher itself, well
sometimes if I get an error like unable to patch because my patch version
file is for some reason incorrect, it will close, but stays open in task
manager as a process running at about 25-50+% CPU, I have been using
Application.Exit for any closing commands, I have replaced the patch error
message box like the following
If patchVer = latest Then
Form1.Label1.Text = "No New Updates"
ElseIf patchVer > latest Then
MessageBox.Show("Error in patch Version, deleting patch.txt.")
Try
If IO.File.Exists("patch.txt") Then
IO.File.Delete("patch.txt")
Application.Exit()
End If
Catch ex As Exception
End Try
End If
The original code is like this.
If patchVer = latest Then
Form1.Label1.Text = "No New Updates"
ElseIf patchVer > latest Then
MessageBox.Show("Error in patch Version. Repatching Now")
Try
Functions.finishedLaunching()
If IO.File.Exists("patch.txt") Then
IO.File.Delete("patch.txt")
End If
Application.Restart()
Catch ex As Exception
MessageBox.Show("Can not repatch.")
Application.Exit()
End Try
End If
another problem would be if the patch.txt file was higher than the actual
patch version, MessageBox.Show("Error in patch Version. Repatching Now")
loops over and over after Application.Restart() and each time you click OK
it closes but leaves behind a process, adding a process each time you do
this.
Okay so I have a game launcher written in VB.NET, which includes file
security as a separate form which opens before the launcher itself, well
sometimes if I get an error like unable to patch because my patch version
file is for some reason incorrect, it will close, but stays open in task
manager as a process running at about 25-50+% CPU, I have been using
Application.Exit for any closing commands, I have replaced the patch error
message box like the following
If patchVer = latest Then
Form1.Label1.Text = "No New Updates"
ElseIf patchVer > latest Then
MessageBox.Show("Error in patch Version, deleting patch.txt.")
Try
If IO.File.Exists("patch.txt") Then
IO.File.Delete("patch.txt")
Application.Exit()
End If
Catch ex As Exception
End Try
End If
The original code is like this.
If patchVer = latest Then
Form1.Label1.Text = "No New Updates"
ElseIf patchVer > latest Then
MessageBox.Show("Error in patch Version. Repatching Now")
Try
Functions.finishedLaunching()
If IO.File.Exists("patch.txt") Then
IO.File.Delete("patch.txt")
End If
Application.Restart()
Catch ex As Exception
MessageBox.Show("Can not repatch.")
Application.Exit()
End Try
End If
another problem would be if the patch.txt file was higher than the actual
patch version, MessageBox.Show("Error in patch Version. Repatching Now")
loops over and over after Application.Restart() and each time you click OK
it closes but leaves behind a process, adding a process each time you do
this.
(iOS) adding multiple items to scrollview, but can't scroll?
(iOS) adding multiple items to scrollview, but can't scroll?
I'm writing a UI for iOS and I need to create a scrolling view of
note-type widgets. I'm experimenting with creating a scrollview and adding
some UIView objects to it, but for some reason, I can't scroll, am I doing
something wrong? Here's what I'm doing:
[_testScrollView setBackgroundColor:[UIColor purpleColor]];
NSUInteger size = 100;
float height = _testScrollView.frame.size.height/10;
float width = _testScrollView.frame.size.width;
float currTop = 0;
CGSize fooSize = CGSizeMake(_testScrollView.frame.size.width,
_testScrollView.frame.size.height);
[_testScrollView setContentSize:fooSize];
for (NSUInteger i = 0; i < size; i++)
{
double red = ((double)arc4random() / ARC4RANDOM_MAX);
double green = ((double)arc4random() / ARC4RANDOM_MAX);
double blue = ((double)arc4random() / ARC4RANDOM_MAX);
CGRect currFrame = CGRectMake(0, currTop, width, height);
UIView* testView = [[UIView alloc] initWithFrame:currFrame];
[testView setBackgroundColor:[UIColor colorWithRed:red green:green
blue:blue alpha:1.0]];
[_testScrollView addSubview:testView];
currTop += height;
}
I would've expected to scroll through the scrollview and be able to go
through all of the 100 UIViews added. What am I missing?
I'm writing a UI for iOS and I need to create a scrolling view of
note-type widgets. I'm experimenting with creating a scrollview and adding
some UIView objects to it, but for some reason, I can't scroll, am I doing
something wrong? Here's what I'm doing:
[_testScrollView setBackgroundColor:[UIColor purpleColor]];
NSUInteger size = 100;
float height = _testScrollView.frame.size.height/10;
float width = _testScrollView.frame.size.width;
float currTop = 0;
CGSize fooSize = CGSizeMake(_testScrollView.frame.size.width,
_testScrollView.frame.size.height);
[_testScrollView setContentSize:fooSize];
for (NSUInteger i = 0; i < size; i++)
{
double red = ((double)arc4random() / ARC4RANDOM_MAX);
double green = ((double)arc4random() / ARC4RANDOM_MAX);
double blue = ((double)arc4random() / ARC4RANDOM_MAX);
CGRect currFrame = CGRectMake(0, currTop, width, height);
UIView* testView = [[UIView alloc] initWithFrame:currFrame];
[testView setBackgroundColor:[UIColor colorWithRed:red green:green
blue:blue alpha:1.0]];
[_testScrollView addSubview:testView];
currTop += height;
}
I would've expected to scroll through the scrollview and be able to go
through all of the 100 UIViews added. What am I missing?
Using MySQL results array more than once
Using MySQL results array more than once
I have the following code in my page
<?php
$dbc = mysql_connect();
$db = mysql_select_db();
$results= mysql_query("SELECT * FROM tbl_teams");
?>
<div class="datagrid"><table>
<thead><tr><th>header</th><th>header</th><th>header</th></tr></thead>
<tbody>
<tr>
<td>
<select name="game1_team1"><option value="0">Choose Team 1</OPTION><?php
while($row = mysql_fetch_array($results)) {echo '<option
value="'.$row['team_ID'].'">'. $row['team_name'].'</option>';}?></select>
</td>
<td>Vs.</td>
<td>
<select name="game1_team2"><option value="0">Choose Team 2</OPTION><?php
while($row = mysql_fetch_array($results)) {echo '<option
value="'.$row['team_ID'].'">'. $row['team_name'].'</option>';}?></select>
</td>
</tr>
The code shows the names of football teams from the MySQL table in
dropdown game1_team1 but not in game1_team2; it's as though I can't use
the same query twice. How do I remedy this? I'd like to use the same
values for 60 identical drop downs on the page.
Can I store the values into an array and resuse them in each dropdown?
I have the following code in my page
<?php
$dbc = mysql_connect();
$db = mysql_select_db();
$results= mysql_query("SELECT * FROM tbl_teams");
?>
<div class="datagrid"><table>
<thead><tr><th>header</th><th>header</th><th>header</th></tr></thead>
<tbody>
<tr>
<td>
<select name="game1_team1"><option value="0">Choose Team 1</OPTION><?php
while($row = mysql_fetch_array($results)) {echo '<option
value="'.$row['team_ID'].'">'. $row['team_name'].'</option>';}?></select>
</td>
<td>Vs.</td>
<td>
<select name="game1_team2"><option value="0">Choose Team 2</OPTION><?php
while($row = mysql_fetch_array($results)) {echo '<option
value="'.$row['team_ID'].'">'. $row['team_name'].'</option>';}?></select>
</td>
</tr>
The code shows the names of football teams from the MySQL table in
dropdown game1_team1 but not in game1_team2; it's as though I can't use
the same query twice. How do I remedy this? I'd like to use the same
values for 60 identical drop downs on the page.
Can I store the values into an array and resuse them in each dropdown?
Android get contact name from contact list
Android get contact name from contact list
I'm trying to get a contact name from contacts list. I have a function
that accepts SMS and pulled out the phone number. Now I'm trying to see if
anyone is with this phone number contact list. I checked the forum and
found a neat explanation.
I'm trying to get a contact name from contacts list. I have a function
that accepts SMS and pulled out the phone number. Now I'm trying to see if
anyone is with this phone number contact list. I checked the forum and
found a neat explanation.
how to call wsdl in c#
how to call wsdl in c#
how to call a WSDL in c#? can anyone tell me alternate solution for the
given task perform and the given
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
request.addProperty("username",PhoneNumber);
request.addProperty(" passward", PhoneNumber);ere
how to call a WSDL in c#? can anyone tell me alternate solution for the
given task perform and the given
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
request.addProperty("username",PhoneNumber);
request.addProperty(" passward", PhoneNumber);ere
Css opacity and image
Css opacity and image
I have image inside div with transparency , the problem it´s with this
image , the div needs be trasparent but no the image , when use opacity in
div the image also change to this opacity and that´s the problem
#cp_advise
{
position:absolute;
width:100%;
height:99%;
left:50%;
margin-left:-50%;
background-color:#111;
z-index:999;
-ms-filter:"progid:DXImageTransform.Microsoft.Alpha(Opacity=50)";
filter: alpha(opacity=60);
-moz-opacity:0.6;
-khtml-opacity: 0.6;
opacity: 0.6;
text-align:center;
}
<div id="cp_advise">
<img src='services.png'>
</div>
I try use z-index over the image but continue the problem
Thank´s , Regards !
I have image inside div with transparency , the problem it´s with this
image , the div needs be trasparent but no the image , when use opacity in
div the image also change to this opacity and that´s the problem
#cp_advise
{
position:absolute;
width:100%;
height:99%;
left:50%;
margin-left:-50%;
background-color:#111;
z-index:999;
-ms-filter:"progid:DXImageTransform.Microsoft.Alpha(Opacity=50)";
filter: alpha(opacity=60);
-moz-opacity:0.6;
-khtml-opacity: 0.6;
opacity: 0.6;
text-align:center;
}
<div id="cp_advise">
<img src='services.png'>
</div>
I try use z-index over the image but continue the problem
Thank´s , Regards !
Tuesday, 20 August 2013
How parse HTML in PHP?
How parse HTML in PHP?
I know we can use PHP DOM to parse HTML using PHP. I found lot of
questions here on stackoverflow too. But I have a specific requirement. I
have an HTML content like below
<p class="Heading1-P">
<span class="Heading1-H">Chapter 1</span>
</p>
<p class="Normal-P">
<span class="Normal-H">This is chapter 1</span>
</p>
<p class="Heading1-P">
<span class="Heading1-H">Chapter 2</span>
</p>
<p class="Normal-P">
<span class="Normal-H">This is chapter 2</span>
</p>
<p class="Heading1-P">
<span class="Heading1-H">Chapter 3</span>
</p>
<p class="Normal-P">
<span class="Normal-H">This is chapter 3</span>
</p>
I want to parse the above HTML and save the conent into two different
array like
$heading and $content
$heading = array('Chapter 1','Chapter 2','Chapter 3');
$content = array('This is chapter 1','This is chapter 2','This is chapter
3');
I can achieve this simply using jQuery. But I am not sure, is it the right
way. It would be great if some can point me to right direction. Thanks in
advance.
I know we can use PHP DOM to parse HTML using PHP. I found lot of
questions here on stackoverflow too. But I have a specific requirement. I
have an HTML content like below
<p class="Heading1-P">
<span class="Heading1-H">Chapter 1</span>
</p>
<p class="Normal-P">
<span class="Normal-H">This is chapter 1</span>
</p>
<p class="Heading1-P">
<span class="Heading1-H">Chapter 2</span>
</p>
<p class="Normal-P">
<span class="Normal-H">This is chapter 2</span>
</p>
<p class="Heading1-P">
<span class="Heading1-H">Chapter 3</span>
</p>
<p class="Normal-P">
<span class="Normal-H">This is chapter 3</span>
</p>
I want to parse the above HTML and save the conent into two different
array like
$heading and $content
$heading = array('Chapter 1','Chapter 2','Chapter 3');
$content = array('This is chapter 1','This is chapter 2','This is chapter
3');
I can achieve this simply using jQuery. But I am not sure, is it the right
way. It would be great if some can point me to right direction. Thanks in
advance.
Loading Bitmaps Properly in Android
Loading Bitmaps Properly in Android
I'm creating an android app and have run into OOM problems due to Bitmap
images. I certainly need to make the images smaller in terms of memory
however I would like to practice correct memory consumption and load them
correctly.
Currently my layouts contain the references to the images within the
res/drawable-hdpi folder as their backgrounds. I looked at this other
stack overflow question: outOfMemoryError with background drawables where
the person asking the question had the same problem as I did. I see that
the answer states that I should reference the Bitmaps in java and then
recycle onPause and set them back up during onResume. Now does this mean
that I should not set the backgrounds in xml and then do so within java
oncreate and then recycle and set them back up during onResume? Also, I
was looking into WeakReferencing but have found myself getting confused by
it... Could anyone give me a good explanation of WeakReferencing?
I appreciate all answers,
Cheers,
Jake
I'm creating an android app and have run into OOM problems due to Bitmap
images. I certainly need to make the images smaller in terms of memory
however I would like to practice correct memory consumption and load them
correctly.
Currently my layouts contain the references to the images within the
res/drawable-hdpi folder as their backgrounds. I looked at this other
stack overflow question: outOfMemoryError with background drawables where
the person asking the question had the same problem as I did. I see that
the answer states that I should reference the Bitmaps in java and then
recycle onPause and set them back up during onResume. Now does this mean
that I should not set the backgrounds in xml and then do so within java
oncreate and then recycle and set them back up during onResume? Also, I
was looking into WeakReferencing but have found myself getting confused by
it... Could anyone give me a good explanation of WeakReferencing?
I appreciate all answers,
Cheers,
Jake
Conditional comments - Include javascript based on IE Version
Conditional comments - Include javascript based on IE Version
I am running a DotNetNuke CMS website built on ASP.NET framework.
I have a few scripts in my page skin that I do not want to run on IE8 and
below. I've been google'ing around, and I've found this IE conditional
statement.
<![if gt IE 8]>
As per http://msdn.microsoft.com/en-us/library/ms537512%28v=vs.85%29.aspx
, this snippit should include the code inbetween for any browser that is
greater than IE8. I attempted to use this conditional statement in the
following manner:
<![if gt IE 8]>
<script type="text/javascript"
src="//s7.addthis.com/js/300/addthis_widget.js#pubid=ra-4f21643b21c50811"></script>
<![endif]-->
However, this does not seem to work, and the scripts do not run on any
browser. Is there a better way to accomplish this goal? Is there a syntax
error in my code?
Thanks for your help! Alex
I am running a DotNetNuke CMS website built on ASP.NET framework.
I have a few scripts in my page skin that I do not want to run on IE8 and
below. I've been google'ing around, and I've found this IE conditional
statement.
<![if gt IE 8]>
As per http://msdn.microsoft.com/en-us/library/ms537512%28v=vs.85%29.aspx
, this snippit should include the code inbetween for any browser that is
greater than IE8. I attempted to use this conditional statement in the
following manner:
<![if gt IE 8]>
<script type="text/javascript"
src="//s7.addthis.com/js/300/addthis_widget.js#pubid=ra-4f21643b21c50811"></script>
<![endif]-->
However, this does not seem to work, and the scripts do not run on any
browser. Is there a better way to accomplish this goal? Is there a syntax
error in my code?
Thanks for your help! Alex
How can I get a block cursor in Vim in the Cygwin terminal?
How can I get a block cursor in Vim in the Cygwin terminal?
I am used to having a block cursor in normal mode in Vim. This makes sense
with the Vim paradigm; when you press x, it is clear which character will
be deleted.
I've installed Cygwin on a Windows computer, but when I use Vim in its
terminal, I get the I cursor, even in normal mode. How can I make the
cursor be a block instead?
I am used to having a block cursor in normal mode in Vim. This makes sense
with the Vim paradigm; when you press x, it is clear which character will
be deleted.
I've installed Cygwin on a Windows computer, but when I use Vim in its
terminal, I get the I cursor, even in normal mode. How can I make the
cursor be a block instead?
Concat content of ContentPresenter
Concat content of ContentPresenter
Trying to set the text inside progressBar and i am getting properly with
Setters. but i have to concat this value with:
{TemplateBinding Value}+"% Completed
How do i concat with some other Text.
Code where text printed inside progressbar:
<Border x:Name="whiteBorder" >
<ContentPresenter x:Name="perHolder" Content="{TemplateBinding
Value}" VerticalAlignment="Center" HorizontalAlignment="Right"/>
</Border>
Trying to set the text inside progressBar and i am getting properly with
Setters. but i have to concat this value with:
{TemplateBinding Value}+"% Completed
How do i concat with some other Text.
Code where text printed inside progressbar:
<Border x:Name="whiteBorder" >
<ContentPresenter x:Name="perHolder" Content="{TemplateBinding
Value}" VerticalAlignment="Center" HorizontalAlignment="Right"/>
</Border>
Call a console app from remote machine [on hold]
Call a console app from remote machine [on hold]
I have a console app installed on my Server,Which I have developed myself
And I want to call a function inside that console app from a remote
machine ..Is it possible? If yes How can I achieve this? Like You all know
if it was a ASP.Net Web applicatio , I can Call its function through an
API.I Am wondering IF there is any way of calling a console application
function from outside world through C# code or something else?
I have a console app installed on my Server,Which I have developed myself
And I want to call a function inside that console app from a remote
machine ..Is it possible? If yes How can I achieve this? Like You all know
if it was a ASP.Net Web applicatio , I can Call its function through an
API.I Am wondering IF there is any way of calling a console application
function from outside world through C# code or something else?
Multi project setup for testing with gradle in android
Multi project setup for testing with gradle in android
I'm migrating my android project to gradle. I'm using multi-project
configuration for several android-libraries and it's working ok, but I'm
having a problem setting up my testing project with multi-project
settings. For external reasons I need to continue using this structure.
MyProject/
| settings.gradle
+ MyApp/
| build.gradle
| src
| res
| libs
+ Instrumentation-Tests/
| build.gradle
| src
| res
| libs
my current configuration looks like:
settings.gradle:
include ':MyApp', 'Instrumentation-Tests'
MyAppp/build.gradle:
apply plugin: 'android'
repositories {
mavenCentral()
}
dependencies {
compile files('.....jar')
compile project('....')
compile 'com.android.support:support-v4:13.0.+'
}
android {
compileSdkVersion 17
buildToolsVersion "17.0.0"
defaultConfig {
minSdkVersion 11
targetSdkVersion 16
}
sourceSets {
main {
manifest.srcFile 'AndroidManifest.xml'
java.srcDirs = ['src']
resources.srcDirs = ['src']
aidl.srcDirs = ['src']
renderscript.srcDirs = ['src']
res.srcDirs = ['res']
assets.srcDirs = ['assets']
}
}
}
And finally my Instrumentation-Tests/build.gradle
apply plugin: 'android'
repositories {
mavenCentral()
}
dependencies {
compile project(':MyApp')
compile files('.....jar')
compile 'com.android.support:support-v4:13.0.+'
}
android {
compileSdkVersion 17
buildToolsVersion "17.0.0"
defaultConfig {
minSdkVersion 11
targetSdkVersion 16
}
sourceSets {
main {
manifest.srcFile 'AndroidManifest.xml'
java.srcDirs = ['src']
resources.srcDirs = ['src']
aidl.srcDirs = ['src']
renderscript.srcDirs = ['src']
res.srcDirs = ['res']
assets.srcDirs = ['assets']
}
}
}
When I run 'gradle compileDebug' the project MyApp is compiled correctly
(and all its modules) but the Instrumentation-Tests compilation fails
because it can not find the android classes defined in MyApp.
I've read documentation and a lot of posts but I couldn't make it work, I
do also tried using:
compile(project(':MyApp')) { transitive = true }
when declaring the dependency.
Does anybody run the same problem? How can I force to include the output
of the MyApp project dependency into the classpath of
Instrumentation-Tests compilation?
Thanks
I'm migrating my android project to gradle. I'm using multi-project
configuration for several android-libraries and it's working ok, but I'm
having a problem setting up my testing project with multi-project
settings. For external reasons I need to continue using this structure.
MyProject/
| settings.gradle
+ MyApp/
| build.gradle
| src
| res
| libs
+ Instrumentation-Tests/
| build.gradle
| src
| res
| libs
my current configuration looks like:
settings.gradle:
include ':MyApp', 'Instrumentation-Tests'
MyAppp/build.gradle:
apply plugin: 'android'
repositories {
mavenCentral()
}
dependencies {
compile files('.....jar')
compile project('....')
compile 'com.android.support:support-v4:13.0.+'
}
android {
compileSdkVersion 17
buildToolsVersion "17.0.0"
defaultConfig {
minSdkVersion 11
targetSdkVersion 16
}
sourceSets {
main {
manifest.srcFile 'AndroidManifest.xml'
java.srcDirs = ['src']
resources.srcDirs = ['src']
aidl.srcDirs = ['src']
renderscript.srcDirs = ['src']
res.srcDirs = ['res']
assets.srcDirs = ['assets']
}
}
}
And finally my Instrumentation-Tests/build.gradle
apply plugin: 'android'
repositories {
mavenCentral()
}
dependencies {
compile project(':MyApp')
compile files('.....jar')
compile 'com.android.support:support-v4:13.0.+'
}
android {
compileSdkVersion 17
buildToolsVersion "17.0.0"
defaultConfig {
minSdkVersion 11
targetSdkVersion 16
}
sourceSets {
main {
manifest.srcFile 'AndroidManifest.xml'
java.srcDirs = ['src']
resources.srcDirs = ['src']
aidl.srcDirs = ['src']
renderscript.srcDirs = ['src']
res.srcDirs = ['res']
assets.srcDirs = ['assets']
}
}
}
When I run 'gradle compileDebug' the project MyApp is compiled correctly
(and all its modules) but the Instrumentation-Tests compilation fails
because it can not find the android classes defined in MyApp.
I've read documentation and a lot of posts but I couldn't make it work, I
do also tried using:
compile(project(':MyApp')) { transitive = true }
when declaring the dependency.
Does anybody run the same problem? How can I force to include the output
of the MyApp project dependency into the classpath of
Instrumentation-Tests compilation?
Thanks
Monday, 19 August 2013
Access Modifiers on methods obtained from Interfaces
Access Modifiers on methods obtained from Interfaces
interface ursus
{
public void eat();
}
class grizzly implements ursus
{
public void eat() //Line 1
{
System.out.println("Grizzly eats Salmon ");
}
}
class polar implements ursus
{
public void eat() //Line 2
{
System.out.println("Polar eats seals ");
}
}
class ursus_test
{
public static void main(String args[])
{
grizzly g = new grizzly();
polar p = new polar();
p.eat();
g.eat();
}
}
When I remove the access modifier "public" from Line1/Line 2, the compiler
complains that I am applying weaker access privileges for the methods
"eat()" obtained from the ursus interface.
Does it mean that all methods obtained from interfaces should be only
"public" on the classes which implement that interface ?
interface ursus
{
public void eat();
}
class grizzly implements ursus
{
public void eat() //Line 1
{
System.out.println("Grizzly eats Salmon ");
}
}
class polar implements ursus
{
public void eat() //Line 2
{
System.out.println("Polar eats seals ");
}
}
class ursus_test
{
public static void main(String args[])
{
grizzly g = new grizzly();
polar p = new polar();
p.eat();
g.eat();
}
}
When I remove the access modifier "public" from Line1/Line 2, the compiler
complains that I am applying weaker access privileges for the methods
"eat()" obtained from the ursus interface.
Does it mean that all methods obtained from interfaces should be only
"public" on the classes which implement that interface ?
SQL Server Query for values within same Table
SQL Server Query for values within same Table
I have a data table (not very well structured) in which I have the following
ClientID | Parameter | Value
111..........Street..........Evergreen
111..........Zip................75244
111..........Country.........USA
222..........Street..........Evergreen
222..........Zip................75244
222..........Country.........USA
333..........Street..........Evergreen
333..........Zip................75240
333..........Country.........USA
444..........Street..........Evergreen
444..........Zip................75240
444..........Country.........USA
555..........Street..........Evergreen
555..........Zip................75240
555..........Country.........USA
666..........Street..........Some Street
666..........Zip................75244
666..........Country.........USA
For this I want to Select all those Client ID that are on Street =
Evergreen BUT also with ZIP 75244, I have over 700K rows so, exporting all
would be a big issue.
My idea was:
SELECT ClientID from (select ClientID from table1 where Value =
'evergreen') Where Zip = '75244'
But it wont give me the accuarte results in this case I would like to get
the values for ClientIDs 111 and 222 because the match the criteria Im
looking for Street= Evergreen adn Zip=75244
Is there a way to do this?
I have a data table (not very well structured) in which I have the following
ClientID | Parameter | Value
111..........Street..........Evergreen
111..........Zip................75244
111..........Country.........USA
222..........Street..........Evergreen
222..........Zip................75244
222..........Country.........USA
333..........Street..........Evergreen
333..........Zip................75240
333..........Country.........USA
444..........Street..........Evergreen
444..........Zip................75240
444..........Country.........USA
555..........Street..........Evergreen
555..........Zip................75240
555..........Country.........USA
666..........Street..........Some Street
666..........Zip................75244
666..........Country.........USA
For this I want to Select all those Client ID that are on Street =
Evergreen BUT also with ZIP 75244, I have over 700K rows so, exporting all
would be a big issue.
My idea was:
SELECT ClientID from (select ClientID from table1 where Value =
'evergreen') Where Zip = '75244'
But it wont give me the accuarte results in this case I would like to get
the values for ClientIDs 111 and 222 because the match the criteria Im
looking for Street= Evergreen adn Zip=75244
Is there a way to do this?
Best strategy to maintain a sorted list subject to realtime updates
Best strategy to maintain a sorted list subject to realtime updates
I'm building a HTML list that is very much similar to Facebooks timeline
feature. The list will ontain at most 100 items, so performance isn't a
requirement.
Unlike Facebook's timeline however, my list would be quite dynamic. For
example different events are arrive in realtime and depending on the
timestamp, might get prepended to the list, inserted (I can't guarantee
that new events will necessarily arrive in time order) and even removed.
On top of that, it would be nice to animate updating of the list
(add/inser/remove) too, but that's a separate issue.
I wonder what the best strategy to maintain the list (sorted by time of
course), once I've built it up with initial data?
Thanks.
I'm building a HTML list that is very much similar to Facebooks timeline
feature. The list will ontain at most 100 items, so performance isn't a
requirement.
Unlike Facebook's timeline however, my list would be quite dynamic. For
example different events are arrive in realtime and depending on the
timestamp, might get prepended to the list, inserted (I can't guarantee
that new events will necessarily arrive in time order) and even removed.
On top of that, it would be nice to animate updating of the list
(add/inser/remove) too, but that's a separate issue.
I wonder what the best strategy to maintain the list (sorted by time of
course), once I've built it up with initial data?
Thanks.
C++ std::stringstream not implicitely converting unsigned char
C++ std::stringstream not implicitely converting unsigned char
I'm using a stringstream in C++ to build (many) SQL queries before
executing them.
mQuery << "INSERT INTO table (col1, col2, col3) VALUES(" << val1 << ", "
<< val2 << ", 0)";
I was kind of happy because it saved me a lot of redundant code, but then
I started getting weird SQL errors:
1064: You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use near
'X, 0)'
/code/pre
pWhere the X stands for some weird garbage character./p
pI use the stringstream to read all kinds of numeric types into the query
string. It seems that whenever I read an uint8_t (which is a typedef for
unsigned char on my box), it will not convert it to the string
representation of its number, but rather interpret it as a character in
what I suppose is ASCII./p
pMy first question is, why does it have that behaviour?
More importantly, I'm interested to know if there is a way to change this
behaviour?/p
pCasting to a higher byte numeric doesn't seem like the most efficient way
to handle it, but it works. However, there are so many queries that I
would have to add a lot of casts into the code. It would also not be
coherent with the rest of the variables./p
I'm using a stringstream in C++ to build (many) SQL queries before
executing them.
mQuery << "INSERT INTO table (col1, col2, col3) VALUES(" << val1 << ", "
<< val2 << ", 0)";
I was kind of happy because it saved me a lot of redundant code, but then
I started getting weird SQL errors:
1064: You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use near
'X, 0)'
/code/pre
pWhere the X stands for some weird garbage character./p
pI use the stringstream to read all kinds of numeric types into the query
string. It seems that whenever I read an uint8_t (which is a typedef for
unsigned char on my box), it will not convert it to the string
representation of its number, but rather interpret it as a character in
what I suppose is ASCII./p
pMy first question is, why does it have that behaviour?
More importantly, I'm interested to know if there is a way to change this
behaviour?/p
pCasting to a higher byte numeric doesn't seem like the most efficient way
to handle it, but it works. However, there are so many queries that I
would have to add a lot of casts into the code. It would also not be
coherent with the rest of the variables./p
Double integral over circular surface
Double integral over circular surface
I've decided to finish my education through completing my last exam (I've
been working for 5 years). The exam is in multivariable calculus and I
took the classes 6 years ago so I am very rusty. Will ask a bunch of
questions over the following weeks and I love you all for helping me.
I got this from an exam answer:
$$\iint\limits_S F\cdot dS=\iint\limits_{x^2+y^2\le1}F(x,y,2)\cdot
(0,0,1)dxdy= 2\pi$$
I presume it goes
$$..\iint\limits_{x^2+y^2\le1}F(x,y,2)\cdot
(0,0,1)dxdy=\iint\limits_{x^2+y^2\le1}0x+0y+2dxdy=\iint\limits_{x^2+y^2\le1}2dxdy=..$$
But how to think for that last step to get $2\pi$? I have never solved a
double integral over a joined surface like that. I relise that $2\pi$ is a
full circle, but I would like to know exactly why I get that answer in
this case.
I've decided to finish my education through completing my last exam (I've
been working for 5 years). The exam is in multivariable calculus and I
took the classes 6 years ago so I am very rusty. Will ask a bunch of
questions over the following weeks and I love you all for helping me.
I got this from an exam answer:
$$\iint\limits_S F\cdot dS=\iint\limits_{x^2+y^2\le1}F(x,y,2)\cdot
(0,0,1)dxdy= 2\pi$$
I presume it goes
$$..\iint\limits_{x^2+y^2\le1}F(x,y,2)\cdot
(0,0,1)dxdy=\iint\limits_{x^2+y^2\le1}0x+0y+2dxdy=\iint\limits_{x^2+y^2\le1}2dxdy=..$$
But how to think for that last step to get $2\pi$? I have never solved a
double integral over a joined surface like that. I relise that $2\pi$ is a
full circle, but I would like to know exactly why I get that answer in
this case.
Sunday, 18 August 2013
Recurrence Relation for Stooge Sort?
Recurrence Relation for Stooge Sort?
could anyone help me through figuring out what a recurrence relation for
Stooge sort would be? I don't need to solve it, I just need to figure out
the relation. I know Stooge Sort has O(n^log3/log1.5) time. I'm just
unsure how to progress from there...
Thanks!
could anyone help me through figuring out what a recurrence relation for
Stooge sort would be? I don't need to solve it, I just need to figure out
the relation. I know Stooge Sort has O(n^log3/log1.5) time. I'm just
unsure how to progress from there...
Thanks!
How to return raw JSON directly from a mongodb query in Java?
How to return raw JSON directly from a mongodb query in Java?
I have the following code:
@RequestMapping(value = "/envinfo", method = RequestMethod.GET)
@ResponseBody
public Map getEnvInfo()
{
BasicQuery basicQuery = new
BasicQuery("{_id:'51a29f6413dc992c24e0283e'}", "{'envinfo':1, '_id':
false }");
Map envinfo= mongoTemplate.findOne(basicQuery, Map.class, "jvmInfo");
return envinfo;
}
As you can notice, the code:
Retrieves JSON from MongoDB
Converts it to a Map object
The Map object is then converted to JSON by Spring MongoData before it is
returned to the browser.
Is it possible to directly return the raw json from MongoDb without going
through the intermediate conversion steps?
I have the following code:
@RequestMapping(value = "/envinfo", method = RequestMethod.GET)
@ResponseBody
public Map getEnvInfo()
{
BasicQuery basicQuery = new
BasicQuery("{_id:'51a29f6413dc992c24e0283e'}", "{'envinfo':1, '_id':
false }");
Map envinfo= mongoTemplate.findOne(basicQuery, Map.class, "jvmInfo");
return envinfo;
}
As you can notice, the code:
Retrieves JSON from MongoDB
Converts it to a Map object
The Map object is then converted to JSON by Spring MongoData before it is
returned to the browser.
Is it possible to directly return the raw json from MongoDb without going
through the intermediate conversion steps?
toJson in PlayfFramework2 for list of objects
toJson in PlayfFramework2 for list of objects
I've read this answer about how simple it is..
But if if I have list of Objects but not just strings:
case class Article(
title:String,
description:String,
examples: Example* // list of Example objects
)
There is Example case class:
case class Example(meaning:String, proofs:String*)
Then how I could transform my Article to json string?
If I use:
def article(word:String) = Action {
implicit val articleFormat = Json.format[Article]
val article = Article.article(word)
Ok( Json.format(article) )
}
I got an error: No unapply function found
When I try to write my unapply method, I got different error about apply..
Don't want to spoil.. Do you have an answer or at least a suggestion?
I've read this answer about how simple it is..
But if if I have list of Objects but not just strings:
case class Article(
title:String,
description:String,
examples: Example* // list of Example objects
)
There is Example case class:
case class Example(meaning:String, proofs:String*)
Then how I could transform my Article to json string?
If I use:
def article(word:String) = Action {
implicit val articleFormat = Json.format[Article]
val article = Article.article(word)
Ok( Json.format(article) )
}
I got an error: No unapply function found
When I try to write my unapply method, I got different error about apply..
Don't want to spoil.. Do you have an answer or at least a suggestion?
ajax request with php responses in sequence, not in array
ajax request with php responses in sequence, not in array
Hi guys here is what I'm trying to do, this is a registration form and
first I'm doing a check to see if the username is available, if it is it
them proceeds with the registration. In case the username is available i
wanted to give the user feedback, that the name is available and it's
proceeded with registration, the issue is, i do the ajax request but the
responses come back together not one and then the other, is there a way i
could do it for responses to come one and then the other, below is the
code: *Note: both php and js files are external
JS file
$.ajax({
url: "register.php",
type: "POST",
data: ({username: nameToCheck, password: userPass, email: userEmail}),
async: true,
beforeSend: ajaxStartName,
success: nameVerify,
error: ajaxErrorName,
complete: function() {
//do something
}
});
function nameVerify(data){
console.log('ajax data: '+data); // this gives both responses, not one
then the other
if(data == 'nameAvailable'){
//user feedback, "name is available, proceeding with registration"
}
else if(data == 'registrationComplete'){
//user feedback, "registration is complete thank you"
{
else if(data == 'nameInUse'){
//user feedback, "name is in use, please select another…"
}
}
php file
<?php
// the connection and db selection here
$result = mysql_query($sql);
$row = mysql_fetch_array($result);
$total = $row[0];
if($total == 1){
echo 'nameInUse';
disconnectDb();
die();
}
else{
echo 'nameAvailable';
register(); //proceed with registration here
}
function register(){
$password= $_POST['password'];//and all other details would be gathered
here and sent
//registration happens here, then if successful
//i placed a for loop here, to simulate the time it would take for reg
process, to no avail
//the echoes always go at same time, is there a way around this?
echo 'registrationComplete';
}
?>
I found a few questions that where similar to mine, but not exactly and
could not find a definite answer, so I'm posting my question, thanks
Hi guys here is what I'm trying to do, this is a registration form and
first I'm doing a check to see if the username is available, if it is it
them proceeds with the registration. In case the username is available i
wanted to give the user feedback, that the name is available and it's
proceeded with registration, the issue is, i do the ajax request but the
responses come back together not one and then the other, is there a way i
could do it for responses to come one and then the other, below is the
code: *Note: both php and js files are external
JS file
$.ajax({
url: "register.php",
type: "POST",
data: ({username: nameToCheck, password: userPass, email: userEmail}),
async: true,
beforeSend: ajaxStartName,
success: nameVerify,
error: ajaxErrorName,
complete: function() {
//do something
}
});
function nameVerify(data){
console.log('ajax data: '+data); // this gives both responses, not one
then the other
if(data == 'nameAvailable'){
//user feedback, "name is available, proceeding with registration"
}
else if(data == 'registrationComplete'){
//user feedback, "registration is complete thank you"
{
else if(data == 'nameInUse'){
//user feedback, "name is in use, please select another…"
}
}
php file
<?php
// the connection and db selection here
$result = mysql_query($sql);
$row = mysql_fetch_array($result);
$total = $row[0];
if($total == 1){
echo 'nameInUse';
disconnectDb();
die();
}
else{
echo 'nameAvailable';
register(); //proceed with registration here
}
function register(){
$password= $_POST['password'];//and all other details would be gathered
here and sent
//registration happens here, then if successful
//i placed a for loop here, to simulate the time it would take for reg
process, to no avail
//the echoes always go at same time, is there a way around this?
echo 'registrationComplete';
}
?>
I found a few questions that where similar to mine, but not exactly and
could not find a definite answer, so I'm posting my question, thanks
weak_ptr is none pointer type
weak_ptr is none pointer type
I used ordinary pointers in my project. I had some problems with memory
and changed ordinary pointers for weak_ptr. I had error:
error: base operand of '->' has non-pointer type 'boost::weak_ptr'
Why? What should I do?
I used ordinary pointers in my project. I had some problems with memory
and changed ordinary pointers for weak_ptr. I had error:
error: base operand of '->' has non-pointer type 'boost::weak_ptr'
Why? What should I do?
iframe OR ajax - What's the difference, really?
iframe OR ajax - What's the difference, really?
I have NEVER used ajax before, but think the time has come! Everyone seems
to be using it!
I have used iFrames back in the day and to be honest, don't really see the
difference between the 2.
I have a site that I want to load links in the centre column, so why would
i use ajax over an iframe?
I have NEVER used ajax before, but think the time has come! Everyone seems
to be using it!
I have used iFrames back in the day and to be honest, don't really see the
difference between the 2.
I have a site that I want to load links in the centre column, so why would
i use ajax over an iframe?
Shutdown (embedded) linux from kernel-space
Shutdown (embedded) linux from kernel-space
I'm working on a modified version of the 2.6.35 kernel for Olinuxino, an
ARM9 based platform. I'm trying to modify the power management driver (the
architecture specific part).
The processor is a Freescale i.MX23. This processor has a "special" pin,
called PSWITCH, that triggers an interrupt that is handled by the power
management driver. If the switch is pressed,the system goes to standby.
This is done in the driver by calling pm_suspend(PM_SUSPEND_STANDBY).
Given my hardware setup, I'd like to, instead, shutdown the system. So my
question is:
What is the preferred way for a kernel-space process to trigger a clean
system halt/poweroff?
I suppose there's a nice little function call out there, but I couldn't
find it so far.
My kernel code (the file I'm working on is arch/arm/mach-mx23/pm.c) can be
found here: github.com/spairal/linux-for-lobster, though my question calls
for a general Linux kernel approach.
I'm working on a modified version of the 2.6.35 kernel for Olinuxino, an
ARM9 based platform. I'm trying to modify the power management driver (the
architecture specific part).
The processor is a Freescale i.MX23. This processor has a "special" pin,
called PSWITCH, that triggers an interrupt that is handled by the power
management driver. If the switch is pressed,the system goes to standby.
This is done in the driver by calling pm_suspend(PM_SUSPEND_STANDBY).
Given my hardware setup, I'd like to, instead, shutdown the system. So my
question is:
What is the preferred way for a kernel-space process to trigger a clean
system halt/poweroff?
I suppose there's a nice little function call out there, but I couldn't
find it so far.
My kernel code (the file I'm working on is arch/arm/mach-mx23/pm.c) can be
found here: github.com/spairal/linux-for-lobster, though my question calls
for a general Linux kernel approach.
Saturday, 17 August 2013
bootstrap menu showing up blank/not able to style
bootstrap menu showing up blank/not able to style
Here's the markup for the dropdown-menu div:
<div class="btn-group-two">
<button class="btn dropdown-toggle" data-toggle="dropdown">
Action
<span class="caret white-caret"></span>
</button>
<ul id="menu" class="dropdown-menu">
<li>one</li>
<li>two</li>
<li>three</li>
</ul>
</div>
CSS:
.btn-group-two ul .dropdown-menu li a{
color: red;
}
What is the problem? something I'm missing? thx.
Here's the markup for the dropdown-menu div:
<div class="btn-group-two">
<button class="btn dropdown-toggle" data-toggle="dropdown">
Action
<span class="caret white-caret"></span>
</button>
<ul id="menu" class="dropdown-menu">
<li>one</li>
<li>two</li>
<li>three</li>
</ul>
</div>
CSS:
.btn-group-two ul .dropdown-menu li a{
color: red;
}
What is the problem? something I'm missing? thx.
Allowing for mouse right-click
Allowing for mouse right-click
Is there a way to allow for the right-click of the mouse? I want a menu to
pop up when the right-button is clicked, Currently when the right button
is clicked the program will exit. I have found information for keyboard
shortcuts but i have not found any information for the mouse.
Is there a way to allow for the right-click of the mouse? I want a menu to
pop up when the right-button is clicked, Currently when the right button
is clicked the program will exit. I have found information for keyboard
shortcuts but i have not found any information for the mouse.
Can't load a gem I created
Can't load a gem I created
I'm trying to build my first gem. Using Ryan Biggs' tutorial as my guide,
I did the following:
1) Created the gem scaffolding:
$ bundle gem hello_world
2) Edited the lib/hello_world.rb file:
require "hello_world/version"
module HelloWorld
def hi
"Hello world!"
end
end
3) Installed the gem via bundler:
$ cd hello_world
$ bundle install
At this point, if I run
$ bundle gem show
it shows
/Users/ykessler/gems/hello_world
so it looks like it installed.
But when I try to require the gem from irb:
require '/Users/ykessler/gems/hello_world'
it can't load it:
2.0.0-p195 :003 > require '/Users/ykessler/gems/hello_world'
LoadError: cannot load such file -- /Users/ykessler/gems/hello_world
from
/Users/ykessler/.rvm/rubies/ruby-2.0.0-p195/lib/ruby/site_ruby/2.0.0/rubygems/core_ext/kernel_require.rb:45:in
`require'
from
/Users/ykessler/.rvm/rubies/ruby-2.0.0-p195/lib/ruby/site_ruby/2.0.0/rubygems/core_ext/kernel_require.rb:45:in
`require'
from (irb):3
from /Users/ykessler/.rvm/rubies/ruby-2.0.0-p195/bin/irb:16:in `<main>'
Where am I going wrong?
I'm trying to build my first gem. Using Ryan Biggs' tutorial as my guide,
I did the following:
1) Created the gem scaffolding:
$ bundle gem hello_world
2) Edited the lib/hello_world.rb file:
require "hello_world/version"
module HelloWorld
def hi
"Hello world!"
end
end
3) Installed the gem via bundler:
$ cd hello_world
$ bundle install
At this point, if I run
$ bundle gem show
it shows
/Users/ykessler/gems/hello_world
so it looks like it installed.
But when I try to require the gem from irb:
require '/Users/ykessler/gems/hello_world'
it can't load it:
2.0.0-p195 :003 > require '/Users/ykessler/gems/hello_world'
LoadError: cannot load such file -- /Users/ykessler/gems/hello_world
from
/Users/ykessler/.rvm/rubies/ruby-2.0.0-p195/lib/ruby/site_ruby/2.0.0/rubygems/core_ext/kernel_require.rb:45:in
`require'
from
/Users/ykessler/.rvm/rubies/ruby-2.0.0-p195/lib/ruby/site_ruby/2.0.0/rubygems/core_ext/kernel_require.rb:45:in
`require'
from (irb):3
from /Users/ykessler/.rvm/rubies/ruby-2.0.0-p195/bin/irb:16:in `<main>'
Where am I going wrong?
Navigation Drawer, closing bug in special area
Navigation Drawer, closing bug in special area
When I touch this area, i got force close: One man sad, that here is no
.closeDrawer(); I don't know, where i must create it. Here is my log:
08-17 20:18:28.275: E/InputEventReceiver(24620): Exception dispatching
input event.
08-17 20:18:28.275: E/MessageQueue-JNI(24620): Exception in MessageQueue
callback: handleReceiveCallback
08-17 20:18:28.285: E/MessageQueue-JNI(24620): java.lang.NullPointerException
08-17 20:18:28.285: E/MessageQueue-JNI(24620): at
android.support.v4.widget.DrawerLayout.isContentView(DrawerLayout.java:805)
08-17 20:18:28.285: E/MessageQueue-JNI(24620): at
android.support.v4.widget.DrawerLayout.onInterceptTouchEvent(DrawerLayout.java:831)
08-17 20:18:28.285: E/MessageQueue-JNI(24620): at
android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:1854)
08-17 20:18:28.285: E/MessageQueue-JNI(24620): at
android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2211)
08-17 20:18:28.285: E/MessageQueue-JNI(24620): at
android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:1912)
08-17 20:18:28.285: E/MessageQueue-JNI(24620): at
android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2211)
08-17 20:18:28.285: E/MessageQueue-JNI(24620): at
android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:1912)
08-17 20:18:28.285: E/MessageQueue-JNI(24620): at
android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2211)
08-17 20:18:28.285: E/MessageQueue-JNI(24620): at
android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:1912)
08-17 20:18:28.285: E/MessageQueue-JNI(24620): at
com.android.internal.policy.impl.PhoneWindow$DecorView.superDispatchTouchEvent(PhoneWindow.java:1966)
08-17 20:18:28.285: E/MessageQueue-JNI(24620): at
com.android.internal.policy.impl.PhoneWindow.superDispatchTouchEvent(PhoneWindow.java:1418)
08-17 20:18:28.285: E/MessageQueue-JNI(24620): at
android.app.Activity.dispatchTouchEvent(Activity.java:2424)
08-17 20:18:28.285: E/MessageQueue-JNI(24620): at
com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchTouchEvent(PhoneWindow.java:1914)
08-17 20:18:28.285: E/MessageQueue-JNI(24620): at
android.view.View.dispatchPointerEvent(View.java:7564)
08-17 20:18:28.285: E/MessageQueue-JNI(24620): at
android.view.ViewRootImpl$ViewPostImeInputStage.processPointerEvent(ViewRootImpl.java:3883)
08-17 20:18:28.285: E/MessageQueue-JNI(24620): at
android.view.ViewRootImpl$ViewPostImeInputStage.onProcess(ViewRootImpl.java:3778)
08-17 20:18:28.285: E/MessageQueue-JNI(24620): at
android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3379)
08-17 20:18:28.285: E/MessageQueue-JNI(24620): at
android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:3429)
08-17 20:18:28.285: E/MessageQueue-JNI(24620): at
android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:3398)
08-17 20:18:28.285: E/MessageQueue-JNI(24620): at
android.view.ViewRootImpl$AsyncInputStage.forward(ViewRootImpl.java:3483)
08-17 20:18:28.285: E/MessageQueue-JNI(24620): at
android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:3406)
08-17 20:18:28.285: E/MessageQueue-JNI(24620): at
android.view.ViewRootImpl$AsyncInputStage.apply(ViewRootImpl.java:3540)
08-17 20:18:28.285: E/MessageQueue-JNI(24620): at
android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3379)
08-17 20:18:28.285: E/MessageQueue-JNI(24620): at
android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:3429)
08-17 20:18:28.285: E/MessageQueue-JNI(24620): at
android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:3398)
08-17 20:18:28.285: E/MessageQueue-JNI(24620): at
android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:3406)
08-17 20:18:28.285: E/MessageQueue-JNI(24620): at
android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3379)
08-17 20:18:28.285: E/MessageQueue-JNI(24620): at
android.view.ViewRootImpl.deliverInputEvent(ViewRootImpl.java:5419)
08-17 20:18:28.285: E/MessageQueue-JNI(24620): at
android.view.ViewRootImpl.doProcessInputEvents(ViewRootImpl.java:5399)
08-17 20:18:28.285: E/MessageQueue-JNI(24620): at
android.view.ViewRootImpl.enqueueInputEvent(ViewRootImpl.java:5370)
08-17 20:18:28.285: E/MessageQueue-JNI(24620): at
android.view.ViewRootImpl$WindowInputEventReceiver.onInputEvent(ViewRootImpl.java:5493)
08-17 20:18:28.285: E/MessageQueue-JNI(24620): at
android.view.InputEventReceiver.dispatchInputEvent(InputEventReceiver.java:182)
08-17 20:18:28.285: E/MessageQueue-JNI(24620): at
android.os.MessageQueue.nativePollOnce(Native Method)
08-17 20:18:28.285: E/MessageQueue-JNI(24620): at
android.os.MessageQueue.next(MessageQueue.java:132)
08-17 20:18:28.285: E/MessageQueue-JNI(24620): at
android.os.Looper.loop(Looper.java:124)
08-17 20:18:28.285: E/MessageQueue-JNI(24620): at
android.app.ActivityThread.main(ActivityThread.java:5103)
08-17 20:18:28.285: E/MessageQueue-JNI(24620): at
java.lang.reflect.Method.invokeNative(Native Method)
08-17 20:18:28.285: E/MessageQueue-JNI(24620): at
java.lang.reflect.Method.invoke(Method.java:525)
08-17 20:18:28.285: E/MessageQueue-JNI(24620): at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
08-17 20:18:28.285: E/MessageQueue-JNI(24620): at
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
08-17 20:18:28.285: E/MessageQueue-JNI(24620): at
dalvik.system.NativeStart.main(Native Method)
08-17 20:18:28.285: D/AndroidRuntime(24620): Shutting down VM
08-17 20:18:28.285: W/dalvikvm(24620): threadid=1: thread exiting with
uncaught exception (group=0x417fd700)
08-17 20:18:28.295: E/AndroidRuntime(24620): FATAL EXCEPTION: main
08-17 20:18:28.295: E/AndroidRuntime(24620): java.lang.NullPointerException
08-17 20:18:28.295: E/AndroidRuntime(24620): at
android.support.v4.widget.DrawerLayout.isContentView(DrawerLayout.java:805)
08-17 20:18:28.295: E/AndroidRuntime(24620): at
android.support.v4.widget.DrawerLayout.onInterceptTouchEvent(DrawerLayout.java:831)
08-17 20:18:28.295: E/AndroidRuntime(24620): at
android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:1854)
08-17 20:18:28.295: E/AndroidRuntime(24620): at
android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2211)
08-17 20:18:28.295: E/AndroidRuntime(24620): at
android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:1912)
08-17 20:18:28.295: E/AndroidRuntime(24620): at
android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2211)
08-17 20:18:28.295: E/AndroidRuntime(24620): at
android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:1912)
08-17 20:18:28.295: E/AndroidRuntime(24620): at
android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2211)
08-17 20:18:28.295: E/AndroidRuntime(24620): at
android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:1912)
08-17 20:18:28.295: E/AndroidRuntime(24620): at
com.android.internal.policy.impl.PhoneWindow$DecorView.superDispatchTouchEvent(PhoneWindow.java:1966)
08-17 20:18:28.295: E/AndroidRuntime(24620): at
com.android.internal.policy.impl.PhoneWindow.superDispatchTouchEvent(PhoneWindow.java:1418)
08-17 20:18:28.295: E/AndroidRuntime(24620): at
android.app.Activity.dispatchTouchEvent(Activity.java:2424)
08-17 20:18:28.295: E/AndroidRuntime(24620): at
com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchTouchEvent(PhoneWindow.java:1914)
08-17 20:18:28.295: E/AndroidRuntime(24620): at
android.view.View.dispatchPointerEvent(View.java:7564)
08-17 20:18:28.295: E/AndroidRuntime(24620): at
android.view.ViewRootImpl$ViewPostImeInputStage.processPointerEvent(ViewRootImpl.java:3883)
08-17 20:18:28.295: E/AndroidRuntime(24620): at
android.view.ViewRootImpl$ViewPostImeInputStage.onProcess(ViewRootImpl.java:3778)
08-17 20:18:28.295: E/AndroidRuntime(24620): at
android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3379)
08-17 20:18:28.295: E/AndroidRuntime(24620): at
android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:3429)
08-17 20:18:28.295: E/AndroidRuntime(24620): at
android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:3398)
08-17 20:18:28.295: E/AndroidRuntime(24620): at
android.view.ViewRootImpl$AsyncInputStage.forward(ViewRootImpl.java:3483)
08-17 20:18:28.295: E/AndroidRuntime(24620): at
android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:3406)
08-17 20:18:28.295: E/AndroidRuntime(24620): at
android.view.ViewRootImpl$AsyncInputStage.apply(ViewRootImpl.java:3540)
08-17 20:18:28.295: E/AndroidRuntime(24620): at
android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3379)
08-17 20:18:28.295: E/AndroidRuntime(24620): at
android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:3429)
08-17 20:18:28.295: E/AndroidRuntime(24620): at
android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:3398)
08-17 20:18:28.295: E/AndroidRuntime(24620): at
android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:3406)
08-17 20:18:28.295: E/AndroidRuntime(24620): at
android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3379)
08-17 20:18:28.295: E/AndroidRuntime(24620): at
android.view.ViewRootImpl.deliverInputEvent(ViewRootImpl.java:5419)
08-17 20:18:28.295: E/AndroidRuntime(24620): at
android.view.ViewRootImpl.doProcessInputEvents(ViewRootImpl.java:5399)
08-17 20:18:28.295: E/AndroidRuntime(24620): at
android.view.ViewRootImpl.enqueueInputEvent(ViewRootImpl.java:5370)
08-17 20:18:28.295: E/AndroidRuntime(24620): at
android.view.ViewRootImpl$WindowInputEventReceiver.onInputEvent(ViewRootImpl.java:5493)
08-17 20:18:28.295: E/AndroidRuntime(24620): at
android.view.InputEventReceiver.dispatchInputEvent(InputEventReceiver.java:182)
08-17 20:18:28.295: E/AndroidRuntime(24620): at
android.os.MessageQueue.nativePollOnce(Native Method)
08-17 20:18:28.295: E/AndroidRuntime(24620): at
android.os.MessageQueue.next(MessageQueue.java:132)
08-17 20:18:28.295: E/AndroidRuntime(24620): at
android.os.Looper.loop(Looper.java:124)
08-17 20:18:28.295: E/AndroidRuntime(24620): at
android.app.ActivityThread.main(ActivityThread.java:5103)
08-17 20:18:28.295: E/AndroidRuntime(24620): at
java.lang.reflect.Method.invokeNative(Native Method)
08-17 20:18:28.295: E/AndroidRuntime(24620): at
java.lang.reflect.Method.invoke(Method.java:525)
08-17 20:18:28.295: E/AndroidRuntime(24620): at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
08-17 20:18:28.295: E/AndroidRuntime(24620): at
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
08-17 20:18:28.295: E/AndroidRuntime(24620): at
dalvik.system.NativeStart.main(Native Method)
Here is drawer xml:
<ListView
android:id="@+id/left_drawer"
android:layout_width="270dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:choiceMode="singleChoice"
android:divider="#E3E9E3"
android:dividerHeight="1dp"
android:showDividers="middle"
android:background="#F3F3F4"/>
</android.support.v4.widget.DrawerLayout>
And here is my code:
import com.mdev.learnit.helpprogramms.Calculator;
import com.mdev.learnit.settings.AboutActivity;
import com.mdev.learnit.settings.SettingsActivity;
import android.app.Activity;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class StartActivity extends Activity {
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
private CharSequence mDrawerTitle;
private CharSequence mTitle;
private String[] mPlanetTitles;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.drawer_main);
mTitle = mDrawerTitle = getTitle();
mPlanetTitles = getResources().getStringArray(R.array.drawer_names);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
// äîáàâëÿåì òåíü ê îòêðûòîìó Navigation Drawer
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow,
GravityCompat.START);
// ïðîïèñûâàåì àäàïòåð ê íàøåìó ñïèñêó
mDrawerList.setAdapter(new ArrayAdapter<String>(this,
R.layout.drawer_text, mPlanetTitles));
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
// äåëàåì èêîíêó ïðèëîæåíèÿ êëèêàáåëüíîé
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
// êîíôèãóðèðóåì íàøó èêíîêó, äîáàâëÿåì òåêñò äëÿ
îòêðûòèÿ/çàêðûòèÿ, äîáàâëÿåì äîïîëíèòåëüíîå èçîáðàæåíèå, êîòîðîå
áóäåò îáîçíà÷àòü îòêðûò ëè Navigation Drawer èëè æå îí çàêðûò
mDrawerToggle = new ActionBarDrawerToggle(
this,
mDrawerLayout,
R.drawable.ic_drawer_white,
R.string.drawer_open,
R.string.drawer_close
) {
public void onDrawerClosed(View view) {
getActionBar().setTitle(mTitle);
invalidateOptionsMenu(); // creates call to
onPrepareOptionsMenu()
}
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle(mDrawerTitle);
invalidateOptionsMenu(); // creates call to
onPrepareOptionsMenu()
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
}
private class DrawerItemClickListener implements
ListView.OnItemClickListener {
@Override
public void onItemClick(AdapterView parent, View view, int
position,long id) {
switch(position) {
case 0:
Intent a = new Intent(StartActivity.this,
AlgebraTheoryActivity.class);
startActivity(a);
break;
case 1:
Intent b = new Intent(StartActivity.this, Calculator.class);
startActivity(b);
break;
case 2:
Intent c = new Intent(StartActivity.this,
SettingsActivity.class);
startActivity(c);
break;
case 3:
Intent d = new Intent(StartActivity.this,
AboutActivity.class);
startActivity(d);
break;
default:
}
}
}
@Override
public void setTitle(CharSequence title) {
mTitle = title;
getActionBar().setTitle(mTitle);
}
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
mDrawerToggle.syncState();
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
public boolean onOptionsItemSelected(MenuItem item) {
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
*Sorry for russian commentaries
One man sad, that here is no .closeDrawer(); I don't know, where i must
create it.
Help me, please.
When I touch this area, i got force close: One man sad, that here is no
.closeDrawer(); I don't know, where i must create it. Here is my log:
08-17 20:18:28.275: E/InputEventReceiver(24620): Exception dispatching
input event.
08-17 20:18:28.275: E/MessageQueue-JNI(24620): Exception in MessageQueue
callback: handleReceiveCallback
08-17 20:18:28.285: E/MessageQueue-JNI(24620): java.lang.NullPointerException
08-17 20:18:28.285: E/MessageQueue-JNI(24620): at
android.support.v4.widget.DrawerLayout.isContentView(DrawerLayout.java:805)
08-17 20:18:28.285: E/MessageQueue-JNI(24620): at
android.support.v4.widget.DrawerLayout.onInterceptTouchEvent(DrawerLayout.java:831)
08-17 20:18:28.285: E/MessageQueue-JNI(24620): at
android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:1854)
08-17 20:18:28.285: E/MessageQueue-JNI(24620): at
android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2211)
08-17 20:18:28.285: E/MessageQueue-JNI(24620): at
android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:1912)
08-17 20:18:28.285: E/MessageQueue-JNI(24620): at
android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2211)
08-17 20:18:28.285: E/MessageQueue-JNI(24620): at
android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:1912)
08-17 20:18:28.285: E/MessageQueue-JNI(24620): at
android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2211)
08-17 20:18:28.285: E/MessageQueue-JNI(24620): at
android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:1912)
08-17 20:18:28.285: E/MessageQueue-JNI(24620): at
com.android.internal.policy.impl.PhoneWindow$DecorView.superDispatchTouchEvent(PhoneWindow.java:1966)
08-17 20:18:28.285: E/MessageQueue-JNI(24620): at
com.android.internal.policy.impl.PhoneWindow.superDispatchTouchEvent(PhoneWindow.java:1418)
08-17 20:18:28.285: E/MessageQueue-JNI(24620): at
android.app.Activity.dispatchTouchEvent(Activity.java:2424)
08-17 20:18:28.285: E/MessageQueue-JNI(24620): at
com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchTouchEvent(PhoneWindow.java:1914)
08-17 20:18:28.285: E/MessageQueue-JNI(24620): at
android.view.View.dispatchPointerEvent(View.java:7564)
08-17 20:18:28.285: E/MessageQueue-JNI(24620): at
android.view.ViewRootImpl$ViewPostImeInputStage.processPointerEvent(ViewRootImpl.java:3883)
08-17 20:18:28.285: E/MessageQueue-JNI(24620): at
android.view.ViewRootImpl$ViewPostImeInputStage.onProcess(ViewRootImpl.java:3778)
08-17 20:18:28.285: E/MessageQueue-JNI(24620): at
android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3379)
08-17 20:18:28.285: E/MessageQueue-JNI(24620): at
android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:3429)
08-17 20:18:28.285: E/MessageQueue-JNI(24620): at
android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:3398)
08-17 20:18:28.285: E/MessageQueue-JNI(24620): at
android.view.ViewRootImpl$AsyncInputStage.forward(ViewRootImpl.java:3483)
08-17 20:18:28.285: E/MessageQueue-JNI(24620): at
android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:3406)
08-17 20:18:28.285: E/MessageQueue-JNI(24620): at
android.view.ViewRootImpl$AsyncInputStage.apply(ViewRootImpl.java:3540)
08-17 20:18:28.285: E/MessageQueue-JNI(24620): at
android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3379)
08-17 20:18:28.285: E/MessageQueue-JNI(24620): at
android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:3429)
08-17 20:18:28.285: E/MessageQueue-JNI(24620): at
android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:3398)
08-17 20:18:28.285: E/MessageQueue-JNI(24620): at
android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:3406)
08-17 20:18:28.285: E/MessageQueue-JNI(24620): at
android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3379)
08-17 20:18:28.285: E/MessageQueue-JNI(24620): at
android.view.ViewRootImpl.deliverInputEvent(ViewRootImpl.java:5419)
08-17 20:18:28.285: E/MessageQueue-JNI(24620): at
android.view.ViewRootImpl.doProcessInputEvents(ViewRootImpl.java:5399)
08-17 20:18:28.285: E/MessageQueue-JNI(24620): at
android.view.ViewRootImpl.enqueueInputEvent(ViewRootImpl.java:5370)
08-17 20:18:28.285: E/MessageQueue-JNI(24620): at
android.view.ViewRootImpl$WindowInputEventReceiver.onInputEvent(ViewRootImpl.java:5493)
08-17 20:18:28.285: E/MessageQueue-JNI(24620): at
android.view.InputEventReceiver.dispatchInputEvent(InputEventReceiver.java:182)
08-17 20:18:28.285: E/MessageQueue-JNI(24620): at
android.os.MessageQueue.nativePollOnce(Native Method)
08-17 20:18:28.285: E/MessageQueue-JNI(24620): at
android.os.MessageQueue.next(MessageQueue.java:132)
08-17 20:18:28.285: E/MessageQueue-JNI(24620): at
android.os.Looper.loop(Looper.java:124)
08-17 20:18:28.285: E/MessageQueue-JNI(24620): at
android.app.ActivityThread.main(ActivityThread.java:5103)
08-17 20:18:28.285: E/MessageQueue-JNI(24620): at
java.lang.reflect.Method.invokeNative(Native Method)
08-17 20:18:28.285: E/MessageQueue-JNI(24620): at
java.lang.reflect.Method.invoke(Method.java:525)
08-17 20:18:28.285: E/MessageQueue-JNI(24620): at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
08-17 20:18:28.285: E/MessageQueue-JNI(24620): at
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
08-17 20:18:28.285: E/MessageQueue-JNI(24620): at
dalvik.system.NativeStart.main(Native Method)
08-17 20:18:28.285: D/AndroidRuntime(24620): Shutting down VM
08-17 20:18:28.285: W/dalvikvm(24620): threadid=1: thread exiting with
uncaught exception (group=0x417fd700)
08-17 20:18:28.295: E/AndroidRuntime(24620): FATAL EXCEPTION: main
08-17 20:18:28.295: E/AndroidRuntime(24620): java.lang.NullPointerException
08-17 20:18:28.295: E/AndroidRuntime(24620): at
android.support.v4.widget.DrawerLayout.isContentView(DrawerLayout.java:805)
08-17 20:18:28.295: E/AndroidRuntime(24620): at
android.support.v4.widget.DrawerLayout.onInterceptTouchEvent(DrawerLayout.java:831)
08-17 20:18:28.295: E/AndroidRuntime(24620): at
android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:1854)
08-17 20:18:28.295: E/AndroidRuntime(24620): at
android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2211)
08-17 20:18:28.295: E/AndroidRuntime(24620): at
android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:1912)
08-17 20:18:28.295: E/AndroidRuntime(24620): at
android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2211)
08-17 20:18:28.295: E/AndroidRuntime(24620): at
android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:1912)
08-17 20:18:28.295: E/AndroidRuntime(24620): at
android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2211)
08-17 20:18:28.295: E/AndroidRuntime(24620): at
android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:1912)
08-17 20:18:28.295: E/AndroidRuntime(24620): at
com.android.internal.policy.impl.PhoneWindow$DecorView.superDispatchTouchEvent(PhoneWindow.java:1966)
08-17 20:18:28.295: E/AndroidRuntime(24620): at
com.android.internal.policy.impl.PhoneWindow.superDispatchTouchEvent(PhoneWindow.java:1418)
08-17 20:18:28.295: E/AndroidRuntime(24620): at
android.app.Activity.dispatchTouchEvent(Activity.java:2424)
08-17 20:18:28.295: E/AndroidRuntime(24620): at
com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchTouchEvent(PhoneWindow.java:1914)
08-17 20:18:28.295: E/AndroidRuntime(24620): at
android.view.View.dispatchPointerEvent(View.java:7564)
08-17 20:18:28.295: E/AndroidRuntime(24620): at
android.view.ViewRootImpl$ViewPostImeInputStage.processPointerEvent(ViewRootImpl.java:3883)
08-17 20:18:28.295: E/AndroidRuntime(24620): at
android.view.ViewRootImpl$ViewPostImeInputStage.onProcess(ViewRootImpl.java:3778)
08-17 20:18:28.295: E/AndroidRuntime(24620): at
android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3379)
08-17 20:18:28.295: E/AndroidRuntime(24620): at
android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:3429)
08-17 20:18:28.295: E/AndroidRuntime(24620): at
android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:3398)
08-17 20:18:28.295: E/AndroidRuntime(24620): at
android.view.ViewRootImpl$AsyncInputStage.forward(ViewRootImpl.java:3483)
08-17 20:18:28.295: E/AndroidRuntime(24620): at
android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:3406)
08-17 20:18:28.295: E/AndroidRuntime(24620): at
android.view.ViewRootImpl$AsyncInputStage.apply(ViewRootImpl.java:3540)
08-17 20:18:28.295: E/AndroidRuntime(24620): at
android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3379)
08-17 20:18:28.295: E/AndroidRuntime(24620): at
android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:3429)
08-17 20:18:28.295: E/AndroidRuntime(24620): at
android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:3398)
08-17 20:18:28.295: E/AndroidRuntime(24620): at
android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:3406)
08-17 20:18:28.295: E/AndroidRuntime(24620): at
android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3379)
08-17 20:18:28.295: E/AndroidRuntime(24620): at
android.view.ViewRootImpl.deliverInputEvent(ViewRootImpl.java:5419)
08-17 20:18:28.295: E/AndroidRuntime(24620): at
android.view.ViewRootImpl.doProcessInputEvents(ViewRootImpl.java:5399)
08-17 20:18:28.295: E/AndroidRuntime(24620): at
android.view.ViewRootImpl.enqueueInputEvent(ViewRootImpl.java:5370)
08-17 20:18:28.295: E/AndroidRuntime(24620): at
android.view.ViewRootImpl$WindowInputEventReceiver.onInputEvent(ViewRootImpl.java:5493)
08-17 20:18:28.295: E/AndroidRuntime(24620): at
android.view.InputEventReceiver.dispatchInputEvent(InputEventReceiver.java:182)
08-17 20:18:28.295: E/AndroidRuntime(24620): at
android.os.MessageQueue.nativePollOnce(Native Method)
08-17 20:18:28.295: E/AndroidRuntime(24620): at
android.os.MessageQueue.next(MessageQueue.java:132)
08-17 20:18:28.295: E/AndroidRuntime(24620): at
android.os.Looper.loop(Looper.java:124)
08-17 20:18:28.295: E/AndroidRuntime(24620): at
android.app.ActivityThread.main(ActivityThread.java:5103)
08-17 20:18:28.295: E/AndroidRuntime(24620): at
java.lang.reflect.Method.invokeNative(Native Method)
08-17 20:18:28.295: E/AndroidRuntime(24620): at
java.lang.reflect.Method.invoke(Method.java:525)
08-17 20:18:28.295: E/AndroidRuntime(24620): at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
08-17 20:18:28.295: E/AndroidRuntime(24620): at
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
08-17 20:18:28.295: E/AndroidRuntime(24620): at
dalvik.system.NativeStart.main(Native Method)
Here is drawer xml:
<ListView
android:id="@+id/left_drawer"
android:layout_width="270dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:choiceMode="singleChoice"
android:divider="#E3E9E3"
android:dividerHeight="1dp"
android:showDividers="middle"
android:background="#F3F3F4"/>
</android.support.v4.widget.DrawerLayout>
And here is my code:
import com.mdev.learnit.helpprogramms.Calculator;
import com.mdev.learnit.settings.AboutActivity;
import com.mdev.learnit.settings.SettingsActivity;
import android.app.Activity;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class StartActivity extends Activity {
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
private CharSequence mDrawerTitle;
private CharSequence mTitle;
private String[] mPlanetTitles;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.drawer_main);
mTitle = mDrawerTitle = getTitle();
mPlanetTitles = getResources().getStringArray(R.array.drawer_names);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
// äîáàâëÿåì òåíü ê îòêðûòîìó Navigation Drawer
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow,
GravityCompat.START);
// ïðîïèñûâàåì àäàïòåð ê íàøåìó ñïèñêó
mDrawerList.setAdapter(new ArrayAdapter<String>(this,
R.layout.drawer_text, mPlanetTitles));
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
// äåëàåì èêîíêó ïðèëîæåíèÿ êëèêàáåëüíîé
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
// êîíôèãóðèðóåì íàøó èêíîêó, äîáàâëÿåì òåêñò äëÿ
îòêðûòèÿ/çàêðûòèÿ, äîáàâëÿåì äîïîëíèòåëüíîå èçîáðàæåíèå, êîòîðîå
áóäåò îáîçíà÷àòü îòêðûò ëè Navigation Drawer èëè æå îí çàêðûò
mDrawerToggle = new ActionBarDrawerToggle(
this,
mDrawerLayout,
R.drawable.ic_drawer_white,
R.string.drawer_open,
R.string.drawer_close
) {
public void onDrawerClosed(View view) {
getActionBar().setTitle(mTitle);
invalidateOptionsMenu(); // creates call to
onPrepareOptionsMenu()
}
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle(mDrawerTitle);
invalidateOptionsMenu(); // creates call to
onPrepareOptionsMenu()
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
}
private class DrawerItemClickListener implements
ListView.OnItemClickListener {
@Override
public void onItemClick(AdapterView parent, View view, int
position,long id) {
switch(position) {
case 0:
Intent a = new Intent(StartActivity.this,
AlgebraTheoryActivity.class);
startActivity(a);
break;
case 1:
Intent b = new Intent(StartActivity.this, Calculator.class);
startActivity(b);
break;
case 2:
Intent c = new Intent(StartActivity.this,
SettingsActivity.class);
startActivity(c);
break;
case 3:
Intent d = new Intent(StartActivity.this,
AboutActivity.class);
startActivity(d);
break;
default:
}
}
}
@Override
public void setTitle(CharSequence title) {
mTitle = title;
getActionBar().setTitle(mTitle);
}
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
mDrawerToggle.syncState();
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
public boolean onOptionsItemSelected(MenuItem item) {
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
*Sorry for russian commentaries
One man sad, that here is no .closeDrawer(); I don't know, where i must
create it.
Help me, please.
Subscribe to:
Comments (Atom)