Square roots in modular arithmetic [on hold]
Suppose $n = pq$ with $p$ and $q$ both primes.
Suppose that $\gcd(a, pq) = 1$. Prove that if the equation $x^2 ß a \bmod
n$ has any solutions, then it has four solutions.
Suppose you had a machine that could find all four solutions for some
given $a$. How could you use this machine to factor $n$?
Monday, 30 September 2013
SPFile.CopyTo() vs RootFolder.Files.Add() sharepoint.stackexchange.com
SPFile.CopyTo() vs RootFolder.Files.Add() – sharepoint.stackexchange.com
I've been looking for method of copying a file or folder from one document
library to a number of other libraries with the same name in each subsite
for a particular site collection. What needs to ...
I've been looking for method of copying a file or folder from one document
library to a number of other libraries with the same name in each subsite
for a particular site collection. What needs to ...
Powershell format operator inside function
Powershell format operator inside function
I've found out the format operator is working differently inside a
function compared to a plain script. Here's a simple example of what is
working as expected:
[string]$name = 'Scripting Guy'
[string]$statement = 'PowerShell rocks'
$s = "The {0} thinks that {1}!" -f $name, $statement
write-host $s
producing:
The Scripting Guy thinks that PowerShell rocks!
While inside a function it does something different:
function myFunc( [string] $iname, [string] $istatement) {
$s = "The {0} thinks that {1}!" -f $iname, $istatement
write-host $s
}
[string]$name = 'Scripting Guy'
[string]$statement = 'PowerShell rocks'
myFunc($name, $statement)
produces:
The Scripting Guy PowerShell rocks thinks that !
I tried to play with it to find out what it's doing:
function myFunc( [string] $iname, [string] $istatement) {
$s = "The {0} thinks that {1}! {2} {3}" -f $iname, $istatement,
"=====", $iname
write-host $s
}
[string]$name = 'Scripting Guy'
[string]$statement = 'PowerShell rocks'
myFunc($name, $statement)
This produces:
The Scripting Guy PowerShell rocks thinks that ! ===== Scripting Guy
PowerShell rocks
So now I don't know what to think about this.
I've found out the format operator is working differently inside a
function compared to a plain script. Here's a simple example of what is
working as expected:
[string]$name = 'Scripting Guy'
[string]$statement = 'PowerShell rocks'
$s = "The {0} thinks that {1}!" -f $name, $statement
write-host $s
producing:
The Scripting Guy thinks that PowerShell rocks!
While inside a function it does something different:
function myFunc( [string] $iname, [string] $istatement) {
$s = "The {0} thinks that {1}!" -f $iname, $istatement
write-host $s
}
[string]$name = 'Scripting Guy'
[string]$statement = 'PowerShell rocks'
myFunc($name, $statement)
produces:
The Scripting Guy PowerShell rocks thinks that !
I tried to play with it to find out what it's doing:
function myFunc( [string] $iname, [string] $istatement) {
$s = "The {0} thinks that {1}! {2} {3}" -f $iname, $istatement,
"=====", $iname
write-host $s
}
[string]$name = 'Scripting Guy'
[string]$statement = 'PowerShell rocks'
myFunc($name, $statement)
This produces:
The Scripting Guy PowerShell rocks thinks that ! ===== Scripting Guy
PowerShell rocks
So now I don't know what to think about this.
in C/C++ is it legal to define and initialize several id in one row?
in C/C++ is it legal to define and initialize several id in one row?
case 1: int x, y = 0;// what is in x and y? case 2: int x = 0, y = 1, z =
2; //syntax error before ',' taken
for case 2, I am not willing to code as follow:
int x = 0;
int y = 1;
int z = 2;
Is there a simple statement to do the same job? thanks a lot 1
case 1: int x, y = 0;// what is in x and y? case 2: int x = 0, y = 1, z =
2; //syntax error before ',' taken
for case 2, I am not willing to code as follow:
int x = 0;
int y = 1;
int z = 2;
Is there a simple statement to do the same job? thanks a lot 1
Sunday, 29 September 2013
Jquery Draggable to rearrange divs
Jquery Draggable to rearrange divs
Looking to use .draggable to rearrange some divs on the page. I would like
it to snap into place and then have the other elements rearrange
themselves around it. Not really sure how to approach this. I was able to
get things .draggable() pretty easily as its one line of Jquery. Not
really sure where to go after that.
sample.
<form id="demo-upload" class="dropzone dz-clickable dz-started"
action="http://www.torrentplease.com/dropzone.php">
<div class="dz-default dz-message">
<div class="dz-preview dz-processing dz-image-preview dz-error"
onclick="myFunction()">
<div class="dz-preview dz-processing dz-image-preview dz-error"
onclick="myFunction()">
</div>
</form>
function moveDiv(div){
console.log('clicked');
$(div).draggable({ grid: [ 20,20 ] });
}
Looking to use .draggable to rearrange some divs on the page. I would like
it to snap into place and then have the other elements rearrange
themselves around it. Not really sure how to approach this. I was able to
get things .draggable() pretty easily as its one line of Jquery. Not
really sure where to go after that.
sample.
<form id="demo-upload" class="dropzone dz-clickable dz-started"
action="http://www.torrentplease.com/dropzone.php">
<div class="dz-default dz-message">
<div class="dz-preview dz-processing dz-image-preview dz-error"
onclick="myFunction()">
<div class="dz-preview dz-processing dz-image-preview dz-error"
onclick="myFunction()">
</div>
</form>
function moveDiv(div){
console.log('clicked');
$(div).draggable({ grid: [ 20,20 ] });
}
Where can I download Spring Framework jars
Where can I download Spring Framework jars
SpringSource.org changed their site to http://spring.io but I just don't
understand why can't they give a simpler way to download latest
project/snapshot? Why do they believe in making things so difficult?
Does someone know how to get the latest build without maven/github? from
http://spring.io/projects
Please fix your website structure to help navigate downloading recent
project easily.
SpringSource.org changed their site to http://spring.io but I just don't
understand why can't they give a simpler way to download latest
project/snapshot? Why do they believe in making things so difficult?
Does someone know how to get the latest build without maven/github? from
http://spring.io/projects
Please fix your website structure to help navigate downloading recent
project easily.
onCreate method not getting called
onCreate method not getting called
I have following method inside a ActionBar.TabListener method and when I
am calling the setContentView I am expecting it to call onCreate method
for that view: But that method is not called here.
so, how can I create an activity outside of the onCreate method?
public void onTabSelected(Tab tab, FragmentTransaction arg1) {
int tabPosition = tab.getPosition();
switch (tabPosition) {
case 0:
setContentView(R.layout.class_view);
break;
case 1:
setContentView(R.layout.detail_view);
break;
case 2:
setContentView(R.layout.class_view);
break;
}
}
I have following method inside a ActionBar.TabListener method and when I
am calling the setContentView I am expecting it to call onCreate method
for that view: But that method is not called here.
so, how can I create an activity outside of the onCreate method?
public void onTabSelected(Tab tab, FragmentTransaction arg1) {
int tabPosition = tab.getPosition();
switch (tabPosition) {
case 0:
setContentView(R.layout.class_view);
break;
case 1:
setContentView(R.layout.detail_view);
break;
case 2:
setContentView(R.layout.class_view);
break;
}
}
asp.net gridview if cell row value is equal then
asp.net gridview if cell row value is equal then
i am populating a datatable then binding it to a gridview , now im readin
the rows in the grid and coloring the row if value = [x] the thing when i
try to display on the page the row that is colored im getting it
duplicated lets say i have colored 1 row but the response.write will be
like 100 times the same result , below is my code , hope some one can help
:
protected void gv1_RowDataBound(object sender, GridViewRowEventArgs e)
{
string alert = Request.QueryString["check"];
// loop over all the Rows in the Datagridview
foreach (GridViewRow row in gv1.Rows)
{
// if condition is met color the row text and send email
if (gv1.Rows[0].Cells[0].Text.ToString() == alert)
{
Session ["fn"] = gv1.Rows[0].Cells[2].Text;
gv1.Rows[0].ForeColor = Color.Red;
}
Response.Write(Session["fn"]);
}
i am populating a datatable then binding it to a gridview , now im readin
the rows in the grid and coloring the row if value = [x] the thing when i
try to display on the page the row that is colored im getting it
duplicated lets say i have colored 1 row but the response.write will be
like 100 times the same result , below is my code , hope some one can help
:
protected void gv1_RowDataBound(object sender, GridViewRowEventArgs e)
{
string alert = Request.QueryString["check"];
// loop over all the Rows in the Datagridview
foreach (GridViewRow row in gv1.Rows)
{
// if condition is met color the row text and send email
if (gv1.Rows[0].Cells[0].Text.ToString() == alert)
{
Session ["fn"] = gv1.Rows[0].Cells[2].Text;
gv1.Rows[0].ForeColor = Color.Red;
}
Response.Write(Session["fn"]);
}
Saturday, 28 September 2013
moving files from one foder to another automatically
moving files from one foder to another automatically
I have 100 main folders each folder contains 2 sub folder and name of one
of those folder is "NEW FOLDER" which contain pdf files I want to
overwrite/move those files in another sub folder. kindly provide me a
script/batch file for windows so that all the data moves from "NEW FOLDER"
to adjsent folder at once for n number of main folders
I have 100 main folders each folder contains 2 sub folder and name of one
of those folder is "NEW FOLDER" which contain pdf files I want to
overwrite/move those files in another sub folder. kindly provide me a
script/batch file for windows so that all the data moves from "NEW FOLDER"
to adjsent folder at once for n number of main folders
Update WebBrowser in Delphi
Update WebBrowser in Delphi
Hi I am making a web browser in delphi, so for now I'm doing is letting
the user can modify the headers at will, the current problem is that I use
a checkbox to check when the user wants to use the headers that are in a
memo the problem is that when I use it for the first time it works fine
but when I disable the checkbox and try to use the browser without the
headers is that the headers are still active and that should not be
happening.
The code page used to test local
<? php
$ nav = $ _SERVER ['HTTP_USER_AGENT'];
echo "<h1> Test:". $ nav. "</ h1>";
?>
The code delpi
TForm2.sButton1Click procedure (Sender: TObject);
var
Flags, Headers, targetFrameName, PostData: OleVariant;
Url, Ref: string;
begin
Flags: = '1 ';
TargetFrameName: ='';
PostData: ='';
URL: = sEdit1.Text;
if (sCheckBox1.Checked) then
begin
Headers: = sMemo1.Text;
WebBrowser1.Navigate (URL, Flags, targetFrameName, PostData, Headers);
end
else
begin
Headers: ='';
WebBrowser1.Navigate (URL, Flags, targetFrameName, PostData, Headers);
end;
end;
Hi I am making a web browser in delphi, so for now I'm doing is letting
the user can modify the headers at will, the current problem is that I use
a checkbox to check when the user wants to use the headers that are in a
memo the problem is that when I use it for the first time it works fine
but when I disable the checkbox and try to use the browser without the
headers is that the headers are still active and that should not be
happening.
The code page used to test local
<? php
$ nav = $ _SERVER ['HTTP_USER_AGENT'];
echo "<h1> Test:". $ nav. "</ h1>";
?>
The code delpi
TForm2.sButton1Click procedure (Sender: TObject);
var
Flags, Headers, targetFrameName, PostData: OleVariant;
Url, Ref: string;
begin
Flags: = '1 ';
TargetFrameName: ='';
PostData: ='';
URL: = sEdit1.Text;
if (sCheckBox1.Checked) then
begin
Headers: = sMemo1.Text;
WebBrowser1.Navigate (URL, Flags, targetFrameName, PostData, Headers);
end
else
begin
Headers: ='';
WebBrowser1.Navigate (URL, Flags, targetFrameName, PostData, Headers);
end;
end;
sql subtract subquery sum multiple tables
sql subtract subquery sum multiple tables
How can I subtract the sum of a subquery table from another table?
SELECT i.column1 * i.column2 AS Expr1
, i.column1 * i.column2 - (SELECT SUM(table2.column1) AS Expr1
FROM table2
WHERE (table2.column3 = table1.column3)) AS
derivedExpression
FROM table1
Only the derivedExpression in the first row is correct. The rest rows
returns null for derivedExpression. For Expr1, everything is fine. Any
help?
How can I subtract the sum of a subquery table from another table?
SELECT i.column1 * i.column2 AS Expr1
, i.column1 * i.column2 - (SELECT SUM(table2.column1) AS Expr1
FROM table2
WHERE (table2.column3 = table1.column3)) AS
derivedExpression
FROM table1
Only the derivedExpression in the first row is correct. The rest rows
returns null for derivedExpression. For Expr1, everything is fine. Any
help?
Friday, 27 September 2013
node.js require of a json file
node.js require of a json file
I am trying to require() this JSON file.
{
"info" : function (request) {
var i = "<pre>";
i+= "current working directory: " + process.cwd() + "\n";
i+="request url: " + request.url + "\n";
i+= "</pre>";
return i;
}
}
Using this line
var render = require('./render.json');
But I get an exception from the JSON file of : Unexpected token u
What am I doing wrong please ?
I am trying to require() this JSON file.
{
"info" : function (request) {
var i = "<pre>";
i+= "current working directory: " + process.cwd() + "\n";
i+="request url: " + request.url + "\n";
i+= "</pre>";
return i;
}
}
Using this line
var render = require('./render.json');
But I get an exception from the JSON file of : Unexpected token u
What am I doing wrong please ?
Align images using CSS
Align images using CSS
I'm using this tooltip called open tips. how can I get these images to
align horizontally instead of vertically?
fiddle
the only css I have is:
.images {
top: -20px;
width: 1400px;
float: left;
}
I'm using this tooltip called open tips. how can I get these images to
align horizontally instead of vertically?
fiddle
the only css I have is:
.images {
top: -20px;
width: 1400px;
float: left;
}
jQuery - Smooth scroll only working to top - need it to work to bottom aswell
jQuery - Smooth scroll only working to top - need it to work to bottom aswell
im trying to use a smooth scroll for my href elements. The only problem is
that i can only get it to do it upwards.
The live site is here
If you click on the box "Webdesign" it should do a smooth scrool down to
the .content. The same thing if you hit the button of the bottom of that
content it should scroll up to the top again smoooth(That works fine) -
Its downwards to the start of the "webdesign" content it doesnt work.
script used in the bottom of the site:
<script type="text/javascript">
$("a[href^='#']").click(function(){
var contentPosTop = $('.content').position().top;
$('html, body').stop().animate({
scrollTop: contentPosTop
}, 1500);
});
</script>
Any ideas?
im trying to use a smooth scroll for my href elements. The only problem is
that i can only get it to do it upwards.
The live site is here
If you click on the box "Webdesign" it should do a smooth scrool down to
the .content. The same thing if you hit the button of the bottom of that
content it should scroll up to the top again smoooth(That works fine) -
Its downwards to the start of the "webdesign" content it doesnt work.
script used in the bottom of the site:
<script type="text/javascript">
$("a[href^='#']").click(function(){
var contentPosTop = $('.content').position().top;
$('html, body').stop().animate({
scrollTop: contentPosTop
}, 1500);
});
</script>
Any ideas?
How to iterate through an enumeration of flags and create checkboxes that are checked appropriately for each value?
How to iterate through an enumeration of flags and create checkboxes that
are checked appropriately for each value?
I have an Enum of flags to represent the days of the week, with a few
extra values that indicate weekdays, weekends, every day, or no days.
Here's the Enum:
[Flags]
public enum DayOfWeek : short
{
Sunday = 1,
Monday = 2,
Tuesday = 4,
Wednesday = 8,
Thursday = 16,
Friday = 32,
Saturday = 64,
Weekday = 62,
Weekend = 65,
Everyday = 127,
None = 0
}
I also have a View Model with a property, DayOfWeek with a type of DayOfWeek.
In my View, I need to create a checkbox for each day of the week and
somehow appropriately check the boxes based on which days have been saved.
How can I do this? I'm guessing this needs to be done in a foreach loop,
but that's all I have to go on so far.
are checked appropriately for each value?
I have an Enum of flags to represent the days of the week, with a few
extra values that indicate weekdays, weekends, every day, or no days.
Here's the Enum:
[Flags]
public enum DayOfWeek : short
{
Sunday = 1,
Monday = 2,
Tuesday = 4,
Wednesday = 8,
Thursday = 16,
Friday = 32,
Saturday = 64,
Weekday = 62,
Weekend = 65,
Everyday = 127,
None = 0
}
I also have a View Model with a property, DayOfWeek with a type of DayOfWeek.
In my View, I need to create a checkbox for each day of the week and
somehow appropriately check the boxes based on which days have been saved.
How can I do this? I'm guessing this needs to be done in a foreach loop,
but that's all I have to go on so far.
Php pagination link not showing on last page
Php pagination link not showing on last page
I have a pagination script which works. The first page has a 'next' link,
the last page should have a 'previous' link and the ones in between have
both. The problem is that the last page doesnt show it 'previous' link.
Heres the code
include '../inc/connect.php';
//paganation settings
$per_page = 2;
$pages_query = mysqli_query($link, "SELECT COUNT(`id`) FROM `gallery`") or
die(mysqli_error($link));
$result = mysqli_fetch_array($pages_query, MYSQLI_NUM);
$pages = $result[0] / $per_page;
$page = (isset($_GET['page']) AND (int)$_GET['page'] > 0) ?
(int)$_GET['page'] : 1;
$start = ($page - 1) * $per_page;
$last = ($pages - 1) / $per_page;
$prev = $page - 1;
$next = $page + 1;
//query the db
$q =mysqli_query($link, "SELECT * FROM gallery
ORDER BY id DESC
LIMIT $start, $per_page");
//find out the page we are on and display next and previous links accordingly
if ($page >= 1 && $page < $pages){
echo "<span class='next'>";
echo "<a href=\"?page={$next}\">Next page</a> ";
echo "</span>";
if ($page >=2){
echo "<span class='prev'>";
echo "<a href=\"?page={$prev}\">Previous page</a> ";
echo "</span>";
}
}
else if ($page > $pages + 1){
echo 'No more images in the database';
}
//display images
while($row=mysqli_fetch_array($q)){
echo "<a href='{$row['filename']}' rel='thumbnail'>
<img class='nailthumb-container' src='{$row['filename']}'
alt='{$row['description']}.Image' title='{$row['description']}' />
</a>";
}
I have a pagination script which works. The first page has a 'next' link,
the last page should have a 'previous' link and the ones in between have
both. The problem is that the last page doesnt show it 'previous' link.
Heres the code
include '../inc/connect.php';
//paganation settings
$per_page = 2;
$pages_query = mysqli_query($link, "SELECT COUNT(`id`) FROM `gallery`") or
die(mysqli_error($link));
$result = mysqli_fetch_array($pages_query, MYSQLI_NUM);
$pages = $result[0] / $per_page;
$page = (isset($_GET['page']) AND (int)$_GET['page'] > 0) ?
(int)$_GET['page'] : 1;
$start = ($page - 1) * $per_page;
$last = ($pages - 1) / $per_page;
$prev = $page - 1;
$next = $page + 1;
//query the db
$q =mysqli_query($link, "SELECT * FROM gallery
ORDER BY id DESC
LIMIT $start, $per_page");
//find out the page we are on and display next and previous links accordingly
if ($page >= 1 && $page < $pages){
echo "<span class='next'>";
echo "<a href=\"?page={$next}\">Next page</a> ";
echo "</span>";
if ($page >=2){
echo "<span class='prev'>";
echo "<a href=\"?page={$prev}\">Previous page</a> ";
echo "</span>";
}
}
else if ($page > $pages + 1){
echo 'No more images in the database';
}
//display images
while($row=mysqli_fetch_array($q)){
echo "<a href='{$row['filename']}' rel='thumbnail'>
<img class='nailthumb-container' src='{$row['filename']}'
alt='{$row['description']}.Image' title='{$row['description']}' />
</a>";
}
The type arguments for method cannot be inferred from the usage error for creating a relationship
The type arguments for method cannot be inferred from the usage error for
creating a relationship
So I have a class that describes the Relationship like so:
public class GraphRelationship<TObject> :
Relationship<RelationshipObject>,
IRelationshipAllowingSourceNode<TObject>,
IRelationshipAllowingTargetNode<TObject>
{
string RelationshipName;
public GraphRelationship(string RelationshipName, NodeReference
targetNode, RelationshipObject relationshipTypeObject)
: base(targetNode, relationshipTypeObject)
{
this.RelationshipName = RelationshipName;
}
public override string RelationshipTypeKey
{
get { return RelationshipName; }
}
}
Now I have a method that I want to use to create an instance of the above
mentioned class, but I get this The type arguments for method cannot be
inferred from the usage error.
Here is the method:
public RelationshipReference CreateObjectRelationship(string
relationshipType, string parentObjectId, string childObjectId,
RelationshipObject relationshipProperties)
{
RelationshipReference relationshipReference = 0;
NodeReference parentNodeReference = GetObjectReference(parentObjectId);
NodeReference childNodeReference = GetObjectReference(childObjectId);
relationshipReference =
GraphConnection.CreateRelationship(parentNodeReference, new
GraphRelationship<RelationshipObject>(relationshipType,
childNodeReference, relationshipProperties));
return relationshipReference;
}
Im sure this is a trivial problem, but how would i fix this?
creating a relationship
So I have a class that describes the Relationship like so:
public class GraphRelationship<TObject> :
Relationship<RelationshipObject>,
IRelationshipAllowingSourceNode<TObject>,
IRelationshipAllowingTargetNode<TObject>
{
string RelationshipName;
public GraphRelationship(string RelationshipName, NodeReference
targetNode, RelationshipObject relationshipTypeObject)
: base(targetNode, relationshipTypeObject)
{
this.RelationshipName = RelationshipName;
}
public override string RelationshipTypeKey
{
get { return RelationshipName; }
}
}
Now I have a method that I want to use to create an instance of the above
mentioned class, but I get this The type arguments for method cannot be
inferred from the usage error.
Here is the method:
public RelationshipReference CreateObjectRelationship(string
relationshipType, string parentObjectId, string childObjectId,
RelationshipObject relationshipProperties)
{
RelationshipReference relationshipReference = 0;
NodeReference parentNodeReference = GetObjectReference(parentObjectId);
NodeReference childNodeReference = GetObjectReference(childObjectId);
relationshipReference =
GraphConnection.CreateRelationship(parentNodeReference, new
GraphRelationship<RelationshipObject>(relationshipType,
childNodeReference, relationshipProperties));
return relationshipReference;
}
Im sure this is a trivial problem, but how would i fix this?
Redirect in subfolder .htaccess
Redirect in subfolder .htaccess
I have file /abc/index.html
I want to access it via /index.html with some rules in /abc/.htaccess file.
Is this possible? How?!
I have file /abc/index.html
I want to access it via /index.html with some rules in /abc/.htaccess file.
Is this possible? How?!
Thursday, 26 September 2013
Call custom function inside shortcode
Call custom function inside shortcode
I have a function to display a list of files from a given directory as
links. I then have a shortcode to display the function, but I can't figure
out how to make the shortcode work without using inline php to call the
function. The shortcode only works right now because I have another
third-party plugin that allows inline php in the WordPress text editor.
Here's the function:
function showFiles($path){
if ($handle = opendir($path))
{
$up = substr($path, 0, (strrpos(dirname($path."/."),"/")));
while (false !== ($file = readdir($handle)))
{
if ($file != "." && $file != "..")
{
$fName = $file;
$file = $path.'/'.$file;
if(is_file($file)) {
echo "<li><a href='/".$file."'
target=_blank>".$fName."</a></li>";
}
}
}
closedir($handle);
}
}
And here's a pared down version of the shortcode function I'm using:
function sc_showfiles( $atts, $content = null ) {
extract( shortcode_atts( array(
'type' => '',
), $atts ) );
$showfiles = '<ul><?php
showFiles(\'files/'.$type.'files/'.do_shortcode($content).'\');
?></ul>';
return $showfiles;
}
add_shortcode('showfiles', 'sc_showfiles');
The content area allows the user to enter a shortcode with a user
generated meta so the directory it's pulling from will match the logged in
user.
I've tried about six different things, and haven't been able to achieve
this without calling the showFiles function using inline php. I came close
once using:
$files = showFiles('files/'.$type.'files/'.do_shortcode($content).);
and
$showfiles = '<ul>'.$files.'</ul>';
return $showfiles;
but that threw the list of files at the top of the page, I assume because
the original showFiles function is echoing the html output. But if I
change echo to return in the top function I get nothing.
I have a function to display a list of files from a given directory as
links. I then have a shortcode to display the function, but I can't figure
out how to make the shortcode work without using inline php to call the
function. The shortcode only works right now because I have another
third-party plugin that allows inline php in the WordPress text editor.
Here's the function:
function showFiles($path){
if ($handle = opendir($path))
{
$up = substr($path, 0, (strrpos(dirname($path."/."),"/")));
while (false !== ($file = readdir($handle)))
{
if ($file != "." && $file != "..")
{
$fName = $file;
$file = $path.'/'.$file;
if(is_file($file)) {
echo "<li><a href='/".$file."'
target=_blank>".$fName."</a></li>";
}
}
}
closedir($handle);
}
}
And here's a pared down version of the shortcode function I'm using:
function sc_showfiles( $atts, $content = null ) {
extract( shortcode_atts( array(
'type' => '',
), $atts ) );
$showfiles = '<ul><?php
showFiles(\'files/'.$type.'files/'.do_shortcode($content).'\');
?></ul>';
return $showfiles;
}
add_shortcode('showfiles', 'sc_showfiles');
The content area allows the user to enter a shortcode with a user
generated meta so the directory it's pulling from will match the logged in
user.
I've tried about six different things, and haven't been able to achieve
this without calling the showFiles function using inline php. I came close
once using:
$files = showFiles('files/'.$type.'files/'.do_shortcode($content).);
and
$showfiles = '<ul>'.$files.'</ul>';
return $showfiles;
but that threw the list of files at the top of the page, I assume because
the original showFiles function is echoing the html output. But if I
change echo to return in the top function I get nothing.
Wednesday, 25 September 2013
Accepting XML on server side using RESTEasy
Accepting XML on server side using RESTEasy
I want to create a REFTful web service that accepts XML. I can see a lot
of examples where server is sending response as an XML. But I want to
process request as an XML. Anyone has idea on how to do that?
I want to create a REFTful web service that accepts XML. I can see a lot
of examples where server is sending response as an XML. But I want to
process request as an XML. Anyone has idea on how to do that?
Thursday, 19 September 2013
Eclipse The deployment descriptor of the module 'xxx.war' cannot be loaded or found
Eclipse The deployment descriptor of the module 'xxx.war' cannot be loaded
or found
There's been a number of similar questions raised on this error on Eclipse:
The deployment descriptor of the module 'xxx.war' cannot be loaded or found.
This is a very generic error, and after scouring the web I have multiple
different causes and solutions. I'm going to attempt to list them all
here, so others won't have to go through the same thing I did.
If anyone experienced other causes and solutions, please list them here
too. =)
(Moderators, please wait for me to put the answer up before judging this
question)
or found
There's been a number of similar questions raised on this error on Eclipse:
The deployment descriptor of the module 'xxx.war' cannot be loaded or found.
This is a very generic error, and after scouring the web I have multiple
different causes and solutions. I'm going to attempt to list them all
here, so others won't have to go through the same thing I did.
If anyone experienced other causes and solutions, please list them here
too. =)
(Moderators, please wait for me to put the answer up before judging this
question)
jQuery Remove part of the HTML and append new HTML
jQuery Remove part of the HTML and append new HTML
We have approval with our client, just a heads up to cover me in any way.
We are needing to modify some of the code in a clients site if a cookie is
seen on their computer, the client's site is in ASPX format. I have the
first part of the code created, but where I am getting stuck is this:
I need to remove the last 2000 characters (or so) of the body of the page,
then append the new HTML to it.
I tried:
$('body').html().substring(0, 10050)
but that doesn't work, I also tried copying that HTML (which did work) and
put it back with the new code, but it created a loop of the script
running.
Any suggestions on what I should do? It has to be javascript/jQuery sadly.
//////// EDIT ////////////
My script is brought in by Google Tag Manager, and added to the page at
the bottom, then my script runs, this is what was causing the loop in the
script. Basically, here is the setup:
My Script on my server is loaded into the client site using Google Tag
Manager, added to the bottom of the page. From there it is able to
execute, but when doing this, it creates a loop of adding the Google Tag
Manager script, causing my code to re-add, causing it to re-execute again.
The client is not willing to do anything, he has pretty much told us to
just figure it out, and to not involve his web guy.
We have approval with our client, just a heads up to cover me in any way.
We are needing to modify some of the code in a clients site if a cookie is
seen on their computer, the client's site is in ASPX format. I have the
first part of the code created, but where I am getting stuck is this:
I need to remove the last 2000 characters (or so) of the body of the page,
then append the new HTML to it.
I tried:
$('body').html().substring(0, 10050)
but that doesn't work, I also tried copying that HTML (which did work) and
put it back with the new code, but it created a loop of the script
running.
Any suggestions on what I should do? It has to be javascript/jQuery sadly.
//////// EDIT ////////////
My script is brought in by Google Tag Manager, and added to the page at
the bottom, then my script runs, this is what was causing the loop in the
script. Basically, here is the setup:
My Script on my server is loaded into the client site using Google Tag
Manager, added to the bottom of the page. From there it is able to
execute, but when doing this, it creates a loop of adding the Google Tag
Manager script, causing my code to re-add, causing it to re-execute again.
The client is not willing to do anything, he has pretty much told us to
just figure it out, and to not involve his web guy.
How do I pull a package / deb file from an apt server on a mac?
How do I pull a package / deb file from an apt server on a mac?
How can I programmatically pull down the latest deb file for an apt
package and extract the contents in order to be able to access a script
therein? I want this to work on a mac with the standard suite of tools
(i.e. no apt-get or apt-cache).
Background: My simulation project uses client code to execute. The host
simulation tool runs on a linux environment and is managed through an
internal apt server. One colleague is using apt-get on his linux box to
install the package and then is sending a single file to us. I want our
client to do this programmatically in a way that will work on mac clients.
I have dry run the process (see example answer), but I am surprised nobody
has talked about this already.
Any recommendations on how best to do this?
How can I programmatically pull down the latest deb file for an apt
package and extract the contents in order to be able to access a script
therein? I want this to work on a mac with the standard suite of tools
(i.e. no apt-get or apt-cache).
Background: My simulation project uses client code to execute. The host
simulation tool runs on a linux environment and is managed through an
internal apt server. One colleague is using apt-get on his linux box to
install the package and then is sending a single file to us. I want our
client to do this programmatically in a way that will work on mac clients.
I have dry run the process (see example answer), but I am surprised nobody
has talked about this already.
Any recommendations on how best to do this?
Grunt watch: compile only one file not all
Grunt watch: compile only one file not all
I have grunt setup to compile all of my coffee files into javascript and
maintain all folder structures using dynamic_mappings which works great.
coffee: {
dynamic_mappings: {
files: [{
expand: true,
cwd: 'assets/scripts/src/',
src: '**/*.coffee',
dest: 'assets/scripts/dest/',
ext: '.js'
}]
}
}
What I would like to do is then use watch to compile any changed coffee
file and still maintain folder structure. This works using the above task
with this watch task:
watch: {
coffeescript: {
files: 'assets/scripts/src/**/*.coffee',
tasks: ['coffee:dynamic_mappings']
}
}
The problem is that when one file changes it compiles the entire directory
of coffee into Javascript again, it would be great if it would only
compile the single coffee file that was changed into Javascript. Is this
naturally possible in Grunt or is this a custom feature.
We have custom watch scripts at work and I'm trying to sell them on Grunt
but will need this feature to do it.
I have grunt setup to compile all of my coffee files into javascript and
maintain all folder structures using dynamic_mappings which works great.
coffee: {
dynamic_mappings: {
files: [{
expand: true,
cwd: 'assets/scripts/src/',
src: '**/*.coffee',
dest: 'assets/scripts/dest/',
ext: '.js'
}]
}
}
What I would like to do is then use watch to compile any changed coffee
file and still maintain folder structure. This works using the above task
with this watch task:
watch: {
coffeescript: {
files: 'assets/scripts/src/**/*.coffee',
tasks: ['coffee:dynamic_mappings']
}
}
The problem is that when one file changes it compiles the entire directory
of coffee into Javascript again, it would be great if it would only
compile the single coffee file that was changed into Javascript. Is this
naturally possible in Grunt or is this a custom feature.
We have custom watch scripts at work and I'm trying to sell them on Grunt
but will need this feature to do it.
get ID at time of insert / replicate value into other
get ID at time of insert / replicate value into other
Is it possible to get the ID of what the entry in the MySQL DB is going to
be ? Or even better replicate the value of ID into another field ? For
example I have:
ID and User_ID and I want them always to be the same value
--------------------
| ID User_ID |
| 1 1 |
| 2 2 |
| 3 3 |
| 4 4 |
| 5 5 |
--------------------
And so on
Is it possible to get the ID of what the entry in the MySQL DB is going to
be ? Or even better replicate the value of ID into another field ? For
example I have:
ID and User_ID and I want them always to be the same value
--------------------
| ID User_ID |
| 1 1 |
| 2 2 |
| 3 3 |
| 4 4 |
| 5 5 |
--------------------
And so on
PHP Application Server Blocked Due To CGI/PHP Overload
PHP Application Server Blocked Due To CGI/PHP Overload
I an working on a e-governance Web App made in php which has been blocked
by Server Provider. His mail reads -
DISABLED CONTENT :: CGI/PHP Overload on domainname.org
During a recent audit of the server we found the account [domainname] to
be exceeding our allowed resource usage:
Below they mentioned some of the php pages of my app which they are saying
are using excess resourcethan allowed.
#####################################
AVERAGE SERVER RESOURCE LIMITS
Memory usage may not exceed 10% per domain/file/application<br/>
CPU usage may not exceed 20% per domain/file/application<br/>
Apache connections may not exceed 30 connections<br/>
15 MySQL maximum user connections allowed<br/>
350 emails per hour, per domain
#####################################
I want to ask is there something that i can do with my programming. During
office timing, some 50-60 users might be working on it. Is this due to
concurrent MySQL connections or Apache connections.
Another important thing - this is the 2nd time this is happening this
month. A week ago the same problem occurred. My server provider suggested
me to buy a remote MySQL. So i did bought a remote MySQL and also changed
domain. Again this has happened. Only for 6-8 months this site has more
traffic. Can someone suggest what should i do.
I an working on a e-governance Web App made in php which has been blocked
by Server Provider. His mail reads -
DISABLED CONTENT :: CGI/PHP Overload on domainname.org
During a recent audit of the server we found the account [domainname] to
be exceeding our allowed resource usage:
Below they mentioned some of the php pages of my app which they are saying
are using excess resourcethan allowed.
#####################################
AVERAGE SERVER RESOURCE LIMITS
Memory usage may not exceed 10% per domain/file/application<br/>
CPU usage may not exceed 20% per domain/file/application<br/>
Apache connections may not exceed 30 connections<br/>
15 MySQL maximum user connections allowed<br/>
350 emails per hour, per domain
#####################################
I want to ask is there something that i can do with my programming. During
office timing, some 50-60 users might be working on it. Is this due to
concurrent MySQL connections or Apache connections.
Another important thing - this is the 2nd time this is happening this
month. A week ago the same problem occurred. My server provider suggested
me to buy a remote MySQL. So i did bought a remote MySQL and also changed
domain. Again this has happened. Only for 6-8 months this site has more
traffic. Can someone suggest what should i do.
How to generate data frame following a pattern
How to generate data frame following a pattern
I'm trying to find a quick (i.e. not manual) way of generating a data
frame that follows the following pattern. The columns are accident yearand
development_year:
accident_year development_year
2 10
3 9
3 10
4 8
4 9
4 10
5 7
5 8
... ...
5 10
... ...
10 2
... ...
10 10
So for the accident_year column I need a vector that goes has one 2, two
3s, three 4s and so on. For the other column (development year) I
basically need a vector of sequences 10,9, 10,9,8, 10,9,7, ... ,
10,9,8,7,6,5,4,3,2.
Does anyone know how to easily generate those?
Thanks!
I'm trying to find a quick (i.e. not manual) way of generating a data
frame that follows the following pattern. The columns are accident yearand
development_year:
accident_year development_year
2 10
3 9
3 10
4 8
4 9
4 10
5 7
5 8
... ...
5 10
... ...
10 2
... ...
10 10
So for the accident_year column I need a vector that goes has one 2, two
3s, three 4s and so on. For the other column (development year) I
basically need a vector of sequences 10,9, 10,9,8, 10,9,7, ... ,
10,9,8,7,6,5,4,3,2.
Does anyone know how to easily generate those?
Thanks!
Wednesday, 18 September 2013
Make Xpath choose parts of an attribute
Make Xpath choose parts of an attribute
I have xml-documents with tables. Every table has an attribute hdsl-percent.
First of all, I'd like to know, what exactly that is . Never came across
it. Google didn't yield any useful results.
Now, this attribute contains the widths of the table-columns in
percentages, e.g. hsdl-percent="23.5 36.7 39.7".
Is there any way that I could get XPath to use these values for the widths
of the table-columns? So 23.5% width for the first column and so on...
The problem is that each table is different, many of them with rowspans
and colspans and since I'm using Apache FOP and it doesn't support
table-layout auto, my tables just have width="100%", no column-width
specified and therefore some columns are wider than they should be.
Thanks for your help and suggestions!
I have xml-documents with tables. Every table has an attribute hdsl-percent.
First of all, I'd like to know, what exactly that is . Never came across
it. Google didn't yield any useful results.
Now, this attribute contains the widths of the table-columns in
percentages, e.g. hsdl-percent="23.5 36.7 39.7".
Is there any way that I could get XPath to use these values for the widths
of the table-columns? So 23.5% width for the first column and so on...
The problem is that each table is different, many of them with rowspans
and colspans and since I'm using Apache FOP and it doesn't support
table-layout auto, my tables just have width="100%", no column-width
specified and therefore some columns are wider than they should be.
Thanks for your help and suggestions!
Can Chrome debugger show me the full path to HTML element?
Can Chrome debugger show me the full path to HTML element?
Using Chrome debugger, the "Copy as XPath" returns results that (I think)
are relative to the entity's parent element or maybe parent iframe
(document? form??). I need the entire path from window.top.document. The
entity is deeply nested in a page with many forms and iframes. Extra
points if I can the the path as a jQuery selector.
Using Chrome debugger, the "Copy as XPath" returns results that (I think)
are relative to the entity's parent element or maybe parent iframe
(document? form??). I need the entire path from window.top.document. The
entity is deeply nested in a page with many forms and iframes. Extra
points if I can the the path as a jQuery selector.
Want answer of this 8086 assembly code and values of AL,BL and status flags after every instruction?
Want answer of this 8086 assembly code and values of AL,BL and status
flags after every instruction?
Unable to find the values of status register. I have download the emulator
of 8086 assembly language.I it shows error in line SBB and asking for more
operands.
STC
MOV AL,4CH
SBB
XOR BL,BL
MOV [SI],BL
HLT
flags after every instruction?
Unable to find the values of status register. I have download the emulator
of 8086 assembly language.I it shows error in line SBB and asking for more
operands.
STC
MOV AL,4CH
SBB
XOR BL,BL
MOV [SI],BL
HLT
Pyhton pandas: How to combine the data from many data frames into a single data frame with an array as the data values
Pyhton pandas: How to combine the data from many data frames into a single
data frame with an array as the data values
If I have many panda data frames, with the same index structure, I want to
create a data frame with the same index structure but the data values are
np.arrays (actually I want np.matrix.)
Merging seems to do just fine with simple operations df1 + df2 adds
element wise but np.array((df1,df2)) doesn't do at all what I want.
Does pandas have a method of doing this without rebuilding the entire
object element by element?
E.g. if I have
df1 = col1 col2
1 1 2
2 3 4
df2 = col1 col2
1 5 6
2 7 8
and want
df2 = col1 col2
1 [1,5] [2,6]
2 [3,7] [4,8]
data frame with an array as the data values
If I have many panda data frames, with the same index structure, I want to
create a data frame with the same index structure but the data values are
np.arrays (actually I want np.matrix.)
Merging seems to do just fine with simple operations df1 + df2 adds
element wise but np.array((df1,df2)) doesn't do at all what I want.
Does pandas have a method of doing this without rebuilding the entire
object element by element?
E.g. if I have
df1 = col1 col2
1 1 2
2 3 4
df2 = col1 col2
1 5 6
2 7 8
and want
df2 = col1 col2
1 [1,5] [2,6]
2 [3,7] [4,8]
Google Map Markermanager using a xml file
Google Map Markermanager using a xml file
I am trying to adapt this code (comming from Google Developpers)
//<![CDATA[
var map;
var mgr;
var icons = {};
var allmarkers = [];
function load() {
var myOptions = {
zoom: 3,
center: new google.maps.LatLng(50.62504, -100.10742),
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById('map'),
myOptions);
mgr = new MarkerManager(map);
google.maps.event.addListener(mgr, 'loaded', function(){
setupOfficeMarkers();
google.maps.event.addListener(map, 'zoom_changed', function() {
updateStatus(mgr.getMarkerCount(map.getZoom()));
});
});
}
function getIcon(images) {
var icon = false;
if (images) {
if (icons[images[0]]) {
icon = icons[images[0]];
} else {
var iconImage = new google.maps.MarkerImage('images/' +
images[0] + '.png',
new google.maps.Size(iconData[images[0]].width,
iconData[images[0]].height),
new google.maps.Point(0,0),
new google.maps.Point(0, 32));
var iconShadow = new google.maps.MarkerImage('images/' +
images[1] + '.png',
new google.maps.Size(iconData[images[1]].width,
iconData[images[1]].height),
new google.maps.Point(0,0),
new google.maps.Point(0, 32));
var iconShape = {
coord: [1, 1, 1, 32, 32, 32, 32, 1],
type: 'poly'
};
icons[images[0]] = {
icon : iconImage,
shadow: iconShadow,
shape : iconShape
};
}
}
return icon;
}
function setupOfficeMarkers() {
allmarkers.length = 0;
for (var i in officeLayer) {
if (officeLayer.hasOwnProperty(i)) {
var layer = officeLayer[i];
var markers = [];
for (var j in layer["places"]) {
if (layer["places"].hasOwnProperty(j)) {
var place = layer["places"][j];
var icon = getIcon(place["icon"]);
var title = place["name"];
var posn = new google.maps.LatLng(place["posn"][0],
place["posn"][1]);
var marker = createMarker(posn, title,
getIcon(place["icon"]));
markers.push(marker);
allmarkers.push(marker);
}
}
mgr.addMarkers(markers, layer["zoom"][0], layer["zoom"][2]);
}
}
mgr.refresh();
updateStatus(mgr.getMarkerCount(map.getZoom()));
}
function createMarker(posn, title, icon) {
var markerOptions = {
position: posn,
title: title
};
if(icon !== false){
markerOptions.shadow = icon.shadow;
markerOptions.icon = icon.icon;
markerOptions.shape = icon.shape;
}
var marker = new google.maps.Marker(markerOptions);
google.maps.event.addListener(marker, 'dblclick', function() {
mgr.removeMarker(marker)
updateStatus(mgr.getMarkerCount(map.getZoom()));
});
return marker;
}
function showMarkers() {
mgr.show();
updateStatus(mgr.getMarkerCount(map.getZoom()));
}
function hideMarkers() {
mgr.hide();
updateStatus(mgr.getMarkerCount(map.getZoom()));
}
function deleteMarker() {
var markerNum =
parseInt(document.getElementById("markerNum").value);
mgr.removeMarker(allmarkers[markerNum]);
updateStatus(mgr.getMarkerCount(map.getZoom()));
}
function clearMarkers() {
mgr.clearMarkers();
updateStatus(mgr.getMarkerCount(map.getZoom()));
}
function reloadMarkers() {
setupOfficeMarkers();
}
function updateStatus(html) {
document.getElementById("status").innerHTML = html;
}
//]]>
google-maps-utility-library-v3 Markermanager
It is an example about how to use markermanager but it is using a js file
as raw material and I would like to use a xml file. I tried several
possibilities but no success.
Here you can find the js file
http://google-maps-utility-library-v3.googlecode.com/svn/trunk/markermanager/examples/google_northamerica_offices.js
The target is to adapt the code in order to use a XML file with these
markers:
Name
icon
Icon_shadow
Long
Lat
Zoom_max
Zoom_min
Some help please !
I am trying to adapt this code (comming from Google Developpers)
//<![CDATA[
var map;
var mgr;
var icons = {};
var allmarkers = [];
function load() {
var myOptions = {
zoom: 3,
center: new google.maps.LatLng(50.62504, -100.10742),
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById('map'),
myOptions);
mgr = new MarkerManager(map);
google.maps.event.addListener(mgr, 'loaded', function(){
setupOfficeMarkers();
google.maps.event.addListener(map, 'zoom_changed', function() {
updateStatus(mgr.getMarkerCount(map.getZoom()));
});
});
}
function getIcon(images) {
var icon = false;
if (images) {
if (icons[images[0]]) {
icon = icons[images[0]];
} else {
var iconImage = new google.maps.MarkerImage('images/' +
images[0] + '.png',
new google.maps.Size(iconData[images[0]].width,
iconData[images[0]].height),
new google.maps.Point(0,0),
new google.maps.Point(0, 32));
var iconShadow = new google.maps.MarkerImage('images/' +
images[1] + '.png',
new google.maps.Size(iconData[images[1]].width,
iconData[images[1]].height),
new google.maps.Point(0,0),
new google.maps.Point(0, 32));
var iconShape = {
coord: [1, 1, 1, 32, 32, 32, 32, 1],
type: 'poly'
};
icons[images[0]] = {
icon : iconImage,
shadow: iconShadow,
shape : iconShape
};
}
}
return icon;
}
function setupOfficeMarkers() {
allmarkers.length = 0;
for (var i in officeLayer) {
if (officeLayer.hasOwnProperty(i)) {
var layer = officeLayer[i];
var markers = [];
for (var j in layer["places"]) {
if (layer["places"].hasOwnProperty(j)) {
var place = layer["places"][j];
var icon = getIcon(place["icon"]);
var title = place["name"];
var posn = new google.maps.LatLng(place["posn"][0],
place["posn"][1]);
var marker = createMarker(posn, title,
getIcon(place["icon"]));
markers.push(marker);
allmarkers.push(marker);
}
}
mgr.addMarkers(markers, layer["zoom"][0], layer["zoom"][2]);
}
}
mgr.refresh();
updateStatus(mgr.getMarkerCount(map.getZoom()));
}
function createMarker(posn, title, icon) {
var markerOptions = {
position: posn,
title: title
};
if(icon !== false){
markerOptions.shadow = icon.shadow;
markerOptions.icon = icon.icon;
markerOptions.shape = icon.shape;
}
var marker = new google.maps.Marker(markerOptions);
google.maps.event.addListener(marker, 'dblclick', function() {
mgr.removeMarker(marker)
updateStatus(mgr.getMarkerCount(map.getZoom()));
});
return marker;
}
function showMarkers() {
mgr.show();
updateStatus(mgr.getMarkerCount(map.getZoom()));
}
function hideMarkers() {
mgr.hide();
updateStatus(mgr.getMarkerCount(map.getZoom()));
}
function deleteMarker() {
var markerNum =
parseInt(document.getElementById("markerNum").value);
mgr.removeMarker(allmarkers[markerNum]);
updateStatus(mgr.getMarkerCount(map.getZoom()));
}
function clearMarkers() {
mgr.clearMarkers();
updateStatus(mgr.getMarkerCount(map.getZoom()));
}
function reloadMarkers() {
setupOfficeMarkers();
}
function updateStatus(html) {
document.getElementById("status").innerHTML = html;
}
//]]>
google-maps-utility-library-v3 Markermanager
It is an example about how to use markermanager but it is using a js file
as raw material and I would like to use a xml file. I tried several
possibilities but no success.
Here you can find the js file
http://google-maps-utility-library-v3.googlecode.com/svn/trunk/markermanager/examples/google_northamerica_offices.js
The target is to adapt the code in order to use a XML file with these
markers:
Name
icon
Icon_shadow
Long
Lat
Zoom_max
Zoom_min
Some help please !
Tumblr with webview
Tumblr with webview
In my app i want to post image to tumblr.So i follow the tumblr api and i
used the the sample from the github.This is the github address
"https://github.com/RobertSzkutak/AndroidExamples". And every thing is
fine to upload the image successfully in tumblr. But in this sample they
are using browser to open tumblr login page and authentication.But my
question is how to use webview instead of browser.I google alot,but i did
not find any solution.So please guide me how to do this?.
In my app i want to post image to tumblr.So i follow the tumblr api and i
used the the sample from the github.This is the github address
"https://github.com/RobertSzkutak/AndroidExamples". And every thing is
fine to upload the image successfully in tumblr. But in this sample they
are using browser to open tumblr login page and authentication.But my
question is how to use webview instead of browser.I google alot,but i did
not find any solution.So please guide me how to do this?.
Using VB.net to get Excel Cell Value which is not the correct value?
Using VB.net to get Excel Cell Value which is not the correct value?
I've been stuck on this for the past few hours so I really could do with
some help. I am trying to get numeric (integer and decimal) values from an
Excel spreadsheet and use it create a graph on my form using the chart
control or even display that value in a textbox.
The Value of cell A11 is "2003" and K11 is "12.00" but the returned values
are 0 and 12. I use formulas to calculate the rest of the y values. The
strange thing is that text works fine. Cell A3 has "initial" which comes
back as "initial", it's just the numbers which don't work.
xlApp = New Excel.Application
xlWorkBook = xlApp.Workbooks.Open("C:\File.xls")
xlWorkBook = xlApp.Workbooks.Add("C:\File.xls")
xlSheet = xlWorkBook.Worksheets(1)
Dim x1 As String
Dim y1 As String
x1 = xlSheet.Range("A11").Value.ToString
y1 = xlSheet.Range("K11").Value.ToString
MsgBox(x1)
Thanks in advance
I've been stuck on this for the past few hours so I really could do with
some help. I am trying to get numeric (integer and decimal) values from an
Excel spreadsheet and use it create a graph on my form using the chart
control or even display that value in a textbox.
The Value of cell A11 is "2003" and K11 is "12.00" but the returned values
are 0 and 12. I use formulas to calculate the rest of the y values. The
strange thing is that text works fine. Cell A3 has "initial" which comes
back as "initial", it's just the numbers which don't work.
xlApp = New Excel.Application
xlWorkBook = xlApp.Workbooks.Open("C:\File.xls")
xlWorkBook = xlApp.Workbooks.Add("C:\File.xls")
xlSheet = xlWorkBook.Worksheets(1)
Dim x1 As String
Dim y1 As String
x1 = xlSheet.Range("A11").Value.ToString
y1 = xlSheet.Range("K11").Value.ToString
MsgBox(x1)
Thanks in advance
Generating unique download link to download once only
This summary is not available. Please
click here to view the post.
Tuesday, 17 September 2013
formatting xml string to xml format for jaxb in java
formatting xml string to xml format for jaxb in java
I have a requirement that i have the string xml and i want to use this xml
string in another level to display in xml format.
My xmlgenerator is :
import javax.xml.bind.Marshaller;
import javax.xml.stream.XMLStreamWriter;
import com.db.accounting.application.server.common.DDAMessage;
@SuppressWarnings("restriction")
public class XmlGenerator {
private JAXBContext jaxbContext;
private XMLOutputFactory xmlOutputFactory;
public XmlGenerator() {
try {
jaxbContext = JAXBContext
.newInstance("com.db.accounting.application.server.jaxbautogenerated");
xmlOutputFactory = XMLOutputFactory.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
}
public final String getMessage(DDAMessage ddaMessage) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
Marshaller jaxbMarshaller =
jaxbContext.createMarshaller();
jaxbMarshaller.setProperty("jaxb.encoding", "UTF-8");
jaxbMarshaller.setProperty(Marshaller.JAXB_FRAGMENT,
true);
XMLStreamWriter xmlStreamWriter = xmlOutputFactory
.createXMLStreamWriter(baos, (String)
jaxbMarshaller
.getProperty(Marshaller.JAXB_ENCODING));
xmlStreamWriter.writeStartDocument((String)
jaxbMarshaller
.getProperty(Marshaller.JAXB_ENCODING),
"1.0");
ObjectFactory factory = new ObjectFactory();
TXNREQUEST txnrequest = factory.createTXNREQUEST();
TXNREQHDR txnreqhdr =
factory.createTXNREQUESTTXNREQHDR();
PFTACTGORDERMST pftactgordermst = factory
.createTXNREQUESTTXNREQHDRPFTACTGORDERMST();
PFTACTGORDERTXN pftactgordertxn = factory
.createTXNREQUESTTXNREQHDRPFTACTGORDERTXN();
pftactgordermst.setOUID("ift sift header");
pftactgordermst.setONSHREOFSHREINDCTR("ACU");
pftactgordermst.setORGN("1004");
pftactgordermst.setPREEXCTDFLG("1");
pftactgordermst.setNOOFBKNGS("2");
txnreqhdr.setPFTACTGORDERMST(pftactgordermst);
pftactgordertxn.setACNTREFTYP("7");
pftactgordertxn.setDRCRFLG("1");
pftactgordertxn.setTXNCRNCY("USD");
pftactgordertxn.setTXNAMT("XYZ");
pftactgordertxn.setVALDT("DDMMYY");
pftactgordertxn.setCUSREF("FFMMLL");
pftactgordertxn.setCNTRCTIDNTFRSOURCE("22630-1");
pftactgordertxn.setOWNERSHIPCODE("gle expense code");
pftactgordertxn.setPRDCTCODE("4210");
pftactgordertxn.setMRKTNGCODE("0072");
txnreqhdr.setPFTACTGORDERTXN(pftactgordertxn);
txnrequest.setTXNREQHDR(txnreqhdr);
jaxbMarshaller.marshal(txnrequest, xmlStreamWriter);
xmlStreamWriter.writeEndDocument();
xmlStreamWriter.close();
} catch (Exception e) {
e.printStackTrace();
}
return new String(baos.toByteArray());
}
}
From this file i am able to generate the xml file in string and when i am
accessing this xml in next level, I want display in xml format in log
file.
Thanks In Advance Ravindar Nidigonda
I have a requirement that i have the string xml and i want to use this xml
string in another level to display in xml format.
My xmlgenerator is :
import javax.xml.bind.Marshaller;
import javax.xml.stream.XMLStreamWriter;
import com.db.accounting.application.server.common.DDAMessage;
@SuppressWarnings("restriction")
public class XmlGenerator {
private JAXBContext jaxbContext;
private XMLOutputFactory xmlOutputFactory;
public XmlGenerator() {
try {
jaxbContext = JAXBContext
.newInstance("com.db.accounting.application.server.jaxbautogenerated");
xmlOutputFactory = XMLOutputFactory.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
}
public final String getMessage(DDAMessage ddaMessage) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
Marshaller jaxbMarshaller =
jaxbContext.createMarshaller();
jaxbMarshaller.setProperty("jaxb.encoding", "UTF-8");
jaxbMarshaller.setProperty(Marshaller.JAXB_FRAGMENT,
true);
XMLStreamWriter xmlStreamWriter = xmlOutputFactory
.createXMLStreamWriter(baos, (String)
jaxbMarshaller
.getProperty(Marshaller.JAXB_ENCODING));
xmlStreamWriter.writeStartDocument((String)
jaxbMarshaller
.getProperty(Marshaller.JAXB_ENCODING),
"1.0");
ObjectFactory factory = new ObjectFactory();
TXNREQUEST txnrequest = factory.createTXNREQUEST();
TXNREQHDR txnreqhdr =
factory.createTXNREQUESTTXNREQHDR();
PFTACTGORDERMST pftactgordermst = factory
.createTXNREQUESTTXNREQHDRPFTACTGORDERMST();
PFTACTGORDERTXN pftactgordertxn = factory
.createTXNREQUESTTXNREQHDRPFTACTGORDERTXN();
pftactgordermst.setOUID("ift sift header");
pftactgordermst.setONSHREOFSHREINDCTR("ACU");
pftactgordermst.setORGN("1004");
pftactgordermst.setPREEXCTDFLG("1");
pftactgordermst.setNOOFBKNGS("2");
txnreqhdr.setPFTACTGORDERMST(pftactgordermst);
pftactgordertxn.setACNTREFTYP("7");
pftactgordertxn.setDRCRFLG("1");
pftactgordertxn.setTXNCRNCY("USD");
pftactgordertxn.setTXNAMT("XYZ");
pftactgordertxn.setVALDT("DDMMYY");
pftactgordertxn.setCUSREF("FFMMLL");
pftactgordertxn.setCNTRCTIDNTFRSOURCE("22630-1");
pftactgordertxn.setOWNERSHIPCODE("gle expense code");
pftactgordertxn.setPRDCTCODE("4210");
pftactgordertxn.setMRKTNGCODE("0072");
txnreqhdr.setPFTACTGORDERTXN(pftactgordertxn);
txnrequest.setTXNREQHDR(txnreqhdr);
jaxbMarshaller.marshal(txnrequest, xmlStreamWriter);
xmlStreamWriter.writeEndDocument();
xmlStreamWriter.close();
} catch (Exception e) {
e.printStackTrace();
}
return new String(baos.toByteArray());
}
}
From this file i am able to generate the xml file in string and when i am
accessing this xml in next level, I want display in xml format in log
file.
Thanks In Advance Ravindar Nidigonda
uploading of files WCF c#
uploading of files WCF c#
I am working on uploading files with a WCF web service, here's my code for
uploading:
public string UploadTransactionsFile(string uploadPath)
{
string uploadTransactionsFile;
if (String.IsNullOrEmpty(uploadPath))
return string.Empty;
if (!ValidateTransactionsFile(uploadPath))
return string.Empty;
try
{
var dir = @"C:\Upload\";
string myUploadPath = dir;
var myFileName = Path.GetFileName(uploadPath);
CheckDirectory(myUploadPath);
var client = new WebClient { Credentials =
CredentialCache.DefaultCredentials };
client.UploadFile(myUploadPath + myFileName, "PUT", uploadPath);
client.Dispose();
uploadTransactionsFile = "ok";
}
catch (Exception ex)
{
uploadTransactionsFile = ex.Message;
}
return uploadTransactionsFile;
}
I created a Windows Forms test client and added the service reference, but
my code in calling the method and hardcoded the file i want to upload:
private testServiceClient testService;
private void Button_Click(object sender, RoutedEventArgs e)
{
var File = "C:\\file.csv";
testService = new testServiceClient();
mgiService.UploadTransactionFile(File);
}
I can upload files using one computer, but when I put my test client to
another computer, then I can't, because the file is just passing the
stringpath, which cannot be found on server computer.
Am I missing something?
Do I have to send my file as byte[]? If so, then how do I do this?
I am working on uploading files with a WCF web service, here's my code for
uploading:
public string UploadTransactionsFile(string uploadPath)
{
string uploadTransactionsFile;
if (String.IsNullOrEmpty(uploadPath))
return string.Empty;
if (!ValidateTransactionsFile(uploadPath))
return string.Empty;
try
{
var dir = @"C:\Upload\";
string myUploadPath = dir;
var myFileName = Path.GetFileName(uploadPath);
CheckDirectory(myUploadPath);
var client = new WebClient { Credentials =
CredentialCache.DefaultCredentials };
client.UploadFile(myUploadPath + myFileName, "PUT", uploadPath);
client.Dispose();
uploadTransactionsFile = "ok";
}
catch (Exception ex)
{
uploadTransactionsFile = ex.Message;
}
return uploadTransactionsFile;
}
I created a Windows Forms test client and added the service reference, but
my code in calling the method and hardcoded the file i want to upload:
private testServiceClient testService;
private void Button_Click(object sender, RoutedEventArgs e)
{
var File = "C:\\file.csv";
testService = new testServiceClient();
mgiService.UploadTransactionFile(File);
}
I can upload files using one computer, but when I put my test client to
another computer, then I can't, because the file is just passing the
stringpath, which cannot be found on server computer.
Am I missing something?
Do I have to send my file as byte[]? If so, then how do I do this?
Import XML into Azure
Import XML into Azure
Somebody knows how to simply import xml into sql azure please? I will
thank you for that. any tutorial or else... I tried OPENXML but not
supported in azure I tried different software too, but nothing works?
Somebody knows how to simply import xml into sql azure please? I will
thank you for that. any tutorial or else... I tried OPENXML but not
supported in azure I tried different software too, but nothing works?
Jersey Restful API Validation
Jersey Restful API Validation
how can i validate user name and password using jersey restful API.
Here is the code Below:
I tried using the HttpRequest and HttpResponse
@POST
@Path("/login")
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
@Produces(MediaType.APPLICATION_JSON)
public String postLoginJson(@FormParam("userName") String userName,
@FormParam("password") String password) {
String user = null;
try {
user = userObjectJson();
} catch (JSONException e) {
e.printStackTrace();
}
System.out.println("User Name = " + userName);
System.out.println("Password = " + password);
return user;
}
how can i validate user name and password using jersey restful API.
Here is the code Below:
I tried using the HttpRequest and HttpResponse
@POST
@Path("/login")
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
@Produces(MediaType.APPLICATION_JSON)
public String postLoginJson(@FormParam("userName") String userName,
@FormParam("password") String password) {
String user = null;
try {
user = userObjectJson();
} catch (JSONException e) {
e.printStackTrace();
}
System.out.println("User Name = " + userName);
System.out.println("Password = " + password);
return user;
}
Wrong default form values from model
Wrong default form values from model
I have a backup variable for an account's username that I save through
posts in a hidden field, @Html.HiddenFor(u => u.backupUsername). This is
the function the form posts to:
[HttpPost]
public ActionResult Update(AccountModel newInfo)
{
validateUserInfo(newInfo);
if (ModelState.IsValid)
{
newInfo.updateToDatabase();
}
return View(newInfo);
}
In updateToDatabase(), the backup username is updated to match the current
one. I've set breakpoints and looked at the values during debug to confirm
that this does happen and work.
However, as soon as Update() is called again, newInfo.backupUsername is
back to what it was before anything had been changed. What am I missing
here? Shouldn't the form's--and therefore the hidden field's--values get
repopulated from the model passed in?
I have a backup variable for an account's username that I save through
posts in a hidden field, @Html.HiddenFor(u => u.backupUsername). This is
the function the form posts to:
[HttpPost]
public ActionResult Update(AccountModel newInfo)
{
validateUserInfo(newInfo);
if (ModelState.IsValid)
{
newInfo.updateToDatabase();
}
return View(newInfo);
}
In updateToDatabase(), the backup username is updated to match the current
one. I've set breakpoints and looked at the values during debug to confirm
that this does happen and work.
However, as soon as Update() is called again, newInfo.backupUsername is
back to what it was before anything had been changed. What am I missing
here? Shouldn't the form's--and therefore the hidden field's--values get
repopulated from the model passed in?
Sunday, 15 September 2013
Intellij 12 always do "make"(several seconds) even no code change
Intellij 12 always do "make"(several seconds) even no code change
I just start learning the Intellij. I create a small project and create
several java files in a module. There is one thing bothers me, that
Intellij always do a "make", which takes about 6-8 seconds, every time
before run or debug the java code, no matter if I changed the code or not.
I have turned on the "make project automatically" setting in compiler
setting. Anyone have a idea?
I just start learning the Intellij. I create a small project and create
several java files in a module. There is one thing bothers me, that
Intellij always do a "make", which takes about 6-8 seconds, every time
before run or debug the java code, no matter if I changed the code or not.
I have turned on the "make project automatically" setting in compiler
setting. Anyone have a idea?
smoothAnchors.js not working in IE
smoothAnchors.js not working in IE
I'm having trouble getting smoothAnchors.js to work in IE. Can anybody see
where I'm going wrong please?
I am using bigvideo.js on this page
http://thewebsitedeveloper.co.nz/thinkRedTest/sureFire/index.html and also
have a button activating a scrolling animation to a div using
smoothAnchors.js
The scrolling animation works perfectly in all browsers on my local host,
and on the test site it works fine on all browsers except IE where the
scrolling animation is not working. it does work when I turn off
bigvideo.js. Can anybody suggest a way to make this work with the video?
Any help greatly appreciated. Thanks in advance.
HTML
<div class="arrowButton" id="scrollIt">
<a href="#lower-content">
<img src="images/arrowDown2.png" alt="down pointing arrow icon">
</a>
</div>
jQuery
<script>
$(function() {
var BV = new $.BigVideo();
BV.init();
BV.show('video/surefireRedBg.mp4',{ambient:true});
//scrolling to anchor links
$.smoothAnchors("slow");
});
</script>
I'm having trouble getting smoothAnchors.js to work in IE. Can anybody see
where I'm going wrong please?
I am using bigvideo.js on this page
http://thewebsitedeveloper.co.nz/thinkRedTest/sureFire/index.html and also
have a button activating a scrolling animation to a div using
smoothAnchors.js
The scrolling animation works perfectly in all browsers on my local host,
and on the test site it works fine on all browsers except IE where the
scrolling animation is not working. it does work when I turn off
bigvideo.js. Can anybody suggest a way to make this work with the video?
Any help greatly appreciated. Thanks in advance.
HTML
<div class="arrowButton" id="scrollIt">
<a href="#lower-content">
<img src="images/arrowDown2.png" alt="down pointing arrow icon">
</a>
</div>
jQuery
<script>
$(function() {
var BV = new $.BigVideo();
BV.init();
BV.show('video/surefireRedBg.mp4',{ambient:true});
//scrolling to anchor links
$.smoothAnchors("slow");
});
</script>
MappingException: The class 'Acme\UserBundle\Entity\User' was not found in the chain configured namespaces
MappingException: The class 'Acme\UserBundle\Entity\User' was not found in
the chain configured namespaces
I need to use etity_managers instead of auto_mappings
it shows this error.
MappingException: The class 'Acme\UserBundle\Entity\User' was not found in
the chain configured namespaces
my config.yml is like this.
doctrine: dbal:
orm:
auto_generate_proxy_classes: %kernel.debug%
entity_managers:
FOSUserBundle: ~
FOSMessageBundle: ~
AcmeUserBundle: ~
Is there anything I have to do ?
the chain configured namespaces
I need to use etity_managers instead of auto_mappings
it shows this error.
MappingException: The class 'Acme\UserBundle\Entity\User' was not found in
the chain configured namespaces
my config.yml is like this.
doctrine: dbal:
orm:
auto_generate_proxy_classes: %kernel.debug%
entity_managers:
FOSUserBundle: ~
FOSMessageBundle: ~
AcmeUserBundle: ~
Is there anything I have to do ?
perl splitting function exception conditions
perl splitting function exception conditions
I have a requirement for splitting in perl . Please have a look in below Ex
"john","David2,mick",25,"12-12-2009","male"
I have to split this record on comma (,) but should not consider the comma
in quotes...
O/P I required is
john
david2mick
25
12-12-2009
male
Could you please help me in this.
I have a requirement for splitting in perl . Please have a look in below Ex
"john","David2,mick",25,"12-12-2009","male"
I have to split this record on comma (,) but should not consider the comma
in quotes...
O/P I required is
john
david2mick
25
12-12-2009
male
Could you please help me in this.
Why does Bash enclose strings in a backtick and single-quote?
Why does Bash enclose strings in a backtick and single-quote?
Note lines 2 and 4. I always notice this, and get curious as to why they
quote a string with different characters.
root@vm:/# stat 1
stat: cannot stat `1': No such file or directory
root@vm:/# stat /
File: `/'
...
Note lines 2 and 4. I always notice this, and get curious as to why they
quote a string with different characters.
root@vm:/# stat 1
stat: cannot stat `1': No such file or directory
root@vm:/# stat /
File: `/'
...
Nullpointer exception in hashmap when running nutch on a hadoop cluster
Nullpointer exception in hashmap when running nutch on a hadoop cluster
I run nutch crawler on a hadoop cluster with only 2 node, but when i ran
nutch job on hadoop i get a nullpointer exception after "update-table"
phase,
the specific error comes below
Exception in thread "main" java.lang.NullPointerException
at java.util.Hashtable.put(Hashtable.java:394)
at java.util.Properties.setProperty(Properties.java:143)
at org.apache.hadoop.conf.Configuration.set(Configuration.java:419)
at org.apache.nutch.indexer.IndexerJob.createIndexJob(IndexerJob.java:128)
at org.apache.nutch.indexer.solr.SolrIndexerJob.run(SolrIndexerJob.java:44)
at org.apache.nutch.crawl.Crawler.runTool(Crawler.java:68)
at org.apache.nutch.crawl.Crawler.run(Crawler.java:192)
at org.apache.nutch.crawl.Crawler.run(Crawler.java:250)
at org.apache.hadoop.util.ToolRunner.run(ToolRunner.java:65)
at org.apache.nutch.crawl.Crawler.main(Crawler.java:257)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.apache.hadoop.util.RunJar.main(RunJar.java:160)
i'm newbie in hadoop and nutch and don't know where to look.
i use hadoop-1.2.0 and nutch 2.2.1.
i ran nutch crawler by this command
~/hadoop-1.2.0/bin/hadoop jar apache-nutch-2.2.1.job
org.apache.nutch.crawl.Crawler -solr http://10.1.1.69:8090/solr/core1/
urls -depth 1 -topN 1 -batch 111
I run nutch crawler on a hadoop cluster with only 2 node, but when i ran
nutch job on hadoop i get a nullpointer exception after "update-table"
phase,
the specific error comes below
Exception in thread "main" java.lang.NullPointerException
at java.util.Hashtable.put(Hashtable.java:394)
at java.util.Properties.setProperty(Properties.java:143)
at org.apache.hadoop.conf.Configuration.set(Configuration.java:419)
at org.apache.nutch.indexer.IndexerJob.createIndexJob(IndexerJob.java:128)
at org.apache.nutch.indexer.solr.SolrIndexerJob.run(SolrIndexerJob.java:44)
at org.apache.nutch.crawl.Crawler.runTool(Crawler.java:68)
at org.apache.nutch.crawl.Crawler.run(Crawler.java:192)
at org.apache.nutch.crawl.Crawler.run(Crawler.java:250)
at org.apache.hadoop.util.ToolRunner.run(ToolRunner.java:65)
at org.apache.nutch.crawl.Crawler.main(Crawler.java:257)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.apache.hadoop.util.RunJar.main(RunJar.java:160)
i'm newbie in hadoop and nutch and don't know where to look.
i use hadoop-1.2.0 and nutch 2.2.1.
i ran nutch crawler by this command
~/hadoop-1.2.0/bin/hadoop jar apache-nutch-2.2.1.job
org.apache.nutch.crawl.Crawler -solr http://10.1.1.69:8090/solr/core1/
urls -depth 1 -topN 1 -batch 111
sqlplus doesn't start on linux 64
sqlplus doesn't start on linux 64
I installed, on Mint15 64bit, the Oracle Instant client package 11
Each time I try running sqlplus I get message
Error 6 initializing SQL*Plus
SP2-0667: Message file sp1<lang>.msb not found
SP2-0750: You may need to set ORACLE_HOME to your Oracle software directory
Of course I set correctly the $ORACLE_HOME. I tried to set LANG=us Same
result.
I tried with instant oracle 12.1, same results !?
Except waving to MariaDb ;) What part is wrong in my install ?
I installed, on Mint15 64bit, the Oracle Instant client package 11
Each time I try running sqlplus I get message
Error 6 initializing SQL*Plus
SP2-0667: Message file sp1<lang>.msb not found
SP2-0750: You may need to set ORACLE_HOME to your Oracle software directory
Of course I set correctly the $ORACLE_HOME. I tried to set LANG=us Same
result.
I tried with instant oracle 12.1, same results !?
Except waving to MariaDb ;) What part is wrong in my install ?
Saturday, 14 September 2013
compare and print starting($1) and ending($2) number in given input $1 using unix
compare and print starting($1) and ending($2) number in given input $1
using unix
i having input in a.txt file,
10000030 10000029 10000028 10000027 10000026 10000024 10000023 10000021
10000018 10000018 10000017 10000016 10000015 10000014 10000013 10000011
10000010 10000009 10000008 10000006 10000005 10000004 10000003 10000002
10000001
need output in b.txt
10000001,10000006,6 10000008,10000011,4 10000013,10000019,7
10000021,10000021,1 10000023,10000024,2 10000026,10000030,5
Help me solve this script.....
using unix
i having input in a.txt file,
10000030 10000029 10000028 10000027 10000026 10000024 10000023 10000021
10000018 10000018 10000017 10000016 10000015 10000014 10000013 10000011
10000010 10000009 10000008 10000006 10000005 10000004 10000003 10000002
10000001
need output in b.txt
10000001,10000006,6 10000008,10000011,4 10000013,10000019,7
10000021,10000021,1 10000023,10000024,2 10000026,10000030,5
Help me solve this script.....
Physics-based drawing app
Physics-based drawing app
I'm working on a project that's rather complex for me, considering that I
only recently picked up javascript.
Basically I want to use the box2d phsyics engine and I want to allow users
to draw on on a canvas and then I want box2d physics to act on the objects
the users have drawn.
I worked through these two tutorials and then played around with the
results a little bit:
http://net.tutsplus.com/tutorials/html-css-techniques/build-your-first-game-with-html5/
http://www.williammalone.com/articles/create-html5-canvas-javascript-drawing-app/
So now I have a little drawing app as well as a physics based game. I have
no idea whatsoever how to combine this in any way.
I'd be very grateful if anyone had any sort of general pointers or advice
for me on how I would approach this.
I'm working on a project that's rather complex for me, considering that I
only recently picked up javascript.
Basically I want to use the box2d phsyics engine and I want to allow users
to draw on on a canvas and then I want box2d physics to act on the objects
the users have drawn.
I worked through these two tutorials and then played around with the
results a little bit:
http://net.tutsplus.com/tutorials/html-css-techniques/build-your-first-game-with-html5/
http://www.williammalone.com/articles/create-html5-canvas-javascript-drawing-app/
So now I have a little drawing app as well as a physics based game. I have
no idea whatsoever how to combine this in any way.
I'd be very grateful if anyone had any sort of general pointers or advice
for me on how I would approach this.
Get Albumart in .mp3 file for Windows Store App
Get Albumart in .mp3 file for Windows Store App
How can i get the AlbumArt image in the mp3 file? I am developing Windows
Store app with c#.
MusicProperties class gives me Album name artist name vs. But it cant give
me albumart.
How can i get the AlbumArt image in the mp3 file? I am developing Windows
Store app with c#.
MusicProperties class gives me Album name artist name vs. But it cant give
me albumart.
Python Script To Upload 300,000 files- Sqlite3 or massive list?
Python Script To Upload 300,000 files- Sqlite3 or massive list?
I am writing a script that will upload files to a cloud account. There
will be various directories containing the files, but only one
depth...there will be no nested/directories inside of directories. Each
directory will be a container in which the files will go in. Sometimes the
files may be as large as 300,000 files. I will be using multiprocessing.
I would like to keep track of the filenames, outoutput information,
returns codes using sqlite, so I had a few questions:
1) If I only had sqlite3 run in memory rather than as flat files(since I
only need the info untill I'm done with the script) would it bloat the
memory? 2) Would there be a major performance impact using sqlite3 as
opposed to keeping track with a massive list of lists or a dictionary of
lists?
I am writing a script that will upload files to a cloud account. There
will be various directories containing the files, but only one
depth...there will be no nested/directories inside of directories. Each
directory will be a container in which the files will go in. Sometimes the
files may be as large as 300,000 files. I will be using multiprocessing.
I would like to keep track of the filenames, outoutput information,
returns codes using sqlite, so I had a few questions:
1) If I only had sqlite3 run in memory rather than as flat files(since I
only need the info untill I'm done with the script) would it bloat the
memory? 2) Would there be a major performance impact using sqlite3 as
opposed to keeping track with a massive list of lists or a dictionary of
lists?
Can I get an instance of a class that implements an interface?
Can I get an instance of a class that implements an interface?
I have this function:
/***
* Changes the windows panel and allows a state change
* you can also change the minimum window size
* */
public void changePanel(CBPanel panel){
mainFrame.setContentPane();
mainFrame.setMinimumSize(panel.getMinSize());
mainFrame.setResizable(panel.canResize());
}
It takes CBPanel as the only argument and CBPanel is interface that
generally will be implemented onto a JCOmponent. Is there any way I can
get an instance of the JComponent from interface class?
I call it like so
changePanel(new LoginPanel());
So logically, I should be able to get an instance of the LoginPanel,
right? I was wondering if it does using some kind of type declaration of
type cast?
I have this function:
/***
* Changes the windows panel and allows a state change
* you can also change the minimum window size
* */
public void changePanel(CBPanel panel){
mainFrame.setContentPane();
mainFrame.setMinimumSize(panel.getMinSize());
mainFrame.setResizable(panel.canResize());
}
It takes CBPanel as the only argument and CBPanel is interface that
generally will be implemented onto a JCOmponent. Is there any way I can
get an instance of the JComponent from interface class?
I call it like so
changePanel(new LoginPanel());
So logically, I should be able to get an instance of the LoginPanel,
right? I was wondering if it does using some kind of type declaration of
type cast?
Concatenate 2 letters with preg_replace and regex
Concatenate 2 letters with preg_replace and regex
I have a list of company names to process, and send to various places
after formatting. My current issue is the following :
Example lines
J C PENNEY CO INC
DOLLAR TREE INC
C H ROBINSON WORLDWIDE INC
GOOGLE INC
I would like to concatenate the single letters J C , and C H into JC and
CH, so the final result reads :
JC PENNEY CO INC
DOLLAR TREE INC
CH ROBINSON WORLDWIDE INC
GOOGLE INC
This should happen only at the beginning of the word. I have no problem
finding the pattern, with /^\w\s\w\s/, but how can I remove the space in
the middle? Thanks for your help!
I have a list of company names to process, and send to various places
after formatting. My current issue is the following :
Example lines
J C PENNEY CO INC
DOLLAR TREE INC
C H ROBINSON WORLDWIDE INC
GOOGLE INC
I would like to concatenate the single letters J C , and C H into JC and
CH, so the final result reads :
JC PENNEY CO INC
DOLLAR TREE INC
CH ROBINSON WORLDWIDE INC
GOOGLE INC
This should happen only at the beginning of the word. I have no problem
finding the pattern, with /^\w\s\w\s/, but how can I remove the space in
the middle? Thanks for your help!
Memory waste by postincrement/decrement
Memory waste by postincrement/decrement
Why is it so that memory is wasted when we use a post-increment/ decrement
operator as when the operator returns a temp it is de-allocated and memory
is freed up?
Why is it so that memory is wasted when we use a post-increment/ decrement
operator as when the operator returns a temp it is de-allocated and memory
is freed up?
code restricting creation of more than one object in private constructor in C#
code restricting creation of more than one object in private constructor
in C#
I want to create a code in C# for Private constructor.I want that it
should allow only one object to be created but when I try to create more
than one a message showing " no more object can be created" should be
shown.I don't want to use static constructor in this code.
in C#
I want to create a code in C# for Private constructor.I want that it
should allow only one object to be created but when I try to create more
than one a message showing " no more object can be created" should be
shown.I don't want to use static constructor in this code.
Friday, 13 September 2013
Can not run mongo command in terminal
Can not run mongo command in terminal
I installed mongoDB with a .tar in a certian directory and I can only run
mongo in that directory if i use
./mongo
Otherwise if i try to just use
mongo
The terminal will tell me that it is not installed. What should I do?
I installed mongoDB with a .tar in a certian directory and I can only run
mongo in that directory if i use
./mongo
Otherwise if i try to just use
mongo
The terminal will tell me that it is not installed. What should I do?
How to use String.startWith(..) to ignore leading whitespace?
How to use String.startWith(..) to ignore leading whitespace?
Let's say I have the following that start with "needle", ignoring leading
whitespace:
String haystack = "needle#####^&%#$^%...";
String haystackWithSpace = " needle******!@@#!@@%@%!$...";
I want to capture anything that starts with "needle" or "/s*needle"(if
there was a regex allowed). Is there an elegant way to do this without
calling .trim()? Or is there a way to make a regex work here? I want the
following to be true:
haystackWithSpace.startsWith("needle"); // doesn't ignore leading whitespace
haystackWithSpace.startsWith("/s*needle"); // doesn't work
Basically, is there a String s that will satisfy the following?:
haystack.startsWith(s) == haystackWithSpace.startsWith(s);
Let's say I have the following that start with "needle", ignoring leading
whitespace:
String haystack = "needle#####^&%#$^%...";
String haystackWithSpace = " needle******!@@#!@@%@%!$...";
I want to capture anything that starts with "needle" or "/s*needle"(if
there was a regex allowed). Is there an elegant way to do this without
calling .trim()? Or is there a way to make a regex work here? I want the
following to be true:
haystackWithSpace.startsWith("needle"); // doesn't ignore leading whitespace
haystackWithSpace.startsWith("/s*needle"); // doesn't work
Basically, is there a String s that will satisfy the following?:
haystack.startsWith(s) == haystackWithSpace.startsWith(s);
Our prof says for a double loop, T(n) is a*(n^2) + b*n + c. I think it's just a*(n^2). What's the exact answer?
Our prof says for a double loop, T(n) is a*(n^2) + b*n + c. I think it's
just a*(n^2). What's the exact answer?
This is the slide by our prof.
Example 4: Consider this simple program: 1: s = 0 2: for i = 1 to n do 3:
for j = 1 to n do 4: s= s+i+j 5:end for 6:end for` T(n) =? It's hard to
get the exact expression of T(n) even for this very simple program. We can
see: the loop iterates n2 times, and loop body takes constant number of
instructions. So T(n) = a*(n^2) + bn + c for some constants a, b, c.
Now here's what I think. Let's assume that the body loop takes constant
time 'a'. Then that itself will be looped over for a*(n^2) times. So, I
don't understand from where b*n + c comes! What's the actual answer?
just a*(n^2). What's the exact answer?
This is the slide by our prof.
Example 4: Consider this simple program: 1: s = 0 2: for i = 1 to n do 3:
for j = 1 to n do 4: s= s+i+j 5:end for 6:end for` T(n) =? It's hard to
get the exact expression of T(n) even for this very simple program. We can
see: the loop iterates n2 times, and loop body takes constant number of
instructions. So T(n) = a*(n^2) + bn + c for some constants a, b, c.
Now here's what I think. Let's assume that the body loop takes constant
time 'a'. Then that itself will be looped over for a*(n^2) times. So, I
don't understand from where b*n + c comes! What's the actual answer?
Sqlite randomly slowing down on simple (but big) table on iOS
Sqlite randomly slowing down on simple (but big) table on iOS
I'm working on an enterprise sales app, for iPad, that uses Sqlite as its
internal database, and a strange behaviour recently showed up.
I have a huge table that is filled with information from several other
tables (sort of like a "materialized view"), which can contain over 2
million rows, depending on how the user is set up. When the user wants to
search for an item, the app performs a query on this huge table that has
an indexed column and on other columns that are used as filters and/or
metadata. I'll post the query and the basic idea below. Anyway, this query
usually returns in 2~3 seconds on an iPad 4th gen, no more than that, and
this is just fine. This table is dropped, re-created and filled every time
the user taps a button to synchronize his data with our server.
However, recently the same query in the same table (with no relevant
changes at all), randomly started to take 40~50 seconds. If you do the
same thing later, on the same device, with the same filters (or even
changing the filters!), the same query on the same table takes the 2~3
seconds again. I haven't found any specific situation that causes this
slowdown, the app is the only one running at that time. The device is not
the problem, we've seen this happen on at least 5 different iPads, one is
an iPad 3 and the others are iPads 4th gen.
I don't think it is some sort of caching, since the app does not cache
anything, and these times are rather random. Sometimes they take 40
seconds for 10 times in a row, then suddenly it starts to take only 2
seconds again, and the same thing the other way. The only thing that is
clear to me is that this slowdown only occurs after intensive use (1 - 2
days of work using the app), so I'm also having troubles to cause this
behaviour while debugging on the iPad I have with me.
What I've tried:
Attach Instruments to the process and check what resources are being used
during the slowdown. The app does INTENSIVE use of the iPad's 'disk'
(flash memory) during the whole time. I don't have the example to analyse
it again now, but I think the CPU usage was around 30%. The RAM usage is
stable at 90~100MB, which is normal for our app.
Run VACCUM on the db; - reduced ~50MB on a database I had as example.
Run ANALYZE on the db; - didn't see any improvements
Run REINDEX on the db; - seems to be helping a little, but it's not
solving the problem.
Kill the process and start over - nothing changes
The huge table is constructed as the following, and does NOT have any
foreign keys or other any other constraint:
CREATE TABLE FMV_CATALOG(
UNIQUE_ID TEXT,
PRODUCT_ID INTEGER,
<bunch of metadata/filtered columns - total of 20 columns>
);
And the query that is made to find the products is:
SELECT
PRODUCT_ID
,UNIQUE_ID
<all other required columns, ~20 columns>
FROM
FMV_CATALOG
WHERE
UNIQUE_ID = '<some id>_<other id>'
AND PRODUCT_NAME LIKE '%iPhone%'
<and other optional, rarely used, filters.>
I'm totally out of ideas, so any help will be appreciated.
Thanks!
I'm working on an enterprise sales app, for iPad, that uses Sqlite as its
internal database, and a strange behaviour recently showed up.
I have a huge table that is filled with information from several other
tables (sort of like a "materialized view"), which can contain over 2
million rows, depending on how the user is set up. When the user wants to
search for an item, the app performs a query on this huge table that has
an indexed column and on other columns that are used as filters and/or
metadata. I'll post the query and the basic idea below. Anyway, this query
usually returns in 2~3 seconds on an iPad 4th gen, no more than that, and
this is just fine. This table is dropped, re-created and filled every time
the user taps a button to synchronize his data with our server.
However, recently the same query in the same table (with no relevant
changes at all), randomly started to take 40~50 seconds. If you do the
same thing later, on the same device, with the same filters (or even
changing the filters!), the same query on the same table takes the 2~3
seconds again. I haven't found any specific situation that causes this
slowdown, the app is the only one running at that time. The device is not
the problem, we've seen this happen on at least 5 different iPads, one is
an iPad 3 and the others are iPads 4th gen.
I don't think it is some sort of caching, since the app does not cache
anything, and these times are rather random. Sometimes they take 40
seconds for 10 times in a row, then suddenly it starts to take only 2
seconds again, and the same thing the other way. The only thing that is
clear to me is that this slowdown only occurs after intensive use (1 - 2
days of work using the app), so I'm also having troubles to cause this
behaviour while debugging on the iPad I have with me.
What I've tried:
Attach Instruments to the process and check what resources are being used
during the slowdown. The app does INTENSIVE use of the iPad's 'disk'
(flash memory) during the whole time. I don't have the example to analyse
it again now, but I think the CPU usage was around 30%. The RAM usage is
stable at 90~100MB, which is normal for our app.
Run VACCUM on the db; - reduced ~50MB on a database I had as example.
Run ANALYZE on the db; - didn't see any improvements
Run REINDEX on the db; - seems to be helping a little, but it's not
solving the problem.
Kill the process and start over - nothing changes
The huge table is constructed as the following, and does NOT have any
foreign keys or other any other constraint:
CREATE TABLE FMV_CATALOG(
UNIQUE_ID TEXT,
PRODUCT_ID INTEGER,
<bunch of metadata/filtered columns - total of 20 columns>
);
And the query that is made to find the products is:
SELECT
PRODUCT_ID
,UNIQUE_ID
<all other required columns, ~20 columns>
FROM
FMV_CATALOG
WHERE
UNIQUE_ID = '<some id>_<other id>'
AND PRODUCT_NAME LIKE '%iPhone%'
<and other optional, rarely used, filters.>
I'm totally out of ideas, so any help will be appreciated.
Thanks!
How can i make my CSS class to fit my image size?
How can i make my CSS class to fit my image size?
Hi I have image of this size :
<span class="Col2">
<img src="../Content/Images/20_thumb.jpg" width="281" height="200"
border="0" alt="image" />
</span>
And I have this CSS style which I am applying over this image:
.listRowA {
border: 1px solid #fff;
}
.listRowAHover {
background-color: #F4E4E4;
border: 1px solid #fff;
}
My hover style :
.listPageCol {
padding:5px;
margin-right:75px;
cursor:pointer;
}
Here problem I am facing is when I hover my image I can see pointer and
background-color outside my image also.So how can I fix this to fit to my
image?
Hi I have image of this size :
<span class="Col2">
<img src="../Content/Images/20_thumb.jpg" width="281" height="200"
border="0" alt="image" />
</span>
And I have this CSS style which I am applying over this image:
.listRowA {
border: 1px solid #fff;
}
.listRowAHover {
background-color: #F4E4E4;
border: 1px solid #fff;
}
My hover style :
.listPageCol {
padding:5px;
margin-right:75px;
cursor:pointer;
}
Here problem I am facing is when I hover my image I can see pointer and
background-color outside my image also.So how can I fix this to fit to my
image?
Thursday, 12 September 2013
AngularJS - How to write unit test case for ng-init directive?
AngularJS - How to write unit test case for ng-init directive?
I have ng-init set to call a function init in my controller scope.
<div ng-init="init('start')" ng-controller="ProgressController"></div>
My test suite is as below.
describe("Progress controller", function () {
var $scope = null;
var controller = null;
beforeEach(module('MyApp'));
beforeEach(inject(function ($rootScope, $controller) {
$scope = $rootScope.$new();
controller = $controller('ProgressController', {
$scope: $scope
});
}));
}
How do I include ng-init in my test case so that whenever the controller
is initialized, init function should be triggered?
I have ng-init set to call a function init in my controller scope.
<div ng-init="init('start')" ng-controller="ProgressController"></div>
My test suite is as below.
describe("Progress controller", function () {
var $scope = null;
var controller = null;
beforeEach(module('MyApp'));
beforeEach(inject(function ($rootScope, $controller) {
$scope = $rootScope.$new();
controller = $controller('ProgressController', {
$scope: $scope
});
}));
}
How do I include ng-init in my test case so that whenever the controller
is initialized, init function should be triggered?
Django: querying multiple types of objects
Django: querying multiple types of objects
I have a fairly basic model that allows users to create posts of different
'types'. There's currently a Text type and a Photo type that inherits from
a base 'Post' type.
I'm currently pulling TextPosts and PhotoPosts and chaining the two
QuerySets, but this seems like a bad idea.
Is there a way to simply query for both types of posts at once? The reason
I'm not using .filter() on Post itself is because I (presumably) don't
have any way of getting the TextPost or PhotoPost object from it (or do
I?)
PS: Does it make more sense to call it BasePost or Post if I'll never be
using Post by itself?
class Post(AutoDateTimeModel):
POST_TYPES = (
# Linkable Social Networks
('TEXT', 'Text'),
('PHOTO', 'Photo'),
('LINK', 'Link'),
)
post_type = models.ForeignKey(ContentType)
user = models.ForeignKey(User, blank=True, null=True)
interests = models.ManyToManyField(Interest, related_name='interests')
class Meta:
app_label = 'posts'
ordering = ('-created_at',)
def save(self, *args, **kwargs):
if not self.pk:
self.post_type = ContentType.objects.get_for_model(type(self))
# import pdb; pdb.set_trace()
super(Post, self).save(*args, **kwargs)
class TextPost(Post):
""" Text post model """
body = models.TextField()
class Meta:
app_label = 'posts'
class PhotoPost(Post):
""" Photo post model. This can contain multiple photos. """
description = models.TextField()
class Meta:
app_label = 'posts'
class Photo(models.Model):
""" Individual image model, used in photo posts. """
caption = models.TextField()
# source_url = models.URLField(blank=True, null=True)
image = ImageField(upload_to=upload_to)
post = models.ForeignKey(PhotoPost, blank=True, null=True,
related_name='photos')
user = models.ForeignKey(User, blank=True, null=True,
related_name='photos')
class Meta:
app_label = 'posts'
def __unicode__(self):
return 'Photo Object by: ' + str(self.user.get_full_name())
I have a fairly basic model that allows users to create posts of different
'types'. There's currently a Text type and a Photo type that inherits from
a base 'Post' type.
I'm currently pulling TextPosts and PhotoPosts and chaining the two
QuerySets, but this seems like a bad idea.
Is there a way to simply query for both types of posts at once? The reason
I'm not using .filter() on Post itself is because I (presumably) don't
have any way of getting the TextPost or PhotoPost object from it (or do
I?)
PS: Does it make more sense to call it BasePost or Post if I'll never be
using Post by itself?
class Post(AutoDateTimeModel):
POST_TYPES = (
# Linkable Social Networks
('TEXT', 'Text'),
('PHOTO', 'Photo'),
('LINK', 'Link'),
)
post_type = models.ForeignKey(ContentType)
user = models.ForeignKey(User, blank=True, null=True)
interests = models.ManyToManyField(Interest, related_name='interests')
class Meta:
app_label = 'posts'
ordering = ('-created_at',)
def save(self, *args, **kwargs):
if not self.pk:
self.post_type = ContentType.objects.get_for_model(type(self))
# import pdb; pdb.set_trace()
super(Post, self).save(*args, **kwargs)
class TextPost(Post):
""" Text post model """
body = models.TextField()
class Meta:
app_label = 'posts'
class PhotoPost(Post):
""" Photo post model. This can contain multiple photos. """
description = models.TextField()
class Meta:
app_label = 'posts'
class Photo(models.Model):
""" Individual image model, used in photo posts. """
caption = models.TextField()
# source_url = models.URLField(blank=True, null=True)
image = ImageField(upload_to=upload_to)
post = models.ForeignKey(PhotoPost, blank=True, null=True,
related_name='photos')
user = models.ForeignKey(User, blank=True, null=True,
related_name='photos')
class Meta:
app_label = 'posts'
def __unicode__(self):
return 'Photo Object by: ' + str(self.user.get_full_name())
NullPointerException when running JUnit tests, saying interface is null
NullPointerException when running JUnit tests, saying interface is null
I'm trying to write a java program that allows the user to input a series
of data values then for the program to sort through finding the mean and
the median of that series, using an interface to "treat" different objects
as if they were the same. However when I run my JUnit test, it keeps
saying my interface is null.
NoiseFilter.java
package noisefilter.model;
import java.util.ArrayList;
public interface NoiseFilter {
public double getBestMesurement(ArrayList<Double> samples);
}
AveragingFilter.java
package noisefilter.model;
import java.util.ArrayList;
public class AveragingFilter implements NoiseFilter {
@Override
/**
* The method getBestMeasurement takes an array list of type double and
returns a
*/
public double getBestMesurement(ArrayList<Double> samples) {
// TODO Auto-generated method stub
if (samples.equals(null)) {
throw new IllegalArgumentException("The Samples cannot be null");
}
if (samples.size() < 3) {
throw new IllegalArgumentException("The Sample size must have 3");
}
double sum = 0.0;
for (Double number : samples) {
sum += number;
}
return (sum / samples.size());
}
}
SensorData.java
package noisefilter.model;
import java.util.ArrayList;
public class SensorData implements NoiseFilter {
ArrayList<Double> data;
NoiseFilter filter;
public SensorData() {
this.data = new ArrayList<Double>();
this.filter = null;
}
public void addSample(double sample) {
data.add(sample);
}
public void setFilter(NoiseFilter filterVar) {
this.filter = filterVar;
}
public double getFilteredResult() {
if (filter.equals(null)) {
throw new IllegalStateException("The filter cannot be left null");
}
return filter.getBestMesurement(data);
}
@Override
public double getBestMesurement(ArrayList<Double> samples) {
samples = this.data;
return 0;
}
WhenAveragingFilter.java (JUnit Test)
package noisefilter.tests;
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Test;
import noisefilter.model.NoiseFilter;
import noisefilter.model.SensorData;
public class WhenAverageFiltering {
NoiseFilter filter;
SensorData dataSet;
@Before
public void setUp() throws Exception {
this.dataSet = new SensorData();
dataSet.setFilter(filter);
}
@Test
public void averageOfThree100sShouldBe100() {
dataSet.addSample(100);
dataSet.addSample(100);
dataSet.addSample(100);
assertTrue(dataSet.getFilteredResult() == 100);
}
@Test
public void averageOfThreeDifferent() {
dataSet.addSample(120);
dataSet.addSample(140);
dataSet.addSample(130);
assertTrue(dataSet.getFilteredResult() == 130);
}
@Test
public void averageOfFiveDifferent() {
dataSet.addSample(10);
dataSet.addSample(50);
dataSet.addSample(60);
assertTrue(dataSet.getFilteredResult() == 40);
}
}
Here's the errors that I get when I run the JUnit Test.
java.lang.NullPointerException
at noisefilter.model.SensorData.getFilteredResult(SensorData.java:24)
at
noisefilter.tests.WhenAverageFiltering.averageOfFiveDifferent(WhenAverageFiltering.java:47)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at
org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
at
org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at
org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
at
org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at
org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271)
at
org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70)
at
org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
at
org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at
org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at
org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at
org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at
org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at
org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
I'm trying to write a java program that allows the user to input a series
of data values then for the program to sort through finding the mean and
the median of that series, using an interface to "treat" different objects
as if they were the same. However when I run my JUnit test, it keeps
saying my interface is null.
NoiseFilter.java
package noisefilter.model;
import java.util.ArrayList;
public interface NoiseFilter {
public double getBestMesurement(ArrayList<Double> samples);
}
AveragingFilter.java
package noisefilter.model;
import java.util.ArrayList;
public class AveragingFilter implements NoiseFilter {
@Override
/**
* The method getBestMeasurement takes an array list of type double and
returns a
*/
public double getBestMesurement(ArrayList<Double> samples) {
// TODO Auto-generated method stub
if (samples.equals(null)) {
throw new IllegalArgumentException("The Samples cannot be null");
}
if (samples.size() < 3) {
throw new IllegalArgumentException("The Sample size must have 3");
}
double sum = 0.0;
for (Double number : samples) {
sum += number;
}
return (sum / samples.size());
}
}
SensorData.java
package noisefilter.model;
import java.util.ArrayList;
public class SensorData implements NoiseFilter {
ArrayList<Double> data;
NoiseFilter filter;
public SensorData() {
this.data = new ArrayList<Double>();
this.filter = null;
}
public void addSample(double sample) {
data.add(sample);
}
public void setFilter(NoiseFilter filterVar) {
this.filter = filterVar;
}
public double getFilteredResult() {
if (filter.equals(null)) {
throw new IllegalStateException("The filter cannot be left null");
}
return filter.getBestMesurement(data);
}
@Override
public double getBestMesurement(ArrayList<Double> samples) {
samples = this.data;
return 0;
}
WhenAveragingFilter.java (JUnit Test)
package noisefilter.tests;
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Test;
import noisefilter.model.NoiseFilter;
import noisefilter.model.SensorData;
public class WhenAverageFiltering {
NoiseFilter filter;
SensorData dataSet;
@Before
public void setUp() throws Exception {
this.dataSet = new SensorData();
dataSet.setFilter(filter);
}
@Test
public void averageOfThree100sShouldBe100() {
dataSet.addSample(100);
dataSet.addSample(100);
dataSet.addSample(100);
assertTrue(dataSet.getFilteredResult() == 100);
}
@Test
public void averageOfThreeDifferent() {
dataSet.addSample(120);
dataSet.addSample(140);
dataSet.addSample(130);
assertTrue(dataSet.getFilteredResult() == 130);
}
@Test
public void averageOfFiveDifferent() {
dataSet.addSample(10);
dataSet.addSample(50);
dataSet.addSample(60);
assertTrue(dataSet.getFilteredResult() == 40);
}
}
Here's the errors that I get when I run the JUnit Test.
java.lang.NullPointerException
at noisefilter.model.SensorData.getFilteredResult(SensorData.java:24)
at
noisefilter.tests.WhenAverageFiltering.averageOfFiveDifferent(WhenAverageFiltering.java:47)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at
org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
at
org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at
org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
at
org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at
org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271)
at
org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70)
at
org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
at
org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at
org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at
org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at
org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at
org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at
org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
plot in the x-axis a rotate labels in R
plot in the x-axis a rotate labels in R
I've to plot these data:
day temperature
02/01/2012 13:30:00 10
10/01/2012 20:30:00 8
15/01/2012 13:30:00 12
25/01/2012 20:30:00 6
02/02/2012 13:30:00 5
10/02/2012 20:30:00 3
15/02/2012 13:30:00 6
25/02/2012 20:30:00 -1
02/03/2012 13:30:00 4
10/03/2012 20:30:00 -2
15/03/2012 13:30:00 7
25/03/2012 20:30:00 1
in the x-axis I want to label only the month and the day (e.g. Jan 02 )
rotating of 45 degree. How can I do this using the command plot()?
I've to plot these data:
day temperature
02/01/2012 13:30:00 10
10/01/2012 20:30:00 8
15/01/2012 13:30:00 12
25/01/2012 20:30:00 6
02/02/2012 13:30:00 5
10/02/2012 20:30:00 3
15/02/2012 13:30:00 6
25/02/2012 20:30:00 -1
02/03/2012 13:30:00 4
10/03/2012 20:30:00 -2
15/03/2012 13:30:00 7
25/03/2012 20:30:00 1
in the x-axis I want to label only the month and the day (e.g. Jan 02 )
rotating of 45 degree. How can I do this using the command plot()?
Simple SOAP progam
Simple SOAP progam
I have to do a simple scritp (unix/linux target) to close log_file of a
print spooler program
the spooler program give the chances to call the function over soap, but I
know nothing of it
this is the function:
- <!-- VPSX System Close Account file Command request
-->
- <message name="VPSX_SystemCloseAcct">
<part name="SessID" type="xsd:string" />
<part name="VPSID" type="xsd:string" />
</message>
- <!-- VPSX System close account file Command request/response
-->
- <operation name="VPSX_SystemCloseAcct">
<input message="lrs:VPSX_SystemCloseAcct" />
<output message="lrs:VPSX_SystemCmdResponse" />
</operation>
<!-- VPSX System close account file Command request/response
-->
- <operation name="VPSX_SystemCloseAcct">
<soap:operation soapAction="" />
- <input>
<soap:body use="encoded" namespace="http://www.lrs.com"
encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" />
</input>
- <output>
<soap:body use="encoded" namespace="http://www.lrs.com"
encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" />
</output>
</operation>
is there a simple way (python?php?java?) to do this?
I have to do a simple scritp (unix/linux target) to close log_file of a
print spooler program
the spooler program give the chances to call the function over soap, but I
know nothing of it
this is the function:
- <!-- VPSX System Close Account file Command request
-->
- <message name="VPSX_SystemCloseAcct">
<part name="SessID" type="xsd:string" />
<part name="VPSID" type="xsd:string" />
</message>
- <!-- VPSX System close account file Command request/response
-->
- <operation name="VPSX_SystemCloseAcct">
<input message="lrs:VPSX_SystemCloseAcct" />
<output message="lrs:VPSX_SystemCmdResponse" />
</operation>
<!-- VPSX System close account file Command request/response
-->
- <operation name="VPSX_SystemCloseAcct">
<soap:operation soapAction="" />
- <input>
<soap:body use="encoded" namespace="http://www.lrs.com"
encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" />
</input>
- <output>
<soap:body use="encoded" namespace="http://www.lrs.com"
encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" />
</output>
</operation>
is there a simple way (python?php?java?) to do this?
What is the role of a default constructor exactly?
What is the role of a default constructor exactly?
From Thinking in C++
The first hidden argument to the constructor is the this pointer. this
pointer holds the address of the caller object. In the case of constructor
this pointer points towards an uninitialized block of memory. It is the
job of the constructor to initialize this block of memory properly.
So, basically, the constructor is used to get a pointer to the object's
space in RAM? Is that correct?
How does the default constructor initialize that memory? Does it get
initialized to zero?
From Thinking in C++
The first hidden argument to the constructor is the this pointer. this
pointer holds the address of the caller object. In the case of constructor
this pointer points towards an uninitialized block of memory. It is the
job of the constructor to initialize this block of memory properly.
So, basically, the constructor is used to get a pointer to the object's
space in RAM? Is that correct?
How does the default constructor initialize that memory? Does it get
initialized to zero?
Wednesday, 11 September 2013
Detecting if rectangles (buttons) overlap on x or y axis
Detecting if rectangles (buttons) overlap on x or y axis
I am currently trying to develop a prototype in android where the user is
able to drag 4 separate buttons around the screen.
The trouble I am having is with collision detection. If one of the buttons
is alongside another, for example, only movement along the Y axis should
be permitted. Similarly, if one of the buttons is touching the top or
bottom of another button, only movement along the X axis should be
allowed.
Something like
for (TouchButton t:myButtons)
{
if(!(t.equals(b)))
{
if((b.getY() >= t.getY() && (b.getY() <= (t.getY() +
t.getMeasuredHeight()))))
{
if((b.getX() >= t.getX() && (b.getX() <= (t.getX() +
t.getMeasuredWidth()))))
{
//dont move
}
}
}
should be able to detect if the buttons are touching across both axis? But
how do I determine if it should then be possible to slide up or across the
object?
I am currently trying to develop a prototype in android where the user is
able to drag 4 separate buttons around the screen.
The trouble I am having is with collision detection. If one of the buttons
is alongside another, for example, only movement along the Y axis should
be permitted. Similarly, if one of the buttons is touching the top or
bottom of another button, only movement along the X axis should be
allowed.
Something like
for (TouchButton t:myButtons)
{
if(!(t.equals(b)))
{
if((b.getY() >= t.getY() && (b.getY() <= (t.getY() +
t.getMeasuredHeight()))))
{
if((b.getX() >= t.getX() && (b.getX() <= (t.getX() +
t.getMeasuredWidth()))))
{
//dont move
}
}
}
should be able to detect if the buttons are touching across both axis? But
how do I determine if it should then be possible to slide up or across the
object?
iOS ARC: When and which memory stays alive
iOS ARC: When and which memory stays alive
Say I have a custom NSObject class called customClass with a property
NSMutableArray *thisArray;
I instantiate customClass *instance = [[customClass alloc] init] in my
root view controller. Somewhere in the the customClass implementation
thisArray is set.
Now I have a property in my root view controller NSMutableArray
(strong,nonatomic) *anotherArray and I set it via anotherArray =
customClass.thisArray. If I then set customClass to nil, will anotherArray
still point to an object in memory or is / should it be destroyed? What
about the rest of the object and its properties memory?
Say I have a custom NSObject class called customClass with a property
NSMutableArray *thisArray;
I instantiate customClass *instance = [[customClass alloc] init] in my
root view controller. Somewhere in the the customClass implementation
thisArray is set.
Now I have a property in my root view controller NSMutableArray
(strong,nonatomic) *anotherArray and I set it via anotherArray =
customClass.thisArray. If I then set customClass to nil, will anotherArray
still point to an object in memory or is / should it be destroyed? What
about the rest of the object and its properties memory?
Values retrieved using JS localStorage differs in PHP
Values retrieved using JS localStorage differs in PHP
Below is the php code which would take the session variables using JS.The
values retrieved are correct but mysql query returns zero.But if i
hardcode the same values the mysql query is passing.Appreciate your
help.Thanks in advance.Below is the code. test.php
$msessionEmail =
"<script>document.write(localStorage.getItem(\"sessionEmailID\"));</script>";//Retrieves
"hello@test.com"
$msessionPassword =
"<script>document.write(localStorage.getItem(\"sessionPassword\"));</script>";//Retrieves
"test"
$sessionEmail="hello@test.com";
$sessionPassword="test";
echo gettype($msessionEmail);//it is string
echo gettype($sessionEmail);//it is string
echo $msessionEmail;//hello@test.com
echo $sessionEmail;//hello@test.com
if($msessionEmail==$sessionEmail)
{
echo "equal";
}
else
{
echo "not equal";//This gets printed but their values are same.
}
Below is the php code which would take the session variables using JS.The
values retrieved are correct but mysql query returns zero.But if i
hardcode the same values the mysql query is passing.Appreciate your
help.Thanks in advance.Below is the code. test.php
$msessionEmail =
"<script>document.write(localStorage.getItem(\"sessionEmailID\"));</script>";//Retrieves
"hello@test.com"
$msessionPassword =
"<script>document.write(localStorage.getItem(\"sessionPassword\"));</script>";//Retrieves
"test"
$sessionEmail="hello@test.com";
$sessionPassword="test";
echo gettype($msessionEmail);//it is string
echo gettype($sessionEmail);//it is string
echo $msessionEmail;//hello@test.com
echo $sessionEmail;//hello@test.com
if($msessionEmail==$sessionEmail)
{
echo "equal";
}
else
{
echo "not equal";//This gets printed but their values are same.
}
Not saved image when creating content on Drupal 6
Not saved image when creating content on Drupal 6
this problem: In the form of adding material has fields with images.
Choose a file, click download, the file is loaded, the image is displayed.
Others fill in the form and add material. The material is added, it's
fine, but that's only the images are not stored. But after editing, all
the images are stored properly. That is, the problem only by adding
material. I watched the logs of Drupal (admin/reports/dblog), while adding
no error pops up. In what could be the problem? How can I solve it?
Thank you. Sorry for my bad English.
this problem: In the form of adding material has fields with images.
Choose a file, click download, the file is loaded, the image is displayed.
Others fill in the form and add material. The material is added, it's
fine, but that's only the images are not stored. But after editing, all
the images are stored properly. That is, the problem only by adding
material. I watched the logs of Drupal (admin/reports/dblog), while adding
no error pops up. In what could be the problem? How can I solve it?
Thank you. Sorry for my bad English.
Android black box testing tool
Android black box testing tool
I am searching for a tool/software for black box testing of android apps.
I researched for some of them-Robotium, Calabash. But these tools require
access to the source codes. Also the tool should be free and opensource
for use.
I am searching for a tool/software for black box testing of android apps.
I researched for some of them-Robotium, Calabash. But these tools require
access to the source codes. Also the tool should be free and opensource
for use.
Trying to merge a COUNT query in to an existing SELECT query
Trying to merge a COUNT query in to an existing SELECT query
I'm stuck trying to merge a COUNT query in to an existing SELECT query
that I have.
Currently, I use this SELECT statement to fetch some contact info:
SELECT contact.id_contact, contact.cname, contact.cemail,
contact.trading_id, trading_name.trading_name
FROM contact
INNER JOIN trading_name ON contact.trading_id = trading_name.id_trading_name
WHERE (CHAR_LENGTH(contact.cname) > 0)
ORDER BY contact.cname
I also have this COUNT query which I need to somehow include in to the
same SELECT statement:
SELECT COUNT(AlertID) AS CustomerAlertCountTotal FROM
customer_support_dev.customer_alerts WHERE (AlertTradingID = @tradingid)
Basically I need to know how many 'AlertIDs' there are for each
'trading_name', and for that value to be returned in
'CustomerAlertCountTotal' - but by using just one query.
(If it makes a difference, I'm using a MySQL database)
Hope that makes sense :)
I'm stuck trying to merge a COUNT query in to an existing SELECT query
that I have.
Currently, I use this SELECT statement to fetch some contact info:
SELECT contact.id_contact, contact.cname, contact.cemail,
contact.trading_id, trading_name.trading_name
FROM contact
INNER JOIN trading_name ON contact.trading_id = trading_name.id_trading_name
WHERE (CHAR_LENGTH(contact.cname) > 0)
ORDER BY contact.cname
I also have this COUNT query which I need to somehow include in to the
same SELECT statement:
SELECT COUNT(AlertID) AS CustomerAlertCountTotal FROM
customer_support_dev.customer_alerts WHERE (AlertTradingID = @tradingid)
Basically I need to know how many 'AlertIDs' there are for each
'trading_name', and for that value to be returned in
'CustomerAlertCountTotal' - but by using just one query.
(If it makes a difference, I'm using a MySQL database)
Hope that makes sense :)
Tuesday, 10 September 2013
Defining multiple objects based on size of two lists (python)
Defining multiple objects based on size of two lists (python)
I am trying to find a way of creating objects based on the size of two
lists. I have to create an object for each combination of indices of the
two lists, i.e. if both lists is of the length 3, 9 new objects should be
created and defined.
The lists can be of rather large lengths and it would make the script a
lot nicer if I did not have to use an if loop to go through all possible
combinations.
A first I thought I could do the following:
for i in range(len(list1)):
for j in range(len(list2):
Name_of_Object+[i]+[j] = (object definition)
But this is not possible and I get the following error:
SyntaxError: can't assign to operator
But is there a way of creating objects based on indices of a list?
Best, Martin
(I am using the Canopy environment to do my python programming.)
I am trying to find a way of creating objects based on the size of two
lists. I have to create an object for each combination of indices of the
two lists, i.e. if both lists is of the length 3, 9 new objects should be
created and defined.
The lists can be of rather large lengths and it would make the script a
lot nicer if I did not have to use an if loop to go through all possible
combinations.
A first I thought I could do the following:
for i in range(len(list1)):
for j in range(len(list2):
Name_of_Object+[i]+[j] = (object definition)
But this is not possible and I get the following error:
SyntaxError: can't assign to operator
But is there a way of creating objects based on indices of a list?
Best, Martin
(I am using the Canopy environment to do my python programming.)
Does any-one have a list of the permissible content elements for each SVG element?
Does any-one have a list of the permissible content elements for each SVG
element?
I am trying to build a perl hash which describes the permissible content
elements for each SVG element. Does any-one have a perl script that can do
this?
element?
I am trying to build a perl hash which describes the permissible content
elements for each SVG element. Does any-one have a perl script that can do
this?
Knockout Error: Cannot find closing comment tag to match
Knockout Error: Cannot find closing comment tag to match
This may seem like a duplicate question, but none of the other answers
have helped me. I have the following HTML (it's a Razor template, but no
Razor specifics here).
<p class="search-results-summary">
Results
<!-- ko if: SearchTerms.Query -->
for <span data-bind="html: SearchTerms.Query"></span>
<!-- /ko -->
<!-- ko if: SearchTerms.Names -->
for Names <span data-bind="html: SearchTerms.Names.join(', ')"></span>
<!-- /ko -->
<!-- ko if: SearchTerms.Location && AlternativeLocations &&
AlternativeLocations.length -->
within <span data-bind="text: SearchTerms.LocationRadio"></span>
miles of <span data-bind="html: SearchTerms.Location"></span>.
<!-- ko if: AlternativeLocations && AlternativeLocations.length >
1 -->
<a class="more alternative-locations" href="#">more</a>
<ul id="other-location-matches" data-bind="foreach:
AlternativeLocations.slice(1).sort()" style="display: none">
<li>> Did you mean <a data-bind="html: $data, attr: {
href: Edge.API.CurrentSearchResponse.SearchTerms.mutate({
Location: $data }).getUrl() }"></a>?</li>
</ul>
<!-- /ko -->
<!-- /ko -->
<!-- ko if: SearchTerms.Location && (!AlternativeLocations ||
AlternativeLocations.length == 0) -->
<span class="error">We couldn't find '<span data-bind="html:
SearchTerms.Location"></span>' on the map. Your search ran Worldwide.
</span>
<!-- /ko -->
</p>
When I try to bind this template using Knockout, I get this error:
Error: Cannot find closing comment tag to match: ko if:
SearchTerms.Location && AlternativeLocations &&
AlternativeLocations.length
I have tried:
Upgrading Knockout from 2.2.1 to 2.3.0. No use
Verifying HTML/XML structure. It's good!
Removing the <ul id="other-location-matches"...> seems to get rid of the
issue... but I need that <ul>!!
Any ideas? Am I looking at a Knockout.js bug?
This may seem like a duplicate question, but none of the other answers
have helped me. I have the following HTML (it's a Razor template, but no
Razor specifics here).
<p class="search-results-summary">
Results
<!-- ko if: SearchTerms.Query -->
for <span data-bind="html: SearchTerms.Query"></span>
<!-- /ko -->
<!-- ko if: SearchTerms.Names -->
for Names <span data-bind="html: SearchTerms.Names.join(', ')"></span>
<!-- /ko -->
<!-- ko if: SearchTerms.Location && AlternativeLocations &&
AlternativeLocations.length -->
within <span data-bind="text: SearchTerms.LocationRadio"></span>
miles of <span data-bind="html: SearchTerms.Location"></span>.
<!-- ko if: AlternativeLocations && AlternativeLocations.length >
1 -->
<a class="more alternative-locations" href="#">more</a>
<ul id="other-location-matches" data-bind="foreach:
AlternativeLocations.slice(1).sort()" style="display: none">
<li>> Did you mean <a data-bind="html: $data, attr: {
href: Edge.API.CurrentSearchResponse.SearchTerms.mutate({
Location: $data }).getUrl() }"></a>?</li>
</ul>
<!-- /ko -->
<!-- /ko -->
<!-- ko if: SearchTerms.Location && (!AlternativeLocations ||
AlternativeLocations.length == 0) -->
<span class="error">We couldn't find '<span data-bind="html:
SearchTerms.Location"></span>' on the map. Your search ran Worldwide.
</span>
<!-- /ko -->
</p>
When I try to bind this template using Knockout, I get this error:
Error: Cannot find closing comment tag to match: ko if:
SearchTerms.Location && AlternativeLocations &&
AlternativeLocations.length
I have tried:
Upgrading Knockout from 2.2.1 to 2.3.0. No use
Verifying HTML/XML structure. It's good!
Removing the <ul id="other-location-matches"...> seems to get rid of the
issue... but I need that <ul>!!
Any ideas? Am I looking at a Knockout.js bug?
How can others access my localhost folder in LAMPP?
How can others access my localhost folder in LAMPP?
I have up LAMPP server in my local machine. I want other person to access
my localhost and see the content. How can this be done ? Can it be done
using my IP address ?
I have up LAMPP server in my local machine. I want other person to access
my localhost and see the content. How can this be done ? Can it be done
using my IP address ?
ARMAX model forecasting leads to "ValueError: matrices are not aligned" when passing exog values
ARMAX model forecasting leads to "ValueError: matrices are not aligned"
when passing exog values
I'm struggling with forecasting out of sample values with an ARMAX model.
Fitting the model works fine.
armax_mod31 = sm.tsa.ARMA(endog = sales, order = (3,1), exog = media).fit()
armax_mod31.fittedvalues
Forecasting without exogenous values, as far as I have an according model,
works fine as well.
arma_mod31 = sm.tsa.ARMA(sales, (3,1)).fit()
all_arma = arma_mod31.forecast(steps = 14, alpha = 0.05)
forecast_arma = Series(res_arma[0], index = pd.date_range(start =
"2013-08-21", periods = 14))
ci_arma = DataFrame(res_arma[2], columns = ["lower", "upper"])
However as soon as I want to predict out of sample values I run into
problems.
all_armax = armax_mod31.forecast(steps = 14, alpha = 0.05, exog = media_out)
leads to "ValueError: matrices are not aligned".
My first idea was, that the length of *media_out* does not fit. I checked
it several times and tried out to pass other series as exog. Length of
exog is the same as number of steps. I tried out a time series and also
only *media_out.values*.
Checked the documentation:
"exog : array
If the model is an ARMAX, you must provide out of sample
values for the exogenous variables. This should not include
the constant."
As far as I understand this is what I do. Any ideas what I'm doing wrong?
In addition I found this ipython notebook
http://nbviewer.ipython.org/cb6e9b476a41586958b5 while looking for a
solution on the web. On In [53]: you can see a similar error. The author's
comment suggests a general problem with out-of-sample prediction, am I
right?
I'm running python 2.7.3, pandas 0.12.0-1 and statsmodels 0.5.0-1.
when passing exog values
I'm struggling with forecasting out of sample values with an ARMAX model.
Fitting the model works fine.
armax_mod31 = sm.tsa.ARMA(endog = sales, order = (3,1), exog = media).fit()
armax_mod31.fittedvalues
Forecasting without exogenous values, as far as I have an according model,
works fine as well.
arma_mod31 = sm.tsa.ARMA(sales, (3,1)).fit()
all_arma = arma_mod31.forecast(steps = 14, alpha = 0.05)
forecast_arma = Series(res_arma[0], index = pd.date_range(start =
"2013-08-21", periods = 14))
ci_arma = DataFrame(res_arma[2], columns = ["lower", "upper"])
However as soon as I want to predict out of sample values I run into
problems.
all_armax = armax_mod31.forecast(steps = 14, alpha = 0.05, exog = media_out)
leads to "ValueError: matrices are not aligned".
My first idea was, that the length of *media_out* does not fit. I checked
it several times and tried out to pass other series as exog. Length of
exog is the same as number of steps. I tried out a time series and also
only *media_out.values*.
Checked the documentation:
"exog : array
If the model is an ARMAX, you must provide out of sample
values for the exogenous variables. This should not include
the constant."
As far as I understand this is what I do. Any ideas what I'm doing wrong?
In addition I found this ipython notebook
http://nbviewer.ipython.org/cb6e9b476a41586958b5 while looking for a
solution on the web. On In [53]: you can see a similar error. The author's
comment suggests a general problem with out-of-sample prediction, am I
right?
I'm running python 2.7.3, pandas 0.12.0-1 and statsmodels 0.5.0-1.
datatable.integer64 argument is not working for me should it?
datatable.integer64 argument is not working for me should it?
I am trying to load integer64 as character in fread ?fread indicates that
the integer64 argument is not implemented but the
options(datatable.integer64) is. Though fread keeps loading as int64.
How can I tell fread to load as character. If colClasses is the answer, I
think it does not allow to specify a single column name or index and the
table I load has tens of columns so unpracticable...
Here is a sample
#for int 64
library(bit64)
#for fast everything
library(data.table)
#here is a sample
df <- structure(list(IDFD = structure(c(5.13878419797985e-299,
5.13878419797985e-299,
+ 5.13878419797985e-299, 5.13878419797987e-299, 5.13878419797987e-299,
+ 5.13878419797987e-299, 5.13878419797987e-299, 5.13878419797987e-299,
+ 5.13878419797988e-299, 5.13878419797988e-299), class = "integer64")),
.Names = "IDFD", row.names = c(NA,
+ -10L), class = c("data.table", "data.frame"))
#write the sample to file
write.csv(df,"test.csv",quote=F,row.names=F)
#I can't load it as characters
options(datatable.integer64='character')
str(fread("test.csv",integer64='character'))
Classes 'data.table' and 'data.frame': 10 obs. of 1 variable:
$ IDFD:Class 'integer64' num [1:10] 5.14e-299 5.14e-299 5.14e-299
5.14e-299 5.14e-299 ...
I am trying to load integer64 as character in fread ?fread indicates that
the integer64 argument is not implemented but the
options(datatable.integer64) is. Though fread keeps loading as int64.
How can I tell fread to load as character. If colClasses is the answer, I
think it does not allow to specify a single column name or index and the
table I load has tens of columns so unpracticable...
Here is a sample
#for int 64
library(bit64)
#for fast everything
library(data.table)
#here is a sample
df <- structure(list(IDFD = structure(c(5.13878419797985e-299,
5.13878419797985e-299,
+ 5.13878419797985e-299, 5.13878419797987e-299, 5.13878419797987e-299,
+ 5.13878419797987e-299, 5.13878419797987e-299, 5.13878419797987e-299,
+ 5.13878419797988e-299, 5.13878419797988e-299), class = "integer64")),
.Names = "IDFD", row.names = c(NA,
+ -10L), class = c("data.table", "data.frame"))
#write the sample to file
write.csv(df,"test.csv",quote=F,row.names=F)
#I can't load it as characters
options(datatable.integer64='character')
str(fread("test.csv",integer64='character'))
Classes 'data.table' and 'data.frame': 10 obs. of 1 variable:
$ IDFD:Class 'integer64' num [1:10] 5.14e-299 5.14e-299 5.14e-299
5.14e-299 5.14e-299 ...
How to make this method reusable?
How to make this method reusable?
I have copy pasted this method into two classes. I would rather reuse it
from the first class. This is in a windows forms application.
public void defineMapArea()
{
PictureBox pictureBox1 = new PictureBox();
// Dock the PictureBox to the form and set its background to white.
pictureBox1.Dock = DockStyle.Fill;
pictureBox1.BackColor = Color.White;
// Connect the Paint event of the PictureBox to the event handler method.
pictureBox1.Paint += new
System.Windows.Forms.PaintEventHandler(this.pictureBox1_Paint);
// Add the PictureBox control to the Form.
this.Controls.Add(pictureBox1);
}
The only thing that needs to change in the method from one class to
another is the "this" keyword which refers to the class, as hovering over
"this" confirms. I thought maybe "this" will just apply to the class
calling the method, but i think it still refers to the class that the
method is defined in. It would be fantastic to simply pass a class as a
parameter, but i'm thinking that doesn't work as i have attempted that.
Any help appreciated. Thanks!
I have copy pasted this method into two classes. I would rather reuse it
from the first class. This is in a windows forms application.
public void defineMapArea()
{
PictureBox pictureBox1 = new PictureBox();
// Dock the PictureBox to the form and set its background to white.
pictureBox1.Dock = DockStyle.Fill;
pictureBox1.BackColor = Color.White;
// Connect the Paint event of the PictureBox to the event handler method.
pictureBox1.Paint += new
System.Windows.Forms.PaintEventHandler(this.pictureBox1_Paint);
// Add the PictureBox control to the Form.
this.Controls.Add(pictureBox1);
}
The only thing that needs to change in the method from one class to
another is the "this" keyword which refers to the class, as hovering over
"this" confirms. I thought maybe "this" will just apply to the class
calling the method, but i think it still refers to the class that the
method is defined in. It would be fantastic to simply pass a class as a
parameter, but i'm thinking that doesn't work as i have attempted that.
Any help appreciated. Thanks!
Monday, 9 September 2013
Pass Json Object from Play! framework to HighCharts JS
Pass Json Object from Play! framework to HighCharts JS
http://www.playframework.com/documentation/2.1.x/JavaTodoList
Using the above tutorial as a reference, I have created an application
which sends data from the model to view via the Application controller. I
have managed to display the model(Tasks) as a high chart. The code is
here.
public static Result format(){
return ok(views.html.frmt.render("Visualize it",Task.all()));
}
This goes to this view page. http://ideone.com/ycz9ko
Currently, I use scala templating inside the javascript code itself. Refer
to lines 9-14 and lines 20-24.This unelegant style of doing things is not
really optimal.
I want to be able to accomplish the above using Json instead.
public static Result jsonIt(){
List<Task> tasks = Task.all();
return ok(Json.toJson(tasks));
}
My Qns are how to send the JSON objects to a view template. And how to
parse it into a Highcharts format. Is there some standard procedure to do
this ? Or else I have to write my own method to do this ?
I also found this stackoverflow post useful.how to parse json into
highcharts. However, it didnt answer the part about converting from Play
format to Highcharts format.
Thanks in advance
http://www.playframework.com/documentation/2.1.x/JavaTodoList
Using the above tutorial as a reference, I have created an application
which sends data from the model to view via the Application controller. I
have managed to display the model(Tasks) as a high chart. The code is
here.
public static Result format(){
return ok(views.html.frmt.render("Visualize it",Task.all()));
}
This goes to this view page. http://ideone.com/ycz9ko
Currently, I use scala templating inside the javascript code itself. Refer
to lines 9-14 and lines 20-24.This unelegant style of doing things is not
really optimal.
I want to be able to accomplish the above using Json instead.
public static Result jsonIt(){
List<Task> tasks = Task.all();
return ok(Json.toJson(tasks));
}
My Qns are how to send the JSON objects to a view template. And how to
parse it into a Highcharts format. Is there some standard procedure to do
this ? Or else I have to write my own method to do this ?
I also found this stackoverflow post useful.how to parse json into
highcharts. However, it didnt answer the part about converting from Play
format to Highcharts format.
Thanks in advance
What do I do with async Tasks I don't want to wait for?
What do I do with async Tasks I don't want to wait for?
I am writing a multi player game server and am looking at ways the new C#
async/await features can help me. The core of the server is a loop which
updates all the actors in the game as fast as it can:
while (!shutdown)
{
foreach (var actor in actors)
actor.Update();
// Send and receive pending network messages
// Various other system maintenance
}
This loop is required to handle thousands of actors and update multiple
times per second to keep the game running smoothly. Some actors
occasionally perform slow tasks in their update functions, such as
fetching data from a database, which is where I'd like to use async. Once
this data is retrieved the actor wants to update the game state, which
must be done on the main thread.
As this is a console application, I plan to write a SynchronizationContext
which can dispatch pending delegates to the main loop. This allows those
tasks to update the game once they complete and lets unhandled exceptions
be thrown into the main loop. My question is, how do write the async
update functions? This works very nicely, but breaks the recommendations
not to use async void:
Thing foo;
public override void Update()
{
foo.DoThings();
if (someCondition) {
UpdateAsync();
}
}
async void UpdateAsync()
{
// Get data, but let the server continue in the mean time
var newFoo = await GetFooFromDatabase();
// Now back on the main thread, update game state
this.foo = newFoo;
}
I could make Update() async and propogate the tasks back to the main loop,
but:
I don't want to add overhead to the thousands of updates that will never
use it.
Even in the main loop I don't want to await the tasks and block the loop.
Awaiting the task would cause a deadlock anyway as it needs to complete on
the awaiting thread.
What do I do with all these tasks I can't await? The only time I might
want to know they've all finished is when I'm shutting the server down,
but I don't want to collect every task generated by potentially weeks
worth of updates.
I am writing a multi player game server and am looking at ways the new C#
async/await features can help me. The core of the server is a loop which
updates all the actors in the game as fast as it can:
while (!shutdown)
{
foreach (var actor in actors)
actor.Update();
// Send and receive pending network messages
// Various other system maintenance
}
This loop is required to handle thousands of actors and update multiple
times per second to keep the game running smoothly. Some actors
occasionally perform slow tasks in their update functions, such as
fetching data from a database, which is where I'd like to use async. Once
this data is retrieved the actor wants to update the game state, which
must be done on the main thread.
As this is a console application, I plan to write a SynchronizationContext
which can dispatch pending delegates to the main loop. This allows those
tasks to update the game once they complete and lets unhandled exceptions
be thrown into the main loop. My question is, how do write the async
update functions? This works very nicely, but breaks the recommendations
not to use async void:
Thing foo;
public override void Update()
{
foo.DoThings();
if (someCondition) {
UpdateAsync();
}
}
async void UpdateAsync()
{
// Get data, but let the server continue in the mean time
var newFoo = await GetFooFromDatabase();
// Now back on the main thread, update game state
this.foo = newFoo;
}
I could make Update() async and propogate the tasks back to the main loop,
but:
I don't want to add overhead to the thousands of updates that will never
use it.
Even in the main loop I don't want to await the tasks and block the loop.
Awaiting the task would cause a deadlock anyway as it needs to complete on
the awaiting thread.
What do I do with all these tasks I can't await? The only time I might
want to know they've all finished is when I'm shutting the server down,
but I don't want to collect every task generated by potentially weeks
worth of updates.
Use Javascript to change a table cell color if its value is less than another
Use Javascript to change a table cell color if its value is less than another
Cant figure out what I'm doing wrong here:
Just want cell .tt to be red when its numerical values is less than cell dd
HTML:
<table class="colorMe">
<tr><td class="tt">2000</td><td>3500</td></tr>
<tr><td>3000</td><td>2500</td></tr>
<tr><td id="dd">4000</td><td>4500</td></tr>
</table>
JS:
$(".colorMe .tt" ).each(function() {
var val = parseInt(this.innerHTML, 10);
if (val < document.getElementById("dd");) {
this.style.backgroundColor = "#F00000";
}
});
No Idea why this isn't working
Cant figure out what I'm doing wrong here:
Just want cell .tt to be red when its numerical values is less than cell dd
HTML:
<table class="colorMe">
<tr><td class="tt">2000</td><td>3500</td></tr>
<tr><td>3000</td><td>2500</td></tr>
<tr><td id="dd">4000</td><td>4500</td></tr>
</table>
JS:
$(".colorMe .tt" ).each(function() {
var val = parseInt(this.innerHTML, 10);
if (val < document.getElementById("dd");) {
this.style.backgroundColor = "#F00000";
}
});
No Idea why this isn't working
Ruby nested const_missing method_missing stack too deep
Ruby nested const_missing method_missing stack too deep
I have the following class:
module APIWrapper
include HTTParty
BASE_URI = 'https://example.com/Api'
def self.const_missing(const_name)
anon_class = Class.new do
def self.method_missing method_name, *params
params = {
'Target' => const_name.to_s,
'Method' => method_name.to_s,
}
APIWrapper.call_get params
end
end
end
def self.call_get(params)
get(APIWrapper::BASE_URI, {:query => params})
end
def self.call_post(params)
post(APIWrapper::BASE_URI, params)
end
end
I want to be able to make a call to my wrapper like this:
APIWrapper::User::getAll
I'm getting a stack level too deep error:
1) Error:
test_User_getAll(APITest):
SystemStackError: stack level too deep
api_test.rb:16
What am I doing wrong?
I have the following class:
module APIWrapper
include HTTParty
BASE_URI = 'https://example.com/Api'
def self.const_missing(const_name)
anon_class = Class.new do
def self.method_missing method_name, *params
params = {
'Target' => const_name.to_s,
'Method' => method_name.to_s,
}
APIWrapper.call_get params
end
end
end
def self.call_get(params)
get(APIWrapper::BASE_URI, {:query => params})
end
def self.call_post(params)
post(APIWrapper::BASE_URI, params)
end
end
I want to be able to make a call to my wrapper like this:
APIWrapper::User::getAll
I'm getting a stack level too deep error:
1) Error:
test_User_getAll(APITest):
SystemStackError: stack level too deep
api_test.rb:16
What am I doing wrong?
Find nearest neighbor names from KKNN package
Find nearest neighbor names from KKNN package
I have been trying to build this program or find out how to access what
KKNN does to produce its results. I am using the KKNN function and package
to help predict future baseball stats. It takes in 11 predictor variables
(previous 3 year stats, PA and level, along with age and another
predictor). The predictions work great but what I am hoping to do is when
I am predicting only one player (as this would be ridiculous while
predicting 100s of players), I would like to see maybe the 3 closest
neighbors to the player in question and their previous stats with what
they produced the next year. I am most concerned with the name of the
nearest neighbors as knowing which players are closest will give context
to the prediction that it makes.
I am fine with trying to edit the actual code to the function if that is
the only way to get at these. Even finding the indices would be helpful as
I can backsolve from there to get the names. Thank you so much for all of
your help!
Here is some sample code that should help:
name=c("McGwire,Mark","Bonds,Barry","Helton,Todd","Walker,Larry","Pujols,Albert","Pedroia,Dustin")
z
lag1=c(100,90,75,89,95,70)
lag2=c(120,80,95,79,92,90)
Runs=c(65,120,105,99,65,100)
full=cbind(name,lag1,lag2,Runs)
full=data.frame(full)
learn=full
learn
learn$lag1=as.numeric(as.character(learn$lag1))
learn$lag2=as.numeric(as.character(learn$lag2))
learn$Runs=as.numeric(as.character(learn$Runs))
valid=learn[5,]
learn=learn[-5,]
valid
k=kknn(Runs~lag1+lag2,learn,valid,k=2,distance=1)
summary(k)
fit=fitted(k)
fit
I have been trying to build this program or find out how to access what
KKNN does to produce its results. I am using the KKNN function and package
to help predict future baseball stats. It takes in 11 predictor variables
(previous 3 year stats, PA and level, along with age and another
predictor). The predictions work great but what I am hoping to do is when
I am predicting only one player (as this would be ridiculous while
predicting 100s of players), I would like to see maybe the 3 closest
neighbors to the player in question and their previous stats with what
they produced the next year. I am most concerned with the name of the
nearest neighbors as knowing which players are closest will give context
to the prediction that it makes.
I am fine with trying to edit the actual code to the function if that is
the only way to get at these. Even finding the indices would be helpful as
I can backsolve from there to get the names. Thank you so much for all of
your help!
Here is some sample code that should help:
name=c("McGwire,Mark","Bonds,Barry","Helton,Todd","Walker,Larry","Pujols,Albert","Pedroia,Dustin")
z
lag1=c(100,90,75,89,95,70)
lag2=c(120,80,95,79,92,90)
Runs=c(65,120,105,99,65,100)
full=cbind(name,lag1,lag2,Runs)
full=data.frame(full)
learn=full
learn
learn$lag1=as.numeric(as.character(learn$lag1))
learn$lag2=as.numeric(as.character(learn$lag2))
learn$Runs=as.numeric(as.character(learn$Runs))
valid=learn[5,]
learn=learn[-5,]
valid
k=kknn(Runs~lag1+lag2,learn,valid,k=2,distance=1)
summary(k)
fit=fitted(k)
fit
Things to take care of while writing a file downloader
Things to take care of while writing a file downloader
I understand this is a pretty vague question but I just want to somethings
you feel are important to take care of and are usually forgotten. I am
writing a Video down-loader in Java, and all I am doing is making URL
connection , get file headers and download (don't need to support
multi-threading).
so, is there anything I need to take care of in HTTP,HTTPS,FTP or file
sizes or anything a beginner programmer will have o idea of.
I understand this is a pretty vague question but I just want to somethings
you feel are important to take care of and are usually forgotten. I am
writing a Video down-loader in Java, and all I am doing is making URL
connection , get file headers and download (don't need to support
multi-threading).
so, is there anything I need to take care of in HTTP,HTTPS,FTP or file
sizes or anything a beginner programmer will have o idea of.
Preg_match_all repeated group
Preg_match_all repeated group
this is my string:
zzzzzzz-------eh="koko"------eh="zizi"--------eh="mimi"--------xxxxxx
i need a reg-expression to extract koko, zizi and mimi
but eh='zizi' is optional: so if it doesn't exist like in :
zzzzzzz----------eh="koko"-----------------eh="mimi"----------xxxxxx
i should get only koko and mimi.
the '---' are some text.
i tried
preg_match_all('#zzzzzzz(.*eh="([^"]*)"){2,3}.*xxxxxx#Uix', $strg , $out,
PREG_SET_ORDER);
but it doesn't work.
this is my string:
zzzzzzz-------eh="koko"------eh="zizi"--------eh="mimi"--------xxxxxx
i need a reg-expression to extract koko, zizi and mimi
but eh='zizi' is optional: so if it doesn't exist like in :
zzzzzzz----------eh="koko"-----------------eh="mimi"----------xxxxxx
i should get only koko and mimi.
the '---' are some text.
i tried
preg_match_all('#zzzzzzz(.*eh="([^"]*)"){2,3}.*xxxxxx#Uix', $strg , $out,
PREG_SET_ORDER);
but it doesn't work.
Select database used depending on URL
Select database used depending on URL
Is there any way I can have a single codebase connecting to different
databases depending on the URL used for access?
Example:
company1.example.com connects to database db_company1
company2.example.com connects to database db_company2
Is there any way I can have a single codebase connecting to different
databases depending on the URL used for access?
Example:
company1.example.com connects to database db_company1
company2.example.com connects to database db_company2
Altering Url with onclick tag in btn
Altering Url with onclick tag in btn
I used the following in one view in order to navigate to a specific tab on
an Index view...
button type="button" class="btn blue"
onclick="location.href='Index/#rooms'"><i class="m-icon-swapleft
m-icon-white"></i> Back to Room List</button>
The Url reads like.....ReferralTarget/Index/#rooms
rooms being one of the tabs on the Index view..
<li><a href="#rooms" data-toggle="tab">Rooms</a></li>
<div class="tab-pane" id="rooms">
When I use the same code in another view, I get an error 400 - Bad request
and the Url reads like... /ReferralTarget/EditRoom/Index/#rooms
Is there a way of altering the url to remove text, in this case "Edit
room"..??
If it's related back to the controller, the only difference in the two
views is the EditView Get ActionResult uses a (string id), where the
AddView does not....
Thanks
I used the following in one view in order to navigate to a specific tab on
an Index view...
button type="button" class="btn blue"
onclick="location.href='Index/#rooms'"><i class="m-icon-swapleft
m-icon-white"></i> Back to Room List</button>
The Url reads like.....ReferralTarget/Index/#rooms
rooms being one of the tabs on the Index view..
<li><a href="#rooms" data-toggle="tab">Rooms</a></li>
<div class="tab-pane" id="rooms">
When I use the same code in another view, I get an error 400 - Bad request
and the Url reads like... /ReferralTarget/EditRoom/Index/#rooms
Is there a way of altering the url to remove text, in this case "Edit
room"..??
If it's related back to the controller, the only difference in the two
views is the EditView Get ActionResult uses a (string id), where the
AddView does not....
Thanks
301 Redirect *.php to *.html via .htaccess?
301 Redirect *.php to *.html via .htaccess?
Currently I'm rewriting all incoming requests for *.html to *.php in my
.htaccess:
RewriteEngine on
RewriteCond %{HTTP_HOST} ^example\.com$ [NC]
RewriteRule ^(.*)$ http://www.example.com/$1 [R=301,L]
RewriteRule ^(.*).html$ $1.php [QSA]
ErrorDocument 404 /404.html
So /something.html is rewritten to /something.php.
However, /something.php is still directly accessible in the browser. Now I
want it to redirect to /something.html when people are accessing it in the
browser, so as to avoid 2 distinct URLs for the same page of content.
Is this possible to do in my .htaccess? How? I tried R=301 but it's always
a redirect loop or something. Any help would be appreciated. Thanks!
Currently I'm rewriting all incoming requests for *.html to *.php in my
.htaccess:
RewriteEngine on
RewriteCond %{HTTP_HOST} ^example\.com$ [NC]
RewriteRule ^(.*)$ http://www.example.com/$1 [R=301,L]
RewriteRule ^(.*).html$ $1.php [QSA]
ErrorDocument 404 /404.html
So /something.html is rewritten to /something.php.
However, /something.php is still directly accessible in the browser. Now I
want it to redirect to /something.html when people are accessing it in the
browser, so as to avoid 2 distinct URLs for the same page of content.
Is this possible to do in my .htaccess? How? I tried R=301 but it's always
a redirect loop or something. Any help would be appreciated. Thanks!
Sunday, 8 September 2013
Rails + Carrierwave + RMagick : Crop only if image is large
Rails + Carrierwave + RMagick : Crop only if image is large
I am using carrier-wave to upload images. On upload I am creating
thumbnails for the image which is done using Rmagick method,
resize_to_fill like below.
version :thumb do
process :resize_to_fill=> [150, 150]
end
Here is output of all the RMagick methods carrierwave supports (none of
which i want):
1] :resize_to_fill => [150,150
This works fine on larger images but my smaller images are enlarged to 150
x 150.
2] :resize_to_fit => [150,150]
Again it was resized, I want it left alone!
3] :resize_to_limit => [150,150]
This one leaves it as is, but larger images are not cropped. They are
resized to keep the aspect ratio.
Here is the result I want and how my small and larger images should look.
How do this? I want smaller images to be left alone and crop only larger
images to 150 x 150. Is there another method or options I can pass to
resize_to_fill?
Thanks
I am using carrier-wave to upload images. On upload I am creating
thumbnails for the image which is done using Rmagick method,
resize_to_fill like below.
version :thumb do
process :resize_to_fill=> [150, 150]
end
Here is output of all the RMagick methods carrierwave supports (none of
which i want):
1] :resize_to_fill => [150,150
This works fine on larger images but my smaller images are enlarged to 150
x 150.
2] :resize_to_fit => [150,150]
Again it was resized, I want it left alone!
3] :resize_to_limit => [150,150]
This one leaves it as is, but larger images are not cropped. They are
resized to keep the aspect ratio.
Here is the result I want and how my small and larger images should look.
How do this? I want smaller images to be left alone and crop only larger
images to 150 x 150. Is there another method or options I can pass to
resize_to_fill?
Thanks
MySQL shutdown unexpectedly
MySQL shutdown unexpectedly
2013-09-09 10:21:44 5776 [Note] Plugin 'FEDERATED' is disabled.
2013-09-09 10:21:44 1624 InnoDB: Warning: Using
innodb_additional_mem_pool_size is DEPRECATED. This option may be removed
in future releases, together with the option innodb_use_sys_malloc and
with the InnoDB's internal memory allocator.
2013-09-09 10:21:44 5776 [Note] InnoDB: The InnoDB memory heap is disabled
2013-09-09 10:21:44 5776 [Note] InnoDB: Mutexes and rw_locks use Windows
interlocked functions
2013-09-09 10:21:44 5776 [Note] InnoDB: Compressed tables use zlib 1.2.3
2013-09-09 10:21:44 5776 [Note] InnoDB: Not using CPU crc32 instructions
2013-09-09 10:21:44 5776 [Note] InnoDB: Initializing buffer pool, size =
16.0M
2013-09-09 10:21:44 5776 [Note] InnoDB: Completed initialization of buffer
pool
2013-09-09 10:21:44 5776 [Note] InnoDB: Highest supported file format is
Barracuda.
2013-09-09 10:21:44 5776 [Note] InnoDB: The log sequence numbers 0 and 0
in ibdata files do not match the log sequence number 19862295 in the
ib_logfiles!
2013-09-09 10:21:44 5776 [Note] InnoDB: Database was not shutdown normally!
2013-09-09 10:21:44 5776 [Note] InnoDB: Starting crash recovery.
2013-09-09 10:21:44 5776 [Note] InnoDB: Reading tablespace information
from the .ibd files...
2013-09-09 10:21:44 5776 [ERROR] InnoDB: Attempted to open a previously
opened tablespace. Previous tablespace casualme/scraped_user uses space
ID: 2 at filepath: .\casualme\scraped_user.ibd. Cannot open tablespace
mysql/innodb_index_stats which uses space ID: 2 at filepath:
.\mysql\innodb_index_stats.ibd
InnoDB: Error: could not open single-table tablespace file
.\mysql\innodb_index_stats.ibd
InnoDB: We do not continue the crash recovery, because the table may become
InnoDB: corrupt if we cannot apply the log records in the InnoDB log to it.
InnoDB: To fix the problem and start mysqld:
InnoDB: 1) If there is a permission problem in the file and mysqld cannot
InnoDB: open the file, you should modify the permissions.
InnoDB: 2) If the table is not needed, or you can restore it from a backup,
InnoDB: then you can remove the .ibd file, and InnoDB will do a normal
InnoDB: crash recovery and ignore that table.
InnoDB: 3) If the file system or the disk is broken, and you cannot remove
InnoDB: the .ibd file, you can set innodb_force_recovery > 0 in my.cnf
InnoDB: and force InnoDB to continue crash recovery here.
Hello guys.I need your help. my phpmyadmin is not working. How can i make
it working again, i have a very large data, please help me how to fix
this. i just want to get my database
2013-09-09 10:21:44 5776 [Note] Plugin 'FEDERATED' is disabled.
2013-09-09 10:21:44 1624 InnoDB: Warning: Using
innodb_additional_mem_pool_size is DEPRECATED. This option may be removed
in future releases, together with the option innodb_use_sys_malloc and
with the InnoDB's internal memory allocator.
2013-09-09 10:21:44 5776 [Note] InnoDB: The InnoDB memory heap is disabled
2013-09-09 10:21:44 5776 [Note] InnoDB: Mutexes and rw_locks use Windows
interlocked functions
2013-09-09 10:21:44 5776 [Note] InnoDB: Compressed tables use zlib 1.2.3
2013-09-09 10:21:44 5776 [Note] InnoDB: Not using CPU crc32 instructions
2013-09-09 10:21:44 5776 [Note] InnoDB: Initializing buffer pool, size =
16.0M
2013-09-09 10:21:44 5776 [Note] InnoDB: Completed initialization of buffer
pool
2013-09-09 10:21:44 5776 [Note] InnoDB: Highest supported file format is
Barracuda.
2013-09-09 10:21:44 5776 [Note] InnoDB: The log sequence numbers 0 and 0
in ibdata files do not match the log sequence number 19862295 in the
ib_logfiles!
2013-09-09 10:21:44 5776 [Note] InnoDB: Database was not shutdown normally!
2013-09-09 10:21:44 5776 [Note] InnoDB: Starting crash recovery.
2013-09-09 10:21:44 5776 [Note] InnoDB: Reading tablespace information
from the .ibd files...
2013-09-09 10:21:44 5776 [ERROR] InnoDB: Attempted to open a previously
opened tablespace. Previous tablespace casualme/scraped_user uses space
ID: 2 at filepath: .\casualme\scraped_user.ibd. Cannot open tablespace
mysql/innodb_index_stats which uses space ID: 2 at filepath:
.\mysql\innodb_index_stats.ibd
InnoDB: Error: could not open single-table tablespace file
.\mysql\innodb_index_stats.ibd
InnoDB: We do not continue the crash recovery, because the table may become
InnoDB: corrupt if we cannot apply the log records in the InnoDB log to it.
InnoDB: To fix the problem and start mysqld:
InnoDB: 1) If there is a permission problem in the file and mysqld cannot
InnoDB: open the file, you should modify the permissions.
InnoDB: 2) If the table is not needed, or you can restore it from a backup,
InnoDB: then you can remove the .ibd file, and InnoDB will do a normal
InnoDB: crash recovery and ignore that table.
InnoDB: 3) If the file system or the disk is broken, and you cannot remove
InnoDB: the .ibd file, you can set innodb_force_recovery > 0 in my.cnf
InnoDB: and force InnoDB to continue crash recovery here.
Hello guys.I need your help. my phpmyadmin is not working. How can i make
it working again, i have a very large data, please help me how to fix
this. i just want to get my database
Subscribe to:
Posts (Atom)