Update to the database error when enter more than 1 value
i have a problem, the program just read the first entered Quantity value
in the program and apply it to all rows in database and the value of first
and second row are same, even though in the beginning, first and second
row value are different.
Note: The Database 1 until 1.3 and Program 1 until 1.2 are working
properly, i just want to show you to not confuse you later. My problem is
on Database 1.5 and Program 1.4 , Database 1.6 are just wanted to show
you, the Database supposed to be like that.
First of all, my database is like this:
Product Code || Quantity (Database 1)
0001 100
0002 150
And when i run the program and entered the first "Product Code" in first
row and want to change the first Quantity value to 25, so i just enter 75
in Quantity in the program at the first row like this:
Product Code || Quantity (Program 1, 0001 is at the **first row**)
0001 75
And when i click update, the database changed to this (it works fine):
Product Code || Quantity (Database 1.1)
0001 25
0002 150
When i change the first "Product Code" in first row to second "Product
Code" in first row and want to change the second Quantity value to 100, so
i just enter 50 in Quantity in the program in the first row like this:
Product Code || Quantity (Program 1.2, 0002 still at the **first row**)
0002 50
And when i click update, the database changed to this (it works fine):
Product Code || Quantity (Database 1.3)
0001 25
0002 100
But, when i enter the first "Product Code" in first row and second
"Product code in second row in my program like this:
Product Code || Quantity (Program 1.4, 0001 at **first row** and 0002 at
**second row**)
0001 10
0002 25
And when i click update, the database changed to this (it supposed to be
like Database below):
Product Code || Quantity (Database 1.6)
0001 15
0002 85
But instead of the Database above, it changed to this (it is not working
like i want):
Product Code || Quantity (Database 1.5)
0001 15
0002 15
So, it is like the second row at the database are being ignored and
changed to the same value like in the first row, when i enter both value
at the same time in the program.
Here is the code:
private void UpdateQuantity()
{
int codeValue = 0;
int index = 0;
List<int> integers = new List<int>();
foreach (var tb in textBoxCodeContainer)
{
if (int.TryParse(tb.Text, out codeValue))
{
integers.Add(codeValue);
}
}
using (OleDbConnection conn = new
OleDbConnection(connectionString))
{
conn.Open();
string commandSelect = "SELECT [Quantity], [Description],
[Price] FROM [Seranne] WHERE [Code] = @Code";
string commandUpdate = "UPDATE [Seranne] SET [Quantity] =
@Quantity WHERE [Code] IN(" + string.Join(", ", integers)
+ ")";
using (OleDbCommand cmdSelect = new
OleDbCommand(commandSelect, conn))
using (OleDbCommand cmdUpdate = new
OleDbCommand(commandUpdate, conn))
{
cmdSelect.Parameters.Add("Code",
System.Data.OleDb.OleDbType.Integer);
cmdSelect.Parameters["Code"].Value =
this.textBoxCodeContainer[index].Text;
cmdUpdate.Parameters.Add("Quantity",
System.Data.OleDb.OleDbType.Integer);
using (OleDbDataReader dReader =
cmdSelect.ExecuteReader())
{
while (dReader.Read())
{
if (textBoxQuantityContainer[index].Value != 0)
{
newVal =
Convert.ToInt32(dReader["Quantity"].ToString())
- textBoxQuantityContainer[index].Value;
cmdUpdate.Parameters["Quantity"].Value =
newVal;
int numberOfRows =
cmdUpdate.ExecuteNonQuery();
}
index += 1;
}
dReader.Close();
}
}
conn.Close();
}
}
Could you guys please help me? Thanks.
Saturday, 31 August 2013
toISOString() return wrong date
toISOString() return wrong date
Hy this piece of code return the tomorrow date ?
http://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_toisostring
<!DOCTYPE html>
<html>
<body>
<p id="demo">Click the button to display the date and time as a string,
using the ISO standard.</p>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction()
{
var d = new Date();
var x = document.getElementById("demo");
x.innerHTML=d.toISOString();
}
</script>
</body>
</html>
Hy this piece of code return the tomorrow date ?
http://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_toisostring
<!DOCTYPE html>
<html>
<body>
<p id="demo">Click the button to display the date and time as a string,
using the ISO standard.</p>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction()
{
var d = new Date();
var x = document.getElementById("demo");
x.innerHTML=d.toISOString();
}
</script>
</body>
</html>
JavaScript->CSS: display="";?
JavaScript->CSS: display="";?
In JavaScript, one can set the default display of an element by using the
following code outline:
whateverElement.style.display="";
If whateverElement's display was "none" when this code was run, it will
now be whatever it would be naturally, according to the browser's default
rendering.
If whateverElement was a DIV with no previous matched CSS rules that
define its display, when it's JavaScript display property is set to ""
(blank), its display would be defaulted to its natural, which is "block".
My problem is that I wish to use CSS3 animations by assigning a class to
them through JavaScript, some animations that make it necessary to know
the natural display of the element.
In Google Chrome Canary, I'm noticing that the display property "auto" is
non-existent.
Is there another way in which I can create CSS3 animations where I set the
display property to the "default" or "auto" display of an element?
Some examples...
div{display:inline;} //all divs to be displayed "inline"
div#specific{display:auto;} //#specific to be displayed BLOCK,
disregarding the previous CSS rule.
In JavaScript, one can set the default display of an element by using the
following code outline:
whateverElement.style.display="";
If whateverElement's display was "none" when this code was run, it will
now be whatever it would be naturally, according to the browser's default
rendering.
If whateverElement was a DIV with no previous matched CSS rules that
define its display, when it's JavaScript display property is set to ""
(blank), its display would be defaulted to its natural, which is "block".
My problem is that I wish to use CSS3 animations by assigning a class to
them through JavaScript, some animations that make it necessary to know
the natural display of the element.
In Google Chrome Canary, I'm noticing that the display property "auto" is
non-existent.
Is there another way in which I can create CSS3 animations where I set the
display property to the "default" or "auto" display of an element?
Some examples...
div{display:inline;} //all divs to be displayed "inline"
div#specific{display:auto;} //#specific to be displayed BLOCK,
disregarding the previous CSS rule.
php node into multidimentional array
php node into multidimentional array
This is a script i got so far.
<?php
$xml=
simplexml_load_file("http://meteo.arso.gov.si/uploads/probase/www/observ/surface/text/sl/observationAms_si_latest.xml");
// print_r($xml);
$meteos = $xml->metData;
$spot = array();
foreach ($meteos as $meteo) {
$spot[] = "$meteo->domain_title, $meteo->tsValid_issued, $meteo->t,
$meteo->dd_icon, $meteo->ff_val, $meteo->ffmax_val, $meteo->msl,
$meteo->rr_val, $meteo->rr_val";
}
print_r($spot);
?>
What i get with this is something like:
Array
(
[0] => BILJE NOVA GORICA, 31.08.2013 21:00 CEST, 19.2, E, 1.5, 1.8,
1019, 0, 0
[1] => BOHINJSKA CESNJICA, 31.08.2013 21:00 CEST, 14.4, , , , , ,
[2] => BORST GORENJA VAS, 31.08.2013 21:00 CEST, 15.3, SW, 0.4, 1.3,
1020, 0, 0
what I would like to get is
Array
(
[0] => BILJE NOVA GORICA
[0] => 31.08.2013 21:00 CEST
[1] =>19.2
[2] =>E
[3] =>1.5
[4] =>1.8
[5] =>1019
How do i do that ? Also I would like to find an array that contains
"ILIRSKA BISTRICA" so i can write it to database.
Thx.
This is a script i got so far.
<?php
$xml=
simplexml_load_file("http://meteo.arso.gov.si/uploads/probase/www/observ/surface/text/sl/observationAms_si_latest.xml");
// print_r($xml);
$meteos = $xml->metData;
$spot = array();
foreach ($meteos as $meteo) {
$spot[] = "$meteo->domain_title, $meteo->tsValid_issued, $meteo->t,
$meteo->dd_icon, $meteo->ff_val, $meteo->ffmax_val, $meteo->msl,
$meteo->rr_val, $meteo->rr_val";
}
print_r($spot);
?>
What i get with this is something like:
Array
(
[0] => BILJE NOVA GORICA, 31.08.2013 21:00 CEST, 19.2, E, 1.5, 1.8,
1019, 0, 0
[1] => BOHINJSKA CESNJICA, 31.08.2013 21:00 CEST, 14.4, , , , , ,
[2] => BORST GORENJA VAS, 31.08.2013 21:00 CEST, 15.3, SW, 0.4, 1.3,
1020, 0, 0
what I would like to get is
Array
(
[0] => BILJE NOVA GORICA
[0] => 31.08.2013 21:00 CEST
[1] =>19.2
[2] =>E
[3] =>1.5
[4] =>1.8
[5] =>1019
How do i do that ? Also I would like to find an array that contains
"ILIRSKA BISTRICA" so i can write it to database.
Thx.
Char pointer in c works unexpectedly
Char pointer in c works unexpectedly
main() { char *p = "ayqm"; char c; c = ++*p++; printf("%c",c); } I thought
it should print c but it prints b.Please explain.
Thanks.
main() { char *p = "ayqm"; char c; c = ++*p++; printf("%c",c); } I thought
it should print c but it prints b.Please explain.
Thanks.
How to set max composite size in SWT
How to set max composite size in SWT
Is there any way to set maximal size of composite? Only what i have found
methods
setMinimumSize(Point point)
setSize(Point point)
which allow me to set minimal and prefered size.
Is there any way to set maximal size of composite? Only what i have found
methods
setMinimumSize(Point point)
setSize(Point point)
which allow me to set minimal and prefered size.
How to extract a particular string from a String variable
How to extract a particular string from a String variable
I am getting a string which contains the name of the file along woth
extension for ex as shown below..
String s = abcdf.dat ;// Now as shown file abcde having a .dat extension
Now i want to store the file name only in another string but not the
extension so I want to store in this format such as ..
String p= abcdf ; //only file name please advise how to achieve this
I am getting a string which contains the name of the file along woth
extension for ex as shown below..
String s = abcdf.dat ;// Now as shown file abcde having a .dat extension
Now i want to store the file name only in another string but not the
extension so I want to store in this format such as ..
String p= abcdf ; //only file name please advise how to achieve this
Friday, 30 August 2013
Mongoose connect method fails on simple Node Server. Express, Mongoose, Path
Mongoose connect method fails on simple Node Server. Express, Mongoose, Path
This is the first time I'm running node with mongoose. I'm following some
tutorials in this backbone book and I'm up to this chapter on creating a
restful api using express, mongoose and I'm following the code exactly
I've even come to copying and pasting but it's still not working. Here is
the code:
http://addyosmani.github.io/backbone-fundamentals/#creating-the-back-end
// Module dependencies.
var application_root = __dirname,
express = require( 'express' ), //Web framework
path = require( 'path' ), //Utilities for dealing with file paths
mongoose = require( 'mongoose' ); //MongoDB integration
//Create server
var app = express();
// Configure server
app.configure( function() {
//parses request body and populates request.body
app.use( express.bodyParser() );
//checks request.body for HTTP method overrides
app.use( express.methodOverride() );
//perform route lookup based on url and HTTP method
app.use( app.router );
//Where to serve static content
app.use( express.static( path.join( application_root, 'site') ) );
//Show all errors in development
app.use( express.errorHandler({ dumpExceptions: true, showStack: true
}));
});
//Start server
var port = 4711;
app.listen( port, function() {
console.log( 'Express server listening on port %d in %s mode', port,
app.settings.env );
});
// Routes
app.get( '/api', function( request, response ) {
response.send( 'Library API is running' );
});
//Connect to database
mongoose.connect( 'mongodb://localhost/library_database');
//Schemas
var Book = new mongoose.Schema({
title: String,
author: String,
releaseDate: Date
});
//Models
var BookModel = mongoose.model( 'Book', Book );
I've been poking around on stack overflow and other sites trying to
resolve the issue but nothing I found seemed to allow me to connect to the
mongodb.
The first error is:
events.js:72
throw er; // Unhandled 'error' event
^
Error: failed to connect to [localhost:27017]
at null.<anonymous>
(/Users/jeff/Sites/backbone-ex2/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/server.js:536:74)
at EventEmitter.emit (events.js:106:17)
at null.<anonymous>
(/Users/jeff/Sites/backbone-ex2/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/connection_pool.js:140:15)
at EventEmitter.emit (events.js:98:17)
at Socket.<anonymous>
(/Users/jeff/Sites/backbone-ex2/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/connection.js:478:10)
at Socket.EventEmitter.emit (events.js:95:17)
at net.js:411:14
at process._tickCallback (node.js:415:13)
This change seems to fix that issue:
mongoose.connect( 'mongodb://localhost/library_database',
function(err) { if (err) console.log(err); } );
After that express works but mongodb fails to connect:
Express server listening on port 4711 in development mode
[Error: failed to connect to [localhost:27017]]
I tried changing to this:
mongoose = require( 'mongoose' ).Mongoose;
I also tried running mongod in the cli with some variations on options in
the cli but that seems to just bring up the help page. I'm totally
stuck... Any help would be greatly appreciated. Thanks in advance.
This is the first time I'm running node with mongoose. I'm following some
tutorials in this backbone book and I'm up to this chapter on creating a
restful api using express, mongoose and I'm following the code exactly
I've even come to copying and pasting but it's still not working. Here is
the code:
http://addyosmani.github.io/backbone-fundamentals/#creating-the-back-end
// Module dependencies.
var application_root = __dirname,
express = require( 'express' ), //Web framework
path = require( 'path' ), //Utilities for dealing with file paths
mongoose = require( 'mongoose' ); //MongoDB integration
//Create server
var app = express();
// Configure server
app.configure( function() {
//parses request body and populates request.body
app.use( express.bodyParser() );
//checks request.body for HTTP method overrides
app.use( express.methodOverride() );
//perform route lookup based on url and HTTP method
app.use( app.router );
//Where to serve static content
app.use( express.static( path.join( application_root, 'site') ) );
//Show all errors in development
app.use( express.errorHandler({ dumpExceptions: true, showStack: true
}));
});
//Start server
var port = 4711;
app.listen( port, function() {
console.log( 'Express server listening on port %d in %s mode', port,
app.settings.env );
});
// Routes
app.get( '/api', function( request, response ) {
response.send( 'Library API is running' );
});
//Connect to database
mongoose.connect( 'mongodb://localhost/library_database');
//Schemas
var Book = new mongoose.Schema({
title: String,
author: String,
releaseDate: Date
});
//Models
var BookModel = mongoose.model( 'Book', Book );
I've been poking around on stack overflow and other sites trying to
resolve the issue but nothing I found seemed to allow me to connect to the
mongodb.
The first error is:
events.js:72
throw er; // Unhandled 'error' event
^
Error: failed to connect to [localhost:27017]
at null.<anonymous>
(/Users/jeff/Sites/backbone-ex2/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/server.js:536:74)
at EventEmitter.emit (events.js:106:17)
at null.<anonymous>
(/Users/jeff/Sites/backbone-ex2/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/connection_pool.js:140:15)
at EventEmitter.emit (events.js:98:17)
at Socket.<anonymous>
(/Users/jeff/Sites/backbone-ex2/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/connection.js:478:10)
at Socket.EventEmitter.emit (events.js:95:17)
at net.js:411:14
at process._tickCallback (node.js:415:13)
This change seems to fix that issue:
mongoose.connect( 'mongodb://localhost/library_database',
function(err) { if (err) console.log(err); } );
After that express works but mongodb fails to connect:
Express server listening on port 4711 in development mode
[Error: failed to connect to [localhost:27017]]
I tried changing to this:
mongoose = require( 'mongoose' ).Mongoose;
I also tried running mongod in the cli with some variations on options in
the cli but that seems to just bring up the help page. I'm totally
stuck... Any help would be greatly appreciated. Thanks in advance.
Thursday, 29 August 2013
Hide/Show CKEditor buttons on an onclick event
Hide/Show CKEditor buttons on an onclick event
I am developing a simple tool for sending emails.
I am using CKEditor for my textarea formatting.
I want a scenario, whereby by default whereby the formatting buttons do
not show till the user clicks on "Show Formatting buttons"
How can I achieve this with CKEditor without using two textareas.
I am developing a simple tool for sending emails.
I am using CKEditor for my textarea formatting.
I want a scenario, whereby by default whereby the formatting buttons do
not show till the user clicks on "Show Formatting buttons"
How can I achieve this with CKEditor without using two textareas.
How to pass a reference of a hash and array to subroutine
How to pass a reference of a hash and array to subroutine
I am trying to pass a hash reference and array reference to subroutine but
getting error like invalid class string:
sub test{
if($chk == 2)
{
return(\%hash,\@array);
}
}
my ($has, $arr)= test();
Now again i have to pass by reference to "$has, $arr" to a another
subroutine.
How to do this? i was passing them like \%$has, \@$arr but it seems this
is not the currect way to pass to a subroutine.
I am trying to pass a hash reference and array reference to subroutine but
getting error like invalid class string:
sub test{
if($chk == 2)
{
return(\%hash,\@array);
}
}
my ($has, $arr)= test();
Now again i have to pass by reference to "$has, $arr" to a another
subroutine.
How to do this? i was passing them like \%$has, \@$arr but it seems this
is not the currect way to pass to a subroutine.
Wednesday, 28 August 2013
Unique representations of Python objects
Unique representations of Python objects
Let C be a Python class and assume that the constructor of C takes an
integer as argument.
Consider now the instructions
x = C(0)
y = C(0)
The default behavior of Python implies that x and y occupy two different
place in the memory.
It is possible to force x and y to share the same place in memory ?
I would be very happy if some Python decorator makes the job.
Let C be a Python class and assume that the constructor of C takes an
integer as argument.
Consider now the instructions
x = C(0)
y = C(0)
The default behavior of Python implies that x and y occupy two different
place in the memory.
It is possible to force x and y to share the same place in memory ?
I would be very happy if some Python decorator makes the job.
Debugging injected JavaScript with Firebug
Debugging injected JavaScript with Firebug
Is there a way to debug (set breakpoints, follow code step-by-step etc.)
JavaScript code that was dynamically added via AJAX? I can't find it,
seems like it only allows to review inline JS (main page source) and in
external .js files.
Is there a way to debug (set breakpoints, follow code step-by-step etc.)
JavaScript code that was dynamically added via AJAX? I can't find it,
seems like it only allows to review inline JS (main page source) and in
external .js files.
Phonegap builder - is there any Hybrid Facebook connect solution out there based on JS only?
Phonegap builder - is there any Hybrid Facebook connect solution out there
based on JS only?
Im currently developing a simple pure CSS, HTML, JS solution - consisting
of one .html file with a couple of .js files included.
Im building / compiling this into a Android/iOS app through the very smart
Phonegap builder located at: https://build.phonegap.com
What im looking to do is to integrate Facebook connect in my application
and use it as an easy way to create a user.
I've done this before with the Facebook Javascript SDK on a website
project - however I figure if I want to keep the Facebook Connect process
within the Android/iOS app, then this would require some native coding?
Is there anything like a hybrid Facebook connect solution (?) out there
that would enable one to code using the normal Javascript SDK, and then on
native, it would have a native fallback?
It seems to me that should be possible with:?
https://github.com/phonegap-build/FacebookConnect/blob/master/README.md
However by the looks of it, this "jumps" out of the box on only dealing
with your plain simple .js files?
For the note: I have no experience with native coding -Xcode, Eclipse etc
- so trying to avoid this - but not sure if that will be possible.
Any suggestions are welcome - thanks! :)
based on JS only?
Im currently developing a simple pure CSS, HTML, JS solution - consisting
of one .html file with a couple of .js files included.
Im building / compiling this into a Android/iOS app through the very smart
Phonegap builder located at: https://build.phonegap.com
What im looking to do is to integrate Facebook connect in my application
and use it as an easy way to create a user.
I've done this before with the Facebook Javascript SDK on a website
project - however I figure if I want to keep the Facebook Connect process
within the Android/iOS app, then this would require some native coding?
Is there anything like a hybrid Facebook connect solution (?) out there
that would enable one to code using the normal Javascript SDK, and then on
native, it would have a native fallback?
It seems to me that should be possible with:?
https://github.com/phonegap-build/FacebookConnect/blob/master/README.md
However by the looks of it, this "jumps" out of the box on only dealing
with your plain simple .js files?
For the note: I have no experience with native coding -Xcode, Eclipse etc
- so trying to avoid this - but not sure if that will be possible.
Any suggestions are welcome - thanks! :)
js wont show result of calculation
js wont show result of calculation
Quick newbie question, i'm sure it is simple to you, but i cant get my
head around to figure out why my code wont work. Checked online, seems
that i'm doing everything fine, but still wont work... All i'm trying to
do, is to make simple calc and display that in diff field. I have tryed
external and internal JS. Here's my code:
<script type="text/javascript">
function calculate(){
var a = document.calculate.first.value;
var b = document.calculate.second.value;
var c = parseInt(a) + parseInt(b);
document.calculate.result.value = c;
}
</script>
<body>
<form name="calculate">
<input type="text" name="first" size="5">
<input type="text" name="second" size="5">
<input type="button" onclick="calculate()">
<input type="text" name="result" id="result" size="5">
</form>
</body>
Quick newbie question, i'm sure it is simple to you, but i cant get my
head around to figure out why my code wont work. Checked online, seems
that i'm doing everything fine, but still wont work... All i'm trying to
do, is to make simple calc and display that in diff field. I have tryed
external and internal JS. Here's my code:
<script type="text/javascript">
function calculate(){
var a = document.calculate.first.value;
var b = document.calculate.second.value;
var c = parseInt(a) + parseInt(b);
document.calculate.result.value = c;
}
</script>
<body>
<form name="calculate">
<input type="text" name="first" size="5">
<input type="text" name="second" size="5">
<input type="button" onclick="calculate()">
<input type="text" name="result" id="result" size="5">
</form>
</body>
Tuesday, 27 August 2013
Exclude project output from code analyses at build time
Exclude project output from code analyses at build time
Using msbuild on the tfs server, is there a way to exclude output of some
projects from code analyses?
One option is to set the code analyses option for each project and to set
the build definition as "as configured". But I would prefer to enable the
code analyses for all projects by default and exclude some (the c++ ones).
This way one cannot forget to set properties for a new project.
Using msbuild on the tfs server, is there a way to exclude output of some
projects from code analyses?
One option is to set the code analyses option for each project and to set
the build definition as "as configured". But I would prefer to enable the
code analyses for all projects by default and exclude some (the c++ ones).
This way one cannot forget to set properties for a new project.
Php MySql sort custom order by hours
Php MySql sort custom order by hours
I have a mysql table with 3 columns "Event" in text format, "Date" in
format YYYY-MM-DD and "Hour" in format HH:MM. For example:
Event1 2013-08-20 18:30
Event2 2013-08-20 19:30
Event3 2013-08-20 20:00
Event4 2013-08-20 00:00
Event5 2013-08-20 02:30
Event6 2013-08-20 14:50
Event7 2013-08-20 00:30
The database contains various days and various hours into a day. I have to
order all the events first in days and later in hours, but the order of
hours have to be like this example:
Event6 2013-08-20 14:50
Event1 2013-08-20 18:30
Event2 2013-08-20 19:30
Event3 2013-08-20 20:00
Event4 2013-08-20 00:00
Event7 2013-08-20 00:30
Event5 2013-08-20 02:30
The hours 00:00, 01:00, 02:00... are normally at the beginning, but I need
to change the order. The hours 00:00, 01:00, 02:00... should appear at the
end, like you can see in the last example.
My sentence is:
SELECT * FROM Events ORDER BY Date, Hour
But this sentence is not the appropiate for me because it get me back this
values:
Event4 2013-08-20 00:00
Event7 2013-08-20 00:30
Event5 2013-08-20 02:30
Event6 2013-08-20 14:50
Event1 2013-08-20 18:30
Event2 2013-08-20 19:30
Event3 2013-08-20 20:00
Which sentence in MySql or PHP need I to show the results like I want?
Thanks for all ;)
I have a mysql table with 3 columns "Event" in text format, "Date" in
format YYYY-MM-DD and "Hour" in format HH:MM. For example:
Event1 2013-08-20 18:30
Event2 2013-08-20 19:30
Event3 2013-08-20 20:00
Event4 2013-08-20 00:00
Event5 2013-08-20 02:30
Event6 2013-08-20 14:50
Event7 2013-08-20 00:30
The database contains various days and various hours into a day. I have to
order all the events first in days and later in hours, but the order of
hours have to be like this example:
Event6 2013-08-20 14:50
Event1 2013-08-20 18:30
Event2 2013-08-20 19:30
Event3 2013-08-20 20:00
Event4 2013-08-20 00:00
Event7 2013-08-20 00:30
Event5 2013-08-20 02:30
The hours 00:00, 01:00, 02:00... are normally at the beginning, but I need
to change the order. The hours 00:00, 01:00, 02:00... should appear at the
end, like you can see in the last example.
My sentence is:
SELECT * FROM Events ORDER BY Date, Hour
But this sentence is not the appropiate for me because it get me back this
values:
Event4 2013-08-20 00:00
Event7 2013-08-20 00:30
Event5 2013-08-20 02:30
Event6 2013-08-20 14:50
Event1 2013-08-20 18:30
Event2 2013-08-20 19:30
Event3 2013-08-20 20:00
Which sentence in MySql or PHP need I to show the results like I want?
Thanks for all ;)
Image rendered correct link, but cannot load the image
Image rendered correct link, but cannot load the image
I have uploaded a picture to the directory ~\Files\image\C3-E1-B6-74.png,
i saved this in the database. Now I'm trying to display this image.
cshtlm
<img src="@Url.Content(file.FileLink)" alt="test" />
When this page is rendered and I check the image tag
<img alt="test"
src="C:\Users\thomas\Desktop\Freelauncher1005\Freelauncher\Files\image\C3-E1-B6-74.png">
So link is rendered correctly. When I copy this link and paste it in my
folderbrowser then it opens the corresponding image.
When searching for this problem I found
Images under "image/subfolder" cannot be found in the latest Razor Engine
- MVC.NET
I checked the extension and everything is correct.
Does anyone has another possible solution?
Thanks in advance
I have uploaded a picture to the directory ~\Files\image\C3-E1-B6-74.png,
i saved this in the database. Now I'm trying to display this image.
cshtlm
<img src="@Url.Content(file.FileLink)" alt="test" />
When this page is rendered and I check the image tag
<img alt="test"
src="C:\Users\thomas\Desktop\Freelauncher1005\Freelauncher\Files\image\C3-E1-B6-74.png">
So link is rendered correctly. When I copy this link and paste it in my
folderbrowser then it opens the corresponding image.
When searching for this problem I found
Images under "image/subfolder" cannot be found in the latest Razor Engine
- MVC.NET
I checked the extension and everything is correct.
Does anyone has another possible solution?
Thanks in advance
Why Invalid HTML stored in a nvarchar(MAX) makes a select slow?
Why Invalid HTML stored in a nvarchar(MAX) makes a select slow?
I have a nvarchar(max), null column in a table storing HTML. If the HTML
is invalid, simple select takes 2-3 seconds.
Any ideas why?
UPDATE
select ResearchAdvice FROM Subsection where id = 97227
Broken HTML
<P>Possible new Us: <STRONG>Sung Won Park</STRONG> (Choi & Kim),
<STRONG>HC Lee</STRONG> at Kim & Chang. Names came up a little late in
the day, not enough to inclu
I have a nvarchar(max), null column in a table storing HTML. If the HTML
is invalid, simple select takes 2-3 seconds.
Any ideas why?
UPDATE
select ResearchAdvice FROM Subsection where id = 97227
Broken HTML
<P>Possible new Us: <STRONG>Sung Won Park</STRONG> (Choi & Kim),
<STRONG>HC Lee</STRONG> at Kim & Chang. Names came up a little late in
the day, not enough to inclu
Standard for hyperlink appearance, based on type?
Standard for hyperlink appearance, based on type?
This is my first question here, so please be gentle...
It seems that a user often has to make a decision about whether to
directly click on a hyperlink, or do a ctrl-click (click to open in new
window or tab), and that he/she would benefit by knowing some things about
the link before clicking. Specifically:
is this link to an anchor on the same page, or to a different page?
Is this link already set to open a new window/tab (target="_blank") with a
normal click?
Is this link to a script, so that ctrl-click will do nothing but produce a
blank window/tab?
I suppose there are some other choices as well (I won't touch on frames
here), but the point is that users are often up in the air about whether
they want to click or ctrl-click a link. Has there ever been talk of
having a standard in this regard? That is, perhaps have one color (blue)
for "traditional" links (external links with target="_self"), one for
same-page links, and one for links (scripted) in which ctrl-click is not
an option?
This is my first question here, so please be gentle...
It seems that a user often has to make a decision about whether to
directly click on a hyperlink, or do a ctrl-click (click to open in new
window or tab), and that he/she would benefit by knowing some things about
the link before clicking. Specifically:
is this link to an anchor on the same page, or to a different page?
Is this link already set to open a new window/tab (target="_blank") with a
normal click?
Is this link to a script, so that ctrl-click will do nothing but produce a
blank window/tab?
I suppose there are some other choices as well (I won't touch on frames
here), but the point is that users are often up in the air about whether
they want to click or ctrl-click a link. Has there ever been talk of
having a standard in this regard? That is, perhaps have one color (blue)
for "traditional" links (external links with target="_self"), one for
same-page links, and one for links (scripted) in which ctrl-click is not
an option?
Monday, 26 August 2013
Inserting jpeg letterhead layout into a word document - Windows 8
Inserting jpeg letterhead layout into a word document - Windows 8
I have been provided with a jpeg of a letterhead layout by my graphic
designer who operates in Mac - I need to convert this to a Word document
without losing the integrity of the logo. By simply inserting the logo
into the header portion and the footer portion - it does not print well at
all. As most of my letters are sent via email I need to improve this. Can
someone please help?
I operate in Windows 8 by the way. Everything I see and read when trying
to research this does not seem to have the same layout as me.
Tracey
I have been provided with a jpeg of a letterhead layout by my graphic
designer who operates in Mac - I need to convert this to a Word document
without losing the integrity of the logo. By simply inserting the logo
into the header portion and the footer portion - it does not print well at
all. As most of my letters are sent via email I need to improve this. Can
someone please help?
I operate in Windows 8 by the way. Everything I see and read when trying
to research this does not seem to have the same layout as me.
Tracey
Get deep elements by name in Javascript within another element
Get deep elements by name in Javascript within another element
I have a HTML document with multiple div tags like
<div id="id1">
<table>
<tr>
<th>Name</th>
<th>Serial</th>
</tr>
<tr>
<td><input id="Param1" name="Group1" type="text" value
="0"/></td>
<td><input id="Param2" name="Group1" type="text" value
="0"/></td>
</tr>
<tr>
<td><input id="Param3" name="Group2" type="text" value
="0"/></td>
<td><input id="Param4" name="Group2" type="text" value
="0"/></td>
</tr>
</table>
</div>
<div id="id2">
...
...
</div>
How can I select the inputs that have div id as "id1" and make an array of
input ids that have name "Group1" using either Javascript OR jQuery?
I have a HTML document with multiple div tags like
<div id="id1">
<table>
<tr>
<th>Name</th>
<th>Serial</th>
</tr>
<tr>
<td><input id="Param1" name="Group1" type="text" value
="0"/></td>
<td><input id="Param2" name="Group1" type="text" value
="0"/></td>
</tr>
<tr>
<td><input id="Param3" name="Group2" type="text" value
="0"/></td>
<td><input id="Param4" name="Group2" type="text" value
="0"/></td>
</tr>
</table>
</div>
<div id="id2">
...
...
</div>
How can I select the inputs that have div id as "id1" and make an array of
input ids that have name "Group1" using either Javascript OR jQuery?
Representing a finite unordered set in a formal grammar
Representing a finite unordered set in a formal grammar
Goal: find a way to formally define a grammar that recognizes elements
from a set 0 or 1 times in any order. Subsequently, I want to parse it and
generate an AST as well.
For example: Say the set of valid strings in my language is {A, B, C}. I
want to define a grammar that recognizes all valid permutations of any
number of those elements.
Syntactically valid strings would include:
(the empty string)
A,
B A, and
C A B
Syntactically invalid strings would include:
A A, and
B A C B
To be clear, defining all possible permutations explicitly in a CFG is
unacceptable for my purposes, since larger sets would be impossible to
maintain.
From what I understand, such a language fails the pumping lemma for
context free languages, so the solution will not be context free or
regular.
Goal: find a way to formally define a grammar that recognizes elements
from a set 0 or 1 times in any order. Subsequently, I want to parse it and
generate an AST as well.
For example: Say the set of valid strings in my language is {A, B, C}. I
want to define a grammar that recognizes all valid permutations of any
number of those elements.
Syntactically valid strings would include:
(the empty string)
A,
B A, and
C A B
Syntactically invalid strings would include:
A A, and
B A C B
To be clear, defining all possible permutations explicitly in a CFG is
unacceptable for my purposes, since larger sets would be impossible to
maintain.
From what I understand, such a language fails the pumping lemma for
context free languages, so the solution will not be context free or
regular.
Which class is needed to specify encodeByte() method?
Which class is needed to specify encodeByte() method?
I want to import my data from a csv file to hbase in java. But I can't
find the encodeByte method in the Base64 class. In the below line:
Base64.encodeByte(actualSeparator.getBytes())
I get an error.
Can you tell me which class needs to be imported or which file jar I need
to inset in my library?
I want to import my data from a csv file to hbase in java. But I can't
find the encodeByte method in the Base64 class. In the below line:
Base64.encodeByte(actualSeparator.getBytes())
I get an error.
Can you tell me which class needs to be imported or which file jar I need
to inset in my library?
PHP - compare two diffrent type variable bug or issue
PHP - compare two diffrent type variable bug or issue
There is two different type of variables. but while comparing both
variable using == operator it returns weired output. Is this bug or some
other issue? I am surprised. Here is code,
$a=1000;
$b='1000square';
if($a==$b){
echo "a equal b";
}else{
echo "a not equal b";
}
It outputs : a equal b. But expected : a not equal b.
Can anyone explain?
Thanks!!!
There is two different type of variables. but while comparing both
variable using == operator it returns weired output. Is this bug or some
other issue? I am surprised. Here is code,
$a=1000;
$b='1000square';
if($a==$b){
echo "a equal b";
}else{
echo "a not equal b";
}
It outputs : a equal b. But expected : a not equal b.
Can anyone explain?
Thanks!!!
Create openoffice .odt document with Python
Create openoffice .odt document with Python
How can I create an open office .odt file from Python?
I'm looking at this http://wiki.openoffice.org/wiki/Python, but am
confused. I've already got Python 2.7 so where do I go from here? The
above link talks about Open Office shipping with Python. Have I already
got it?? And do I even need OpenOffice? Isn't there just some template,
some way that a document needs to look like so it will will recognized as
odt? Would I need the actual editor?
I'd like something like https://github.com/mikemaccana/python-docx, but
for Open Office.
Sorry for this open ended question, but I really have looked around and
feel that I am missing some vital link/understanding about what is
required.
How can I create an open office .odt file from Python?
I'm looking at this http://wiki.openoffice.org/wiki/Python, but am
confused. I've already got Python 2.7 so where do I go from here? The
above link talks about Open Office shipping with Python. Have I already
got it?? And do I even need OpenOffice? Isn't there just some template,
some way that a document needs to look like so it will will recognized as
odt? Would I need the actual editor?
I'd like something like https://github.com/mikemaccana/python-docx, but
for Open Office.
Sorry for this open ended question, but I really have looked around and
feel that I am missing some vital link/understanding about what is
required.
Sunday, 25 August 2013
Computer cannot boot to Ubuntu 13.04 after installing Netflix-desktop and later Wine
Computer cannot boot to Ubuntu 13.04 after installing Netflix-desktop and
later Wine
Can anyone help me with this issue?
Issue: Black screen after boot attempt from GRUB (cannot boot Ubuntu, not
even in failsafe mode) Process to get to Issue: On Ubuntu 13.04, I
installed netflix-desktop following this procedure; Netflix app didn't
show up in Unity dash, so I uninstalled and reinstalled, still to no
avail. Immediately after, I installed Wine, following this procedure.
Since the Netflix app was still nowhere to be found, I uninstalled Wine
and reinstalled it. Nothing... so I restarted Ubuntu, only to find out
that ever since I cannot boot. I've tried several of the options in
Advanced options for Ubuntu on the GRUB menu but nothing.
I have a computer with Windows 8 Pro dual-boot so I'm able to keep
searching for answers online, but I can't seem to use Ubuntu anymore and
will have to resign and reinstall Ubuntu somehow.
Thank you for taking time in looking at my issue.
later Wine
Can anyone help me with this issue?
Issue: Black screen after boot attempt from GRUB (cannot boot Ubuntu, not
even in failsafe mode) Process to get to Issue: On Ubuntu 13.04, I
installed netflix-desktop following this procedure; Netflix app didn't
show up in Unity dash, so I uninstalled and reinstalled, still to no
avail. Immediately after, I installed Wine, following this procedure.
Since the Netflix app was still nowhere to be found, I uninstalled Wine
and reinstalled it. Nothing... so I restarted Ubuntu, only to find out
that ever since I cannot boot. I've tried several of the options in
Advanced options for Ubuntu on the GRUB menu but nothing.
I have a computer with Windows 8 Pro dual-boot so I'm able to keep
searching for answers online, but I can't seem to use Ubuntu anymore and
will have to resign and reinstall Ubuntu somehow.
Thank you for taking time in looking at my issue.
[ Diet & Fitness ] Open Question : Will I loose thigh fat?
[ Diet & Fitness ] Open Question : Will I loose thigh fat?
http://tinypic.com/r/e8v32o/5 Those are my legs^ I'm 5"5', I weigh 146,
and I'm almost 15. But I hate my body so much, like ok your probably like
dude shut up but I really do! I get called thunder thighs all the time!!!
I won't even go play outside with my brothers cause I don't want anyone to
see me I'm self cautious and everyone always says dude u have big thighs I
have such a low self asteam. I won't even go to my high school orientation
this friday cause of my legs. Idk why but they look a lot skinnier in this
pic? They're a lot bigger in person. My mom just baught me the zumba set
so if I do that aling with a healthy diet can I loose weight? I'm trying
to tone up and loose inches more than loosing weight actually. I'm a pants
size 9. Btw. So how can I drop down to like a 6 or 5!?!? How long will it
take me if I so zumba everyday for like an hour.
http://tinypic.com/r/e8v32o/5 Those are my legs^ I'm 5"5', I weigh 146,
and I'm almost 15. But I hate my body so much, like ok your probably like
dude shut up but I really do! I get called thunder thighs all the time!!!
I won't even go play outside with my brothers cause I don't want anyone to
see me I'm self cautious and everyone always says dude u have big thighs I
have such a low self asteam. I won't even go to my high school orientation
this friday cause of my legs. Idk why but they look a lot skinnier in this
pic? They're a lot bigger in person. My mom just baught me the zumba set
so if I do that aling with a healthy diet can I loose weight? I'm trying
to tone up and loose inches more than loosing weight actually. I'm a pants
size 9. Btw. So how can I drop down to like a 6 or 5!?!? How long will it
take me if I so zumba everyday for like an hour.
How to use txt file as an command
How to use txt file as an command
How can i use a text file as a command? Lets say I'll need a command for
more then one batch file, and to do it easy for the user to edit that
command I'll use a txt file.
@echo off [use command from txt file] type ? Example.txt Pause
How can i use a text file as a command? Lets say I'll need a command for
more then one batch file, and to do it easy for the user to edit that
command I'll use a txt file.
@echo off [use command from txt file] type ? Example.txt Pause
How to sort an array by value?
How to sort an array by value?
I have an array that looks like ["Lloyd's Burgers"=21, "Patty's
Flowers"=17]. How can I sort this array by the number?
I would give sample code but I couldn't find anything in the documentation
about sorting an array by value.
I have an array that looks like ["Lloyd's Burgers"=21, "Patty's
Flowers"=17]. How can I sort this array by the number?
I would give sample code but I couldn't find anything in the documentation
about sorting an array by value.
Deciphering Generics Syntax
Deciphering Generics Syntax
I am reading through a question where the signature of the method is given
below
public static <E extends CharSequence> List<? super E> doIt(List<E> nums)
I am unable to decode the syntax. I am very fresh in generics and unable
to understand this part. Doesn't the first part <E extends CharSequence>
tells what E should be, both for as an argument and as a return type. But
i do see List<? super E>, this defines the bounds for the return type. Can
someone help me understand this with an example?
Thanks.
I am reading through a question where the signature of the method is given
below
public static <E extends CharSequence> List<? super E> doIt(List<E> nums)
I am unable to decode the syntax. I am very fresh in generics and unable
to understand this part. Doesn't the first part <E extends CharSequence>
tells what E should be, both for as an argument and as a return type. But
i do see List<? super E>, this defines the bounds for the return type. Can
someone help me understand this with an example?
Thanks.
Saturday, 24 August 2013
Undefined reference error while calling function
Undefined reference error while calling function
I was coding a simple text based RPG when I came across this error. Here's
the file it occurred in (combat_scene.cpp):
#include <iostream>
#include "header.h"
using namespace std;
void combat_scene(string enemy, int xp_gain, int hp, int dmg, int money)
{
enemy_health = hp;
cout << "\n";
cout << "\n"<< name <<" finds a " << enemy << "!";
while (enemy_health>0 && health>0)
{
health -= dmg;
attacking_turn();
}
if (health>0)
{
exp += xp_gain;
gold += money;
location();
}
else
{
cout <<"\nSorry, "<< name << " you died from a "<< enemy << ".";
}
}
This caused the following error:
||=== RPG, Debug ===|
obj\Debug\home_action.o||In function `Z11home_actionv':|
C:\Users\William\Documents\Stuff\Programming\C++\Randomness\RPG\home_action.cpp|64|undefined
reference to `travel_locations()'|
C:\Users\William\Documents\Stuff\Programming\C++\Randomness\RPG\home_action.cpp|67|undefined
reference to `location()'|
||=== Build finished: 3 errors, 0 warnings (0 minutes, 0 seconds) ===|
The header referenced is (header.h):
#ifndef HEADER_H_INCLUDED
#define HEADER_H_INCLUDED
#include <iostream>
using namespace std;
extern int intel;
extern int strength;
extern int sneak;
extern int damage;
extern int max_health;
extern int max_magic;
extern int enemy_health;
extern int health;
extern int magic;
extern string chosen_class;
extern int die_roll;
extern int goal;
extern int gold;
extern int exp;
extern string name;
extern string current_town;
void level_up();
void calculate_max();
void reset_healths();
void spell();
void attacking_turn();
void home_action();
void calculate_roll(int stat, int difficulty);
void combat_scene(string enemy, int xp_gain, int hp, int dmg, int money);
void location();
int main();
void travel_locations();
I was coding a simple text based RPG when I came across this error. Here's
the file it occurred in (combat_scene.cpp):
#include <iostream>
#include "header.h"
using namespace std;
void combat_scene(string enemy, int xp_gain, int hp, int dmg, int money)
{
enemy_health = hp;
cout << "\n";
cout << "\n"<< name <<" finds a " << enemy << "!";
while (enemy_health>0 && health>0)
{
health -= dmg;
attacking_turn();
}
if (health>0)
{
exp += xp_gain;
gold += money;
location();
}
else
{
cout <<"\nSorry, "<< name << " you died from a "<< enemy << ".";
}
}
This caused the following error:
||=== RPG, Debug ===|
obj\Debug\home_action.o||In function `Z11home_actionv':|
C:\Users\William\Documents\Stuff\Programming\C++\Randomness\RPG\home_action.cpp|64|undefined
reference to `travel_locations()'|
C:\Users\William\Documents\Stuff\Programming\C++\Randomness\RPG\home_action.cpp|67|undefined
reference to `location()'|
||=== Build finished: 3 errors, 0 warnings (0 minutes, 0 seconds) ===|
The header referenced is (header.h):
#ifndef HEADER_H_INCLUDED
#define HEADER_H_INCLUDED
#include <iostream>
using namespace std;
extern int intel;
extern int strength;
extern int sneak;
extern int damage;
extern int max_health;
extern int max_magic;
extern int enemy_health;
extern int health;
extern int magic;
extern string chosen_class;
extern int die_roll;
extern int goal;
extern int gold;
extern int exp;
extern string name;
extern string current_town;
void level_up();
void calculate_max();
void reset_healths();
void spell();
void attacking_turn();
void home_action();
void calculate_roll(int stat, int difficulty);
void combat_scene(string enemy, int xp_gain, int hp, int dmg, int money);
void location();
int main();
void travel_locations();
Python 3.3.2 - Calculator 7 Segment Display w/ Width
Python 3.3.2 - Calculator 7 Segment Display w/ Width
I need to write a program to make a seven segment display. It will work
like this:
def numbers(number, width):
# Code to make number
A typical output could look something like this:
numbers(100, 2)
-- --
| | | | |
| | | | |
| | | | |
| | | | |
-- --
numbers(24, 1)
-
| | |
- -
| |
-
numbers(1234567890, 1)
- - - - - - - -
| | | | | | | | | | | | | |
- - - - - - -
| | | | | | | | | | | | |
- - - - - - -
numbers(8453, 3)
--- --- ---
| | | | | |
| | | | | |
| | | | | |
--- --- --- ---
| | | | |
| | | | |
| | | | |
--- --- ---
Anyway, those are a few examples (which took quite a while to type, mind
you). I know I can use things such as '-' * number and such, but it is
just frustrating as I cannot figure it out! I feel like I should be using
classes or something, but I can't quite put my finger on it.
Thank you.
I need to write a program to make a seven segment display. It will work
like this:
def numbers(number, width):
# Code to make number
A typical output could look something like this:
numbers(100, 2)
-- --
| | | | |
| | | | |
| | | | |
| | | | |
-- --
numbers(24, 1)
-
| | |
- -
| |
-
numbers(1234567890, 1)
- - - - - - - -
| | | | | | | | | | | | | |
- - - - - - -
| | | | | | | | | | | | |
- - - - - - -
numbers(8453, 3)
--- --- ---
| | | | | |
| | | | | |
| | | | | |
--- --- --- ---
| | | | |
| | | | |
| | | | |
--- --- ---
Anyway, those are a few examples (which took quite a while to type, mind
you). I know I can use things such as '-' * number and such, but it is
just frustrating as I cannot figure it out! I feel like I should be using
classes or something, but I can't quite put my finger on it.
Thank you.
Windows Phone EventTrigger not working
Windows Phone EventTrigger not working
I have a DataTemplate which is used to populate a longlistselector. In
this DataTemplate are 2 rows. Row 1 contains a button, when pressed it
should slide open row 2. The problem is when I run the app I get an
UnhandledException.
Here is the DataTemplate:
<DataTemplate>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<!-- 1st ROW -->
<Border Background="Red" HorizontalAlignment="Stretch">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<TextBlock Text="Test Item" FontSize="42" />
<Button Content="v" Grid.Column="1">
<Button.Triggers>
<EventTrigger RoutedEvent="Button.Tap">
<BeginStoryboard>
<Storyboard x:Name="myBoard"
TargetProperty="Border.Height"
TargetName="Slider">
<DoubleAnimation From="0" To="60"
Duration="0:0:2" />
</Storyboard>
</BeginStoryboard>
</EventTrigger>
</Button.Triggers>
</Button>
</Grid>
</Border>
<!-- 2nd ROW -->
<Border x:Name="Slider" Grid.Row="1" Background="Green"
HorizontalAlignment="Stretch" Height="0">
<TextBlock Text="Slider" FontSize="42" />
</Border>
</Grid>
</DataTemplate>
I have a DataTemplate which is used to populate a longlistselector. In
this DataTemplate are 2 rows. Row 1 contains a button, when pressed it
should slide open row 2. The problem is when I run the app I get an
UnhandledException.
Here is the DataTemplate:
<DataTemplate>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<!-- 1st ROW -->
<Border Background="Red" HorizontalAlignment="Stretch">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<TextBlock Text="Test Item" FontSize="42" />
<Button Content="v" Grid.Column="1">
<Button.Triggers>
<EventTrigger RoutedEvent="Button.Tap">
<BeginStoryboard>
<Storyboard x:Name="myBoard"
TargetProperty="Border.Height"
TargetName="Slider">
<DoubleAnimation From="0" To="60"
Duration="0:0:2" />
</Storyboard>
</BeginStoryboard>
</EventTrigger>
</Button.Triggers>
</Button>
</Grid>
</Border>
<!-- 2nd ROW -->
<Border x:Name="Slider" Grid.Row="1" Background="Green"
HorizontalAlignment="Stretch" Height="0">
<TextBlock Text="Slider" FontSize="42" />
</Border>
</Grid>
</DataTemplate>
MySQL Insert if Condition
MySQL Insert if Condition
I Have this cat id - post id relation table.
+----+--------+---------+
| id | cat_id | post_id |
| | | |
| 1 | 11 | 32 |
| 2 | ... | ... |
+----+--------+---------+
I use SELECT WHERE cat_id = 11 AND post_id = 32 and then if no result
found, I do INSERT. Can I rewrite these two queries in One?
I Have this cat id - post id relation table.
+----+--------+---------+
| id | cat_id | post_id |
| | | |
| 1 | 11 | 32 |
| 2 | ... | ... |
+----+--------+---------+
I use SELECT WHERE cat_id = 11 AND post_id = 32 and then if no result
found, I do INSERT. Can I rewrite these two queries in One?
artisan --env not working, why?
artisan --env not working, why?
I run php artisan migrate::install --env=foobar, but PDO can't connect, why?
[PDOException]
SQLSTATE[HY000] [2002] No connection could be made because the target machi
ne actively refused it.
I have added an entry in bootstrap/start.php and I know it is working,
when I browse the webpage it connects like it should.
$env = $app->detectEnvironment(array(
'foobar' => array('foobar.com')
));
I've created the folder app/config/foobar, copied the database.php file
and edited the mysql-array to match my mysql credentials.
What am I doing wrong? Why can't artisan recognize that I want to use my
foobar-envoirment?
I run php artisan migrate::install --env=foobar, but PDO can't connect, why?
[PDOException]
SQLSTATE[HY000] [2002] No connection could be made because the target machi
ne actively refused it.
I have added an entry in bootstrap/start.php and I know it is working,
when I browse the webpage it connects like it should.
$env = $app->detectEnvironment(array(
'foobar' => array('foobar.com')
));
I've created the folder app/config/foobar, copied the database.php file
and edited the mysql-array to match my mysql credentials.
What am I doing wrong? Why can't artisan recognize that I want to use my
foobar-envoirment?
i= Integer.parseInt(dis.readLine()) [Deprecated].. How to resolve it?
i= Integer.parseInt(dis.readLine()) [Deprecated].. How to resolve it?
I have encountered the following error while compiling my Demo code on
DataInputStreamDemo: error:
i= Integer.parseInt(dis.readLine()) [Deprecated]
//where dis = reference DataInputStream obj
I have encountered the following error while compiling my Demo code on
DataInputStreamDemo: error:
i= Integer.parseInt(dis.readLine()) [Deprecated]
//where dis = reference DataInputStream obj
Number of ones to the left of every zero in binary representation
Number of ones to the left of every zero in binary representation
I am seeking the computationally fastest way to determine the total number
of ones to the left of every zero in the binary representation of a
number. That is: for every zero, count the number of ones that are to the
left of it, and then total the counts.
For example:
75 => {1, 0, 0, 1, 0, 1, 1}
{1}
{1}
{1, 1}
Total = 4
I wish to do this programmatically but my attempts are slow and feel
inefficient. Is there some clever method I might use?
I am seeking the computationally fastest way to determine the total number
of ones to the left of every zero in the binary representation of a
number. That is: for every zero, count the number of ones that are to the
left of it, and then total the counts.
For example:
75 => {1, 0, 0, 1, 0, 1, 1}
{1}
{1}
{1, 1}
Total = 4
I wish to do this programmatically but my attempts are slow and feel
inefficient. Is there some clever method I might use?
assignment within an echo statement
assignment within an echo statement
In my PHP file, I have an echo statement, that outputs some HTML, within
which i want to do some assignment based on onclick event.
echo "<td style='padding:10px; text-align:left;'> <a target='_blank'
href='stat.php' onclick='". $_SESSION['dakno'] = $r[$j]; ."'
>".$r[$j]."</a></td>";
I have tried a lot of combinations, but still getting syntax error because
of the onclick section.
echo "<td style='padding:10px; text-align:left;'> <a target='_blank'
href='stat.php' onclick='"<?php $_SESSION['dakno'] = $r[$j]; ?> "'
>".$r[$j]."</a></td>";
Please, help me to remove the syntax error I am making.
In my PHP file, I have an echo statement, that outputs some HTML, within
which i want to do some assignment based on onclick event.
echo "<td style='padding:10px; text-align:left;'> <a target='_blank'
href='stat.php' onclick='". $_SESSION['dakno'] = $r[$j]; ."'
>".$r[$j]."</a></td>";
I have tried a lot of combinations, but still getting syntax error because
of the onclick section.
echo "<td style='padding:10px; text-align:left;'> <a target='_blank'
href='stat.php' onclick='"<?php $_SESSION['dakno'] = $r[$j]; ?> "'
>".$r[$j]."</a></td>";
Please, help me to remove the syntax error I am making.
Friday, 23 August 2013
Loading data into combobox B after selecting value from combobox A
Loading data into combobox B after selecting value from combobox A
I am using jEasyUI.
I am able to load my first combobox with field name "projectID".
When I select a combobox value, I want to populate the axcode field. I
know that my url works, and the data that is retrieved is:
[{"id":"26","groupID":"1","projectID":"18","Description":"Holiday","isActive":"1"},{"id":"28","groupID":"1","projectID":"18","Description":"Other","isActive":"1"},{"id":"24","groupID":"1","projectID":"18","Description":"Sick
Leave","isActive":"1"},{"id":"27","groupID":"1","projectID":"18","Description":"Unpaid
Leave","isActive":"1"},{"id":"25","groupID":"1","projectID":"18","Description":"Vacation","isActive":"1"}]
Can someone tell me why this code doesn't work?
{field:'projectID',
title:'Project/Paid Leave',
width:100,
editor:{
type:'combobox',
options:{
valueField:'id',
textField:'DescriptionCode',
data:cmbprojects,
required:true,
editable:false,
onSelect:function(record){
$('#axCode').combobox('reload','remote_combo_data.php?type=projectax&projectID='+record.id);
}
// closes onSelect
}
// closes options
}
// closes editor
}
// closes field
,
{
field:'axCode',
title:'axCode',
width:100,
editor:{
type:'combobox',
valueField:'id',
textField:'Description',
data:cmbaxcodes,
required:true,
editable:false
}
// closes editor
,formatter:function(value,row,index){return row.Description;}
// closes formatter
}
// closes field
,
{
field:'activityID',
title:'Activity',
width:100,
editor:{
type:'combobox',
options:{
// this is a key/value pair from the data source
valueField:'id',
textField:'ActivityCode',
data:cmbactivities,
required:true,
editable:false
}
// closes options
}
// closes editor
,formatter:function(value,row,index){return row.ActivityCode;}
}
//closes field
I am using jEasyUI.
I am able to load my first combobox with field name "projectID".
When I select a combobox value, I want to populate the axcode field. I
know that my url works, and the data that is retrieved is:
[{"id":"26","groupID":"1","projectID":"18","Description":"Holiday","isActive":"1"},{"id":"28","groupID":"1","projectID":"18","Description":"Other","isActive":"1"},{"id":"24","groupID":"1","projectID":"18","Description":"Sick
Leave","isActive":"1"},{"id":"27","groupID":"1","projectID":"18","Description":"Unpaid
Leave","isActive":"1"},{"id":"25","groupID":"1","projectID":"18","Description":"Vacation","isActive":"1"}]
Can someone tell me why this code doesn't work?
{field:'projectID',
title:'Project/Paid Leave',
width:100,
editor:{
type:'combobox',
options:{
valueField:'id',
textField:'DescriptionCode',
data:cmbprojects,
required:true,
editable:false,
onSelect:function(record){
$('#axCode').combobox('reload','remote_combo_data.php?type=projectax&projectID='+record.id);
}
// closes onSelect
}
// closes options
}
// closes editor
}
// closes field
,
{
field:'axCode',
title:'axCode',
width:100,
editor:{
type:'combobox',
valueField:'id',
textField:'Description',
data:cmbaxcodes,
required:true,
editable:false
}
// closes editor
,formatter:function(value,row,index){return row.Description;}
// closes formatter
}
// closes field
,
{
field:'activityID',
title:'Activity',
width:100,
editor:{
type:'combobox',
options:{
// this is a key/value pair from the data source
valueField:'id',
textField:'ActivityCode',
data:cmbactivities,
required:true,
editable:false
}
// closes options
}
// closes editor
,formatter:function(value,row,index){return row.ActivityCode;}
}
//closes field
$watch a service variable or $broadcast an event with AngularJS
$watch a service variable or $broadcast an event with AngularJS
I'm using a service to share data between controllers. The application has
to update the DOM when a variable is modified. I've found two ways to do
that, you can see the code here:
http://jsfiddle.net/sosegon/9x4N3/7/
myApp.controller( "ctrl1", [ "$scope", "myService", function( $scope,
myService ){
$scope.init = function(){
$scope.myVariable = myService.myVariable;
}; } ] );
myApp.controller( "ctrl2", [ "$scope", "myService", function( $scope,
myService ){
$scope.increaseVal = function(){
var a = myService.myVariable.value;
myService.myVariable.value = a + 1;
}; } ] );
http://jsfiddle.net/sosegon/Y93Wn/3/
myApp.controller( "ctrl1", [ "$scope", "myService", function( $scope,
myService ){
$scope.init = function(){
$scope.increasedCounter = 1;
$scope.myVariable = myService.myVariable;
};
$scope.$on( "increased", function(){
$scope.increasedCounter += 1;
} ); } ] );
myApp.controller( "ctrl2", [ "$scope", "myService", function( $scope,
myService ){
$scope.increaseVal = function(){
myService.increaseVal();
};} ] )
In the first case, I share a variable from the service with the controller
and $watch it in the directive. Here, I can modify the variable directly
in this controller, or any other controller that share it, and the DOM is
updated.
In the other option, I use a function from the service to modify the
variable which $broadcast an event. That event is listened by the
controller, then the DOM is updated.
I'd like to know which option is better and the reasons for that.
Thanks.
I'm using a service to share data between controllers. The application has
to update the DOM when a variable is modified. I've found two ways to do
that, you can see the code here:
http://jsfiddle.net/sosegon/9x4N3/7/
myApp.controller( "ctrl1", [ "$scope", "myService", function( $scope,
myService ){
$scope.init = function(){
$scope.myVariable = myService.myVariable;
}; } ] );
myApp.controller( "ctrl2", [ "$scope", "myService", function( $scope,
myService ){
$scope.increaseVal = function(){
var a = myService.myVariable.value;
myService.myVariable.value = a + 1;
}; } ] );
http://jsfiddle.net/sosegon/Y93Wn/3/
myApp.controller( "ctrl1", [ "$scope", "myService", function( $scope,
myService ){
$scope.init = function(){
$scope.increasedCounter = 1;
$scope.myVariable = myService.myVariable;
};
$scope.$on( "increased", function(){
$scope.increasedCounter += 1;
} ); } ] );
myApp.controller( "ctrl2", [ "$scope", "myService", function( $scope,
myService ){
$scope.increaseVal = function(){
myService.increaseVal();
};} ] )
In the first case, I share a variable from the service with the controller
and $watch it in the directive. Here, I can modify the variable directly
in this controller, or any other controller that share it, and the DOM is
updated.
In the other option, I use a function from the service to modify the
variable which $broadcast an event. That event is listened by the
controller, then the DOM is updated.
I'd like to know which option is better and the reasons for that.
Thanks.
Need to display data queried from GAE datastore in a nice way
Need to display data queried from GAE datastore in a nice way
I want to display data queried from GAE datastore in a nice way (graphs,
etc.) What is the best way to do it?
As I'm already working with GAE, perhaps there is a google API for that?
The only thing I found online is Chart.js but I need to channel the JS
into java which seems complicated.
Any advise will be welcome, Thanks!
I want to display data queried from GAE datastore in a nice way (graphs,
etc.) What is the best way to do it?
As I'm already working with GAE, perhaps there is a google API for that?
The only thing I found online is Chart.js but I need to channel the JS
into java which seems complicated.
Any advise will be welcome, Thanks!
What address families can getaddrinfo return?
What address families can getaddrinfo return?
When I call getaddrinfo with AF_UNSPEC, it can return any address families
it likes: AF_INET, AF_INET6, maybe AppleTalk, bluetooth, datalink, netlink
addresses...
On FreeBSD, it can only return AF_INET or AF_INET6 (checked in source)
On linux, ditto (according to glibc manpage)
What about other systems? Are there platforms where we might get other
address structures?
I'm particularly suspicious of MacOS - the source seems to be missing from
opensource.apple.com/source/Libc and the manpage doesn't say. We have a
vague log file that may indicate getaddrinfo returned some other address
family. Other platforms we support are AIX, Windows, Solaris, HP-UX.
I'm aware I can just check the family in the structure returned. I can't
guess what interesting strings and hints might need to be used to get
non-AF_INET(6) results out though.
When I call getaddrinfo with AF_UNSPEC, it can return any address families
it likes: AF_INET, AF_INET6, maybe AppleTalk, bluetooth, datalink, netlink
addresses...
On FreeBSD, it can only return AF_INET or AF_INET6 (checked in source)
On linux, ditto (according to glibc manpage)
What about other systems? Are there platforms where we might get other
address structures?
I'm particularly suspicious of MacOS - the source seems to be missing from
opensource.apple.com/source/Libc and the manpage doesn't say. We have a
vague log file that may indicate getaddrinfo returned some other address
family. Other platforms we support are AIX, Windows, Solaris, HP-UX.
I'm aware I can just check the family in the structure returned. I can't
guess what interesting strings and hints might need to be used to get
non-AF_INET(6) results out though.
Display img only when it has a title?
Display img only when it has a title?
Basically in my ASP.NET MVC4 project I'm trying to have my
validationmessages as tooltips (which gets displayed when hovered over a
certain image). Right now the error message is inserted into the image
title - however I'd like to ONLY display the image when it has a title
(when it doesn't have a title there is no error message).
How can I do this?
I don't suppose it is possible through CSS so a js/jquery solution would
work too.
To clarify I need to check update the display as the title changes during
runtime. An initial check is not gonna do it.
Basically in my ASP.NET MVC4 project I'm trying to have my
validationmessages as tooltips (which gets displayed when hovered over a
certain image). Right now the error message is inserted into the image
title - however I'd like to ONLY display the image when it has a title
(when it doesn't have a title there is no error message).
How can I do this?
I don't suppose it is possible through CSS so a js/jquery solution would
work too.
To clarify I need to check update the display as the title changes during
runtime. An initial check is not gonna do it.
How to select a derived range of rows and then apply simple math to them
How to select a derived range of rows and then apply simple math to them
Me, not being a pro at excel, don't really know what nomenclature to use
to describe what exactly I need to do.
I am trying to make a button macro that will take in a few settings values
(eg. maximum cost value, number of rows to output, etc..).
Following this, it will move to sheet two and pull in (select?) the data
from a number of rows (that will change in number over time). The # of
columns to pull in will remain the same however.
Visually:
Row 1 value1 value2 value3
Row 2 value1 value2 ...
Select rows 1 and 2, select all values in the columns to the right.
Once this information is selected, I then want to apply a multipler to
some of the values on each row (the multipliers come from a small
"settings" location... Column A1 row 20 to Column A1 row 25... 6 columns
each). The multiplier rows and the columns in the selected data do not
exactly corrospond.. one multiplier should be applied to 8 of the selected
columns while another will only be applied to one column.
The row that the multipliers will be applied to is randomly selected.
After applying the multipliers to this random row, I take that row only,
and paste it onto the active cell on sheet 1. If, in the settings, more
then 1 output row is set, the macro would then repeat the process and
paste another row 1 row below the active cell on sheet 1.. and this
continues until all the rows are outputted.
Me, not being a pro at excel, don't really know what nomenclature to use
to describe what exactly I need to do.
I am trying to make a button macro that will take in a few settings values
(eg. maximum cost value, number of rows to output, etc..).
Following this, it will move to sheet two and pull in (select?) the data
from a number of rows (that will change in number over time). The # of
columns to pull in will remain the same however.
Visually:
Row 1 value1 value2 value3
Row 2 value1 value2 ...
Select rows 1 and 2, select all values in the columns to the right.
Once this information is selected, I then want to apply a multipler to
some of the values on each row (the multipliers come from a small
"settings" location... Column A1 row 20 to Column A1 row 25... 6 columns
each). The multiplier rows and the columns in the selected data do not
exactly corrospond.. one multiplier should be applied to 8 of the selected
columns while another will only be applied to one column.
The row that the multipliers will be applied to is randomly selected.
After applying the multipliers to this random row, I take that row only,
and paste it onto the active cell on sheet 1. If, in the settings, more
then 1 output row is set, the macro would then repeat the process and
paste another row 1 row below the active cell on sheet 1.. and this
continues until all the rows are outputted.
Thursday, 22 August 2013
Probability of random vector lying on a hyperplane
Probability of random vector lying on a hyperplane
I have a random vector $v \in \mathbb R^n$, of which the elements are
independent. Now there is also a hyperplane $S \subseteq \mathbb R^n$ of
dimension $n-1$. The vector is drawn from any continuous probability
distribution. Now my common sense tells me that the probability that the
vector lies on the hyperplane, is zero ($P(v\in S)=0$). But how would I
prove this? And is this even true?
I have a random vector $v \in \mathbb R^n$, of which the elements are
independent. Now there is also a hyperplane $S \subseteq \mathbb R^n$ of
dimension $n-1$. The vector is drawn from any continuous probability
distribution. Now my common sense tells me that the probability that the
vector lies on the hyperplane, is zero ($P(v\in S)=0$). But how would I
prove this? And is this even true?
Deciding whether this map is well defined.
Deciding whether this map is well defined.
If I have the map $f: \mathbb{Z}_{20} \rightarrow \mathbb{Z}_{15}$ where
$x + 20\mathbb{Z} \mapsto x + 15\mathbb{Z}$, I have to determine whether
this is well defined or not. After staring at it for only a couple
minutes, I am pretty sure it is not well defined. Now, I must find a
contradiction to back up my answer. Not sure how to do that though. Maybe
the wording of the problem is just confusing me.
If I have the map $f: \mathbb{Z}_{20} \rightarrow \mathbb{Z}_{15}$ where
$x + 20\mathbb{Z} \mapsto x + 15\mathbb{Z}$, I have to determine whether
this is well defined or not. After staring at it for only a couple
minutes, I am pretty sure it is not well defined. Now, I must find a
contradiction to back up my answer. Not sure how to do that though. Maybe
the wording of the problem is just confusing me.
Windows Login straight to Terminal Server
Windows Login straight to Terminal Server
Essentially I'm looking for some way via batch (or potentially powershell,
but win XP machines so ideally batch) to open up a RDP connection to a LAN
based Terminal Server upon a user logging into a machine. Ideally it would
involve some (maybe partial) SSO process i.e. taking the users currently
logged in credentials and passing this to an mstsc call to log them into a
terminal server, no explorer.exe would load on login, just the connection
straight to the terminal server.
Has anyone achieved something similar like this, any suggestions are
appreciated!
Essentially I'm looking for some way via batch (or potentially powershell,
but win XP machines so ideally batch) to open up a RDP connection to a LAN
based Terminal Server upon a user logging into a machine. Ideally it would
involve some (maybe partial) SSO process i.e. taking the users currently
logged in credentials and passing this to an mstsc call to log them into a
terminal server, no explorer.exe would load on login, just the connection
straight to the terminal server.
Has anyone achieved something similar like this, any suggestions are
appreciated!
Black monitor of death after installing Ubuntu
Black monitor of death after installing Ubuntu
I installed Ubuntu on my Dell Laptop (Windows 7 64 bit) using the Windows
Installer. Everything was fine. After booting I got the choice
http://assets.ubuntu.com/sites/ubuntu/540/u/img/download/U2.2.2_07_medium.jpg
But when I hit "Ubuntu" nothing happens. The monitor is black and stuck.
Not even a cursor appears.
I have no idea what to do now. (Windows still works.)
(By the way: I hate if if websites want to force me to enable
Javascript...grrrrr)
I installed Ubuntu on my Dell Laptop (Windows 7 64 bit) using the Windows
Installer. Everything was fine. After booting I got the choice
http://assets.ubuntu.com/sites/ubuntu/540/u/img/download/U2.2.2_07_medium.jpg
But when I hit "Ubuntu" nothing happens. The monitor is black and stuck.
Not even a cursor appears.
I have no idea what to do now. (Windows still works.)
(By the way: I hate if if websites want to force me to enable
Javascript...grrrrr)
Output New Query from Form
Output New Query from Form
I'm trying to figure out how to make a form that changes Query Example (HTML)
<form action="change.php" method="POST" name="Update">
<table>
<tr>
<td>
<input type="text" value="Enter New Criteria" name="where" >
<input type="text" value="Enter New Criteria" name="where2" >
</td>
</tr>
<tr>
<td align="center" style="font-family:Calibri">
<input type="submit" value="Search"/>
</tr>
</table>
SQL Query
$Query = "SELECT order_number
FROM order_header
WHERE (order_number LIKE **'%CHANGE VALUE HERE%'**
OR order_number LIKE **'%CHANGE VALUE HERE%'**
How would I go about doing that, i'm a complete rookie but I am trying. I
tried a search but maybe I'm not using the correct key words.
I'm trying to figure out how to make a form that changes Query Example (HTML)
<form action="change.php" method="POST" name="Update">
<table>
<tr>
<td>
<input type="text" value="Enter New Criteria" name="where" >
<input type="text" value="Enter New Criteria" name="where2" >
</td>
</tr>
<tr>
<td align="center" style="font-family:Calibri">
<input type="submit" value="Search"/>
</tr>
</table>
SQL Query
$Query = "SELECT order_number
FROM order_header
WHERE (order_number LIKE **'%CHANGE VALUE HERE%'**
OR order_number LIKE **'%CHANGE VALUE HERE%'**
How would I go about doing that, i'm a complete rookie but I am trying. I
tried a search but maybe I'm not using the correct key words.
Circular image view android
Circular image view android
I want to do something like that.
This is a list view row with name and the image of user.
I have done some searching and have done the image circular,but not the
perfect solution. Any help will be helping me.
my code added to the Image Loader class
public Bitmap processBitmap(Bitmap bitmap) {
int pixels = 0;
if (mRound == 0)
pixels = 120;
else
pixels = mRound;
Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),
bitmap.getHeight(), Config.ARGB_8888);
Canvas canvas = new Canvas(output);
final int color = 0xff424242;
final Paint paint = new Paint();
final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
final RectF rectF = new RectF(rect);
final float roundPx = pixels;
paint.setAntiAlias(true);
canvas.drawARGB(0, 0, 0, 0);
paint.setColor(color);
canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
canvas.drawBitmap(bitmap, rect, rect, paint);
return output;
}
Thanks.
I want to do something like that.
This is a list view row with name and the image of user.
I have done some searching and have done the image circular,but not the
perfect solution. Any help will be helping me.
my code added to the Image Loader class
public Bitmap processBitmap(Bitmap bitmap) {
int pixels = 0;
if (mRound == 0)
pixels = 120;
else
pixels = mRound;
Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),
bitmap.getHeight(), Config.ARGB_8888);
Canvas canvas = new Canvas(output);
final int color = 0xff424242;
final Paint paint = new Paint();
final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
final RectF rectF = new RectF(rect);
final float roundPx = pixels;
paint.setAntiAlias(true);
canvas.drawARGB(0, 0, 0, 0);
paint.setColor(color);
canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
canvas.drawBitmap(bitmap, rect, rect, paint);
return output;
}
Thanks.
How does Instagram load data
How does Instagram load data
how do you think instagram developed there android app? did they developed
an external webpage and loaded it in a webview, or they used the native
side and loaded the images and related comments...
Thanks
how do you think instagram developed there android app? did they developed
an external webpage and loaded it in a webview, or they used the native
side and loaded the images and related comments...
Thanks
Wednesday, 21 August 2013
Common Splunk Log Message Creation Utility Method
Common Splunk Log Message Creation Utility Method
I'm trying to follow the Splunk method of logging information when I want
to log something. I'm passing in things like the type of layer that is
being called, the method, the class, the url path in the case of our rest
layer calls...etc. I want to come up with a common method to create the
String that goes in the LOG.error message. Maybe have 3 common methods one
for each layer (rest, service and dao since they will take a different
number of parameters). What is the best way to do this?
LOG.error("key=value, key=value, key=value, e);
I'm trying to follow the Splunk method of logging information when I want
to log something. I'm passing in things like the type of layer that is
being called, the method, the class, the url path in the case of our rest
layer calls...etc. I want to come up with a common method to create the
String that goes in the LOG.error message. Maybe have 3 common methods one
for each layer (rest, service and dao since they will take a different
number of parameters). What is the best way to do this?
LOG.error("key=value, key=value, key=value, e);
Auto Layout view resizing frustrations when designing in Interface Builder
Auto Layout view resizing frustrations when designing in Interface Builder
Problem: UIView size is "locked" when designing with Auto Layout in IB
I've uploaded a 20 second video that illustrates my problem, but let me
describe it. You may recognize the project: it's right out of Apple's WWDC
2012 "Introduction to Auto Layout." I've got a simple iPhone view in
Interface Builder where I've already got a button and label along the
bottom. The next step is to add a UIView. Here's where things get ugly.
When I drag the UIView out of the palette in Interface Builder and onto
the iPhone window, as soon as I let it go it seems to become locked in to
its starting size. I place it in the upper left corner, and I'd like to
drag it horizontally to the right side of the window, and vertically to
where it will be up against (minus the padding) the button and label along
the bottom. But, when I try to resize it, I cannot. It's stuck on its
original size!
The video illustrating my problem is here:
http://www.youtube.com/watch?v=jsW4UwnCEkw
You can see me grab the right edge of the view and try to pull it along to
the right side of the window, but it won't expand. You can then see me
move the entire view to the right side (it retains its size) and then try
the opposite: grabbing the left side and trying to expand it so that it
sizes up against the left side of the window. In both cases, the view is
simply locked to its original size.
What gives! Auto Layout in Interface Builder is just the most frustrating
thing. How do I resize a view by dragging? Thanks!
(Note: Xcode 4.6.3.)
Problem: UIView size is "locked" when designing with Auto Layout in IB
I've uploaded a 20 second video that illustrates my problem, but let me
describe it. You may recognize the project: it's right out of Apple's WWDC
2012 "Introduction to Auto Layout." I've got a simple iPhone view in
Interface Builder where I've already got a button and label along the
bottom. The next step is to add a UIView. Here's where things get ugly.
When I drag the UIView out of the palette in Interface Builder and onto
the iPhone window, as soon as I let it go it seems to become locked in to
its starting size. I place it in the upper left corner, and I'd like to
drag it horizontally to the right side of the window, and vertically to
where it will be up against (minus the padding) the button and label along
the bottom. But, when I try to resize it, I cannot. It's stuck on its
original size!
The video illustrating my problem is here:
http://www.youtube.com/watch?v=jsW4UwnCEkw
You can see me grab the right edge of the view and try to pull it along to
the right side of the window, but it won't expand. You can then see me
move the entire view to the right side (it retains its size) and then try
the opposite: grabbing the left side and trying to expand it so that it
sizes up against the left side of the window. In both cases, the view is
simply locked to its original size.
What gives! Auto Layout in Interface Builder is just the most frustrating
thing. How do I resize a view by dragging? Thanks!
(Note: Xcode 4.6.3.)
Problems deserializing List of objects
Problems deserializing List of objects
I am having trouble deserializing a list of objects. I can get just one
object to serialize into an object but cannot get the list. I get no error
it just returns an empty List. This is the XML that gets returned:
<locations>
<location locationtype="building" locationtypeid="1">
<id>1</id>
<name>Building Name</name>
<description>Description of Building</description>
</location>
</locations>
This is the class I have and I am deserializing in the GetAll method:
[Serializable()]
[XmlRoot("location")]
public class Building
{
private string method;
[XmlElement("id")]
public int LocationID { get; set; }
[XmlElement("name")]
public string Name { get; set; }
[XmlElement("description")]
public string Description { get; set; }
[XmlElement("mubuildingid")]
public string MUBuildingID { get; set; }
public List<Building> GetAll()
{
var listBuildings = new List<Building>();
var building = new Building();
var request = WebRequest.Create(method) as HttpWebRequest;
var response = request.GetResponse() as HttpWebResponse;
var streamReader = new StreamReader(response.GetResponseStream());
TextReader reader = streamReader;
var serializer = new XmlSerializer(typeof(List<Building>),
new XmlRootAttribute() { ElementName = "locations" });
listBuildings = (List<Building>)serializer.Deserialize(reader);
return listBuildings;
}
}
I am having trouble deserializing a list of objects. I can get just one
object to serialize into an object but cannot get the list. I get no error
it just returns an empty List. This is the XML that gets returned:
<locations>
<location locationtype="building" locationtypeid="1">
<id>1</id>
<name>Building Name</name>
<description>Description of Building</description>
</location>
</locations>
This is the class I have and I am deserializing in the GetAll method:
[Serializable()]
[XmlRoot("location")]
public class Building
{
private string method;
[XmlElement("id")]
public int LocationID { get; set; }
[XmlElement("name")]
public string Name { get; set; }
[XmlElement("description")]
public string Description { get; set; }
[XmlElement("mubuildingid")]
public string MUBuildingID { get; set; }
public List<Building> GetAll()
{
var listBuildings = new List<Building>();
var building = new Building();
var request = WebRequest.Create(method) as HttpWebRequest;
var response = request.GetResponse() as HttpWebResponse;
var streamReader = new StreamReader(response.GetResponseStream());
TextReader reader = streamReader;
var serializer = new XmlSerializer(typeof(List<Building>),
new XmlRootAttribute() { ElementName = "locations" });
listBuildings = (List<Building>)serializer.Deserialize(reader);
return listBuildings;
}
}
DataView LIKE function on Integer value
DataView LIKE function on Integer value
I have Sql table Tracks which keeps track information such as TrackID and
TrackName. I have c# application with textbox and listbox. I use dataSet
to retrieve sql table and when I write "3" on textbox, I want to get track
names on listbox which has TrackID as "3". My code follows:
lbxTracks.DataSource = new DataView(das.Tables[0], "TrackID LIKE " +
idNo.ToString(), "TrackName", DataViewRowState.CurrentRows);
But I get an error as LIKE function cannot be used on System.Int32..
Any ideas?
I have Sql table Tracks which keeps track information such as TrackID and
TrackName. I have c# application with textbox and listbox. I use dataSet
to retrieve sql table and when I write "3" on textbox, I want to get track
names on listbox which has TrackID as "3". My code follows:
lbxTracks.DataSource = new DataView(das.Tables[0], "TrackID LIKE " +
idNo.ToString(), "TrackName", DataViewRowState.CurrentRows);
But I get an error as LIKE function cannot be used on System.Int32..
Any ideas?
How to debug tests from a Maven build in Eclipse?
How to debug tests from a Maven build in Eclipse?
How is it possible to start a Maven build and let the tests appear in the
debug perspective of Eclipse?
How is it possible to start a Maven build and let the tests appear in the
debug perspective of Eclipse?
CSS - center image and show shadow on top
CSS - center image and show shadow on top
I have a image in a div having id container but it is messing the things
up. It is not centering plus the box-shadow is not shown on image. I added
margin:auto but It did not helped me. I think margin:auto centers all
fixed-width elements but in my case, you know image is resized by CSS. Any
other solution ? Maybe absolute positioning work but the container height
will get zero. I don't want to use Javascript/jQuery.
I have this bin for ya!
I have a image in a div having id container but it is messing the things
up. It is not centering plus the box-shadow is not shown on image. I added
margin:auto but It did not helped me. I think margin:auto centers all
fixed-width elements but in my case, you know image is resized by CSS. Any
other solution ? Maybe absolute positioning work but the container height
will get zero. I don't want to use Javascript/jQuery.
I have this bin for ya!
Tuesday, 20 August 2013
Sharing assemblies without GAC
Sharing assemblies without GAC
We have several solutions, stand-alone applications that uses the same
licensing and update service which is currently located in the GAC.
Once again we've encountered versioning issues.
Is there an elegant way to share an assembly at the client computer
without using GAC?
We have several solutions, stand-alone applications that uses the same
licensing and update service which is currently located in the GAC.
Once again we've encountered versioning issues.
Is there an elegant way to share an assembly at the client computer
without using GAC?
Rails: Heroku with Omniauth and Facebook
Rails: Heroku with Omniauth and Facebook
I am working on an app that allows you to authenticate with Facebook to
signup and log into the app. For some reason when working with multiple
dynos, it appears that session management isn't carried over.
I can watch my logs log the user in, but when the user is redirected, the
app logs the user out for some reason
Here is my AuthorizationsController:
class AuthorizationsController < ApplicationController
skip_before_filter :redirect_to_signed_in_path, :prepare_for_mobile,
:redirect_to_https, :force_www!
def create
authentication =
Authorization.find_by_provider_and_uid(auth['provider'], auth['uid'])
if authentication
flash[:notice] = "Signed In Successfully"
sign_in authentication.user, event: :authentication
redirect_to root_path
elsif user_signed_in?
current_user.apply_omniauth(auth)
if current_user.save
current_user.update_attribute(:"allow_#{auth['provider']}_sync",
true)
PullSocialActionsWorker.perform_async(current_user.id,
auth["provider"])
redirect_to edit_social_profile_path, flash: { error:
"#{auth["provider"]} Integration is processing" }
else
redirect_to edit_social_profile_path, flash: { error: "An error
has occurred. Please try again." }
end
else
password = Devise.friendly_token[0,20]
athlete = Athlete.new(email: generate_auth_email(params[:provider]),
password: password, password_confirmation: password )
athlete.apply_omniauth(auth)
begin
athlete.subscriptions.build(trial_expiry: DateTime.now + 30,
active: true, account_type_id: AccountType.free.id)
if athlete.save(validate: false)
sign_in athlete, event: :authentication
redirect_to root_path, notice: "Account created and signed in
successfully"
else
redirect_to root_path, flash: { error: "An error has occurred.
Please try again." }
end
rescue ActiveRecord::RecordNotUnique
redirect_to root_path, flash: { error: "The email address you are
trying to connect already exists. Perhaps you
#{ActionController::Base.helpers.link_to "Forgot Your Password?",
new_user_password_path}".html_safe }
end
end
end
def failure
redirect_to root_url, notice: "An Error has occurred. Please try again!"
end
private
def auth
request.env["omniauth.auth"]
end
def generate_auth_email(provider)
if provider == "twitter"
"#{auth.uid}@twitter.com"
else
auth.info.try(:email)
end
end
end
Gemfile:
gem 'omniauth'
gem 'omniauth-facebook', '1.4.0'
I am also using Memcache/Dalli for caching...
gem 'memcachier'
gem 'dalli'
Anyone else run into this issue before?
I am working on an app that allows you to authenticate with Facebook to
signup and log into the app. For some reason when working with multiple
dynos, it appears that session management isn't carried over.
I can watch my logs log the user in, but when the user is redirected, the
app logs the user out for some reason
Here is my AuthorizationsController:
class AuthorizationsController < ApplicationController
skip_before_filter :redirect_to_signed_in_path, :prepare_for_mobile,
:redirect_to_https, :force_www!
def create
authentication =
Authorization.find_by_provider_and_uid(auth['provider'], auth['uid'])
if authentication
flash[:notice] = "Signed In Successfully"
sign_in authentication.user, event: :authentication
redirect_to root_path
elsif user_signed_in?
current_user.apply_omniauth(auth)
if current_user.save
current_user.update_attribute(:"allow_#{auth['provider']}_sync",
true)
PullSocialActionsWorker.perform_async(current_user.id,
auth["provider"])
redirect_to edit_social_profile_path, flash: { error:
"#{auth["provider"]} Integration is processing" }
else
redirect_to edit_social_profile_path, flash: { error: "An error
has occurred. Please try again." }
end
else
password = Devise.friendly_token[0,20]
athlete = Athlete.new(email: generate_auth_email(params[:provider]),
password: password, password_confirmation: password )
athlete.apply_omniauth(auth)
begin
athlete.subscriptions.build(trial_expiry: DateTime.now + 30,
active: true, account_type_id: AccountType.free.id)
if athlete.save(validate: false)
sign_in athlete, event: :authentication
redirect_to root_path, notice: "Account created and signed in
successfully"
else
redirect_to root_path, flash: { error: "An error has occurred.
Please try again." }
end
rescue ActiveRecord::RecordNotUnique
redirect_to root_path, flash: { error: "The email address you are
trying to connect already exists. Perhaps you
#{ActionController::Base.helpers.link_to "Forgot Your Password?",
new_user_password_path}".html_safe }
end
end
end
def failure
redirect_to root_url, notice: "An Error has occurred. Please try again!"
end
private
def auth
request.env["omniauth.auth"]
end
def generate_auth_email(provider)
if provider == "twitter"
"#{auth.uid}@twitter.com"
else
auth.info.try(:email)
end
end
end
Gemfile:
gem 'omniauth'
gem 'omniauth-facebook', '1.4.0'
I am also using Memcache/Dalli for caching...
gem 'memcachier'
gem 'dalli'
Anyone else run into this issue before?
Added website with a subdomain on Mountain Lion server couldn't be found on other machines
Added website with a subdomain on Mountain Lion server couldn't be found
on other machines
My server is accessible via example.com and I want my website to be
accessed via sub.example.com. I added a website to Mountain Lion server
with domain name that's actually a subdomain; sub.example.com. I than
added a new host name to DNS service, so that the hostname sub.example.com
resolves to the IP address of the server (192.168.1.2).
Now, I can view the website sub.example.com on the server itself, but
other clients in the local network are not able to access the website.
The command nslookup sub.example.com has this result:
Server: 192.168.1.2
Address: 192.168.1.2#53
Name: sub.example.com
Address: 192.168.1.2
Did I configure the website correctly? What's going wrong?
on other machines
My server is accessible via example.com and I want my website to be
accessed via sub.example.com. I added a website to Mountain Lion server
with domain name that's actually a subdomain; sub.example.com. I than
added a new host name to DNS service, so that the hostname sub.example.com
resolves to the IP address of the server (192.168.1.2).
Now, I can view the website sub.example.com on the server itself, but
other clients in the local network are not able to access the website.
The command nslookup sub.example.com has this result:
Server: 192.168.1.2
Address: 192.168.1.2#53
Name: sub.example.com
Address: 192.168.1.2
Did I configure the website correctly? What's going wrong?
Python slow on fetchone, hangs on fetchall
Python slow on fetchone, hangs on fetchall
I'm writing a script to SELECT query a database and parse through ~33,000
records. Unfortunately I'm running into problems at the
cursor.fetchone()/cursor.fetchall() phase of things.
I first tried iterating through the cursor a record at a time like so:
# Run through every record, extract the kanji, then query for FK and weight
printStatus("Starting weight calculations")
while True:
# Get the next row in the cursor
row = cursor.fetchone()
if row == None:
break
# TODO: Determine if there's any kanji in row[2]
weight = float((row[3] + row[4]))/2
printStatus("Weight: " + str(weight))
Based on the output of printStatus (it prints out a timestamp plus
whatever string is passed to it), the script took approximately 1 second
to process each row. This lead me to believe that the query was being
re-run each time the loop iterated (with a LIMIT 1 or something), as it
took ~1 second for the same query to run once in something like
SQLiteStudio [i]and[/i] return all 33,000 rows. I calculated that, at that
rate, it would take around 7 hours to get through all 33,000 records.
Instead of sitting through that, I tried to use cursor.fetchall() instead:
results = cursor.fetchall()
# Run through every record, extract the kanji, then query for FK and weight
printStatus("Starting weight calculations")
for row in results:
# TODO: Determine if there's any kanji in row[2]
weight = float((row[3] + row[4]))/2
printStatus("Weight: " + str(weight))
Unfortunately, the Python executable locked up at 25% CPU and ~6MB of RAM
when it got to the cursor.fetchall() line. I left the script running for
~10 minutes, but nothing happened.
Is ~33,000 returned rows (about 5MB of data) too much for Python to grab
at once? Am I stuck iterating through one at a time? Or is there something
I can do to speed things up?
EDIT: Here's some console output
12:56:26.019000: Adding new column 'weight' and related index to r_ele
12:56:26.019000: Querying database
12:56:28.079000: Starting weight calculations
12:56:28.079000: Weight: 1.0
12:56:28.079000: Weight: 0.5
12:56:28.080000: Weight: 0.5
12:56:28.338000: Weight: 1.0
12:56:28.339000: Weight: 3.0
12:56:28.843000: Weight: 1.5
12:56:28.844000: Weight: 1.0
12:56:28.844000: Weight: 0.5
12:56:28.844000: Weight: 0.5
12:56:28.845000: Weight: 0.5
12:56:29.351000: Weight: 0.5
12:56:29.855000: Weight: 0.5
12:56:29.856000: Weight: 1.0
12:56:30.371000: Weight: 0.5
12:56:30.885000: Weight: 0.5
12:56:31.146000: Weight: 0.5
12:56:31.650000: Weight: 1.0
12:56:32.432000: Weight: 0.5
12:56:32.951000: Weight: 0.5
12:56:32.951000: Weight: 0.5
12:56:32.952000: Weight: 1.0
12:56:33.454000: Weight: 0.5
12:56:33.455000: Weight: 0.5
12:56:33.455000: Weight: 1.0
12:56:33.716000: Weight: 0.5
12:56:33.716000: Weight: 1.0
And here's the SQL query:
SELECT
re.id as _id,
re.fk,
(SELECT k_ele.value FROM k_ele WHERE k_ele.fk = re.fk) as kanji,
(SELECT COUNT(re_pri.value) FROM re_pri WHERE re_pri.fk = re.id) as
re_priority,
(SELECT COUNT(ke_pri.value) FROM ke_pri WHERE ke_pri.fk = (SELECT k_ele.id
FROM k_ele WHERE k_ele.value = (SELECT k_ele.value FROM k_ele WHERE
k_ele.fk = re.fk))) as ke_priority
FROM
r_ele as re
WHERE
(SELECT COUNT(re_pri.value) FROM re_pri WHERE re_pri.fk = re.id) +
(SELECT COUNT(ke_pri.value) FROM ke_pri WHERE ke_pri.fk = (SELECT k_ele.id
FROM k_ele WHERE k_ele.value = (SELECT k_ele.value FROM k_ele WHERE
k_ele.fk = re.fk))) > 0;
I'm writing a script to SELECT query a database and parse through ~33,000
records. Unfortunately I'm running into problems at the
cursor.fetchone()/cursor.fetchall() phase of things.
I first tried iterating through the cursor a record at a time like so:
# Run through every record, extract the kanji, then query for FK and weight
printStatus("Starting weight calculations")
while True:
# Get the next row in the cursor
row = cursor.fetchone()
if row == None:
break
# TODO: Determine if there's any kanji in row[2]
weight = float((row[3] + row[4]))/2
printStatus("Weight: " + str(weight))
Based on the output of printStatus (it prints out a timestamp plus
whatever string is passed to it), the script took approximately 1 second
to process each row. This lead me to believe that the query was being
re-run each time the loop iterated (with a LIMIT 1 or something), as it
took ~1 second for the same query to run once in something like
SQLiteStudio [i]and[/i] return all 33,000 rows. I calculated that, at that
rate, it would take around 7 hours to get through all 33,000 records.
Instead of sitting through that, I tried to use cursor.fetchall() instead:
results = cursor.fetchall()
# Run through every record, extract the kanji, then query for FK and weight
printStatus("Starting weight calculations")
for row in results:
# TODO: Determine if there's any kanji in row[2]
weight = float((row[3] + row[4]))/2
printStatus("Weight: " + str(weight))
Unfortunately, the Python executable locked up at 25% CPU and ~6MB of RAM
when it got to the cursor.fetchall() line. I left the script running for
~10 minutes, but nothing happened.
Is ~33,000 returned rows (about 5MB of data) too much for Python to grab
at once? Am I stuck iterating through one at a time? Or is there something
I can do to speed things up?
EDIT: Here's some console output
12:56:26.019000: Adding new column 'weight' and related index to r_ele
12:56:26.019000: Querying database
12:56:28.079000: Starting weight calculations
12:56:28.079000: Weight: 1.0
12:56:28.079000: Weight: 0.5
12:56:28.080000: Weight: 0.5
12:56:28.338000: Weight: 1.0
12:56:28.339000: Weight: 3.0
12:56:28.843000: Weight: 1.5
12:56:28.844000: Weight: 1.0
12:56:28.844000: Weight: 0.5
12:56:28.844000: Weight: 0.5
12:56:28.845000: Weight: 0.5
12:56:29.351000: Weight: 0.5
12:56:29.855000: Weight: 0.5
12:56:29.856000: Weight: 1.0
12:56:30.371000: Weight: 0.5
12:56:30.885000: Weight: 0.5
12:56:31.146000: Weight: 0.5
12:56:31.650000: Weight: 1.0
12:56:32.432000: Weight: 0.5
12:56:32.951000: Weight: 0.5
12:56:32.951000: Weight: 0.5
12:56:32.952000: Weight: 1.0
12:56:33.454000: Weight: 0.5
12:56:33.455000: Weight: 0.5
12:56:33.455000: Weight: 1.0
12:56:33.716000: Weight: 0.5
12:56:33.716000: Weight: 1.0
And here's the SQL query:
SELECT
re.id as _id,
re.fk,
(SELECT k_ele.value FROM k_ele WHERE k_ele.fk = re.fk) as kanji,
(SELECT COUNT(re_pri.value) FROM re_pri WHERE re_pri.fk = re.id) as
re_priority,
(SELECT COUNT(ke_pri.value) FROM ke_pri WHERE ke_pri.fk = (SELECT k_ele.id
FROM k_ele WHERE k_ele.value = (SELECT k_ele.value FROM k_ele WHERE
k_ele.fk = re.fk))) as ke_priority
FROM
r_ele as re
WHERE
(SELECT COUNT(re_pri.value) FROM re_pri WHERE re_pri.fk = re.id) +
(SELECT COUNT(ke_pri.value) FROM ke_pri WHERE ke_pri.fk = (SELECT k_ele.id
FROM k_ele WHERE k_ele.value = (SELECT k_ele.value FROM k_ele WHERE
k_ele.fk = re.fk))) > 0;
POP3 SSL connection with javamail doesn't work
POP3 SSL connection with javamail doesn't work
I have some troubles with POP3 SSL certificate.
This is my code:
public static void main(String[] args) throws Exception {
Properties props = new Properties();
props.put("mail.host", "pop.gmail.com");
props.put("mail.store.protocol", "pop3s");
props.put("mail.pop3s.port", "995");
props.put("mail.pop3.ssl.trust","pop.gmail.com"); // or "*"
Session session = Session.getInstance(props);
session.setDebug(true);
Store store = session.getStore();
store.connect("mymail@gmail.com","mypassword");
Folder inbox = store.getFolder("INBOX");
if (inbox == null) {
throw new RuntimeException("INBOX Not found");
}
inbox.open(Folder.READ_WRITE);
Message[] messages = inbox.getMessages();
System.out.println("Found "+messages.length+" messages");
inbox.close(false);
store.close();
}
And this is the error during store.connect:
PKIX path building failed:
sun.security.provider.certpath.SunCertPathBuilderException: unable to find
valid certification path to requested target
I read that seems to be an invalid certificate, I also tried to add
"mail.pop3.ssl.trust" property but it did not solve.
What can it be?
Thanks
I have some troubles with POP3 SSL certificate.
This is my code:
public static void main(String[] args) throws Exception {
Properties props = new Properties();
props.put("mail.host", "pop.gmail.com");
props.put("mail.store.protocol", "pop3s");
props.put("mail.pop3s.port", "995");
props.put("mail.pop3.ssl.trust","pop.gmail.com"); // or "*"
Session session = Session.getInstance(props);
session.setDebug(true);
Store store = session.getStore();
store.connect("mymail@gmail.com","mypassword");
Folder inbox = store.getFolder("INBOX");
if (inbox == null) {
throw new RuntimeException("INBOX Not found");
}
inbox.open(Folder.READ_WRITE);
Message[] messages = inbox.getMessages();
System.out.println("Found "+messages.length+" messages");
inbox.close(false);
store.close();
}
And this is the error during store.connect:
PKIX path building failed:
sun.security.provider.certpath.SunCertPathBuilderException: unable to find
valid certification path to requested target
I read that seems to be an invalid certificate, I also tried to add
"mail.pop3.ssl.trust" property but it did not solve.
What can it be?
Thanks
fatal error C1083: Cannot open compiler generated file
fatal error C1083: Cannot open compiler generated file
I have on my (custom made) makefile: OBJS=obj\A\class_A.obj
obj\A\class_A.obj : A\class_A.cpp A\class_A.h
Now, when I manually create folder obj\A - all compiles well. BUT: when I
delete folder A - compiler fails with error message: fatal error C1083:
Cannot open compiler generated file: 'obj\A\class_A.obj': No such file or
directory
so - again - The error occurs on the following folder hierarchy: A
class_A.cpp class_A.h Obj
But does not happen on this: A class_A.cpp class_A.h Obj A
Any ideas? Is this a VS compiler bug?
This, btw, compiles well with Cygwin.
I have on my (custom made) makefile: OBJS=obj\A\class_A.obj
obj\A\class_A.obj : A\class_A.cpp A\class_A.h
Now, when I manually create folder obj\A - all compiles well. BUT: when I
delete folder A - compiler fails with error message: fatal error C1083:
Cannot open compiler generated file: 'obj\A\class_A.obj': No such file or
directory
so - again - The error occurs on the following folder hierarchy: A
class_A.cpp class_A.h Obj
But does not happen on this: A class_A.cpp class_A.h Obj A
Any ideas? Is this a VS compiler bug?
This, btw, compiles well with Cygwin.
How to get Chain of certificates in X509_STORE_CTX object as X509 objects in C code
How to get Chain of certificates in X509_STORE_CTX object as X509 objects
in C code
I want to get access to all certificates from a X509_STORE_CTX object
using openssl C code.
I can get a single certificate like this ctx->cert if I have a pointer to
a X509_STORE_CTX object (X509_STORE_CTX *ctx ) but if there is a chain how
can I get a list of all as X509 objects.
Thanks
in C code
I want to get access to all certificates from a X509_STORE_CTX object
using openssl C code.
I can get a single certificate like this ctx->cert if I have a pointer to
a X509_STORE_CTX object (X509_STORE_CTX *ctx ) but if there is a chain how
can I get a list of all as X509 objects.
Thanks
Monday, 19 August 2013
Inserting new row in table from Ajax dynamically
Inserting new row in table from Ajax dynamically
I am getting json string from the web service and want display that in
html page. I have used ajax for dynamically displaying the row in the
table. But the problem is all record are present in the single row.
Code:
function showall(){
var user = document.getElementById("user_name").value;
alert(user);
var row = $("<tr>");
var nextrow = $("</tr>");
$.ajax({
type: "POST",
url: "webresources/hello/showrequests",
data : user,
success : function(data){
console.log(data);
$.each(data, function(index, store){
$.each(store, function(key,value){
row.append($("<td>").html(value));
});
$('#requests').append(row);
$('#requests').append(nextrow);
});
},
error: function(e){
alert("error"+e+"has occured");
}
});
}
output comes like
col11 | col12 | col13 | col21 | col22 | col23|
And i am expecting like
col11 | col12 | col13 |
col21 | col22 | col23|
What I need to do in ajax more? Thank you
I am getting json string from the web service and want display that in
html page. I have used ajax for dynamically displaying the row in the
table. But the problem is all record are present in the single row.
Code:
function showall(){
var user = document.getElementById("user_name").value;
alert(user);
var row = $("<tr>");
var nextrow = $("</tr>");
$.ajax({
type: "POST",
url: "webresources/hello/showrequests",
data : user,
success : function(data){
console.log(data);
$.each(data, function(index, store){
$.each(store, function(key,value){
row.append($("<td>").html(value));
});
$('#requests').append(row);
$('#requests').append(nextrow);
});
},
error: function(e){
alert("error"+e+"has occured");
}
});
}
output comes like
col11 | col12 | col13 | col21 | col22 | col23|
And i am expecting like
col11 | col12 | col13 |
col21 | col22 | col23|
What I need to do in ajax more? Thank you
Segfault caused by std::ostream::sentry in this overload of stream operator
Segfault caused by std::ostream::sentry in this overload of stream operator
My goal is to overload the << operator so that objects of the Param class
are printed appropriately to standard out.
The Param class is defined in the globals.h and globals.cpp files. Below
these files, there is a main.cpp test program. Further below this are 3
text input files myparam__lb, myparam__mid, and myparam_ub. Put all of
these files into the same directory, and it's a reduced-size version of
the real case in question.
Here is a backtrace from the real case:
#0 0x00007ffff772811e in std::ostream::sentry::sentry(std::ostream&) ()
from /usr/lib/x86_64-linux-gnu/libstdc++.so.6
#1 0x00007ffff7728829 in std::basic_ostream<char, std::char_traits<char>
>& std::__ostream_insert<char, std::char_traits<char>
>(std::basic_ostream<char, std::char_traits<char> >&, char const*, long)
() from /usr/lib/x86_64-linux-gnu/libstdc++.so.6
#2 0x00007ffff7728c0f in std::basic_ostream<char, std::char_traits<char>
>& std::operator<< <std::char_traits<char> >(std::basic_ostream<char,
std::char_traits<char> >&, char const*) () from
/usr/lib/x86_64-linux-gnu/libstdc++.so.6
#3 0x0000000000450d32 in initSimulation5 () at ../simulation5.cpp:809
#4 0x000000000042c853 in Policy::Policy (this=0x7fffffffb090) at
../globals_mode.cpp:183
#5 0x00000000004325c4 in readPoliciesFromScript (policies=...,
filename=...) at ../globals_utilities.cpp:321
#6 0x0000000000436280 in main (argc=1, argv=0x7fffffffe0d8) at
../main.cpp:122
This code was correctly running on another machine, but on the current
machine, it segfaults. (Both machines 64-bit Ubuntu, but different
kernels, Ubuntu versions, etc.)
QUESTION: What is wrong with my code for the overloaded << operator?
globals.h
//globals.h
/* Initialize a Param object with the base file path to the
* text files containing the low, mid, and high estimates.
* If the low, mid, and high estimates are, respectively,
* stored in files
*
* ./input/myparam__lb
* ./input/myparam__mid
* ./input/myparam__ub
*
* then the base file path should be "./input/myparam".
*/
class Param {
public:
Param(string baseFilePath, const int size);
/*! Set Param to its low estimates */
void setLevelLow();
/*! Set Param to its mid estimates */
void setLevelMid();
/*! Set Param to its high estimates */
void setLevelHigh();
/*! Display range of Param values using an ostream */
friend ostream& operator<< (ostream &out, Param &cParam);
/*
* The overloaded operators below allow a Param object to be passed
* to a function as a (const|nonconst) std::vector<double>& and
* return a reference to the appropriate set of values based on
* whether the Param object is set to its low, mid, or high
* estimates.
*/
operator std::vector<double>& () {
if( level < 0 ) return lb;
if( level > 0 ) return ub;
return mid;
}
operator const std::vector<double>& () const {
if( level < 0 ) return lb;
if( level > 0 ) return ub;
return mid;
}
private:
int level;
std::vector<double> lb;
std::vector<double> mid;
std::vector<double> ub;
void readRatesFromFile(std::vector<double>& x, const string filePath,
const int size);
};
globals.cpp
void Param::setLevelLow() { level = -1; }
void Param::setLevelMid() { level = 0; }
void Param::setLevelHigh() { level = 1; }
ostream& operator<< (ostream &out, Param &cParam) {
/* obtain correct level of parameter */
vector<double> *pParam;
switch(cParam.level) {
case -1:
pParam = &(cParam.lb);
out << "-";
break;
case 0:
pParam = &(cParam.mid);
out << "0";
break;
case 1:
pParam = &(cParam.ub);
out << "+";
break;
default:
std::cerr << "level=" << cParam.level << " when calling
<<(ostream&,Param&)";
exit(1);
break;
}
/* obtain value(s) of parameter */
streamsize pre = cout.precision();
cout.precision(5);
out << " Value = ";
double smallest, largest;
smallest = *min_element(pParam->begin(), pParam->end());
largest = *max_element(pParam->begin(), pParam->end());
if(smallest==largest) {
out << smallest;
} else {
out << "[" << fixed << smallest << ", " <<
fixed << largest << "]";
}
cout.precision(pre);
}
Param::Param(string baseFilePath, const int size) {
/* Read lower-bound values from file */
readRatesFromFile(lb, baseFilePath+"__lb", size);
/* Read midpoint estimate values from file */
readRatesFromFile(mid, baseFilePath+"__mid", size);
/* Read upper-bound values from file */
readRatesFromFile(ub, baseFilePath+"__ub", size);
/* by default use midpoint estimate */
setLevelMid();
}
void Param::readRatesFromFile(std::vector<double>& x, const string
filePath, const int size) {
char line[100];
x.clear();
x.resize(size,0.0);
fstream f_in(filePath.c_str(), ios::in);
if(f_in.fail()) {
cerr << "ERROR: Param::param() failed to open file \"" <<
filePath.c_str() << "\". Exiting...\n";
exit(1);
}
for(int i=0; i<size; ++i) {
f_in.getline(line,100);
x[i]=strtod(line,NULL);
}
f_in.close();
}
main.cpp
//main.cpp
#include <iostream>
#include "globals.h"
int main(int argc, char** argv) {
Param d("./myparam",3);
std::cout << d << "\n";
return 0;
}
myparam__lb
0.13
0.24
0.45
myparam__mid
0.29
0.39
0.56
myparam__ub
0.50
0.61
0.72
My goal is to overload the << operator so that objects of the Param class
are printed appropriately to standard out.
The Param class is defined in the globals.h and globals.cpp files. Below
these files, there is a main.cpp test program. Further below this are 3
text input files myparam__lb, myparam__mid, and myparam_ub. Put all of
these files into the same directory, and it's a reduced-size version of
the real case in question.
Here is a backtrace from the real case:
#0 0x00007ffff772811e in std::ostream::sentry::sentry(std::ostream&) ()
from /usr/lib/x86_64-linux-gnu/libstdc++.so.6
#1 0x00007ffff7728829 in std::basic_ostream<char, std::char_traits<char>
>& std::__ostream_insert<char, std::char_traits<char>
>(std::basic_ostream<char, std::char_traits<char> >&, char const*, long)
() from /usr/lib/x86_64-linux-gnu/libstdc++.so.6
#2 0x00007ffff7728c0f in std::basic_ostream<char, std::char_traits<char>
>& std::operator<< <std::char_traits<char> >(std::basic_ostream<char,
std::char_traits<char> >&, char const*) () from
/usr/lib/x86_64-linux-gnu/libstdc++.so.6
#3 0x0000000000450d32 in initSimulation5 () at ../simulation5.cpp:809
#4 0x000000000042c853 in Policy::Policy (this=0x7fffffffb090) at
../globals_mode.cpp:183
#5 0x00000000004325c4 in readPoliciesFromScript (policies=...,
filename=...) at ../globals_utilities.cpp:321
#6 0x0000000000436280 in main (argc=1, argv=0x7fffffffe0d8) at
../main.cpp:122
This code was correctly running on another machine, but on the current
machine, it segfaults. (Both machines 64-bit Ubuntu, but different
kernels, Ubuntu versions, etc.)
QUESTION: What is wrong with my code for the overloaded << operator?
globals.h
//globals.h
/* Initialize a Param object with the base file path to the
* text files containing the low, mid, and high estimates.
* If the low, mid, and high estimates are, respectively,
* stored in files
*
* ./input/myparam__lb
* ./input/myparam__mid
* ./input/myparam__ub
*
* then the base file path should be "./input/myparam".
*/
class Param {
public:
Param(string baseFilePath, const int size);
/*! Set Param to its low estimates */
void setLevelLow();
/*! Set Param to its mid estimates */
void setLevelMid();
/*! Set Param to its high estimates */
void setLevelHigh();
/*! Display range of Param values using an ostream */
friend ostream& operator<< (ostream &out, Param &cParam);
/*
* The overloaded operators below allow a Param object to be passed
* to a function as a (const|nonconst) std::vector<double>& and
* return a reference to the appropriate set of values based on
* whether the Param object is set to its low, mid, or high
* estimates.
*/
operator std::vector<double>& () {
if( level < 0 ) return lb;
if( level > 0 ) return ub;
return mid;
}
operator const std::vector<double>& () const {
if( level < 0 ) return lb;
if( level > 0 ) return ub;
return mid;
}
private:
int level;
std::vector<double> lb;
std::vector<double> mid;
std::vector<double> ub;
void readRatesFromFile(std::vector<double>& x, const string filePath,
const int size);
};
globals.cpp
void Param::setLevelLow() { level = -1; }
void Param::setLevelMid() { level = 0; }
void Param::setLevelHigh() { level = 1; }
ostream& operator<< (ostream &out, Param &cParam) {
/* obtain correct level of parameter */
vector<double> *pParam;
switch(cParam.level) {
case -1:
pParam = &(cParam.lb);
out << "-";
break;
case 0:
pParam = &(cParam.mid);
out << "0";
break;
case 1:
pParam = &(cParam.ub);
out << "+";
break;
default:
std::cerr << "level=" << cParam.level << " when calling
<<(ostream&,Param&)";
exit(1);
break;
}
/* obtain value(s) of parameter */
streamsize pre = cout.precision();
cout.precision(5);
out << " Value = ";
double smallest, largest;
smallest = *min_element(pParam->begin(), pParam->end());
largest = *max_element(pParam->begin(), pParam->end());
if(smallest==largest) {
out << smallest;
} else {
out << "[" << fixed << smallest << ", " <<
fixed << largest << "]";
}
cout.precision(pre);
}
Param::Param(string baseFilePath, const int size) {
/* Read lower-bound values from file */
readRatesFromFile(lb, baseFilePath+"__lb", size);
/* Read midpoint estimate values from file */
readRatesFromFile(mid, baseFilePath+"__mid", size);
/* Read upper-bound values from file */
readRatesFromFile(ub, baseFilePath+"__ub", size);
/* by default use midpoint estimate */
setLevelMid();
}
void Param::readRatesFromFile(std::vector<double>& x, const string
filePath, const int size) {
char line[100];
x.clear();
x.resize(size,0.0);
fstream f_in(filePath.c_str(), ios::in);
if(f_in.fail()) {
cerr << "ERROR: Param::param() failed to open file \"" <<
filePath.c_str() << "\". Exiting...\n";
exit(1);
}
for(int i=0; i<size; ++i) {
f_in.getline(line,100);
x[i]=strtod(line,NULL);
}
f_in.close();
}
main.cpp
//main.cpp
#include <iostream>
#include "globals.h"
int main(int argc, char** argv) {
Param d("./myparam",3);
std::cout << d << "\n";
return 0;
}
myparam__lb
0.13
0.24
0.45
myparam__mid
0.29
0.39
0.56
myparam__ub
0.50
0.61
0.72
X isn't working with nvidia geforce, no screens found
X isn't working with nvidia geforce, no screens found
I recently installed ubuntu on a Lenovo Y500 with a Nvidia geforce chip.
startx does not work.
First I was told that module nvidia did not exist, so I installed
nvidia-current, which eliminated that issue. My X log file says my driver
ought to be supporting my gpu. However, the file also returns the
following warnings:
Falling back to old probe method for vesa
Falling back to old probe method for modesetting
Falling back to old probe method for fbdev
And eventually:
Failed to initialize the NVIDIA GPU at PCI:1:0:0.
Failing initialization o x screen 0
So for some reason my GPU isn't initializing, even though my driver should
be working with it.
Running startx reveals:
NVIDIA: could not open the device file /dev/nvidia0 (Input/Output error).
But that doesn't get recorded in the log file, for some reason. In dev, I
can find the nvidia0 file, but when I nano it it's empty. I suspect this
is because of the file type, not its contents and I'm just being stupid,
but I thought it might be relevant. Nothing else I can think of reveals
anything about this file.
So I thought, maybe it's a permissions issue. Sudo startx returned the
same results. Logging in as root changes nothing.
I am now stuck. I can come up with nothing else. Help me, askubuntu,
you're my only hope!
I recently installed ubuntu on a Lenovo Y500 with a Nvidia geforce chip.
startx does not work.
First I was told that module nvidia did not exist, so I installed
nvidia-current, which eliminated that issue. My X log file says my driver
ought to be supporting my gpu. However, the file also returns the
following warnings:
Falling back to old probe method for vesa
Falling back to old probe method for modesetting
Falling back to old probe method for fbdev
And eventually:
Failed to initialize the NVIDIA GPU at PCI:1:0:0.
Failing initialization o x screen 0
So for some reason my GPU isn't initializing, even though my driver should
be working with it.
Running startx reveals:
NVIDIA: could not open the device file /dev/nvidia0 (Input/Output error).
But that doesn't get recorded in the log file, for some reason. In dev, I
can find the nvidia0 file, but when I nano it it's empty. I suspect this
is because of the file type, not its contents and I'm just being stupid,
but I thought it might be relevant. Nothing else I can think of reveals
anything about this file.
So I thought, maybe it's a permissions issue. Sudo startx returned the
same results. Logging in as root changes nothing.
I am now stuck. I can come up with nothing else. Help me, askubuntu,
you're my only hope!
acceleo get stereotypes' attributs from within a module
acceleo get stereotypes' attributs from within a module
I'm writing a module which writes an LDIF file,
I've a stereotype called 'User' defined by a metaclasse that have many
attributs (username, password, role,..)
The problem is that I cannot access those attributs from within the module..
How should I do!
I'm writing a module which writes an LDIF file,
I've a stereotype called 'User' defined by a metaclasse that have many
attributs (username, password, role,..)
The problem is that I cannot access those attributs from within the module..
How should I do!
VBA - Select Cells from Pivot Table
VBA - Select Cells from Pivot Table
I am quite a novice at VBA and first time posting, so please bear with me.
I am trying to copy data from a pivot table and paste value into a
separate worksheet. I need to leave the macro as flexible as possible to
cater for any potential future changes to the pivot. In essence I would
like to copy (for example) A6:E77, but this row range may need to change
(so to A6:E84, rather than A6:G77) if the underlying data changes. I can
select all the vertical non-blank cells in a discontinguous data set
using:
Range("A6", Range("A1048576").End(xlUp)).Select
However how can I then select all the cells in columns B:E that are
alongside the cells chosen in column A?
I have tried using the following code, but it seems to ignore the
End.(xlUp) command.
Range("A6:E1048576", Range("A6:E1048576").End(xlUp)).Select
Any ideas? I appreciate the help :)
I am quite a novice at VBA and first time posting, so please bear with me.
I am trying to copy data from a pivot table and paste value into a
separate worksheet. I need to leave the macro as flexible as possible to
cater for any potential future changes to the pivot. In essence I would
like to copy (for example) A6:E77, but this row range may need to change
(so to A6:E84, rather than A6:G77) if the underlying data changes. I can
select all the vertical non-blank cells in a discontinguous data set
using:
Range("A6", Range("A1048576").End(xlUp)).Select
However how can I then select all the cells in columns B:E that are
alongside the cells chosen in column A?
I have tried using the following code, but it seems to ignore the
End.(xlUp) command.
Range("A6:E1048576", Range("A6:E1048576").End(xlUp)).Select
Any ideas? I appreciate the help :)
writing in AsynchronousSocketChannel
writing in AsynchronousSocketChannel
I want to respond to browser when browse localhost:8080 but nothing happen
what should i do and what is mt program problem.
this is my complete code: it accept browser connection successfully but
nothing happen!
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousChannelGroup;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class SufeSurf {
public static void main(String[] args) {
int port = 8080;
try {
final AsynchronousChannelGroup group =
AsynchronousChannelGroup.withThreadPool(Executors
.newSingleThreadExecutor());
final AsynchronousServerSocketChannel server =
AsynchronousServerSocketChannel.open(group).bind(
new InetSocketAddress(port));
System.out.println("Server listening on " + port);
server.accept("Client connection",
new CompletionHandler<AsynchronousSocketChannel,
Object>() {
public void completed(AsynchronousSocketChannel ch, Object
att) {
System.out.println("Accepted a connection");
ch.write(ByteBuffer.wrap("aaa".getBytes()));
// accept the next connection
server.accept("Client connection", this);
}
public void failed(Throwable exc, Object att) {
System.out.println("Failed to accept connection");
}
});
group.awaitTermination(Long.MAX_VALUE, TimeUnit.SECONDS);
} catch (IOException | InterruptedException e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}
}
any help apperciated!
I want to respond to browser when browse localhost:8080 but nothing happen
what should i do and what is mt program problem.
this is my complete code: it accept browser connection successfully but
nothing happen!
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousChannelGroup;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class SufeSurf {
public static void main(String[] args) {
int port = 8080;
try {
final AsynchronousChannelGroup group =
AsynchronousChannelGroup.withThreadPool(Executors
.newSingleThreadExecutor());
final AsynchronousServerSocketChannel server =
AsynchronousServerSocketChannel.open(group).bind(
new InetSocketAddress(port));
System.out.println("Server listening on " + port);
server.accept("Client connection",
new CompletionHandler<AsynchronousSocketChannel,
Object>() {
public void completed(AsynchronousSocketChannel ch, Object
att) {
System.out.println("Accepted a connection");
ch.write(ByteBuffer.wrap("aaa".getBytes()));
// accept the next connection
server.accept("Client connection", this);
}
public void failed(Throwable exc, Object att) {
System.out.println("Failed to accept connection");
}
});
group.awaitTermination(Long.MAX_VALUE, TimeUnit.SECONDS);
} catch (IOException | InterruptedException e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}
}
any help apperciated!
Sunday, 18 August 2013
whats the difference between ns4 and ns2 soap client
whats the difference between ns4 and ns2 soap client
I have a code which I am trying to understand..I see the following in the
code..whats the difference between ns4 and ns2?where can i GET more info
on this?
request = self.search_soapclient.factory.create('ns4:SearchRequest')
subquery =
self.search_soapclient.factory.create('ns2:SubQueryCriteriaEntity')
I have a code which I am trying to understand..I see the following in the
code..whats the difference between ns4 and ns2?where can i GET more info
on this?
request = self.search_soapclient.factory.create('ns4:SearchRequest')
subquery =
self.search_soapclient.factory.create('ns2:SubQueryCriteriaEntity')
Is there a way to know if a user pressed the key ENTER using readline() method? - Java
Is there a way to know if a user pressed the key ENTER using readline()
method? - Java
I want to recognize if a user sent a text, using readline method from
BufferedReader. While the user didn't send anything, the Thread keeps
sleeping. Is there a way to do this? I'm trying for a long time, but no
success yet.. I guess I have to recognize if a ENTER key was pressed.. but
I donwt know how to do this.. The interface of my program is the console..
method? - Java
I want to recognize if a user sent a text, using readline method from
BufferedReader. While the user didn't send anything, the Thread keeps
sleeping. Is there a way to do this? I'm trying for a long time, but no
success yet.. I guess I have to recognize if a ENTER key was pressed.. but
I donwt know how to do this.. The interface of my program is the console..
iRedMail Debian Server Has Stopped Sending Mail
iRedMail Debian Server Has Stopped Sending Mail
My Debian 7 IRedmail server has stopped sending mail. I have looked in
/var/log/mail.(log/err/warn)
and found no errors to show.
My Debian 7 IRedmail server has stopped sending mail. I have looked in
/var/log/mail.(log/err/warn)
and found no errors to show.
car park charge according to vehicle type
car park charge according to vehicle type
Write a program called "Car Park Program" that, given the type of vehicle
('c' for car, 'b' for bus, 't' for truck) and the hours a vehicle spent in
the parking lot, returns the parking fee based on the rates shown below.
Car $2 per hour Bus $3 per hour Truck $4 per hour
This is my answer, but its wrong on line 16 where it says: ( if type==c )
why is it wrong???
#include <stdio.h>
main()
{
char type;
float hours, fee;
printf("\n\nCar Park Program: ");
printf("\n\n-----------------------------------");
printf("\n\nType of vehicle");
printf("\n\nc-Car");
printf("\n\nb-Bus");
printf("\n\nt-Truck");
printf("\n\nEnter type of vehicle: ");
scanf("%c", &type);
printf("Number of hours: ");
scanf("%f", &hours);
if (type==c)
{
fee=2*hours;
printf("\n\n\nParking fee: $.2f \n\n\n\n", fee);
}
if (type==b)
{
fee=3*hours;
printf("\n\n\nParking fee: $.2f \n\n\n\n", fee);
}
if (type==t)
{
fee=4*hours;
printf("\n\n\nParking fee: $.2f \n\n\n\n", fee);
}
}
Write a program called "Car Park Program" that, given the type of vehicle
('c' for car, 'b' for bus, 't' for truck) and the hours a vehicle spent in
the parking lot, returns the parking fee based on the rates shown below.
Car $2 per hour Bus $3 per hour Truck $4 per hour
This is my answer, but its wrong on line 16 where it says: ( if type==c )
why is it wrong???
#include <stdio.h>
main()
{
char type;
float hours, fee;
printf("\n\nCar Park Program: ");
printf("\n\n-----------------------------------");
printf("\n\nType of vehicle");
printf("\n\nc-Car");
printf("\n\nb-Bus");
printf("\n\nt-Truck");
printf("\n\nEnter type of vehicle: ");
scanf("%c", &type);
printf("Number of hours: ");
scanf("%f", &hours);
if (type==c)
{
fee=2*hours;
printf("\n\n\nParking fee: $.2f \n\n\n\n", fee);
}
if (type==b)
{
fee=3*hours;
printf("\n\n\nParking fee: $.2f \n\n\n\n", fee);
}
if (type==t)
{
fee=4*hours;
printf("\n\n\nParking fee: $.2f \n\n\n\n", fee);
}
}
Why operator && does not work in WordPress Javascript/jQuery code?
Why operator && does not work in WordPress Javascript/jQuery code?
I'm creating web site in WordPress, but suddenly && operator stopped
working in Javascript/jQuery codes. For example the code
<p>Click the button to trigger a function.</p>
<button onclick="myFunction()">Click me</button>
<p id="demo"></p>
<script>
function myFunction()
{
var x=9, y=3;
if (x < 10 && y > 1){
document.getElementById("demo").innerHTML="Hello World";
}
}
</script>
perfectly is working without WordPress, but inside WordPress there are no
result after clicking the button. The code is working inside WordPress
without && operator (e.g. if (x < 10)) or using the || operator instead of
&&.
I'm creating web site in WordPress, but suddenly && operator stopped
working in Javascript/jQuery codes. For example the code
<p>Click the button to trigger a function.</p>
<button onclick="myFunction()">Click me</button>
<p id="demo"></p>
<script>
function myFunction()
{
var x=9, y=3;
if (x < 10 && y > 1){
document.getElementById("demo").innerHTML="Hello World";
}
}
</script>
perfectly is working without WordPress, but inside WordPress there are no
result after clicking the button. The code is working inside WordPress
without && operator (e.g. if (x < 10)) or using the || operator instead of
&&.
Reading from a file or a big database
Reading from a file or a big database
I have a list of 100000 products. I wish to store the specs of the
products, no search on these specs.
Two ways that I can think of are
To store the specs as key-value pair in a mysql database
Store the values in a file and just read from there.
Which of the two ways mentioned will be space and read efficient, given I
am not going to search on those key-value pairs.
Any other approach to solve the problem efficiently will be appreciated.
Thanks !
I have a list of 100000 products. I wish to store the specs of the
products, no search on these specs.
Two ways that I can think of are
To store the specs as key-value pair in a mysql database
Store the values in a file and just read from there.
Which of the two ways mentioned will be space and read efficient, given I
am not going to search on those key-value pairs.
Any other approach to solve the problem efficiently will be appreciated.
Thanks !
Saturday, 17 August 2013
Auth::logout() is ignored in Laravel 4
Auth::logout() is ignored in Laravel 4
I have one user class which consists of two types of users and want to
allow different users to go to different pages.
I have created a filter as follows
Route::filter('isExpert', function()
{
$userIsExpert = 0;
$userIsLoggedIn = Auth::check();
if ($userIsLoggedIn && Auth::user()->role == 'expert') {
$userIsExpert = 1;
}
Log::info('Logged in: ' . $userIsLoggedIn . ' && Expert: ' .
$userIsExpert);
if ($userIsExpert == 0)
{
Log::info('should be logging out now.');
Auth::logout();
return Auth::basic();
}
});
And routing like so
Route::get('/winners', array('before' => 'isExpert', function()
{
$winners = DB::select('select * from winners');
return View::make('winners.index')->with('winners',$winners);
}));
The thought is this: If it's not an expert, it will logout and redirect to
login page. If it is, it will simply continue. However, Auth::logout();
doesn't ever log out the user.
Question
Why is not Auth::logout() working? I've tried placing it anywhere in the
app to no avail.
cheers
I have one user class which consists of two types of users and want to
allow different users to go to different pages.
I have created a filter as follows
Route::filter('isExpert', function()
{
$userIsExpert = 0;
$userIsLoggedIn = Auth::check();
if ($userIsLoggedIn && Auth::user()->role == 'expert') {
$userIsExpert = 1;
}
Log::info('Logged in: ' . $userIsLoggedIn . ' && Expert: ' .
$userIsExpert);
if ($userIsExpert == 0)
{
Log::info('should be logging out now.');
Auth::logout();
return Auth::basic();
}
});
And routing like so
Route::get('/winners', array('before' => 'isExpert', function()
{
$winners = DB::select('select * from winners');
return View::make('winners.index')->with('winners',$winners);
}));
The thought is this: If it's not an expert, it will logout and redirect to
login page. If it is, it will simply continue. However, Auth::logout();
doesn't ever log out the user.
Question
Why is not Auth::logout() working? I've tried placing it anywhere in the
app to no avail.
cheers
Remapping keys - only modifiers?
Remapping keys - only modifiers?
Are the modifier keys (shift, ctrl, alt, meta, super) the only keys that
can be remapped? Is there any distinction between right and left
modifiers? How do I know what synergy defines as Meta and Super?
I have Win7 as server and OS X as client and a nice, Matias Tactile Pro
keyboard. I want to block the Windows key on the Win7 side but have a
Command key on the SO X side. I think if I can map the Windows key to
"Meta" (or something else innocuous) in Win7, I can have Synergy remap it
to Command for OS X.
I'm open to other suggestions.
Are the modifier keys (shift, ctrl, alt, meta, super) the only keys that
can be remapped? Is there any distinction between right and left
modifiers? How do I know what synergy defines as Meta and Super?
I have Win7 as server and OS X as client and a nice, Matias Tactile Pro
keyboard. I want to block the Windows key on the Win7 side but have a
Command key on the SO X side. I think if I can map the Windows key to
"Meta" (or something else innocuous) in Win7, I can have Synergy remap it
to Command for OS X.
I'm open to other suggestions.
Does empty have a gradable antonym in English?
Does empty have a gradable antonym in English?
Empty doesn't seem to have a gradable antonym. If something is not empty
and not full, then it is not empty, but is there a single word expression
for this?
Edit: To make it more evident, I'm looking for something like what warm is
on the scale of cold and hot.
Empty doesn't seem to have a gradable antonym. If something is not empty
and not full, then it is not empty, but is there a single word expression
for this?
Edit: To make it more evident, I'm looking for something like what warm is
on the scale of cold and hot.
Error: Array type has incomplete element type and binary operand error
Error: Array type has incomplete element type and binary operand error
I am trying to make a multi-program database in C.
Here is the code:
#include<stdio.h>
#include<stdlib.h>
#include "function.c"
int main()
{
info();
example();
printf("\n\n\n");
char name[1][10], id[1][10], grade[1][1];
char choice;
int x=0;
int sal[1];
FILE *fp;
printf("Would you like to continue? Y/N: ");
scanf("%c",&choice);
fflush(stdin);
if(choice == 'Y' || choice == 'y')
{
system("cls");
fp = fopen("database.txt","w");
if(fp == NULL)
{
printf("File does not exist!");
return 0;
}
else
{
while(x<=1)
{
printf("Enter Employee name no.%d: ",(x+1));
scanf("%s",name[x]);
fprintf(fp, "Employee Name: %s\n",name);
printf("Enter Employee ID: ");
scanf("%s",id[x]);
fprintf(fp, "Employee ID: %s\n",id);
printf("Enter Employee Grade Level (A-E): ");
scanf("%s",grade[x]);
fprintf(fp, "Employee Grade Level: %s\n",grade);
printf("Enter Employee's Basic Salary: ");
scanf("%d",&sal[x]);
fprintf(fp, "Employee's Basic Salary: %d\n\n\n",sal);
printf("Employee's bonus: %d\n",bonus(grade[x],sal[x]));
printf("Employee's allowance: %d\n",allowance(grade[x], sal[x]));
printf("\n");
}
}
fclose(fp);
}
else
{
return 0;
}
return 0;
}
function.c :
#include<stdio.h>
#include "function.h"
int bonus(char *grade[1][], int *sal[])
{
int bonus;
int *b;
int x;
b = &bonus;
for(x=0;x<=1;x++)
{
switch(*grade[x])
{
case 'A':
bonus = (1/4) * *sal[x];
break;
case 'B':
bonus = (1/5) * *sal[x];
break;
case 'C':
bonus = (15/100) * *sal[x];
break;
case 'D':
bonus = (1/10) * *sal[x];
break;
case 'E':
bonus = (5/100) * *sal[x];
break;
default:
printf("Invalid Choice!!");
break;
}
return bonus;
}
}
int allowance(char *grade[1][], int *sal[])
{
int all;
int *a;
int x;
a = &all;
for(x=0;x<=1;x++)
{
switch(*grade[x])
{
case 'A':
all = (3/10) * *sal[x];
break;
case 'B':
all = (6/25) * *sal[x];
break;
case 'C':
all = (9/50) * *sal[x];
break;
case 'D':
all = (3/25) * *sal[x];
break;
case 'E':
all = (3/50) * *sal[x];
break;
default:
printf("Invalid Choice!!");
break;
}
return all;
}
}
When I try to run the program, I get:
2 0 C:\Users\nithin\Desktop\Online Courses\C Programming\Final
Project\function.c In file included from C:\Users\nithin\Desktop\Online
Courses\C Programming\Final Project\function.c 4 17
C:\Users\nithin\Desktop\Online Courses\C Programming\Final
Project\function.h [Error] array type has incomplete element type 5 21
C:\Users\nithin\Desktop\Online Courses\C Programming\Final
Project\function.h [Error] array type has incomplete element type 4 17
C:\Users\nithin\Desktop\Online Courses\C Programming\Final
Project\function.c [Error] array type has incomplete element type
C:\Users\nithin\Desktop\Online Courses\C Programming\Final
Project\function.c In function 'bonus': 18 19
C:\Users\nithin\Desktop\Online Courses\C Programming\Final
Project\function.c [Error] invalid operands to binary * (have 'int' and
'int *') 21 19 C:\Users\nithin\Desktop\Online Courses\C Programming\Final
Project\function.c [Error] invalid operands to binary * (have 'int' and
'int *') 24 22 C:\Users\nithin\Desktop\Online Courses\C Programming\Final
Project\function.c [Error] invalid operands to binary * (have 'int' and
'int *') 27 20 C:\Users\nithin\Desktop\Online Courses\C Programming\Final
Project\function.c [Error] invalid operands to binary * (have 'int' and
'int *') 30 21 C:\Users\nithin\Desktop\Online Courses\C Programming\Final
Project\function.c [Error] invalid operands to binary * (have 'int' and
'int *') C:\Users\nithin\Desktop\Online Courses\C Programming\Final
Project\function.c At top level: 41 21 C:\Users\nithin\Desktop\Online
Courses\C Programming\Final Project\function.c [Error] array type has
incomplete element type C:\Users\nithin\Desktop\Online Courses\C
Programming\Final Project\function.c In function 'allowance': 54 17
C:\Users\nithin\Desktop\Online Courses\C Programming\Final
Project\function.c [Error] invalid operands to binary * (have 'int' and
'int *') 57 17 C:\Users\nithin\Desktop\Online Courses\C Programming\Final
Project\function.c [Error] invalid operands to binary * (have 'int' and
'int *') 60 17 C:\Users\nithin\Desktop\Online Courses\C Programming\Final
Project\function.c [Error] invalid operands to binary * (have 'int' and
'int *') 63 17 C:\Users\nithin\Desktop\Online Courses\C Programming\Final
Project\function.c [Error] invalid operands to binary * (have 'int' and
'int *') 66 17 C:\Users\nithin\Desktop\Online Courses\C Programming\Final
Project\function.c [Error] invalid operands to binary * (have 'int' and
'int *')
I do not know what the problem is (I'm a beginner in C programming).
My first question: What does array type has incomplete element type mean?
Next question: Why am I still getting the invalid operands to binary *
error?
Any help would be appreciated.
I am trying to make a multi-program database in C.
Here is the code:
#include<stdio.h>
#include<stdlib.h>
#include "function.c"
int main()
{
info();
example();
printf("\n\n\n");
char name[1][10], id[1][10], grade[1][1];
char choice;
int x=0;
int sal[1];
FILE *fp;
printf("Would you like to continue? Y/N: ");
scanf("%c",&choice);
fflush(stdin);
if(choice == 'Y' || choice == 'y')
{
system("cls");
fp = fopen("database.txt","w");
if(fp == NULL)
{
printf("File does not exist!");
return 0;
}
else
{
while(x<=1)
{
printf("Enter Employee name no.%d: ",(x+1));
scanf("%s",name[x]);
fprintf(fp, "Employee Name: %s\n",name);
printf("Enter Employee ID: ");
scanf("%s",id[x]);
fprintf(fp, "Employee ID: %s\n",id);
printf("Enter Employee Grade Level (A-E): ");
scanf("%s",grade[x]);
fprintf(fp, "Employee Grade Level: %s\n",grade);
printf("Enter Employee's Basic Salary: ");
scanf("%d",&sal[x]);
fprintf(fp, "Employee's Basic Salary: %d\n\n\n",sal);
printf("Employee's bonus: %d\n",bonus(grade[x],sal[x]));
printf("Employee's allowance: %d\n",allowance(grade[x], sal[x]));
printf("\n");
}
}
fclose(fp);
}
else
{
return 0;
}
return 0;
}
function.c :
#include<stdio.h>
#include "function.h"
int bonus(char *grade[1][], int *sal[])
{
int bonus;
int *b;
int x;
b = &bonus;
for(x=0;x<=1;x++)
{
switch(*grade[x])
{
case 'A':
bonus = (1/4) * *sal[x];
break;
case 'B':
bonus = (1/5) * *sal[x];
break;
case 'C':
bonus = (15/100) * *sal[x];
break;
case 'D':
bonus = (1/10) * *sal[x];
break;
case 'E':
bonus = (5/100) * *sal[x];
break;
default:
printf("Invalid Choice!!");
break;
}
return bonus;
}
}
int allowance(char *grade[1][], int *sal[])
{
int all;
int *a;
int x;
a = &all;
for(x=0;x<=1;x++)
{
switch(*grade[x])
{
case 'A':
all = (3/10) * *sal[x];
break;
case 'B':
all = (6/25) * *sal[x];
break;
case 'C':
all = (9/50) * *sal[x];
break;
case 'D':
all = (3/25) * *sal[x];
break;
case 'E':
all = (3/50) * *sal[x];
break;
default:
printf("Invalid Choice!!");
break;
}
return all;
}
}
When I try to run the program, I get:
2 0 C:\Users\nithin\Desktop\Online Courses\C Programming\Final
Project\function.c In file included from C:\Users\nithin\Desktop\Online
Courses\C Programming\Final Project\function.c 4 17
C:\Users\nithin\Desktop\Online Courses\C Programming\Final
Project\function.h [Error] array type has incomplete element type 5 21
C:\Users\nithin\Desktop\Online Courses\C Programming\Final
Project\function.h [Error] array type has incomplete element type 4 17
C:\Users\nithin\Desktop\Online Courses\C Programming\Final
Project\function.c [Error] array type has incomplete element type
C:\Users\nithin\Desktop\Online Courses\C Programming\Final
Project\function.c In function 'bonus': 18 19
C:\Users\nithin\Desktop\Online Courses\C Programming\Final
Project\function.c [Error] invalid operands to binary * (have 'int' and
'int *') 21 19 C:\Users\nithin\Desktop\Online Courses\C Programming\Final
Project\function.c [Error] invalid operands to binary * (have 'int' and
'int *') 24 22 C:\Users\nithin\Desktop\Online Courses\C Programming\Final
Project\function.c [Error] invalid operands to binary * (have 'int' and
'int *') 27 20 C:\Users\nithin\Desktop\Online Courses\C Programming\Final
Project\function.c [Error] invalid operands to binary * (have 'int' and
'int *') 30 21 C:\Users\nithin\Desktop\Online Courses\C Programming\Final
Project\function.c [Error] invalid operands to binary * (have 'int' and
'int *') C:\Users\nithin\Desktop\Online Courses\C Programming\Final
Project\function.c At top level: 41 21 C:\Users\nithin\Desktop\Online
Courses\C Programming\Final Project\function.c [Error] array type has
incomplete element type C:\Users\nithin\Desktop\Online Courses\C
Programming\Final Project\function.c In function 'allowance': 54 17
C:\Users\nithin\Desktop\Online Courses\C Programming\Final
Project\function.c [Error] invalid operands to binary * (have 'int' and
'int *') 57 17 C:\Users\nithin\Desktop\Online Courses\C Programming\Final
Project\function.c [Error] invalid operands to binary * (have 'int' and
'int *') 60 17 C:\Users\nithin\Desktop\Online Courses\C Programming\Final
Project\function.c [Error] invalid operands to binary * (have 'int' and
'int *') 63 17 C:\Users\nithin\Desktop\Online Courses\C Programming\Final
Project\function.c [Error] invalid operands to binary * (have 'int' and
'int *') 66 17 C:\Users\nithin\Desktop\Online Courses\C Programming\Final
Project\function.c [Error] invalid operands to binary * (have 'int' and
'int *')
I do not know what the problem is (I'm a beginner in C programming).
My first question: What does array type has incomplete element type mean?
Next question: Why am I still getting the invalid operands to binary *
error?
Any help would be appreciated.
Check the surroundings neighbors of a certain cell in matrix Matlab
Check the surroundings neighbors of a certain cell in matrix Matlab
I have a matrix A size 480x640, for each pixel I want to check its
neighbours. The neighbours of the pixel arr determined by a value N. For
example this is a part of matrix A where all the zeros are the neighbours
of pixel X when N=3:
0 0 0 0 0 0 0
0 0 0 0 0 0 0
0 0 0 0 0 0 0
0 0 0 X 0 0 0
0 0 0 0 0 0 0
0 0 0 0 0 0 0
0 0 0 0 0 0 0
so as shown, because N=3 then all these zeros are considered the pixel X
neighbours. The problem is if X will be located before the index N=3 as
shown here the neighbours will be pixels having the one values:
X 1 1 1 0 0 0
1 1 1 1 0 0 0
1 1 1 1 0 0 0
1 1 1 1 0 0 0
0 0 0 0 0 0 0
0 0 0 0 0 0 0
0 0 0 0 0 0 0
So If anyone could advise how can I handle this?
I have a matrix A size 480x640, for each pixel I want to check its
neighbours. The neighbours of the pixel arr determined by a value N. For
example this is a part of matrix A where all the zeros are the neighbours
of pixel X when N=3:
0 0 0 0 0 0 0
0 0 0 0 0 0 0
0 0 0 0 0 0 0
0 0 0 X 0 0 0
0 0 0 0 0 0 0
0 0 0 0 0 0 0
0 0 0 0 0 0 0
so as shown, because N=3 then all these zeros are considered the pixel X
neighbours. The problem is if X will be located before the index N=3 as
shown here the neighbours will be pixels having the one values:
X 1 1 1 0 0 0
1 1 1 1 0 0 0
1 1 1 1 0 0 0
1 1 1 1 0 0 0
0 0 0 0 0 0 0
0 0 0 0 0 0 0
0 0 0 0 0 0 0
So If anyone could advise how can I handle this?
Squid3 trying to add a custom external_acl_type
Squid3 trying to add a custom external_acl_type
I'm trying to create an external acl helper for squid3 to (hopefully) cut
down some config lines from my squid3 server and I wrote a simple python
script for it:
#!/usr/bin/python
import sys
import logging
import time
logger = logging.getLogger( 'squid_auth' )
logger.setLevel( logging.DEBUG )
fh = logging.FileHandler( 'spam.log' )
fh.setLevel( logging.DEBUG )
formatter = logging.Formatter( '%(asctime)s - %(name)s - %(levelname)s -
%(message)s' )
fh.setFormatter( formatter )
logger.addHandler( fh )
def grant ():
sys.stdout.write( 'OK\n' )
sys.stdout.flush()
def deny ():
sys.stdout.write( 'ERR\n' )
sys.stdout.flush()
while True:
line = sys.stdin.readline().strip()
if line:
logger.info( line )
grant()
else:
time.sleep( 1 )
and added it into my squid.conf:
external_acl_type custom_acl %SRC %LOGIN %DST
/etc/changemyip/squid/config/acl.py
acl CustomAcl external custom_acl
http_access allow CustomAcl
The path to the script is right (I can execute it in shell), the program
has execute rights and everything but, when I reload squid I get this
error about 5-6 times then squid crashes:
Aug 17 14:08:52 server7 (squid): The custom_acl helpers are crashing too
rapidly, need help!
Aug 17 14:08:52 server7 squid[28233]: Squid Parent: child process 28290
exited with status 1
Aug 17 14:08:52 server7 squid[28233]: Exiting due to repeated, frequent
failures
As you can see the script is just printing OK\n to the stdout to grant
everyone. I haven't even started implementing any logic to it.
Tested with squid version: 3.1.19
I'm trying to create an external acl helper for squid3 to (hopefully) cut
down some config lines from my squid3 server and I wrote a simple python
script for it:
#!/usr/bin/python
import sys
import logging
import time
logger = logging.getLogger( 'squid_auth' )
logger.setLevel( logging.DEBUG )
fh = logging.FileHandler( 'spam.log' )
fh.setLevel( logging.DEBUG )
formatter = logging.Formatter( '%(asctime)s - %(name)s - %(levelname)s -
%(message)s' )
fh.setFormatter( formatter )
logger.addHandler( fh )
def grant ():
sys.stdout.write( 'OK\n' )
sys.stdout.flush()
def deny ():
sys.stdout.write( 'ERR\n' )
sys.stdout.flush()
while True:
line = sys.stdin.readline().strip()
if line:
logger.info( line )
grant()
else:
time.sleep( 1 )
and added it into my squid.conf:
external_acl_type custom_acl %SRC %LOGIN %DST
/etc/changemyip/squid/config/acl.py
acl CustomAcl external custom_acl
http_access allow CustomAcl
The path to the script is right (I can execute it in shell), the program
has execute rights and everything but, when I reload squid I get this
error about 5-6 times then squid crashes:
Aug 17 14:08:52 server7 (squid): The custom_acl helpers are crashing too
rapidly, need help!
Aug 17 14:08:52 server7 squid[28233]: Squid Parent: child process 28290
exited with status 1
Aug 17 14:08:52 server7 squid[28233]: Exiting due to repeated, frequent
failures
As you can see the script is just printing OK\n to the stdout to grant
everyone. I haven't even started implementing any logic to it.
Tested with squid version: 3.1.19
Calculate the highest palindrome that is the product of two 3-digit numbers
Calculate the highest palindrome that is the product of two 3-digit numbers
I'm stuck on Euler#4 which is to calculate the highest palindrome number
by product of two 3-digit numbers. The answer I'm getting is always 0.
Evidently help is required.
#include <stdio.h>
#include <conio.h>
int main()
{
int i,j,h=0,m=0,p=0;
clrscr();
for(i=100;i<1000;i++)
{
for(j=100;j<1000;j++)
{
p=i*j;
h=p/100000;
m=p%10;
if(h==m)
{
h=(p/10000)%10;
m=(p/10)%10;
if(h==m)
{
h=(p/1000)%10;
m=(p%1000)/100;
if(h==p)
{
printf("%d\n",p);
}
}
}
}
}
return 0;
}
I'm stuck on Euler#4 which is to calculate the highest palindrome number
by product of two 3-digit numbers. The answer I'm getting is always 0.
Evidently help is required.
#include <stdio.h>
#include <conio.h>
int main()
{
int i,j,h=0,m=0,p=0;
clrscr();
for(i=100;i<1000;i++)
{
for(j=100;j<1000;j++)
{
p=i*j;
h=p/100000;
m=p%10;
if(h==m)
{
h=(p/10000)%10;
m=(p/10)%10;
if(h==m)
{
h=(p/1000)%10;
m=(p%1000)/100;
if(h==p)
{
printf("%d\n",p);
}
}
}
}
}
return 0;
}
Subscribe to:
Comments (Atom)