Copy file to clipboard in Delphi
Anybody know how to copy file in Delphi? It likes press Ctrl+ C on a file
or folder, and then we can Paste at somewhere ? I just know how to copy a
text by Clipbrd Unit, but i don't know with a file, folder ! Please help
me !
Saturday, 31 August 2013
can the order of code make this program faster?
can the order of code make this program faster?
Hi this is my first post, I am learning how to write code so technically I
am a newbie.
I am learning python I am still at the very basics, I was getting to Know
the if statement and I tried to mix it with another concepts(function
definition,input,variables) in order to get a wider vision of python, I
wrote some code without a specific idea of what I wanted to do I just
wanted to mix everything that I have learned so far so probably I over do
it and its not practical, it "works" when I run it.
The question that I have its not about how to do it more efficient or with
less code it is about the order of code in all programming in general.
Here I'll show 2 different order of code that gives the same result with
exactly the same code(but with different order).
on (1) I define a function on the first line.
on (2) I define the same function closer to when I use it on line 5.
which one is faster? is defining a function "closer" to when I need it
impractical for the complexity of larger programs(but does it make it
faster), or defining a function "far" from where I need it makes a larger
program slower when running(but also more practical).
(1)
def t(n1,n2):
v=n1-n2
return abs(v)
a = int(input('how old are you? \n'))
b = int(input('how old is your best friend? \n'))
c=t(a,b)
if a==b:
print ('you are both the same age')
else:
print('you are not the same age\nthe difference of years is %s
year(s)' % c)
input()
(2)
a = int(input('how old are you? \n'))
b = int(input('how old is your best friend? \n'))
def t(n1,n2):
v=n1-n2
return abs(v)
c=t(a,b)
if a==b:
print ('you are both the same age')
else:
print('you are not the same age\nthe difference of years is %s
year(s)' % c)
input()
Hi this is my first post, I am learning how to write code so technically I
am a newbie.
I am learning python I am still at the very basics, I was getting to Know
the if statement and I tried to mix it with another concepts(function
definition,input,variables) in order to get a wider vision of python, I
wrote some code without a specific idea of what I wanted to do I just
wanted to mix everything that I have learned so far so probably I over do
it and its not practical, it "works" when I run it.
The question that I have its not about how to do it more efficient or with
less code it is about the order of code in all programming in general.
Here I'll show 2 different order of code that gives the same result with
exactly the same code(but with different order).
on (1) I define a function on the first line.
on (2) I define the same function closer to when I use it on line 5.
which one is faster? is defining a function "closer" to when I need it
impractical for the complexity of larger programs(but does it make it
faster), or defining a function "far" from where I need it makes a larger
program slower when running(but also more practical).
(1)
def t(n1,n2):
v=n1-n2
return abs(v)
a = int(input('how old are you? \n'))
b = int(input('how old is your best friend? \n'))
c=t(a,b)
if a==b:
print ('you are both the same age')
else:
print('you are not the same age\nthe difference of years is %s
year(s)' % c)
input()
(2)
a = int(input('how old are you? \n'))
b = int(input('how old is your best friend? \n'))
def t(n1,n2):
v=n1-n2
return abs(v)
c=t(a,b)
if a==b:
print ('you are both the same age')
else:
print('you are not the same age\nthe difference of years is %s
year(s)' % c)
input()
NSMutableArray with Cyrillic text
NSMutableArray with Cyrillic text
I try to load words from a txt file using following code:
NSURL *filePath = [[NSBundle mainBundle] URLForResource:@"testFile"
withExtension:@"txt"];
NSString*stringPath = [filePath absoluteString];
NSData *drfData = [NSData dataWithContentsOfURL:[NSURL
URLWithString:stringPath]];
NSString *str = [[NSString alloc]initWithData:drfData
encoding:NSUTF8StringEncoding];
Works great, even if I use cyrillic words ("ïðèâåò").
Now, I use following code to add each word as object to my NSMutableArray.
To detect what is a word, I separated them by comma in my testFile.txt
document.
int nLastPoint = 0;
int nCount = 0;
for (int i = 0; i< str.length; i++) {
if ([[str substringWithRange:NSMakeRange(i,
1)]isEqualToString:@","]) {
[lst_wordlist addObject:[[[str
substringWithRange:NSMakeRange(nLastPoint, nCount)]
stringByTrimmingCharactersInSet:[NSCharacterSet
whitespaceAndNewlineCharacterSet]] uppercaseString]];
nLastPoint = i+1;
nCount = 0;
}else{
nCount++;
}
}
int nLength = 0;
for (int i = 0; i< [lst_wordlist count]; i++) {
if ([[lst_wordlist objectAtIndex:i]length]>nLength) {
nLength = [[lst_wordlist objectAtIndex:i]length];
}
}
NSLog(@"%@",lst_wordlist);
Works great, again ONLY if I use english words. With Cyrillic words
doesn't work.
This is my NSLog when I use a cyrillic word.
"\U041f\U0420\U0418\U0412\U0415\U0422",
WORD2,
WORD3,
Any ideas? How can I fix it? I tried to change debugger from LLDB to GDB,
doesn't fix the problem.
I try to load words from a txt file using following code:
NSURL *filePath = [[NSBundle mainBundle] URLForResource:@"testFile"
withExtension:@"txt"];
NSString*stringPath = [filePath absoluteString];
NSData *drfData = [NSData dataWithContentsOfURL:[NSURL
URLWithString:stringPath]];
NSString *str = [[NSString alloc]initWithData:drfData
encoding:NSUTF8StringEncoding];
Works great, even if I use cyrillic words ("ïðèâåò").
Now, I use following code to add each word as object to my NSMutableArray.
To detect what is a word, I separated them by comma in my testFile.txt
document.
int nLastPoint = 0;
int nCount = 0;
for (int i = 0; i< str.length; i++) {
if ([[str substringWithRange:NSMakeRange(i,
1)]isEqualToString:@","]) {
[lst_wordlist addObject:[[[str
substringWithRange:NSMakeRange(nLastPoint, nCount)]
stringByTrimmingCharactersInSet:[NSCharacterSet
whitespaceAndNewlineCharacterSet]] uppercaseString]];
nLastPoint = i+1;
nCount = 0;
}else{
nCount++;
}
}
int nLength = 0;
for (int i = 0; i< [lst_wordlist count]; i++) {
if ([[lst_wordlist objectAtIndex:i]length]>nLength) {
nLength = [[lst_wordlist objectAtIndex:i]length];
}
}
NSLog(@"%@",lst_wordlist);
Works great, again ONLY if I use english words. With Cyrillic words
doesn't work.
This is my NSLog when I use a cyrillic word.
"\U041f\U0420\U0418\U0412\U0415\U0422",
WORD2,
WORD3,
Any ideas? How can I fix it? I tried to change debugger from LLDB to GDB,
doesn't fix the problem.
How do I alternate DIV colors in a while loop?
How do I alternate DIV colors in a while loop?
Let's say I have a code that looks like this:
while ($info = mysql_fetch_assoc($data_p)) {
$name = stripslashes($info['name']);
$desc = stripslashes($info['description']);
$desc = substr($desc, 0, 150);
$price = stripslashes($info['price']);
Print "<div style=\"width:600px; height:150px; border:1px solid black;
overflow:hidden\"><div style=\"height:148px; width:25%; border:1px
solid red; float:left\"><center><img src=\"".$picture."\"
height=\"120\" width=\"120\" style=\"margin-top:15px\"
/></center></div><div style=\"height:150px; width:50%; border:1px
solid blue; float:left; text-overflow: ellipsis;
padding-top:5px\"><center><font size=\"+1\"><b><a
href=\"result.php?product=".urlencode($name)."\">".$name."</b></a></font><br><br>".$desc."...</center></div><div
style=\"height:150px; width:24%; border:1px solid green;
float:left\"><center><h1>$".$price."</h1><button>Add to
Cart</button></center></div></div>";
The main DIV that is first defined in the while loop I would like to
alternate two shades of grey. So in the results it would look like light
dark light dark etc...I've tried simply repeating the echos again with a
different color but that makes duplicates of each result. Is there a way
to do this?
Let's say I have a code that looks like this:
while ($info = mysql_fetch_assoc($data_p)) {
$name = stripslashes($info['name']);
$desc = stripslashes($info['description']);
$desc = substr($desc, 0, 150);
$price = stripslashes($info['price']);
Print "<div style=\"width:600px; height:150px; border:1px solid black;
overflow:hidden\"><div style=\"height:148px; width:25%; border:1px
solid red; float:left\"><center><img src=\"".$picture."\"
height=\"120\" width=\"120\" style=\"margin-top:15px\"
/></center></div><div style=\"height:150px; width:50%; border:1px
solid blue; float:left; text-overflow: ellipsis;
padding-top:5px\"><center><font size=\"+1\"><b><a
href=\"result.php?product=".urlencode($name)."\">".$name."</b></a></font><br><br>".$desc."...</center></div><div
style=\"height:150px; width:24%; border:1px solid green;
float:left\"><center><h1>$".$price."</h1><button>Add to
Cart</button></center></div></div>";
The main DIV that is first defined in the while loop I would like to
alternate two shades of grey. So in the results it would look like light
dark light dark etc...I've tried simply repeating the echos again with a
different color but that makes duplicates of each result. Is there a way
to do this?
Finding repetitive substrings
Finding repetitive substrings
Having some arbitrary string such as
hello hello hello I am I am I am your string string string string of strings
Can I somehow find repetitive sub-strings? In this case it would be
'hello', 'I am' and 'string'.
I have been wondering about this for some time but I still can not find
any real solution. I also have read some articles concerning this topic
and hit up on suffix trees but can this help me even though I need to find
every repetition e.g. with repetition count higher than two?
Having some arbitrary string such as
hello hello hello I am I am I am your string string string string of strings
Can I somehow find repetitive sub-strings? In this case it would be
'hello', 'I am' and 'string'.
I have been wondering about this for some time but I still can not find
any real solution. I also have read some articles concerning this topic
and hit up on suffix trees but can this help me even though I need to find
every repetition e.g. with repetition count higher than two?
Definitive C Input/Output Guide
Definitive C Input/Output Guide
Since the semester recently started a lot of similar questions regarding
IO in C (and C++) keep pouring in and the answers are often the same:
while(!feof()) is bad, use fgets() instead of scanf(), etc.
Do you think a community wiki is needed so all the duplicate questions
could be directed to that single answer? Or do you think they are still
sufficiently different so that those who ask would benefit from a question
tailored to their demands? Some just downvote and comment suggesting
posting on homework.stackexchange.com, but this doesnt't help.
After reading How should duplicate questions be handled? and What's the
etiquette for answering two similar questions? it seems to boil down to
the question how similar are two posts to be considered duplicate.
If you feel that most of the questions were indeed duplicates and that
this could grow into a community wiki page, please post your tricks of the
trade on IO in C including use, best practices, no-nos, notes on history
or implementation details and links to useful resources.
Since the semester recently started a lot of similar questions regarding
IO in C (and C++) keep pouring in and the answers are often the same:
while(!feof()) is bad, use fgets() instead of scanf(), etc.
Do you think a community wiki is needed so all the duplicate questions
could be directed to that single answer? Or do you think they are still
sufficiently different so that those who ask would benefit from a question
tailored to their demands? Some just downvote and comment suggesting
posting on homework.stackexchange.com, but this doesnt't help.
After reading How should duplicate questions be handled? and What's the
etiquette for answering two similar questions? it seems to boil down to
the question how similar are two posts to be considered duplicate.
If you feel that most of the questions were indeed duplicates and that
this could grow into a community wiki page, please post your tricks of the
trade on IO in C including use, best practices, no-nos, notes on history
or implementation details and links to useful resources.
knitr 1.4.1 ending comment in chunk do not display correctly
knitr 1.4.1 ending comment in chunk do not display correctly
I am using knitr 1.4.1 and have observed that when the last line of a
chunk (.Rnw file) is a comment, this comment does not display as the
previous comments.
Her is a minimal example:
\documentclass[a4paper]{article}
\begin{document}
<<chunk, echo=TRUE>>=
## comment before output
x <- sum(1:10) ## sum number from 1 to 10
x
(x <- sum(1:10)) ## sum number from 1 to 10
## comment after output
x
## final comment
@
\end{document}
With knitr 1.4.1 all comments but the last one are displayed in italic.
Any hint on how I could make the last comment look as the other ones would
be welcome.
I am using knitr 1.4.1 and have observed that when the last line of a
chunk (.Rnw file) is a comment, this comment does not display as the
previous comments.
Her is a minimal example:
\documentclass[a4paper]{article}
\begin{document}
<<chunk, echo=TRUE>>=
## comment before output
x <- sum(1:10) ## sum number from 1 to 10
x
(x <- sum(1:10)) ## sum number from 1 to 10
## comment after output
x
## final comment
@
\end{document}
With knitr 1.4.1 all comments but the last one are displayed in italic.
Any hint on how I could make the last comment look as the other ones would
be welcome.
Friday, 30 August 2013
How To That Jqurey Edit for Google Chrome Moving
How To That Jqurey Edit for Google Chrome Moving
How To That Jqurey Edit for Google Chrome Moving... Place Help me, That
Script (div - Moving) reyaly worked in mozilla firefox, I want to move
that google chrome, Jqurey script blow,......
(function ($) {
var TABLE_ID = 0;
$.fn.freezeHeader = function (params) {
var copiedHeader = null;
function freezeHeader(elem) {
var idObj = elem.attr('id') || ('tbl-' + (++TABLE_ID));
if (elem.length > 0 && elem[0].tagName.toLowerCase() ==
"table") {
var obj = {
id: idObj,
grid: elem,
container: null,
header: null,
divScroll: null,
openDivScroll: null,
closeDivScroll: null,
scroller: null
};
if (params && params.height !== undefined) {
obj.divScroll = '<div id="hdScroll' + obj.id + '"
style="height: ' + params.height + '; overflow-y:
scroll">';
obj.closeDivScroll = '</div>';
}
obj.header = obj.grid.find('thead');
if (params && params.height !== undefined) {
if ($('#hdScroll' + obj.id).length == 0) {
obj.grid.wrapAll(obj.divScroll);
}
}
obj.scroller = params && params.height !== undefined
? $('#hdScroll' + obj.id)
: $(window);
obj.scroller.on('scroll', function () {
if ($('#hd' + obj.id).length == 0) {
obj.grid.before('<div id="hd' + obj.id + '"></div>');
}
obj.container = $('#hd' + obj.id);
if (obj.header.offset() != null) {
if (limiteAlcancado(obj, params)) {
if (!copiedHeader) {
cloneHeaderRow(obj);
copiedHeader = true;
}
}
else {
if (($(document).scrollTop() >
obj.header.offset().top)) {
obj.container.css("position", "absolute");
obj.container.css("top",
(obj.grid.find("tr:last").offset().top -
obj.header.height()) + "px");
}
else {
obj.container.css("visibility", "hidden");
obj.container.css("top", "0px");
obj.container.width(0);
}
copiedHeader = false;
}
}
});
}
}
function limiteAlcancado(obj, params) {
if (params && params.height !== undefined) {
return (obj.header.offset().top <=
obj.scroller.offset().top);
}
else {
return ($(document).scrollTop() > obj.header.offset().top
&& $(document).scrollTop() < (obj.grid.height() -
obj.header.height() - obj.grid.find("tr:last").height()) +
obj.header.offset().top);
}
}
function cloneHeaderRow(obj) {
obj.container.html('');
obj.container.val('');
var tabela = $('<table style="margin: 0 0;"></table>');
var atributos = obj.grid.prop("attributes");
$.each(atributos, function () {
if (this.name != "id") {
tabela.attr(this.name, this.value);
}
});
tabela.append('<thead>' + obj.header.html() + '</thead>');
obj.container.append(tabela);
obj.container.width(obj.header.width());
obj.container.height(obj.header.height);
obj.container.find('th').each(function (index) {
var cellWidth = obj.grid.find('th').eq(index).width();
$(this).css('width', cellWidth);
});
obj.container.css("visibility", "visible");
if (params && params.height !== undefined) {
obj.container.css("top", obj.scroller.offset().top + "px");
obj.container.css("position", "absolute");
} else {
obj.container.css("top", "0px");
obj.container.css("position", "fixed");
}
}
return this.each(function (i, e) {
freezeHeader($(e));
});
};
})(jQuery);
Place Help Me, How To That Jqurey Edit for Google Chrome Moving... Place
Help me, That Script (div - Moving) reyaly worked in mozilla firefox, I
want to move that google chrome,
How To That Jqurey Edit for Google Chrome Moving... Place Help me, That
Script (div - Moving) reyaly worked in mozilla firefox, I want to move
that google chrome, Jqurey script blow,......
(function ($) {
var TABLE_ID = 0;
$.fn.freezeHeader = function (params) {
var copiedHeader = null;
function freezeHeader(elem) {
var idObj = elem.attr('id') || ('tbl-' + (++TABLE_ID));
if (elem.length > 0 && elem[0].tagName.toLowerCase() ==
"table") {
var obj = {
id: idObj,
grid: elem,
container: null,
header: null,
divScroll: null,
openDivScroll: null,
closeDivScroll: null,
scroller: null
};
if (params && params.height !== undefined) {
obj.divScroll = '<div id="hdScroll' + obj.id + '"
style="height: ' + params.height + '; overflow-y:
scroll">';
obj.closeDivScroll = '</div>';
}
obj.header = obj.grid.find('thead');
if (params && params.height !== undefined) {
if ($('#hdScroll' + obj.id).length == 0) {
obj.grid.wrapAll(obj.divScroll);
}
}
obj.scroller = params && params.height !== undefined
? $('#hdScroll' + obj.id)
: $(window);
obj.scroller.on('scroll', function () {
if ($('#hd' + obj.id).length == 0) {
obj.grid.before('<div id="hd' + obj.id + '"></div>');
}
obj.container = $('#hd' + obj.id);
if (obj.header.offset() != null) {
if (limiteAlcancado(obj, params)) {
if (!copiedHeader) {
cloneHeaderRow(obj);
copiedHeader = true;
}
}
else {
if (($(document).scrollTop() >
obj.header.offset().top)) {
obj.container.css("position", "absolute");
obj.container.css("top",
(obj.grid.find("tr:last").offset().top -
obj.header.height()) + "px");
}
else {
obj.container.css("visibility", "hidden");
obj.container.css("top", "0px");
obj.container.width(0);
}
copiedHeader = false;
}
}
});
}
}
function limiteAlcancado(obj, params) {
if (params && params.height !== undefined) {
return (obj.header.offset().top <=
obj.scroller.offset().top);
}
else {
return ($(document).scrollTop() > obj.header.offset().top
&& $(document).scrollTop() < (obj.grid.height() -
obj.header.height() - obj.grid.find("tr:last").height()) +
obj.header.offset().top);
}
}
function cloneHeaderRow(obj) {
obj.container.html('');
obj.container.val('');
var tabela = $('<table style="margin: 0 0;"></table>');
var atributos = obj.grid.prop("attributes");
$.each(atributos, function () {
if (this.name != "id") {
tabela.attr(this.name, this.value);
}
});
tabela.append('<thead>' + obj.header.html() + '</thead>');
obj.container.append(tabela);
obj.container.width(obj.header.width());
obj.container.height(obj.header.height);
obj.container.find('th').each(function (index) {
var cellWidth = obj.grid.find('th').eq(index).width();
$(this).css('width', cellWidth);
});
obj.container.css("visibility", "visible");
if (params && params.height !== undefined) {
obj.container.css("top", obj.scroller.offset().top + "px");
obj.container.css("position", "absolute");
} else {
obj.container.css("top", "0px");
obj.container.css("position", "fixed");
}
}
return this.each(function (i, e) {
freezeHeader($(e));
});
};
})(jQuery);
Place Help Me, How To That Jqurey Edit for Google Chrome Moving... Place
Help me, That Script (div - Moving) reyaly worked in mozilla firefox, I
want to move that google chrome,
What is the supertype of all functions in Scala?
What is the supertype of all functions in Scala?
I know I can do instanceOf checks against Function1 or Function2 etc but
is there a generic way to see if something is function or not (it can have
arbitray number of args). I tried defining something like this:
type FuncType = (Any*) -> Any
But that did not work either. Basically I have some code that looks like
this:
call = (name: Any, args: Any*) -> if name.isFunction then
name.castAs[Function].apply(args) else name
aFunction = (name: String) => "Hello " + name
notAFunction = "Hello rick"
call(aFunction, "rick")
call(notAFunction)
I know I can do instanceOf checks against Function1 or Function2 etc but
is there a generic way to see if something is function or not (it can have
arbitray number of args). I tried defining something like this:
type FuncType = (Any*) -> Any
But that did not work either. Basically I have some code that looks like
this:
call = (name: Any, args: Any*) -> if name.isFunction then
name.castAs[Function].apply(args) else name
aFunction = (name: String) => "Hello " + name
notAFunction = "Hello rick"
call(aFunction, "rick")
call(notAFunction)
Thursday, 29 August 2013
How in the model we can use localization string for the error message
How in the model we can use localization string for the error message
I use this class
[Required(ErrorMessage = "Username is required") ]
public string UserName { get; set; }
Though when I try to use this code
[Required(ErrorMessage = Localization.UserNameRequired) ]
public string UserName { get; set; }
It throws the compile error and doesn't allow me to use this localized
string. Am I doing something wrong?
I use this class
[Required(ErrorMessage = "Username is required") ]
public string UserName { get; set; }
Though when I try to use this code
[Required(ErrorMessage = Localization.UserNameRequired) ]
public string UserName { get; set; }
It throws the compile error and doesn't allow me to use this localized
string. Am I doing something wrong?
Wednesday, 28 August 2013
Inputting values to a string as a website URL for the page to be downloaded
Inputting values to a string as a website URL for the page to be downloaded
I'm messing around with the System.Net library in C# and I'm trying to
simply have it set up such that you enter an url and it will take that as
a string and put that into the parameter for the URl in the
Client.DownloadString() field.
Here is my code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
namespace StringDownloadTest
{
class GetInformation
{
string EnterString;
public string InputString()
{
EnterString = Console.ReadLine();
return EnterString;
}
}
class DownloadString
{
static void Main(string[] args)
{
GetInformation R = new GetInformation();
R.InputString();
string downloadedString;
System.Net.WebClient client;
client = new System.Net.WebClient();
downloadedString = client.DownloadString(R.InputString());
Console.WriteLine("String: {0}", downloadedString);
}
}
}
Any help here, it will compile but the program crashes.
I'm messing around with the System.Net library in C# and I'm trying to
simply have it set up such that you enter an url and it will take that as
a string and put that into the parameter for the URl in the
Client.DownloadString() field.
Here is my code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
namespace StringDownloadTest
{
class GetInformation
{
string EnterString;
public string InputString()
{
EnterString = Console.ReadLine();
return EnterString;
}
}
class DownloadString
{
static void Main(string[] args)
{
GetInformation R = new GetInformation();
R.InputString();
string downloadedString;
System.Net.WebClient client;
client = new System.Net.WebClient();
downloadedString = client.DownloadString(R.InputString());
Console.WriteLine("String: {0}", downloadedString);
}
}
}
Any help here, it will compile but the program crashes.
Any good way to save an unsubmitted form?
Any good way to save an unsubmitted form?
I know it's a difficult task, but is there any good way to save form input
when the user navigates to a different page without submitting, so when
they come back they won't have to re-enter the info?
I'm using Rails 4, Simple Form, and jQuery, but I'm open to any solution
that isn't an ugly hack.
I know it's a difficult task, but is there any good way to save form input
when the user navigates to a different page without submitting, so when
they come back they won't have to re-enter the info?
I'm using Rails 4, Simple Form, and jQuery, but I'm open to any solution
that isn't an ugly hack.
adding and subtracting dynamic time difference from a set time in PHP?
adding and subtracting dynamic time difference from a set time in PHP?
what I am trying to do might be quite be simple but I don't know how to
get it working.
I did re-search strtotime funtion and read PHP MANUAL
And that led me to the code bellow. I think the fundamental of the code
bellow is correct but the (00:30) is not correct!
Anyway, lets say I have set the time to (00:30) by $strtotime = '00:30';
at the start of the PHP code. now I want to add and/or subtract the
$offset/3600 value from the (00:30).
The $offset/3600 value is a time difference between two timezones if you
are wondering what that is and where its values coming from by the way.
I am trying to use the code bellow:
<?php
$strtotime = '00:30';
if (0 > $offset)
{
// For negative offset (hours behind)
$time = $offset / 3600 + (00:30);
}
elseif (0 < $offset)
{
// For positive offset (hours ahead)
$time - $offset / 3600 - (00:30);
}
else
{
// For offsets in the same timezone.
$time = "in the same timezone as";
}
echo "{$strtotime}";
?>
this code will only echo 00:30 and it wont add or subtract the $offset /
3600 value from it!
is there anything else that i need to do? or I am totally on the wrong path?
what I am trying to do might be quite be simple but I don't know how to
get it working.
I did re-search strtotime funtion and read PHP MANUAL
And that led me to the code bellow. I think the fundamental of the code
bellow is correct but the (00:30) is not correct!
Anyway, lets say I have set the time to (00:30) by $strtotime = '00:30';
at the start of the PHP code. now I want to add and/or subtract the
$offset/3600 value from the (00:30).
The $offset/3600 value is a time difference between two timezones if you
are wondering what that is and where its values coming from by the way.
I am trying to use the code bellow:
<?php
$strtotime = '00:30';
if (0 > $offset)
{
// For negative offset (hours behind)
$time = $offset / 3600 + (00:30);
}
elseif (0 < $offset)
{
// For positive offset (hours ahead)
$time - $offset / 3600 - (00:30);
}
else
{
// For offsets in the same timezone.
$time = "in the same timezone as";
}
echo "{$strtotime}";
?>
this code will only echo 00:30 and it wont add or subtract the $offset /
3600 value from it!
is there anything else that i need to do? or I am totally on the wrong path?
Multiple jquery dialogs in index.php
Multiple jquery dialogs in index.php
The general idea is to make a site that looks like windows enviroment, so
I have add two icons for example and when someone click on them, takes two
different dialog boxes.
In to my site's index page I have add this inside head tags:
<link rel="stylesheet"
href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css"
/>
<script
src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
<!-- JQUERY DIALOG SCRIPT -->
<script>
var $JQ_ = jQuery.noConflict();
$JQ_(function () {
$JQ_("#rl_module_dialog").dialog({
autoOpen: false,
width: 'auto',
resizable: false,
show: {
effect: "fade",
duration: 250
},
hide: {
effect: "fade",
duration: 250
}
});
$JQ_("#opener").click(function () {
$JQ_("#rl_module_dialog").dialog("open");
});
});
</script>
I also have two separated php files that are icluded into my index page
and they contain this...
First:
<div id="rl_module_dialog" class="rl_module_dialog" title=""><?php include
'**/**/something.php'; ?></div>
<div class="nm_icon" id="opener"><div class="icon"> </div></div>
Second
<div id="rl_module_dialog" class="rl_module_dialog" title=""><?php include
'**/**/something_else.php'; ?></div>
<div class="vath_icon" id="opener"><div class="icon"> </div></div>
If I don't include the second one, dialog works fine. If I place them
both, none is working! There is any way to use my jquery dialog script for
more than one dialog in same page?
The general idea is to make a site that looks like windows enviroment, so
I have add two icons for example and when someone click on them, takes two
different dialog boxes.
In to my site's index page I have add this inside head tags:
<link rel="stylesheet"
href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css"
/>
<script
src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
<!-- JQUERY DIALOG SCRIPT -->
<script>
var $JQ_ = jQuery.noConflict();
$JQ_(function () {
$JQ_("#rl_module_dialog").dialog({
autoOpen: false,
width: 'auto',
resizable: false,
show: {
effect: "fade",
duration: 250
},
hide: {
effect: "fade",
duration: 250
}
});
$JQ_("#opener").click(function () {
$JQ_("#rl_module_dialog").dialog("open");
});
});
</script>
I also have two separated php files that are icluded into my index page
and they contain this...
First:
<div id="rl_module_dialog" class="rl_module_dialog" title=""><?php include
'**/**/something.php'; ?></div>
<div class="nm_icon" id="opener"><div class="icon"> </div></div>
Second
<div id="rl_module_dialog" class="rl_module_dialog" title=""><?php include
'**/**/something_else.php'; ?></div>
<div class="vath_icon" id="opener"><div class="icon"> </div></div>
If I don't include the second one, dialog works fine. If I place them
both, none is working! There is any way to use my jquery dialog script for
more than one dialog in same page?
Tuesday, 27 August 2013
Is there a way to source cron jobs from a file
Is there a way to source cron jobs from a file
One of our servers has around 20-25 different cron jobs scheduled on it.
Usually, we periodically check-in the cron jobs to a file in the repo
using crontab -l > cron.jobs
While bringing up a new server, which is a replica of the previous server
(in terms of OS and deployed code base), is it possible to source the cron
jobs for the new server from a file containing valid cron jobs?
One of our servers has around 20-25 different cron jobs scheduled on it.
Usually, we periodically check-in the cron jobs to a file in the repo
using crontab -l > cron.jobs
While bringing up a new server, which is a replica of the previous server
(in terms of OS and deployed code base), is it possible to source the cron
jobs for the new server from a file containing valid cron jobs?
Lua source code manipulation: get innermost function() location for a given line
Lua source code manipulation: get innermost function() location for a
given line
I've got a syntactically correct file with Lua 5.1 source code.
I've got a position (line and character offset) inside that file.
I need to get an offset in bytes to the closing parenthesis of the
innermost function() body that contains that position (or figure out that
the position belongs to the main chunk of the file).
I.e.:
local function foo()
^ result
print("bar")
^ input
end
local foo = function()
^ result
print("bar")
^ input
end
local foo = function()
return function()
^ result
print("bar")
^ input
end
end
...And so on.
How do I do that robustly?
given line
I've got a syntactically correct file with Lua 5.1 source code.
I've got a position (line and character offset) inside that file.
I need to get an offset in bytes to the closing parenthesis of the
innermost function() body that contains that position (or figure out that
the position belongs to the main chunk of the file).
I.e.:
local function foo()
^ result
print("bar")
^ input
end
local foo = function()
^ result
print("bar")
^ input
end
local foo = function()
return function()
^ result
print("bar")
^ input
end
end
...And so on.
How do I do that robustly?
AngularJS: Can you get a 'digest in progress' error from multiple $scope.$apply() calls?
AngularJS: Can you get a 'digest in progress' error from multiple
$scope.$apply() calls?
In a large application where you might have a large scope, if you call
$scope.$apply multiple times in rapid succession, can you get a 'scope
already in progress' error?
E.g, I have a directive which is linked to the bootstrap switch plugin.
This directive simply shows an on/off switch which the user can click to
toggle a boolean value as true/false. Each time the user clicks this
button, my directive does a $scope.$apply() in which one scope variable is
changed to reflect the new state of the switch (on or off).
I was worried that if a user clicks the switch in rapid succession, I
might get the 'digest already in progress' error. However, that isn't the
case, each time things go very smoothly and the scope value is updated
everywhere instantly despite multiple $scope.$apply() calls being fired.
Is this because $scope.$apply is optimized somehow so it doesn't run a
full digest, but only updates those values which were changed, or is it
just because my scope is relatively small at the moment so the full digest
isn't taking long to be run?
$scope.$apply() calls?
In a large application where you might have a large scope, if you call
$scope.$apply multiple times in rapid succession, can you get a 'scope
already in progress' error?
E.g, I have a directive which is linked to the bootstrap switch plugin.
This directive simply shows an on/off switch which the user can click to
toggle a boolean value as true/false. Each time the user clicks this
button, my directive does a $scope.$apply() in which one scope variable is
changed to reflect the new state of the switch (on or off).
I was worried that if a user clicks the switch in rapid succession, I
might get the 'digest already in progress' error. However, that isn't the
case, each time things go very smoothly and the scope value is updated
everywhere instantly despite multiple $scope.$apply() calls being fired.
Is this because $scope.$apply is optimized somehow so it doesn't run a
full digest, but only updates those values which were changed, or is it
just because my scope is relatively small at the moment so the full digest
isn't taking long to be run?
AngularJS: ng-repeat in directive with isolated scope and $last
AngularJS: ng-repeat in directive with isolated scope and $last
I am trying to catch $last property to be notified when ng-repeat finishes
off. I've created special directive for that (ngRepeatDoneNotification).
Ng-repeat applies to another element directive (unit). So, there is a
construction with three directives:
<unit ng-repeat="unit in collection" ng-repeat-done-notification
id="{{unit.id}}"></unit>
Once I set scope to be isolated, $last disappeared in my notifier directive.
App.directive('ngRepeatDoneNotification', function() {
return function(scope, element, attrs) {
if (scope.$last){ // ISSUE IS HERE
window.alert("im the last!");
}
};
});
App.directive('unit', function() {
return {
restrict: 'E',
replace: true,
scope: {id: '@'}, // ONCE I ISOLATE SCOPE, $last DISAPPEARED
templateUrl: '/partials/unit.html',
link: function(scope, element) {}
}
});
I've create jsFiddle http://jsfiddle.net/4erLA/1/
How is it possible to catch this?
I am trying to catch $last property to be notified when ng-repeat finishes
off. I've created special directive for that (ngRepeatDoneNotification).
Ng-repeat applies to another element directive (unit). So, there is a
construction with three directives:
<unit ng-repeat="unit in collection" ng-repeat-done-notification
id="{{unit.id}}"></unit>
Once I set scope to be isolated, $last disappeared in my notifier directive.
App.directive('ngRepeatDoneNotification', function() {
return function(scope, element, attrs) {
if (scope.$last){ // ISSUE IS HERE
window.alert("im the last!");
}
};
});
App.directive('unit', function() {
return {
restrict: 'E',
replace: true,
scope: {id: '@'}, // ONCE I ISOLATE SCOPE, $last DISAPPEARED
templateUrl: '/partials/unit.html',
link: function(scope, element) {}
}
});
I've create jsFiddle http://jsfiddle.net/4erLA/1/
How is it possible to catch this?
Textbox/input text element longer than it should be
Textbox/input text element longer than it should be
So the problem is that in my div around listbox(select) + textbox(input
text) + button(input submit) I have width:250px for the whole div and for
the each thing inside it I have width:100%.
That makes me assume that they should logically fill the space inside that
div. But the problem is that the textbox(input text in the fiddle) is
kinda longer(or the other elements are shorter?).
Any ideas why and how to solve this problem?
Demo: http://jsfiddle.net/xXVHu/15/
In my whole code all the divs I have have some kind of meaning so if you
feel like they are useless, they aren't!
So the problem is that in my div around listbox(select) + textbox(input
text) + button(input submit) I have width:250px for the whole div and for
the each thing inside it I have width:100%.
That makes me assume that they should logically fill the space inside that
div. But the problem is that the textbox(input text in the fiddle) is
kinda longer(or the other elements are shorter?).
Any ideas why and how to solve this problem?
Demo: http://jsfiddle.net/xXVHu/15/
In my whole code all the divs I have have some kind of meaning so if you
feel like they are useless, they aren't!
Access to publicly available project with all the artefacts (files) created during the development
Access to publicly available project with all the artefacts (files)
created during the development
Does anyone know where I could get an access to a project that contains
all the artefacts (documents) that were created during the development? So
I would like to get all the word, pdf, power designer, etc. files as well
as all the source code. If possible, I would prefer that all this files
are stored in some of the software reporitories.
created during the development
Does anyone know where I could get an access to a project that contains
all the artefacts (documents) that were created during the development? So
I would like to get all the word, pdf, power designer, etc. files as well
as all the source code. If possible, I would prefer that all this files
are stored in some of the software reporitories.
how can I move certain type of file from one folder to another
how can I move certain type of file from one folder to another
how can I move certain type of file from one folder to another using
Command prompt?
or
Can I move the specific type of file and also copying the folder structure
to a new place?
how can I move certain type of file from one folder to another using
Command prompt?
or
Can I move the specific type of file and also copying the folder structure
to a new place?
Monday, 26 August 2013
Windows Can't Start bout computer software or computer hardware
Windows Can't Start bout computer software or computer hardware
What is the reason Without OS CD My Windows Can't Start up during Switch
on My Computer If any settings problem?
What is the reason Without OS CD My Windows Can't Start up during Switch
on My Computer If any settings problem?
Return rows with the greatest row count - MS-SQL
Return rows with the greatest row count - MS-SQL
insert into CallData ([800num], CompanyName) values ('8009874321',
'cars'); insert into CallData ([800num], CompanyName) values
('8009874321', 'Newsales'); insert into CallData ([800num], CompanyName)
values ('8009874321', 'Newsales'); insert into CallData ([800num],
CompanyName) values ('8009870000', 'BenaSales'); insert into CallData
([800num], CompanyName) values ('8009870000', 'BenaSales'); insert into
CallData ([800num], CompanyName) values ('8009870000', 'BenaSales2');
insert into CallData ([800num], CompanyName) values ('8009870000',
'BenaSales2');
Running SQLServer 2008 Requirement 1: When the 800num matches I would like
to return a single row, the row with the greatest row count. Requirement
2: If the 800num row count matches then return both rows.
Results would be: 8009874321 Newsales 8009870000 BenaSales 8009870000
BenaSales2
Any help would be great.
insert into CallData ([800num], CompanyName) values ('8009874321',
'cars'); insert into CallData ([800num], CompanyName) values
('8009874321', 'Newsales'); insert into CallData ([800num], CompanyName)
values ('8009874321', 'Newsales'); insert into CallData ([800num],
CompanyName) values ('8009870000', 'BenaSales'); insert into CallData
([800num], CompanyName) values ('8009870000', 'BenaSales'); insert into
CallData ([800num], CompanyName) values ('8009870000', 'BenaSales2');
insert into CallData ([800num], CompanyName) values ('8009870000',
'BenaSales2');
Running SQLServer 2008 Requirement 1: When the 800num matches I would like
to return a single row, the row with the greatest row count. Requirement
2: If the 800num row count matches then return both rows.
Results would be: 8009874321 Newsales 8009870000 BenaSales 8009870000
BenaSales2
Any help would be great.
How do I trigger the manipulation of the DOM after a partial view is loaded in AngularJS?
How do I trigger the manipulation of the DOM after a partial view is
loaded in AngularJS?
How do I trigger the manipulation of the DOM after a partial view is
loaded in AngularJS?
If I were using jQuery, I could do
$(document).ready(function(){
// do stuff here
}
But in Angular, in particular with partial views, how would I do such? As
a more concrete example, I have the following basic non-interactive
Angular app (html and js on the same page source):
http://cssquirrel.com/testcases/ang-demo/
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Angular Question</title>
</head>
<body data-ng-app="demoApp">
<div data-ng-view=""></div>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
<script>
var app = angular.module('demoApp', []);
var controller = {
demoController: function ($scope, demoFactory) {
$scope.fruits = demoFactory.getFruits();
}
};
var factory = {
demoFactory: function () {
var fruits = ['apples', 'bananas', 'cherries'];
var factory = {
getFruits: function () {
return fruits;
}
};
return factory;
}
}
function appRoute($routeProvider) {
$routeProvider
.when('/step-1',
{
controller: 'demoController',
templateUrl: 'partial.html'
})
.otherwise({ redirectTo: '/step-1' });
};
app.config(appRoute);
app.factory(factory);
app.controller(controller);
</script>
</body>
</html>
Which has the following partial:
http://cssquirrel.com/testcases/ang-demo/partial.html
<ul>
<li data-ng-repeat="fruit in fruits">{{fruit}}</li>
</ul>
So, if in this basic app, I wanted to add a class "active" to the first
list item in the list after the partial view has finished loading, how
would I go about it?
loaded in AngularJS?
How do I trigger the manipulation of the DOM after a partial view is
loaded in AngularJS?
If I were using jQuery, I could do
$(document).ready(function(){
// do stuff here
}
But in Angular, in particular with partial views, how would I do such? As
a more concrete example, I have the following basic non-interactive
Angular app (html and js on the same page source):
http://cssquirrel.com/testcases/ang-demo/
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Angular Question</title>
</head>
<body data-ng-app="demoApp">
<div data-ng-view=""></div>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
<script>
var app = angular.module('demoApp', []);
var controller = {
demoController: function ($scope, demoFactory) {
$scope.fruits = demoFactory.getFruits();
}
};
var factory = {
demoFactory: function () {
var fruits = ['apples', 'bananas', 'cherries'];
var factory = {
getFruits: function () {
return fruits;
}
};
return factory;
}
}
function appRoute($routeProvider) {
$routeProvider
.when('/step-1',
{
controller: 'demoController',
templateUrl: 'partial.html'
})
.otherwise({ redirectTo: '/step-1' });
};
app.config(appRoute);
app.factory(factory);
app.controller(controller);
</script>
</body>
</html>
Which has the following partial:
http://cssquirrel.com/testcases/ang-demo/partial.html
<ul>
<li data-ng-repeat="fruit in fruits">{{fruit}}</li>
</ul>
So, if in this basic app, I wanted to add a class "active" to the first
list item in the list after the partial view has finished loading, how
would I go about it?
C# extract string using regular expression
C# extract string using regular expression
I have a html string which i'm parsing which looks like below. I need to
get the value of @Footer.
strHTML = "<html><html>\r\n\r\n<head>\r\n<meta http-equiv=Content-Type
content=\"text/html; charset=windows-1252\">\r\n
<meta name=Generator content=\"Microsoft Word
14></head></head><body>
<p>@Footer=CONFIDENTIAL<p></body></html>"
I have tried the below code, how do i get the value?
Regex m = new Regex("@Footer", RegexOptions.Compiled);
foreach (Match VariableMatch in m.Matches(strHTML.ToString()))
{
Console.WriteLine(VariableMatch);
}
I have a html string which i'm parsing which looks like below. I need to
get the value of @Footer.
strHTML = "<html><html>\r\n\r\n<head>\r\n<meta http-equiv=Content-Type
content=\"text/html; charset=windows-1252\">\r\n
<meta name=Generator content=\"Microsoft Word
14></head></head><body>
<p>@Footer=CONFIDENTIAL<p></body></html>"
I have tried the below code, how do i get the value?
Regex m = new Regex("@Footer", RegexOptions.Compiled);
foreach (Match VariableMatch in m.Matches(strHTML.ToString()))
{
Console.WriteLine(VariableMatch);
}
How Do I Get iFrames Side-by-Side?
How Do I Get iFrames Side-by-Side?
I need to pull a web page into our vBulletin site webpage to inform our
community about our servers status. Basically, I need to use iFrames. I
have them in there but I cant get them side by side.
I've hunted all over the internet and all the comments I have read do not
do it. Here is the code I have to work with:
<center>
<iframe
src="http://cache.www.gametracker.com/components/html0/?host=63.251.20.99:6820&bgColor=16100D&fontColor=B9946D&titleBgColor=150C08&titleColor=B9946D&borderColor=000000&linkColor=FFFF99&borderLinkColor=FFFFFF&showMap=0¤tPlayersHeight=350&showCurrPlayers=1&showTopPlayers=0&showBlogs=0&width=180"
frameborder="0" scrolling="no" width="100%" height="512">
</iframe>
<iframe
src="http://cache.www.gametracker.com/components/html0/?host=74.91.116.62:27015&bgColor=16100D&fontColor=B9946D&titleBgColor=150C08&titleColor=B9946D&borderColor=000000&linkColor=FFFF99&borderLinkColor=FFFFFF&showMap=1¤tPlayersHeight=200&showCurrPlayers=1&showTopPlayers=0&showBlogs=0&width=180"
frameborder="0" scrolling="no" width="100%" height="512">
</iframe>
<iframe
src="http://cache.www.gametracker.com/components/html0/?host=70.42.74.135:27015&bgColor=16100D&fontColor=B9946D&titleBgColor=150C08&titleColor=B9946D&borderColor=000000&linkColor=FFFF99&borderLinkColor=FFFFFF&showMap=1¤tPlayersHeight=200&showCurrPlayers=1&showTopPlayers=0&showBlogs=0&width=180"
frameborder="0" scrolling="no" width="100%" height="512">
</iframe>
</center>
Need to adjust the iframes side by side with each other. Any help would be
greatly appreciated.
I need to pull a web page into our vBulletin site webpage to inform our
community about our servers status. Basically, I need to use iFrames. I
have them in there but I cant get them side by side.
I've hunted all over the internet and all the comments I have read do not
do it. Here is the code I have to work with:
<center>
<iframe
src="http://cache.www.gametracker.com/components/html0/?host=63.251.20.99:6820&bgColor=16100D&fontColor=B9946D&titleBgColor=150C08&titleColor=B9946D&borderColor=000000&linkColor=FFFF99&borderLinkColor=FFFFFF&showMap=0¤tPlayersHeight=350&showCurrPlayers=1&showTopPlayers=0&showBlogs=0&width=180"
frameborder="0" scrolling="no" width="100%" height="512">
</iframe>
<iframe
src="http://cache.www.gametracker.com/components/html0/?host=74.91.116.62:27015&bgColor=16100D&fontColor=B9946D&titleBgColor=150C08&titleColor=B9946D&borderColor=000000&linkColor=FFFF99&borderLinkColor=FFFFFF&showMap=1¤tPlayersHeight=200&showCurrPlayers=1&showTopPlayers=0&showBlogs=0&width=180"
frameborder="0" scrolling="no" width="100%" height="512">
</iframe>
<iframe
src="http://cache.www.gametracker.com/components/html0/?host=70.42.74.135:27015&bgColor=16100D&fontColor=B9946D&titleBgColor=150C08&titleColor=B9946D&borderColor=000000&linkColor=FFFF99&borderLinkColor=FFFFFF&showMap=1¤tPlayersHeight=200&showCurrPlayers=1&showTopPlayers=0&showBlogs=0&width=180"
frameborder="0" scrolling="no" width="100%" height="512">
</iframe>
</center>
Need to adjust the iframes side by side with each other. Any help would be
greatly appreciated.
Doctrine2: Create query for ManytoMany without inversed side
Doctrine2: Create query for ManytoMany without inversed side
I'm new to Doctrine and having a hard time trying to figure out howto
write the query below with Doctrine2 in Symfony2 which gives me a list of
User objects as result.
Query description: A teacher must get a list of users that are assigned to
the courses he has been assigned to as teacher
Select * from fos_user_user as user
LEFT JOIN course_assigned_students as cas ON cas.student_id = user.id
WHERE cas.course_id IN
(SELECT cat.course_id from course_assigned_teachers where
teachers_id = 1)
GROUP BY user.id
Or similar
Select * from fos_user_user as user
LEFT JOIN course_assigned_students as cas ON cas.student_id = user.id
LEFT JOIN course_assigned_teachers as cat ON cat.course_id =
cas.course_id
WHERE cat.teachers_id = 1
GROUP BY user.id
tables:
fos_user_user: id
course_assigned_students: student_id, course_id
course_assigned_teachers: teachers_id, course_id
course: id
Course Entity
/**
* @var User $teachers
*
* @ORM\ManyToMany(targetEntity="Application\Sonata\UserBundle\Entity\User")
* @ORM\JoinTable(name="course_assigned_teachers",
* joinColumns={@ORM\JoinColumn(name="course_id",
referencedColumnName="id")},
* inverseJoinColumns={@ORM\JoinColumn(name="teachers_id",
referencedColumnName="id")}
* )
*/
protected $teachers;
/**
* @var User $students
*
* @ORM\ManyToMany(targetEntity="Application\Sonata\UserBundle\Entity\User")
* @ORM\JoinTable(name="course_assigned_students",
* joinColumns={@ORM\JoinColumn(name="course_id",
referencedColumnName="id")},
* inverseJoinColumns={@ORM\JoinColumn(name="student_id",
referencedColumnName="id")}
* )
*/
protected $students;
My problem is that I don't want my User Entity to have references to
Course, because not every application will make use of the CourseBundle.
Do I have to create CourseAssignedStudents and CourseAssignedTeachers
entities which represents the join tables?
So I can do something like:
$users = $this->getDoctrine()->getEntityManager()
->createQuery('SELECT user FROM ApplicationSonataUserBundle:User user
LEFT JOIN CourseBundle:CourseAssignedStudents cas WITH
cas.student_id = user.id
WHERE cas.course_id IN (SELECT cat.course_id FROM
CourseBundle:CourseAssignedTeachers cat where
cat.teachers_id = :uid)
GROUP BY user.id')
->setParameter('uid', $this->getUser()->getId())
->execute();
I'm new to Doctrine and having a hard time trying to figure out howto
write the query below with Doctrine2 in Symfony2 which gives me a list of
User objects as result.
Query description: A teacher must get a list of users that are assigned to
the courses he has been assigned to as teacher
Select * from fos_user_user as user
LEFT JOIN course_assigned_students as cas ON cas.student_id = user.id
WHERE cas.course_id IN
(SELECT cat.course_id from course_assigned_teachers where
teachers_id = 1)
GROUP BY user.id
Or similar
Select * from fos_user_user as user
LEFT JOIN course_assigned_students as cas ON cas.student_id = user.id
LEFT JOIN course_assigned_teachers as cat ON cat.course_id =
cas.course_id
WHERE cat.teachers_id = 1
GROUP BY user.id
tables:
fos_user_user: id
course_assigned_students: student_id, course_id
course_assigned_teachers: teachers_id, course_id
course: id
Course Entity
/**
* @var User $teachers
*
* @ORM\ManyToMany(targetEntity="Application\Sonata\UserBundle\Entity\User")
* @ORM\JoinTable(name="course_assigned_teachers",
* joinColumns={@ORM\JoinColumn(name="course_id",
referencedColumnName="id")},
* inverseJoinColumns={@ORM\JoinColumn(name="teachers_id",
referencedColumnName="id")}
* )
*/
protected $teachers;
/**
* @var User $students
*
* @ORM\ManyToMany(targetEntity="Application\Sonata\UserBundle\Entity\User")
* @ORM\JoinTable(name="course_assigned_students",
* joinColumns={@ORM\JoinColumn(name="course_id",
referencedColumnName="id")},
* inverseJoinColumns={@ORM\JoinColumn(name="student_id",
referencedColumnName="id")}
* )
*/
protected $students;
My problem is that I don't want my User Entity to have references to
Course, because not every application will make use of the CourseBundle.
Do I have to create CourseAssignedStudents and CourseAssignedTeachers
entities which represents the join tables?
So I can do something like:
$users = $this->getDoctrine()->getEntityManager()
->createQuery('SELECT user FROM ApplicationSonataUserBundle:User user
LEFT JOIN CourseBundle:CourseAssignedStudents cas WITH
cas.student_id = user.id
WHERE cas.course_id IN (SELECT cat.course_id FROM
CourseBundle:CourseAssignedTeachers cat where
cat.teachers_id = :uid)
GROUP BY user.id')
->setParameter('uid', $this->getUser()->getId())
->execute();
Extraction Of Face From a Bitmap
Extraction Of Face From a Bitmap
After being given suggestions to use circular crop i implemented it in my
application to use to extract face from the bitmap but its too inefficient
i mean its of no use and similar to cropping from the rectangular face.
Now here is what i have done up til now:
Launched Camera
Taken Picture
Detected The face in the Picture
Painting a rectangular window in the area face has been detected
Now the serious issue am facing is getting face from that bitmap. I just
want to get the face. Ignore all the other details that were in the face
detection window. If it was matlab it could have been too simpler with the
help of edge detection techniques and segmentation algorithms and
function. I want to know how can i do the same process in android
application? plz do share the code snippets if u know of any. This is
taking too much of my time and i just want to get over with this face
extraction part.
Code i did till now:
public class Makeover extends Activity {
private static final int TAKE_PICTURE_CODE = 100;
private static final int MAX_FACES = 5;
private Bitmap cameraBitmap = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
((Button)findViewById(R.id.take_picture)).setOnClickListener(btnClick);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent
data) {
super.onActivityResult(requestCode, resultCode, data);
if(TAKE_PICTURE_CODE == requestCode){
processCameraImage(data);
}
}
private void openCamera(){
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, TAKE_PICTURE_CODE);
}
private void processCameraImage(Intent intent){
setContentView(R.layout.detectlayout);
((Button)findViewById(R.id.detect_face)).setOnClickListener(btnClick);
ImageView imageView = (ImageView)findViewById(R.id.image_view);
cameraBitmap = (Bitmap)intent.getExtras().get("data");
imageView.setImageBitmap(cameraBitmap);
}
private void detectFaces(){
Bitmap bmFace = null;
if(null != cameraBitmap){
int width = cameraBitmap.getWidth();
int height = cameraBitmap.getHeight();
FaceDetector detector = new FaceDetector(width,
height,Makeover.MAX_FACES);
Face[] faces = new Face[Makeover.MAX_FACES];
Bitmap bitmap565 = Bitmap.createBitmap(width, height,
Config.RGB_565);
Paint ditherPaint = new Paint();
Paint drawPaint = new Paint();
//jo bhi krna hai ab bitmap565 k sath krna hai apse wo image hai main
ditherPaint.setDither(true);
drawPaint.setColor(Color.RED);
drawPaint.setStyle(Paint.Style.STROKE);
drawPaint.setStrokeWidth(2);
Canvas canvas = new Canvas();
canvas.setBitmap(bitmap565);
canvas.drawBitmap(cameraBitmap, 0, 0, ditherPaint);
int facesFound = detector.findFaces(bitmap565, faces);
PointF midPoint = new PointF();
float eyeDistance = 0.0f;
float confidence = 0.0f;
Log.i("FaceDetector", "Number of faces found: " + facesFound);
if(facesFound > 0)
{
for(int index=0; index<facesFound; ++index){
faces[index].getMidPoint(midPoint);
eyeDistance = faces[index].eyesDistance();
confidence = faces[index].confidence();
Log.i("FaceDetector",
"Confidence: " + confidence +
", Eye distance: " + eyeDistance +
", Mid Point: (" + midPoint.x + ",
" + midPoint.y + ")");
canvas.drawRect((int)midPoint.x - eyeDistance ,
(int)midPoint.y -
eyeDistance ,
(int)midPoint.x +
eyeDistance,
(int)midPoint.y +
eyeDistance,
drawPaint);
}
}
for(int count=0;count<detector.findFaces(bitmap565, faces);count++)
{
float left;
float top;
PointF midPoints=new PointF();
faces[count].getMidPoint(midPoint);
eyeDistance=faces[count].eyesDistance();
left = midPoint.x - (float)(1.4 * eyeDistance);
top = midPoint.y - (float)(1.8 * eyeDistance);
bmFace = Bitmap.createBitmap(cameraBitmap, (int) left, (int)
top, (int) (2.8 * eyeDistance), (int) (3.6 * eyeDistance));
}
String filepath = Environment.getExternalStorageDirectory() +
"/facedetect" + System.currentTimeMillis() + ".jpg";
try {
FileOutputStream fos = new
FileOutputStream(filepath);
bitmap565.compress(CompressFormat.JPEG, 90, fos);
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
ImageView imageView =
(ImageView)findViewById(R.id.image_view);
imageView.setImageBitmap(bmFace);
}
}
private View.OnClickListener btnClick = new View.OnClickListener() {
@Override
public void onClick(View v) {
switch(v.getId()){
case R.id.take_picture: openCamera();
break;
case R.id.detect_face: detectFaces();
break;
}
}
};
}
After being given suggestions to use circular crop i implemented it in my
application to use to extract face from the bitmap but its too inefficient
i mean its of no use and similar to cropping from the rectangular face.
Now here is what i have done up til now:
Launched Camera
Taken Picture
Detected The face in the Picture
Painting a rectangular window in the area face has been detected
Now the serious issue am facing is getting face from that bitmap. I just
want to get the face. Ignore all the other details that were in the face
detection window. If it was matlab it could have been too simpler with the
help of edge detection techniques and segmentation algorithms and
function. I want to know how can i do the same process in android
application? plz do share the code snippets if u know of any. This is
taking too much of my time and i just want to get over with this face
extraction part.
Code i did till now:
public class Makeover extends Activity {
private static final int TAKE_PICTURE_CODE = 100;
private static final int MAX_FACES = 5;
private Bitmap cameraBitmap = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
((Button)findViewById(R.id.take_picture)).setOnClickListener(btnClick);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent
data) {
super.onActivityResult(requestCode, resultCode, data);
if(TAKE_PICTURE_CODE == requestCode){
processCameraImage(data);
}
}
private void openCamera(){
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, TAKE_PICTURE_CODE);
}
private void processCameraImage(Intent intent){
setContentView(R.layout.detectlayout);
((Button)findViewById(R.id.detect_face)).setOnClickListener(btnClick);
ImageView imageView = (ImageView)findViewById(R.id.image_view);
cameraBitmap = (Bitmap)intent.getExtras().get("data");
imageView.setImageBitmap(cameraBitmap);
}
private void detectFaces(){
Bitmap bmFace = null;
if(null != cameraBitmap){
int width = cameraBitmap.getWidth();
int height = cameraBitmap.getHeight();
FaceDetector detector = new FaceDetector(width,
height,Makeover.MAX_FACES);
Face[] faces = new Face[Makeover.MAX_FACES];
Bitmap bitmap565 = Bitmap.createBitmap(width, height,
Config.RGB_565);
Paint ditherPaint = new Paint();
Paint drawPaint = new Paint();
//jo bhi krna hai ab bitmap565 k sath krna hai apse wo image hai main
ditherPaint.setDither(true);
drawPaint.setColor(Color.RED);
drawPaint.setStyle(Paint.Style.STROKE);
drawPaint.setStrokeWidth(2);
Canvas canvas = new Canvas();
canvas.setBitmap(bitmap565);
canvas.drawBitmap(cameraBitmap, 0, 0, ditherPaint);
int facesFound = detector.findFaces(bitmap565, faces);
PointF midPoint = new PointF();
float eyeDistance = 0.0f;
float confidence = 0.0f;
Log.i("FaceDetector", "Number of faces found: " + facesFound);
if(facesFound > 0)
{
for(int index=0; index<facesFound; ++index){
faces[index].getMidPoint(midPoint);
eyeDistance = faces[index].eyesDistance();
confidence = faces[index].confidence();
Log.i("FaceDetector",
"Confidence: " + confidence +
", Eye distance: " + eyeDistance +
", Mid Point: (" + midPoint.x + ",
" + midPoint.y + ")");
canvas.drawRect((int)midPoint.x - eyeDistance ,
(int)midPoint.y -
eyeDistance ,
(int)midPoint.x +
eyeDistance,
(int)midPoint.y +
eyeDistance,
drawPaint);
}
}
for(int count=0;count<detector.findFaces(bitmap565, faces);count++)
{
float left;
float top;
PointF midPoints=new PointF();
faces[count].getMidPoint(midPoint);
eyeDistance=faces[count].eyesDistance();
left = midPoint.x - (float)(1.4 * eyeDistance);
top = midPoint.y - (float)(1.8 * eyeDistance);
bmFace = Bitmap.createBitmap(cameraBitmap, (int) left, (int)
top, (int) (2.8 * eyeDistance), (int) (3.6 * eyeDistance));
}
String filepath = Environment.getExternalStorageDirectory() +
"/facedetect" + System.currentTimeMillis() + ".jpg";
try {
FileOutputStream fos = new
FileOutputStream(filepath);
bitmap565.compress(CompressFormat.JPEG, 90, fos);
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
ImageView imageView =
(ImageView)findViewById(R.id.image_view);
imageView.setImageBitmap(bmFace);
}
}
private View.OnClickListener btnClick = new View.OnClickListener() {
@Override
public void onClick(View v) {
switch(v.getId()){
case R.id.take_picture: openCamera();
break;
case R.id.detect_face: detectFaces();
break;
}
}
};
}
Sunday, 25 August 2013
Error posting to Tumblr The operation couldnt be completed. (Request failed error 400.)
Error posting to Tumblr The operation couldn't be completed. (Request
failed error 400.)
I am generating a gif and saving it in Documents Directory.
when i try to post Gif from NSBundle there is no issue but when i try to
upload gif from document directory, it authenticate successfully, but
shows error while posting i.e JXHTTPMultipartBody.m (78) ERROR: The
operation couldn't be completed. (Cocoa error 260.)
Error posting to Tumblr The operation couldn't be completed. (Request
failed error 400.).
code snippet i am using is
[TMAPIClient sharedInstance].OAuthConsumerKey =
@"gHTqzg8WGOuTAnuwmmLzPRzcAV8CoxVLCOUXlUN25Q0XLjyols";
[TMAPIClient sharedInstance].OAuthConsumerSecret =
@"Q7WLovQS2qR739tGyhH2hycmyoYc1a4OZ2dwl3B7ah7v0LGiAu";
[TMAPIClient sharedInstance].OAuthToken =
@"1KxwXLQ9ctrq4SpUKlrPiKZtT4skGHapejQYBdHBIKLc69XeMs";
[TMAPIClient sharedInstance].OAuthTokenSecret =
@"RSswzFPW5uvhkMtlJ0AU9KxF0ltDaTgPRn1EioISracAfn9sAf";
[[TMAPIClient sharedInstance] authenticate:@"myapp://tumblr-authorize"
callback:^(NSError *error) {
// You are now authenticated (if !error)
if (error)
NSLog(@"Authentication failed: %@ %@", error, [error
description]);
else{
NSLog(@"Authentication successful!");
[[TMAPIClient sharedInstance] photo:@"test.tumblr.com"
filePathArray:[[NSFileManager
defaultManager]contentsOfDirectoryAtPath:[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask,
YES)objectAtIndex:0]
error:NULL]
contentTypeArray:@[@"image/gif"]
parameters:@{@"caption" : @"Hello Gif"}
callback:^(id response, NSError
*error) {
if (error)
{
NSLog(@"Error posting to
Tumblr
%@",error.localizedDescription);
}
else
NSLog(@"Posted to Tumblr");
NSLog(@"response %@",response);
}];
}
}];
failed error 400.)
I am generating a gif and saving it in Documents Directory.
when i try to post Gif from NSBundle there is no issue but when i try to
upload gif from document directory, it authenticate successfully, but
shows error while posting i.e JXHTTPMultipartBody.m (78) ERROR: The
operation couldn't be completed. (Cocoa error 260.)
Error posting to Tumblr The operation couldn't be completed. (Request
failed error 400.).
code snippet i am using is
[TMAPIClient sharedInstance].OAuthConsumerKey =
@"gHTqzg8WGOuTAnuwmmLzPRzcAV8CoxVLCOUXlUN25Q0XLjyols";
[TMAPIClient sharedInstance].OAuthConsumerSecret =
@"Q7WLovQS2qR739tGyhH2hycmyoYc1a4OZ2dwl3B7ah7v0LGiAu";
[TMAPIClient sharedInstance].OAuthToken =
@"1KxwXLQ9ctrq4SpUKlrPiKZtT4skGHapejQYBdHBIKLc69XeMs";
[TMAPIClient sharedInstance].OAuthTokenSecret =
@"RSswzFPW5uvhkMtlJ0AU9KxF0ltDaTgPRn1EioISracAfn9sAf";
[[TMAPIClient sharedInstance] authenticate:@"myapp://tumblr-authorize"
callback:^(NSError *error) {
// You are now authenticated (if !error)
if (error)
NSLog(@"Authentication failed: %@ %@", error, [error
description]);
else{
NSLog(@"Authentication successful!");
[[TMAPIClient sharedInstance] photo:@"test.tumblr.com"
filePathArray:[[NSFileManager
defaultManager]contentsOfDirectoryAtPath:[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask,
YES)objectAtIndex:0]
error:NULL]
contentTypeArray:@[@"image/gif"]
parameters:@{@"caption" : @"Hello Gif"}
callback:^(id response, NSError
*error) {
if (error)
{
NSLog(@"Error posting to
Tumblr
%@",error.localizedDescription);
}
else
NSLog(@"Posted to Tumblr");
NSLog(@"response %@",response);
}];
}
}];
usage of setTimeout function in AJAX
usage of setTimeout function in AJAX
I.m currently following a tutorial about how to load content from a MYSQL
db without reloading the page.
I just want to understand the use of setTimeout in this code. What's it
for? I tried removing that part and ajax still works. Why would you need
to delay a task, isn't ajax meant to be realtime update?
// load
$(document).ready(function () {
done();
});
// timeout function
function done() {
setTimeout(function () {
updates();
done();
}, 200);
}
// fetch data from db
function updates() {
$.getJSON("update.php", function (data) {
$("ul").empty();
$.each(data.result, function () {
$("ul").append("<li>ID: " + this['msg_id'] + "</li><br
/><li>ID: " + this['msg'] + "</li><br />");
});
});
}
I.m currently following a tutorial about how to load content from a MYSQL
db without reloading the page.
I just want to understand the use of setTimeout in this code. What's it
for? I tried removing that part and ajax still works. Why would you need
to delay a task, isn't ajax meant to be realtime update?
// load
$(document).ready(function () {
done();
});
// timeout function
function done() {
setTimeout(function () {
updates();
done();
}, 200);
}
// fetch data from db
function updates() {
$.getJSON("update.php", function (data) {
$("ul").empty();
$.each(data.result, function () {
$("ul").append("<li>ID: " + this['msg_id'] + "</li><br
/><li>ID: " + this['msg'] + "</li><br />");
});
});
}
Saturday, 24 August 2013
Visualizing intersections between online communities
Visualizing intersections between online communities
Let's say you wanted to map the intersections between n different online
communities. For example:
80% of CrossValidated users also have a Stack Overflow account
50% of Hacker News users also have a Reddit account
etc.
What would be a good way to visualize this? Any examples of existing
diagrams?
I've seen this question, which provides an answer. But I'm curious to know
if there are other visualization techniques that would specifically lend
themselves to comparing the relationships between communities.
Let's say you wanted to map the intersections between n different online
communities. For example:
80% of CrossValidated users also have a Stack Overflow account
50% of Hacker News users also have a Reddit account
etc.
What would be a good way to visualize this? Any examples of existing
diagrams?
I've seen this question, which provides an answer. But I'm curious to know
if there are other visualization techniques that would specifically lend
themselves to comparing the relationships between communities.
Paypal DirectPayment automatically calculate shipping cost?
Paypal DirectPayment automatically calculate shipping cost?
Paypal has this shipping fee calculator that is automatically added when
the customer reviewed the purchase in Paypal website.
But that calculator only works for payment with Paypal account (Express
Checkout) and doesn't work for Credit Card (Direct Payment) payment.
Must I write my own shipping cost calculator in my app?
Sorry for the broad question, but I can't seem to find this info on Google.
Thanks
Paypal has this shipping fee calculator that is automatically added when
the customer reviewed the purchase in Paypal website.
But that calculator only works for payment with Paypal account (Express
Checkout) and doesn't work for Credit Card (Direct Payment) payment.
Must I write my own shipping cost calculator in my app?
Sorry for the broad question, but I can't seem to find this info on Google.
Thanks
Problems when make bochs on Mac OS X mountain lion
Problems when make bochs on Mac OS X mountain lion
I have installed the X11 on Mac:
when I input some codes in terminal:
./configure --with-x11
make
After that, there appears some problems:
x.cc:37:22: error: X11/Xlib.h: No such file or directory
x.cc:38:23: error: X11/Xutil.h: No such file or directory
x.cc:39:21: error: X11/Xos.h: No such file or directory
x.cc:40:23: error: X11/Xatom.h: No such file or directory
x.cc:41:24: error: X11/keysym.h: No such file or directory
x.cc:42:35: error: X11/extensions/Xrandr.h: No such file or directory
x.cc:86: error: expected constructor, destructor, or type conversion
before '*' token
x.cc:88: error: expected initializer before '*' token
x.cc:89: error: 'Colormap' does not name a type
x.cc:104: error: 'Window' does not name a type
x.cc:105: error: 'GC' does not name a type
x.cc:108: error: expected initializer before '*' token
x.cc:136: error: 'Pixmap' does not name a type
x.cc:140: error: 'Pixmap' does not name a type
x.cc:146: error: 'Pixmap' does not name a type
x.cc:304: error: variable or field 'xkeypress' declared void
x.cc:304: error: 'KeySym' was not declared in this scope
x.cc:304: error: expected primary-expression before 'int'
x.cc:326: error: 'Colormap' was not declared in this scope
x.cc:326: error: expected primary-expression before 'n_tries'
x.cc:326: error: initializer expression list treated as compound expression
x.cc:326: error: expected ',' or ';' before '{' token
I have installed the X11 on Mac:
when I input some codes in terminal:
./configure --with-x11
make
After that, there appears some problems:
x.cc:37:22: error: X11/Xlib.h: No such file or directory
x.cc:38:23: error: X11/Xutil.h: No such file or directory
x.cc:39:21: error: X11/Xos.h: No such file or directory
x.cc:40:23: error: X11/Xatom.h: No such file or directory
x.cc:41:24: error: X11/keysym.h: No such file or directory
x.cc:42:35: error: X11/extensions/Xrandr.h: No such file or directory
x.cc:86: error: expected constructor, destructor, or type conversion
before '*' token
x.cc:88: error: expected initializer before '*' token
x.cc:89: error: 'Colormap' does not name a type
x.cc:104: error: 'Window' does not name a type
x.cc:105: error: 'GC' does not name a type
x.cc:108: error: expected initializer before '*' token
x.cc:136: error: 'Pixmap' does not name a type
x.cc:140: error: 'Pixmap' does not name a type
x.cc:146: error: 'Pixmap' does not name a type
x.cc:304: error: variable or field 'xkeypress' declared void
x.cc:304: error: 'KeySym' was not declared in this scope
x.cc:304: error: expected primary-expression before 'int'
x.cc:326: error: 'Colormap' was not declared in this scope
x.cc:326: error: expected primary-expression before 'n_tries'
x.cc:326: error: initializer expression list treated as compound expression
x.cc:326: error: expected ',' or ';' before '{' token
High Availability on Windows Azure Websites
High Availability on Windows Azure Websites
One of my main apps is hosted on Windows Azure's Websites platform. Given
last night's downtime, I realized that I need something that allows my app
to stay online if Azure decides to go to hell again.
My current setup is 1 WAWS instance (w/ autoscaling set to 1..3 instances
@ 70% CPU) and SQL Azure as a backend.
I really enjoy having WAWS's automatic git deployment feature and would
rather keep it (Web Roles can't autodeploy easily afaik), but what other
solutions could I use to reach HA + lower latencies for most of my
clients?
I've read about/though about the following scenarios:
Keep it as is and suck it up if Azure goes down again,
Generate additional regions using the same autodeploy scripts [but I'd
have to mirror my SQL Azure DBs somehow)
Move to Web Roles/VMs w/ traffic manager and self-host my DBs on my own
[either keeping SQL Server or moving to MariaDB]
Move to Amazon, Rackspace or whatever allows me to keep
What would you suggest?
One of my main apps is hosted on Windows Azure's Websites platform. Given
last night's downtime, I realized that I need something that allows my app
to stay online if Azure decides to go to hell again.
My current setup is 1 WAWS instance (w/ autoscaling set to 1..3 instances
@ 70% CPU) and SQL Azure as a backend.
I really enjoy having WAWS's automatic git deployment feature and would
rather keep it (Web Roles can't autodeploy easily afaik), but what other
solutions could I use to reach HA + lower latencies for most of my
clients?
I've read about/though about the following scenarios:
Keep it as is and suck it up if Azure goes down again,
Generate additional regions using the same autodeploy scripts [but I'd
have to mirror my SQL Azure DBs somehow)
Move to Web Roles/VMs w/ traffic manager and self-host my DBs on my own
[either keeping SQL Server or moving to MariaDB]
Move to Amazon, Rackspace or whatever allows me to keep
What would you suggest?
jQuery acts strange in Chrome with AJAX (example)
jQuery acts strange in Chrome with AJAX (example)
Im experiencing a strange issue in Chrome (or new Opera browser) and was
hoping you could shed some light to it.
Edit: Live example:
www.wcore.cz/demo/cms
login: demo password: demo
If you go to "Mùj profil" -> "Upravit" -> "Ulozit" it shows loading in
Firefox, IE etc, but not in Chrome.
I want to display a loading status to a user after he clicks an element
but it is not working when I have async=false set up in my Ajax call. It
basically waits until the call is completed and after then shows fills the
element with the "loading". It works just fine in FF, older Operas, IE..
I know that this explanation might be litle confusing, but someone could
know whats this all about.
Thank you for any tips.
Im experiencing a strange issue in Chrome (or new Opera browser) and was
hoping you could shed some light to it.
Edit: Live example:
www.wcore.cz/demo/cms
login: demo password: demo
If you go to "Mùj profil" -> "Upravit" -> "Ulozit" it shows loading in
Firefox, IE etc, but not in Chrome.
I want to display a loading status to a user after he clicks an element
but it is not working when I have async=false set up in my Ajax call. It
basically waits until the call is completed and after then shows fills the
element with the "loading". It works just fine in FF, older Operas, IE..
I know that this explanation might be litle confusing, but someone could
know whats this all about.
Thank you for any tips.
Change layout of the built-in application
Change layout of the built-in application
Is it possible to change the layout of the built-in application of the
Android?
I have Samsung S Duos and I want to change layout of some
application(dialer, SMS messenger and phone book(contacts) are not so
user-friendly for dual SIM cards)
Is it possible to make buttons of this applications bigger or smaller or
to add a new option (sub menu)?
If yes, is there easier way than rewriting and compiling whole Android
source? Or maybe there is an option to change the phone book(contacts) and
reinstall it as a new application?
Any help is appreciated
Is it possible to change the layout of the built-in application of the
Android?
I have Samsung S Duos and I want to change layout of some
application(dialer, SMS messenger and phone book(contacts) are not so
user-friendly for dual SIM cards)
Is it possible to make buttons of this applications bigger or smaller or
to add a new option (sub menu)?
If yes, is there easier way than rewriting and compiling whole Android
source? Or maybe there is an option to change the phone book(contacts) and
reinstall it as a new application?
Any help is appreciated
How prove this $\sum_{k=1}^{n}\frac{k}{3^k-2^k}
How prove this $\sum_{k=1}^{n}\frac{k}{3^k-2^k}
prove that $$\sum_{k=1}^{n}\dfrac{k}{3^k-2^k}<\dfrac{5}{3}$$
my idea: use $$3^k-2^k>2^k(k\ge 2)$$ then $$\Longleftrightarrow
1+\sum_{k=2}^{n}\dfrac{k}{3^k-2^k}<1+\sum_{k=2}^{n}\dfrac{k}{2^k}<1+\sum_{k=2}^{\infty}\dfrac{k}{2^k}=1+\dfrac{3}{2}>\dfrac{5}{3}$$
use this methods,I can't prove it
other idea: $$3^k-2^k>2\cdot 2^k(k\ge 3)$$
But This same can't prove it
so This problem have other nice methods? Thank you
prove that $$\sum_{k=1}^{n}\dfrac{k}{3^k-2^k}<\dfrac{5}{3}$$
my idea: use $$3^k-2^k>2^k(k\ge 2)$$ then $$\Longleftrightarrow
1+\sum_{k=2}^{n}\dfrac{k}{3^k-2^k}<1+\sum_{k=2}^{n}\dfrac{k}{2^k}<1+\sum_{k=2}^{\infty}\dfrac{k}{2^k}=1+\dfrac{3}{2}>\dfrac{5}{3}$$
use this methods,I can't prove it
other idea: $$3^k-2^k>2\cdot 2^k(k\ge 3)$$
But This same can't prove it
so This problem have other nice methods? Thank you
how to get the text of second TD with all tr having class warning
how to get the text of second TD with all tr having class warning
The code which i am working on is as follows:
<table>
<tr class="warning">
<td> 1 </td>
<td> name </td>
<td> address </td>
<td> phone no </td>
<td> Location </td>
</tr>
<tr>
<td> 3 </td>
<td> name2 </td>
<td> address2 </td>
<td> phone no2 </td>
<td> Location2 </td>
</tr>
<tr class="warning">
<td> 6 </td>
<td> name5 </td>
<td> address5 </td>
<td> phone no5 </td>
<td> Location5 </td>
</tr>
<tr>
<td> 7 </td>
<td> name6 </td>
<td> address6 </td>
<td> phone no6 </td>
<td> Location6 </td>
</tr>
I like to get the text of all second TD with all tr with class warning.
I have tried using _.each method but wasn't succesful
The code which i am working on is as follows:
<table>
<tr class="warning">
<td> 1 </td>
<td> name </td>
<td> address </td>
<td> phone no </td>
<td> Location </td>
</tr>
<tr>
<td> 3 </td>
<td> name2 </td>
<td> address2 </td>
<td> phone no2 </td>
<td> Location2 </td>
</tr>
<tr class="warning">
<td> 6 </td>
<td> name5 </td>
<td> address5 </td>
<td> phone no5 </td>
<td> Location5 </td>
</tr>
<tr>
<td> 7 </td>
<td> name6 </td>
<td> address6 </td>
<td> phone no6 </td>
<td> Location6 </td>
</tr>
I like to get the text of all second TD with all tr with class warning.
I have tried using _.each method but wasn't succesful
Friday, 23 August 2013
Why a blog uses HTTPS? Does it necessary?
Why a blog uses HTTPS? Does it necessary?
I saw that some normal blogs used HTTPS? Why they did so? Django
https://www.djangoproject.com/ uses it too. Thanks.
I saw that some normal blogs used HTTPS? Why they did so? Django
https://www.djangoproject.com/ uses it too. Thanks.
Change Python version in Maya
Change Python version in Maya
I'm trying to change the version of python within maya. Specifically, I
want maya (maya 2013) script editor to use python2.7 and all other
packages/modules attached to that version. I also want to be able to
import pymel and maya from eclipse.
I've tried following this response but no luck. Maya still points to its
default version.
From python, i try to import pymel with
import pymel.core as pm
and I get an error that reads
File "", line 1, in File
"/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pymel/core/init.py",
line 6, in import pymel.versions as _versions File
"/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pymel/versions.py",
line 12, in from maya.OpenMaya import MGlobal as _MGlobal ImportError: Bad
magic number in
/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/maya/OpenMaya.pyc
Thanks in advance.
I'm trying to change the version of python within maya. Specifically, I
want maya (maya 2013) script editor to use python2.7 and all other
packages/modules attached to that version. I also want to be able to
import pymel and maya from eclipse.
I've tried following this response but no luck. Maya still points to its
default version.
From python, i try to import pymel with
import pymel.core as pm
and I get an error that reads
File "", line 1, in File
"/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pymel/core/init.py",
line 6, in import pymel.versions as _versions File
"/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pymel/versions.py",
line 12, in from maya.OpenMaya import MGlobal as _MGlobal ImportError: Bad
magic number in
/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/maya/OpenMaya.pyc
Thanks in advance.
Trying to pass images from a model/herlper file to a slideshow in codeigniter using a an array and foreach
Trying to pass images from a model/herlper file to a slideshow in
codeigniter using a an array and foreach
I have a controller pages.php:
class Pages extends CI_Controller {
public function index($page = 'home')
{
if ( ! file_exists('application/views/pages/'.$page.'.php'))
{
// Whoops, we don't have a page for that!
show_404();
}
$this->lang->load('common/menu.php');
$this->lang->load('pages/'.$page.'.php');
$data = array();
$this->load->helper('slideshow');
$data['slideshow'] = get_image_array();
$this->load->view('templates/common/header', $data);
$this->load->view('modules/slideshow', $data);
$this->load->view('pages/'.$page, $data);
$this->load->view('templates/common/footer', $data);
}
}
My slideshow_helper file:
function get_image_array(){
$images = array(img("slideshow/desktop/home1.jpg",
"one"),img("slideshow/desktop/home2.jpg",
"two"),img("slideshow/desktop/home3.jpg", "three"));
$captions = array("first image", "second image", "third image");
return array_combine($images, $captions);
}
And the slideshow view:
<div class="container">
<div class="row">
<div class="col-xs-12">
<div id="carousel-desktop" class="carousel slide visible-md
visible-lg">
<ol class="carousel-indicators">
<li data-target="#carousel-desktop" data-slide-to="0"
class="active"></li>
<li data-target="#carousel-desktop"
data-slide-to="1"></li>
<li data-target="#carousel-desktop"
data-slide-to="2"></li>
</ol>
<div class="carousel-inner">
<?php $i = 1; ?>
<?php foreach ($image as $imageSrc => $caption ):?>
<?php $item_class = ($i == 1) ? 'item active' :
'item'; ?>
<div class="<?php echo $item_class; ?>">
<?php echo $image; if($caption != ""){ ?>
<div class="carousel-caption">
<?php echo $caption;?>
</div>
<?php } ?>
</div>
<?php $i++; ?>
<?php endforeach; ?>
</div>
<a class="left carousel-control" href="#carousel-desktop"
data-slide="prev">
<span class="icon-chevron-sign-left"></span>
</a>
<a class="right carousel-control"
href="#carousel-desktop" data-slide="next">
<span class="icon-chevron-sign-right"></span>
</a>
</div>
<br />
</div>
</div>
</div>
<br />
Unfortunately this does not work am I missing something? I get the
following error:
A PHP Error was encountered
Severity: Notice
Message: Undefined variable: image
Filename: pages/home.php
-AND-
A PHP Error was encountered
Severity: Warning
Message: Invalid argument supplied for foreach()
Filename: pages/home.php
Or is it completly wrong I should point out that this site will not have
access to a database.
When I have the array in the view file it works.
What I am trying to do is have a different model/helper file for each page
as each page of this controller will have a slideshow but each with
different images. So rather than recreating the view part countless times
I want to simply have a new array for each page. I was thinking of using
something like:
$this->load->helper('pages/'.$page);
-or-
$this->load->model('pages/'.$page.'.php');
so each page has its own model/helper filer but obvioulsy as I cannot get
the first bit working I have no idea if this second bit will work.
Any help will be very much appriciated
codeigniter using a an array and foreach
I have a controller pages.php:
class Pages extends CI_Controller {
public function index($page = 'home')
{
if ( ! file_exists('application/views/pages/'.$page.'.php'))
{
// Whoops, we don't have a page for that!
show_404();
}
$this->lang->load('common/menu.php');
$this->lang->load('pages/'.$page.'.php');
$data = array();
$this->load->helper('slideshow');
$data['slideshow'] = get_image_array();
$this->load->view('templates/common/header', $data);
$this->load->view('modules/slideshow', $data);
$this->load->view('pages/'.$page, $data);
$this->load->view('templates/common/footer', $data);
}
}
My slideshow_helper file:
function get_image_array(){
$images = array(img("slideshow/desktop/home1.jpg",
"one"),img("slideshow/desktop/home2.jpg",
"two"),img("slideshow/desktop/home3.jpg", "three"));
$captions = array("first image", "second image", "third image");
return array_combine($images, $captions);
}
And the slideshow view:
<div class="container">
<div class="row">
<div class="col-xs-12">
<div id="carousel-desktop" class="carousel slide visible-md
visible-lg">
<ol class="carousel-indicators">
<li data-target="#carousel-desktop" data-slide-to="0"
class="active"></li>
<li data-target="#carousel-desktop"
data-slide-to="1"></li>
<li data-target="#carousel-desktop"
data-slide-to="2"></li>
</ol>
<div class="carousel-inner">
<?php $i = 1; ?>
<?php foreach ($image as $imageSrc => $caption ):?>
<?php $item_class = ($i == 1) ? 'item active' :
'item'; ?>
<div class="<?php echo $item_class; ?>">
<?php echo $image; if($caption != ""){ ?>
<div class="carousel-caption">
<?php echo $caption;?>
</div>
<?php } ?>
</div>
<?php $i++; ?>
<?php endforeach; ?>
</div>
<a class="left carousel-control" href="#carousel-desktop"
data-slide="prev">
<span class="icon-chevron-sign-left"></span>
</a>
<a class="right carousel-control"
href="#carousel-desktop" data-slide="next">
<span class="icon-chevron-sign-right"></span>
</a>
</div>
<br />
</div>
</div>
</div>
<br />
Unfortunately this does not work am I missing something? I get the
following error:
A PHP Error was encountered
Severity: Notice
Message: Undefined variable: image
Filename: pages/home.php
-AND-
A PHP Error was encountered
Severity: Warning
Message: Invalid argument supplied for foreach()
Filename: pages/home.php
Or is it completly wrong I should point out that this site will not have
access to a database.
When I have the array in the view file it works.
What I am trying to do is have a different model/helper file for each page
as each page of this controller will have a slideshow but each with
different images. So rather than recreating the view part countless times
I want to simply have a new array for each page. I was thinking of using
something like:
$this->load->helper('pages/'.$page);
-or-
$this->load->model('pages/'.$page.'.php');
so each page has its own model/helper filer but obvioulsy as I cannot get
the first bit working I have no idea if this second bit will work.
Any help will be very much appriciated
linking google plus to a button to add vote and take to an other link.
linking google plus to a button to add vote and take to an other link.
I am working on a project recently it's my first project and the clients
has some weird requirement. I have got 5 links in my website and my client
want it to be something like this that whenever someone clicks on any link
on the webpage automatically it social counts on google + and than
transfer to the desired webpage. For example If I have a buy now button
and the user clicks on it, it will automatically add a google plus vote
and will take me to the product page. Please help me with your answers and
explain the whole thing to me, as I am just a beginner. Regards, Saman.
I am working on a project recently it's my first project and the clients
has some weird requirement. I have got 5 links in my website and my client
want it to be something like this that whenever someone clicks on any link
on the webpage automatically it social counts on google + and than
transfer to the desired webpage. For example If I have a buy now button
and the user clicks on it, it will automatically add a google plus vote
and will take me to the product page. Please help me with your answers and
explain the whole thing to me, as I am just a beginner. Regards, Saman.
Thursday, 22 August 2013
Scala parameters pattern (Spray routing example)
Scala parameters pattern (Spray routing example)
Sorry about the vague title...wasn't sure how to characterize this.
I've seen/used a certain code construction in Scala for some time but I
don't know how it works. It looks like this (example from Spray routing):
path( "foo" / Segment / Segment ) { (a,b) => { // <-- What's this style
with a,b?
...
}}
In this example, the Segements in the path are bound to a and b
respectively inside the associated block. I know how to use this pattern
but how does it work? Why didn't it bind something to "foo"?
I'm not so interested in how spray works for my purpose here, but what
facility of Scala is this, and how would I write my own?
Thanks, Greg
Sorry about the vague title...wasn't sure how to characterize this.
I've seen/used a certain code construction in Scala for some time but I
don't know how it works. It looks like this (example from Spray routing):
path( "foo" / Segment / Segment ) { (a,b) => { // <-- What's this style
with a,b?
...
}}
In this example, the Segements in the path are bound to a and b
respectively inside the associated block. I know how to use this pattern
but how does it work? Why didn't it bind something to "foo"?
I'm not so interested in how spray works for my purpose here, but what
facility of Scala is this, and how would I write my own?
Thanks, Greg
SqlDataSource InsertCommand Missing Required Parameters
SqlDataSource InsertCommand Missing Required Parameters
I keep getting an OleDbException :"No value given for one or more required
parameters" - Not very specific.
I have had no luck finding a solution to my problem online. I have tried
many different things like not declaring the Parameters in the form and
creating them at run time in the code behind.
Here is my ugly code:
<asp:sqldatasource ID="datasource" runat="server" ConnectionString="<%$
ConnectionStrings:ConnectionString %>" ProviderName="<%$
ConnectionStrings:ConnectionString.ProviderName %>"
SelectCommand="SELECT [ID], [Test Data] AS Test_Data, [More Data] AS
More_Data FROM [Main]"
UpdateCommand="UPDATE [Main] SET [Test Data]=@TestData, [More
Data]=@MoreData WHERE [ID]=@ID"
InsertCommand="INSERT INTO [Main] ([ID], [Test Data], [More Data])
VALUES (@InsertID, @InsertTestData, @InsertMoreData)"
DeleteCommand="" >
<UpdateParameters>
<asp:ControlParameter Name="TestData" ControlId="updateTest"
PropertyName="Text" />
<asp:ControlParameter Name="MoreData" ControlId="updateMore"
PropertyName="Text" />
<asp:ControlParameter Name="InsertTestData" ControlId="insertTest"
PropertyName="Text" />
<asp:ControlParameter Name="InsertID" ControlId="insertIDD"
PropertyName="SelectedValue" />
<asp:ControlParameter Name="InsertMoreData" ControlId="insertMore"
PropertyName="Text" />
<asp:ControlParameter Name="ID" ControlId="DropDownList2"
PropertyName="SelectedValue" />
</UpdateParameters>
</asp:sqldatasource>
<asp:GridView ID="GridView1" runat="server" AllowSorting="true"
DataSourceID="datasource"></asp:GridView>
<br />
<asp:DropDownList ID="insertIDD" DataSourceID="datasource"
DataTextField="ID" runat="server"
Font-Bold="False"></asp:DropDownList>
<asp:TextBox ID="insertTest" runat="server"></asp:TextBox>
<asp:TextBox ID="insertMore" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Insert" OnClick="Insert" />
<br />
<asp:DropDownList ID="DropDownList2" runat="server"
DataSourceID="datasource" DataTextField="ID"
OnTextChanged="populateDrop" AutoPostBack="true"></asp:DropDownList>
<asp:TextBox ID="updateTest" runat="server"></asp:TextBox>
<asp:TextBox ID="updateMore" runat="server"></asp:TextBox>
<asp:Button ID="Button2" runat="server" Text="Update" OnClick="Update" />
<br />
<asp:Button ID="Button3" runat="server" Text="Delete" OnClick="Delete"
/>**
And the C# Code Behind:
namespace WebApplication2
{
public partial class WebForm1 : System.Web.UI.Page
{
DataView dv = new DataView();
protected void Page_Load(object sender, EventArgs e)
{
dv = (DataView)datasource.Select(DataSourceSelectArguments.Empty);
updateTest.Text = dv[0]["Test_Data"].ToString();
updateMore.Text = dv[0]["More_Data"].ToString();
}
protected void Insert(object sender, EventArgs e)
{
datasource.Insert();
}
protected void Update(object sender, EventArgs e)
{
datasource.Update();
updateTest.Text = "";
updateMore.Text = "";
}
SELECT and UPDATE work without any problem. No matter what I try I cannot
get the INSERT INTO command to be happy. I am sure it is something simple
that I am missing, but any help would be greatly appreciated, thanks!
I keep getting an OleDbException :"No value given for one or more required
parameters" - Not very specific.
I have had no luck finding a solution to my problem online. I have tried
many different things like not declaring the Parameters in the form and
creating them at run time in the code behind.
Here is my ugly code:
<asp:sqldatasource ID="datasource" runat="server" ConnectionString="<%$
ConnectionStrings:ConnectionString %>" ProviderName="<%$
ConnectionStrings:ConnectionString.ProviderName %>"
SelectCommand="SELECT [ID], [Test Data] AS Test_Data, [More Data] AS
More_Data FROM [Main]"
UpdateCommand="UPDATE [Main] SET [Test Data]=@TestData, [More
Data]=@MoreData WHERE [ID]=@ID"
InsertCommand="INSERT INTO [Main] ([ID], [Test Data], [More Data])
VALUES (@InsertID, @InsertTestData, @InsertMoreData)"
DeleteCommand="" >
<UpdateParameters>
<asp:ControlParameter Name="TestData" ControlId="updateTest"
PropertyName="Text" />
<asp:ControlParameter Name="MoreData" ControlId="updateMore"
PropertyName="Text" />
<asp:ControlParameter Name="InsertTestData" ControlId="insertTest"
PropertyName="Text" />
<asp:ControlParameter Name="InsertID" ControlId="insertIDD"
PropertyName="SelectedValue" />
<asp:ControlParameter Name="InsertMoreData" ControlId="insertMore"
PropertyName="Text" />
<asp:ControlParameter Name="ID" ControlId="DropDownList2"
PropertyName="SelectedValue" />
</UpdateParameters>
</asp:sqldatasource>
<asp:GridView ID="GridView1" runat="server" AllowSorting="true"
DataSourceID="datasource"></asp:GridView>
<br />
<asp:DropDownList ID="insertIDD" DataSourceID="datasource"
DataTextField="ID" runat="server"
Font-Bold="False"></asp:DropDownList>
<asp:TextBox ID="insertTest" runat="server"></asp:TextBox>
<asp:TextBox ID="insertMore" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Insert" OnClick="Insert" />
<br />
<asp:DropDownList ID="DropDownList2" runat="server"
DataSourceID="datasource" DataTextField="ID"
OnTextChanged="populateDrop" AutoPostBack="true"></asp:DropDownList>
<asp:TextBox ID="updateTest" runat="server"></asp:TextBox>
<asp:TextBox ID="updateMore" runat="server"></asp:TextBox>
<asp:Button ID="Button2" runat="server" Text="Update" OnClick="Update" />
<br />
<asp:Button ID="Button3" runat="server" Text="Delete" OnClick="Delete"
/>**
And the C# Code Behind:
namespace WebApplication2
{
public partial class WebForm1 : System.Web.UI.Page
{
DataView dv = new DataView();
protected void Page_Load(object sender, EventArgs e)
{
dv = (DataView)datasource.Select(DataSourceSelectArguments.Empty);
updateTest.Text = dv[0]["Test_Data"].ToString();
updateMore.Text = dv[0]["More_Data"].ToString();
}
protected void Insert(object sender, EventArgs e)
{
datasource.Insert();
}
protected void Update(object sender, EventArgs e)
{
datasource.Update();
updateTest.Text = "";
updateMore.Text = "";
}
SELECT and UPDATE work without any problem. No matter what I try I cannot
get the INSERT INTO command to be happy. I am sure it is something simple
that I am missing, but any help would be greatly appreciated, thanks!
swf embed works only for selected domains.
swf embed works only for selected domains.
Since about a week or two the swf embed feature stopped working for my
website. I realized that it stopped working for a few websites but was
still working for soundcloud.com. After doing some research i was able to
pinpoint the issue to a single open graph tag.
A website containing the following does seam to work:
<!DOCTYPE html>
<html lang="en" xml:lang="en" xmlns="http://www.w3.org/1999/xhtml"><head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<meta charset="utf-8">
<meta content="music.song" property="og:type">
<meta content="http://venc.pl/test.html" property="og:url">
<meta content="Asd - Keygen Music" property="og:title">
<meta
content="http://i1.sndcdn.com/artworks-000026602093-dp518o-t500x500.jpg?16b9957"
property="og:image">
<meta content="Listen to Asd / Asd - Keygen Music | Explore the largest
community of artists, bands, podcasters and creators of music &
audio." property="og:description">
<meta content="SoundCloud" property="og:site_name">
<meta content="video" name="medium">
<meta content="98" property="og:video:height">
<meta content="460" property="og:video:width">
<meta content="application/x-shockwave-flash" property="og:video:type">
<meta content="http://player.soundcloud.com/player2.swf" property="og:video">
</head></html>
But the following does not
<!DOCTYPE html>
<html lang="en" xml:lang="en" xmlns="http://www.w3.org/1999/xhtml"><head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<meta charset="utf-8">
<meta content="music.song" property="og:type">
<meta content="http://venc.pl/test2.html" property="og:url">
<meta content="Asd - Keygen Music" property="og:title">
<meta
content="http://i1.sndcdn.com/artworks-000026602093-dp518o-t500x500.jpg?16b9957"
property="og:image">
<meta content="Listen to Asd / Asd - Keygen Music | Explore the largest
community of artists, bands, podcasters and creators of music &
audio." property="og:description">
<meta content="SoundCloud" property="og:site_name">
<meta content="video" name="medium">
<meta content="98" property="og:video:height">
<meta content="460" property="og:video:width">
<meta content="application/x-shockwave-flash" property="og:video:type">
<meta content="http://venc.pl/player.swf" property="og:video">
</head></html>
So it basically boils down to changes in the domain presented in the
og:video tag (). There used to be a whitelist of websites enabled to embed
swf on facebook a few years ago. The idea was dropped but I think that
Facebook just got back to it.
How can I get in touch with facebook to resolve this issue? If a
whitelisting is needed how do I ask for being whitelisted?
Since about a week or two the swf embed feature stopped working for my
website. I realized that it stopped working for a few websites but was
still working for soundcloud.com. After doing some research i was able to
pinpoint the issue to a single open graph tag.
A website containing the following does seam to work:
<!DOCTYPE html>
<html lang="en" xml:lang="en" xmlns="http://www.w3.org/1999/xhtml"><head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<meta charset="utf-8">
<meta content="music.song" property="og:type">
<meta content="http://venc.pl/test.html" property="og:url">
<meta content="Asd - Keygen Music" property="og:title">
<meta
content="http://i1.sndcdn.com/artworks-000026602093-dp518o-t500x500.jpg?16b9957"
property="og:image">
<meta content="Listen to Asd / Asd - Keygen Music | Explore the largest
community of artists, bands, podcasters and creators of music &
audio." property="og:description">
<meta content="SoundCloud" property="og:site_name">
<meta content="video" name="medium">
<meta content="98" property="og:video:height">
<meta content="460" property="og:video:width">
<meta content="application/x-shockwave-flash" property="og:video:type">
<meta content="http://player.soundcloud.com/player2.swf" property="og:video">
</head></html>
But the following does not
<!DOCTYPE html>
<html lang="en" xml:lang="en" xmlns="http://www.w3.org/1999/xhtml"><head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<meta charset="utf-8">
<meta content="music.song" property="og:type">
<meta content="http://venc.pl/test2.html" property="og:url">
<meta content="Asd - Keygen Music" property="og:title">
<meta
content="http://i1.sndcdn.com/artworks-000026602093-dp518o-t500x500.jpg?16b9957"
property="og:image">
<meta content="Listen to Asd / Asd - Keygen Music | Explore the largest
community of artists, bands, podcasters and creators of music &
audio." property="og:description">
<meta content="SoundCloud" property="og:site_name">
<meta content="video" name="medium">
<meta content="98" property="og:video:height">
<meta content="460" property="og:video:width">
<meta content="application/x-shockwave-flash" property="og:video:type">
<meta content="http://venc.pl/player.swf" property="og:video">
</head></html>
So it basically boils down to changes in the domain presented in the
og:video tag (). There used to be a whitelist of websites enabled to embed
swf on facebook a few years ago. The idea was dropped but I think that
Facebook just got back to it.
How can I get in touch with facebook to resolve this issue? If a
whitelisting is needed how do I ask for being whitelisted?
Xamarin - Collaps text
Xamarin - Collaps text
just got Xamarin Studio installed. Looks really cool and looks like it
could replace my VS. However, I really enjoyed collapsing my code when
some dirty parts began to grow.
I used to introduce the code- part with #region and finished it with
just got Xamarin Studio installed. Looks really cool and looks like it
could replace my VS. However, I really enjoyed collapsing my code when
some dirty parts began to grow.
I used to introduce the code- part with #region and finished it with
centos 6.0 : how to print to a Xerox laser printer
centos 6.0 : how to print to a Xerox laser printer
I use a centos 6.0. How can I print to the Xerox printer from my
applications -- like LibreOffice, emacs, eclipse, chrome, etc ?
I use a centos 6.0. How can I print to the Xerox printer from my
applications -- like LibreOffice, emacs, eclipse, chrome, etc ?
Remove unwanted resource strings in Silverlight Application in Visual Studio 2010
Remove unwanted resource strings in Silverlight Application in Visual
Studio 2010
I have a silverlight application(Silverlight 4.0) and have a lot of
strings in the ApplicationStrings.resx file. I want to remove the unwanted
resource strings in the resource file. Please help me out.
Studio 2010
I have a silverlight application(Silverlight 4.0) and have a lot of
strings in the ApplicationStrings.resx file. I want to remove the unwanted
resource strings in the resource file. Please help me out.
Wednesday, 21 August 2013
How do I extend the String class?
How do I extend the String class?
Extending core classes in javascript is dead easy. I get the impression
it's not quite so easy in C#. I was wanting to add some things to the
String class so that I could do stuff like:
string s = "the cat's mat sat";
string sql = s.smartsingleQuote();
thus giving me
the cat''s mat sat
Is that even feasible, or do I have to write a function for that?
Extending core classes in javascript is dead easy. I get the impression
it's not quite so easy in C#. I was wanting to add some things to the
String class so that I could do stuff like:
string s = "the cat's mat sat";
string sql = s.smartsingleQuote();
thus giving me
the cat''s mat sat
Is that even feasible, or do I have to write a function for that?
rcs checkout without touching the current working file
rcs checkout without touching the current working file
The idea is somehow ridiculous, but still I'm wondering whether there is
an actual way.
My object: I would like to view a older version of a RCS file without
touching the latest working version. Below are my thoughts:
Method 1: check out the older version to another directory (ridiculous
since the concept looks totally wrong)
Method 2: create another branch based on the older version and then put
the file into the branch (but inevitably, the checking out of the older
version still need to over write the latest working file one time at
least)
Yan
The idea is somehow ridiculous, but still I'm wondering whether there is
an actual way.
My object: I would like to view a older version of a RCS file without
touching the latest working version. Below are my thoughts:
Method 1: check out the older version to another directory (ridiculous
since the concept looks totally wrong)
Method 2: create another branch based on the older version and then put
the file into the branch (but inevitably, the checking out of the older
version still need to over write the latest working file one time at
least)
Yan
Use Collections java object in Processing.js
Use Collections java object in Processing.js
I'm in need of the Collections object but Processing.js keeps spitting
back an error saying Collections is not defined as though it doesn't
recognize it as an object. I'm trying to find the minimum value of an
ArrayList by using the Collections.min function so this would be really
useful.
ArrayList<int> aaa = new ArrayList<int> ();
println(aaa);
Collections<int> fff = new Collections<int> ();
println(fff);
I'm in need of the Collections object but Processing.js keeps spitting
back an error saying Collections is not defined as though it doesn't
recognize it as an object. I'm trying to find the minimum value of an
ArrayList by using the Collections.min function so this would be really
useful.
ArrayList<int> aaa = new ArrayList<int> ();
println(aaa);
Collections<int> fff = new Collections<int> ();
println(fff);
How can I get music from other languages on my iPhone?
How can I get music from other languages on my iPhone?
So, I have English iTunes and I wanted to get a Spanish song. Is there a
way I could change iTunes to get it and then change it back or something?
So, I have English iTunes and I wanted to get a Spanish song. Is there a
way I could change iTunes to get it and then change it back or something?
java client-server program crashes after first iteration through loop
java client-server program crashes after first iteration through loop
I an having a problem with a client-server application - the program runs
correctly though until the second time the client must input data - upon
debugging the coed it appears that the client always crashes on the line
linesIn = din.readInt(); on the second iteration through the loop
also the following error is displayed
Exception in thread "main" java.net.SocketException: Connection reset
at java.net.SocketInputStream.read(SocketInputStream.java:189)
at java.net.SocketInputStream.read(SocketInputStream.java:121)
at java.net.SocketInputStream.read(SocketInputStream.java:203)
at java.io.DataInputStream.readInt(DataInputStream.java:387)
at syssoftclient.Syssoftclient.main(Syssoftclient.java:65)
any help would be greatly appreciated
server thread code
package systemssoftwarebookingsystem;
import java.net.*;
import java.io.*;
import java.util.Scanner;
public class serverThread extends Thread
{
private Socket socket = null;
private PrintWriter write = null;
private BufferedReader read = null;
public serverThread(Socket socket)
{
super("serverThread");
this.socket = socket;
}
public void run()
{
Scanner in;
in = new Scanner(System.in);
char[] input;
int inputReferance = 0;
int inputSeatAmount = 0;
boolean filmFound = false;
boolean exit = false;
try
{
read = new BufferedReader(new
InputStreamReader(socket.getInputStream()));
write = new PrintWriter(new
DataOutputStream(socket.getOutputStream()));
DataOutputStream out = new
DataOutputStream(socket.getOutputStream());
int choice = 0;
while (exit == false)
{
choice = 0;
out.writeInt(5);
write.println("Welcome please make your selection from the
options below \n 1: make a booking \n 2: cancel a booking
\n 3: view available films \n 4: logout");
write.flush();
input = new char[1];
read.read(input);
choice = Integer.parseInt(new String(input));
switch (choice)
{
case 1:
{
Film tempFilm = null;
out.writeInt(1);
write.println("Please enter the referance number
of the film you wish to watch");
write.flush();
read.read(input);
inputReferance = Integer.parseInt(new String(input));
for (Film s : server.filmList)
{
if (s.referanceNumber == inputReferance)
{
filmFound = true;
tempFilm = s;
}
}
if (filmFound == false)
{
out.writeInt(1);
write.println("Sorry. That referance number
was not recognised. Please try again");
write.flush();
break;
}
if (filmFound == true)
{
out.writeInt(1);
write.println("Please enter the numbe rof
seats you wish to book");
write.flush();
inputSeatAmount = read.read(input);
inputSeatAmount = Integer.parseInt(new
String(input));
if (tempFilm.seatsAvailable < inputSeatAmount)
{
out.writeInt(2);
write.println("Sorry. There are not
enough seats available for that film \n
Only " + tempFilm.seatsAvailable + "seats
are available");
write.flush();
break;
}
server.bookings.add(new
Booking(inputReferance, server.bookingNumber,
inputSeatAmount));
server.bookingNumber++;
out.writeInt(1);
write.println("booking placed successfully");
write.flush();
break;
}
}
case 2:
{
out.writeInt(1);
write.println("Please enter the booking number of
the booking you wish to cancel");
write.flush();
inputReferance = read.read(input);
inputReferance = Integer.parseInt(new String(input));
for (Booking s : server.bookings)
{
if (s.bookingNumber == inputReferance)
{
filmFound = true;
break;
}
}
if (filmFound == false)
{
out.writeInt(1);
write.println("Sorry. That booking number was
not recognised. Please try again");
write.flush();
break;
}
server.bookings.remove(inputReferance);
out.writeInt(1);
write.println("booking cancelled");
write.flush();
break;
}
case 3:
{
for (Film s : server.filmList)
{
out.writeInt(6);
write.println("Title :" + s.name + "\n Time :
" + s.showingTime + "\n Date : " + s.day + " "
+ s.month + " " + s.year + "\n Price : " +
s.price + "\n Referance Number : " +
s.referanceNumber + "\n");
write.flush();
}
out.writeInt(1);
write.println("end of list");
write.flush();
break;
}
case 4:
{
exit = true;
out.writeInt(1);
write.println("Bye.");
write.flush();
break;
}
}
}
socket.close();
} catch (IOException e)
{
e.printStackTrace();
}
}
}
client code
package syssoftclient;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
public class Syssoftclient
{
public static void main(String[] args) throws IOException
{
try
{
InetAddress internetAddress = InetAddress.getLocalHost();
System.out.println("The address and hostname are: " +
internetAddress);
System.out.println("The Hostname: " +
internetAddress.getHostName());
System.out.println("The Address only: " +
internetAddress.getHostAddress());
} catch (UnknownHostException e)
{
System.err.println("Connection problem " + e);
}
Socket SocketC = null;
PrintWriter out = null;
BufferedReader in = null;
boolean exit = false;
try
{
SocketC = new Socket(InetAddress.getLocalHost().getHostName(),
8888);
out = new PrintWriter(SocketC.getOutputStream(), true);
in = new BufferedReader(new
InputStreamReader(SocketC.getInputStream()));
} catch (UnknownHostException e)
{
System.err.println("Host not recognised");
System.exit(1);
} catch (IOException e)
{
System.err.println("Couldn't get I/O for the connection");
System.exit(1);
}
String fromServer = null;
String fromUser = null;
BufferedReader stdIn = new BufferedReader(new
InputStreamReader(System.in));
DataInputStream din;
din = new DataInputStream(SocketC.getInputStream());
int lineCount = 0;
int linesIn = 0;
while (exit == false)
{
lineCount = 0;
linesIn = din.readInt();
while (lineCount < linesIn)
{
fromServer = in.readLine();
System.out.println("Server: " + fromServer);
lineCount++;
}
if ("Bye.".equals(fromServer))
{
System.out.println("Quitting");
exit = true;
break;
}
System.out.println("Client: ");
fromUser = stdIn.readLine(); //reads userinput
if (fromUser != null)
{
out.println(fromUser); //sends user input to the server
out.flush();
}
if ("exit".equals(fromUser))
{
exit = true;
}
}
out.close();
in.close();
stdIn.close();
SocketC.close(); //close everything before ending program
}
}
I an having a problem with a client-server application - the program runs
correctly though until the second time the client must input data - upon
debugging the coed it appears that the client always crashes on the line
linesIn = din.readInt(); on the second iteration through the loop
also the following error is displayed
Exception in thread "main" java.net.SocketException: Connection reset
at java.net.SocketInputStream.read(SocketInputStream.java:189)
at java.net.SocketInputStream.read(SocketInputStream.java:121)
at java.net.SocketInputStream.read(SocketInputStream.java:203)
at java.io.DataInputStream.readInt(DataInputStream.java:387)
at syssoftclient.Syssoftclient.main(Syssoftclient.java:65)
any help would be greatly appreciated
server thread code
package systemssoftwarebookingsystem;
import java.net.*;
import java.io.*;
import java.util.Scanner;
public class serverThread extends Thread
{
private Socket socket = null;
private PrintWriter write = null;
private BufferedReader read = null;
public serverThread(Socket socket)
{
super("serverThread");
this.socket = socket;
}
public void run()
{
Scanner in;
in = new Scanner(System.in);
char[] input;
int inputReferance = 0;
int inputSeatAmount = 0;
boolean filmFound = false;
boolean exit = false;
try
{
read = new BufferedReader(new
InputStreamReader(socket.getInputStream()));
write = new PrintWriter(new
DataOutputStream(socket.getOutputStream()));
DataOutputStream out = new
DataOutputStream(socket.getOutputStream());
int choice = 0;
while (exit == false)
{
choice = 0;
out.writeInt(5);
write.println("Welcome please make your selection from the
options below \n 1: make a booking \n 2: cancel a booking
\n 3: view available films \n 4: logout");
write.flush();
input = new char[1];
read.read(input);
choice = Integer.parseInt(new String(input));
switch (choice)
{
case 1:
{
Film tempFilm = null;
out.writeInt(1);
write.println("Please enter the referance number
of the film you wish to watch");
write.flush();
read.read(input);
inputReferance = Integer.parseInt(new String(input));
for (Film s : server.filmList)
{
if (s.referanceNumber == inputReferance)
{
filmFound = true;
tempFilm = s;
}
}
if (filmFound == false)
{
out.writeInt(1);
write.println("Sorry. That referance number
was not recognised. Please try again");
write.flush();
break;
}
if (filmFound == true)
{
out.writeInt(1);
write.println("Please enter the numbe rof
seats you wish to book");
write.flush();
inputSeatAmount = read.read(input);
inputSeatAmount = Integer.parseInt(new
String(input));
if (tempFilm.seatsAvailable < inputSeatAmount)
{
out.writeInt(2);
write.println("Sorry. There are not
enough seats available for that film \n
Only " + tempFilm.seatsAvailable + "seats
are available");
write.flush();
break;
}
server.bookings.add(new
Booking(inputReferance, server.bookingNumber,
inputSeatAmount));
server.bookingNumber++;
out.writeInt(1);
write.println("booking placed successfully");
write.flush();
break;
}
}
case 2:
{
out.writeInt(1);
write.println("Please enter the booking number of
the booking you wish to cancel");
write.flush();
inputReferance = read.read(input);
inputReferance = Integer.parseInt(new String(input));
for (Booking s : server.bookings)
{
if (s.bookingNumber == inputReferance)
{
filmFound = true;
break;
}
}
if (filmFound == false)
{
out.writeInt(1);
write.println("Sorry. That booking number was
not recognised. Please try again");
write.flush();
break;
}
server.bookings.remove(inputReferance);
out.writeInt(1);
write.println("booking cancelled");
write.flush();
break;
}
case 3:
{
for (Film s : server.filmList)
{
out.writeInt(6);
write.println("Title :" + s.name + "\n Time :
" + s.showingTime + "\n Date : " + s.day + " "
+ s.month + " " + s.year + "\n Price : " +
s.price + "\n Referance Number : " +
s.referanceNumber + "\n");
write.flush();
}
out.writeInt(1);
write.println("end of list");
write.flush();
break;
}
case 4:
{
exit = true;
out.writeInt(1);
write.println("Bye.");
write.flush();
break;
}
}
}
socket.close();
} catch (IOException e)
{
e.printStackTrace();
}
}
}
client code
package syssoftclient;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
public class Syssoftclient
{
public static void main(String[] args) throws IOException
{
try
{
InetAddress internetAddress = InetAddress.getLocalHost();
System.out.println("The address and hostname are: " +
internetAddress);
System.out.println("The Hostname: " +
internetAddress.getHostName());
System.out.println("The Address only: " +
internetAddress.getHostAddress());
} catch (UnknownHostException e)
{
System.err.println("Connection problem " + e);
}
Socket SocketC = null;
PrintWriter out = null;
BufferedReader in = null;
boolean exit = false;
try
{
SocketC = new Socket(InetAddress.getLocalHost().getHostName(),
8888);
out = new PrintWriter(SocketC.getOutputStream(), true);
in = new BufferedReader(new
InputStreamReader(SocketC.getInputStream()));
} catch (UnknownHostException e)
{
System.err.println("Host not recognised");
System.exit(1);
} catch (IOException e)
{
System.err.println("Couldn't get I/O for the connection");
System.exit(1);
}
String fromServer = null;
String fromUser = null;
BufferedReader stdIn = new BufferedReader(new
InputStreamReader(System.in));
DataInputStream din;
din = new DataInputStream(SocketC.getInputStream());
int lineCount = 0;
int linesIn = 0;
while (exit == false)
{
lineCount = 0;
linesIn = din.readInt();
while (lineCount < linesIn)
{
fromServer = in.readLine();
System.out.println("Server: " + fromServer);
lineCount++;
}
if ("Bye.".equals(fromServer))
{
System.out.println("Quitting");
exit = true;
break;
}
System.out.println("Client: ");
fromUser = stdIn.readLine(); //reads userinput
if (fromUser != null)
{
out.println(fromUser); //sends user input to the server
out.flush();
}
if ("exit".equals(fromUser))
{
exit = true;
}
}
out.close();
in.close();
stdIn.close();
SocketC.close(); //close everything before ending program
}
}
Batch jobs - prevent concurrency
Batch jobs - prevent concurrency
I have several batch jobs running on a SAP Java system using SAP Java
Scheduler. Unfortunately, I haven't come across any documentation that
shows how to prevent concurrent executions for periodic jobs. All I've
seen is "a new instance of the job will be executed at the next interval".
This ruins my fi-fo processing logic so I need to find a way to prevent
it. If the scheduler API had a way of checking for the same job
executions, this would be solved but haven't seen an example yet.
As a general architectural approach, other means to do this seems like
using a DB table - an indicator table for marking current executions - or
a JNDI parameter which would be checked first when the job starts. I could
also "attempt" to use a static integer but that would fail me on clustered
instances. The system is J2EE5 compliant and supports EJB 3.0, so a
"singleton EJB" is not available either. I could set the max pool size for
a bean and achieve a similar result maybe.
I'd like to hear your opinions on how to achieve this goal using different
architectures.
Kind Regards,
S. Gökhan Topçu
I have several batch jobs running on a SAP Java system using SAP Java
Scheduler. Unfortunately, I haven't come across any documentation that
shows how to prevent concurrent executions for periodic jobs. All I've
seen is "a new instance of the job will be executed at the next interval".
This ruins my fi-fo processing logic so I need to find a way to prevent
it. If the scheduler API had a way of checking for the same job
executions, this would be solved but haven't seen an example yet.
As a general architectural approach, other means to do this seems like
using a DB table - an indicator table for marking current executions - or
a JNDI parameter which would be checked first when the job starts. I could
also "attempt" to use a static integer but that would fail me on clustered
instances. The system is J2EE5 compliant and supports EJB 3.0, so a
"singleton EJB" is not available either. I could set the max pool size for
a bean and achieve a similar result maybe.
I'd like to hear your opinions on how to achieve this goal using different
architectures.
Kind Regards,
S. Gökhan Topçu
Is it possible to use fingerprint scanner for authenticating users on a web application?
Is it possible to use fingerprint scanner for authenticating users on a
web application?
I have a web application created in asp.net which is being authenticated
using conventional username/password method. This application is just for
managing employees data and this authentication is fine, but a problem is
coming. currently all daily wage employees comes at the about same time
which makes a long queue before the receptionist and quarrel over their
time that they are standing here for last 5 or 10 minutes for getting
entry. Right now the BI is to collect a predefined amount from daily wage
workers before giving them entry, and if they are late then fine is also
added to this amount. This step of collection and verifying time take
at-least 1 minute - 3 minutes depending upon the quality of receptionist,
which make the exact time employee late. I had increased the late time in
backend but this was not practical as genuine late comers were also
granted entry without fine.
The only solution that comes to me is to getting some bioscanner installed
and linking them to the server. However I have never used a fingerprint
scanner before and just need to know it is fisible or not in web
environment.
It is a web application because their office are having 6 branches.
web application?
I have a web application created in asp.net which is being authenticated
using conventional username/password method. This application is just for
managing employees data and this authentication is fine, but a problem is
coming. currently all daily wage employees comes at the about same time
which makes a long queue before the receptionist and quarrel over their
time that they are standing here for last 5 or 10 minutes for getting
entry. Right now the BI is to collect a predefined amount from daily wage
workers before giving them entry, and if they are late then fine is also
added to this amount. This step of collection and verifying time take
at-least 1 minute - 3 minutes depending upon the quality of receptionist,
which make the exact time employee late. I had increased the late time in
backend but this was not practical as genuine late comers were also
granted entry without fine.
The only solution that comes to me is to getting some bioscanner installed
and linking them to the server. However I have never used a fingerprint
scanner before and just need to know it is fisible or not in web
environment.
It is a web application because their office are having 6 branches.
Tuesday, 20 August 2013
weird bug in ios vinyl emulation source code
weird bug in ios vinyl emulation source code
I need help for a small test that I'm doing with some part of code that I
found here :
http://blog.weareglow.com/2011/01/vinyl-scratch-emulation-on-iphone/
The original source code has a bug very weird. After a while the velocity
become strange and stay at ~ 22000 (just on slow movement, not in normal
or fast speed) at a special position in the stream.
I made a project to reproduce the bug. (Here
https://bitbucket.org/ppeau/ios-ave/src) I'm using always the same track
and the bug arrived always at the same position.
I'm not able to understand what is the problem. So I'm looking for a smart
one who able to explain what is the problem and how to resolve it.
Thank for all
I need help for a small test that I'm doing with some part of code that I
found here :
http://blog.weareglow.com/2011/01/vinyl-scratch-emulation-on-iphone/
The original source code has a bug very weird. After a while the velocity
become strange and stay at ~ 22000 (just on slow movement, not in normal
or fast speed) at a special position in the stream.
I made a project to reproduce the bug. (Here
https://bitbucket.org/ppeau/ios-ave/src) I'm using always the same track
and the bug arrived always at the same position.
I'm not able to understand what is the problem. So I'm looking for a smart
one who able to explain what is the problem and how to resolve it.
Thank for all
Correct Field Name For "Album Artist" ID3 Tag In SoX With LAME
Correct Field Name For "Album Artist" ID3 Tag In SoX With LAME
I've got SoX compiled with LAME, and it works fine, I can make an .mp3
file with common ID3 tags.
But I can't figure out what to call the "Album Artist" field so that I can
specify a value. For example:
sox -n --comment "Title=Sweep" --comment "album_artist=ALBUM ARTIST TEST"
input.mp3 synth 3 sine 20-20000
Will properly make a file that sounds like a sweeping sine wave, and the
ID3 title will be "Sweep". But the Album artist field is still blank. I've
tried several variations, to no avail:
band bandname albumartist album_artist group orchestra accompaniment
soloist performer leadperformer TPE2, which is the technical name in ID3
for the field I'm trying to give a value.
But none of them seem to work. Does anybody know the right "name" to use
for this value?
I've got SoX compiled with LAME, and it works fine, I can make an .mp3
file with common ID3 tags.
But I can't figure out what to call the "Album Artist" field so that I can
specify a value. For example:
sox -n --comment "Title=Sweep" --comment "album_artist=ALBUM ARTIST TEST"
input.mp3 synth 3 sine 20-20000
Will properly make a file that sounds like a sweeping sine wave, and the
ID3 title will be "Sweep". But the Album artist field is still blank. I've
tried several variations, to no avail:
band bandname albumartist album_artist group orchestra accompaniment
soloist performer leadperformer TPE2, which is the technical name in ID3
for the field I'm trying to give a value.
But none of them seem to work. Does anybody know the right "name" to use
for this value?
Issue in Adding Cursor Values to ArrayList
Issue in Adding Cursor Values to ArrayList
I am trying to query the default phone content provider's Phone Numbers
and storing the values thus obtained into an ArrayList ar = new
ArrayList(); Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,
null, null, null, null);
if (cur.getCount() > 0){
while (cur.getCount() > 0){
while(cur.moveToNext()){
//unique id
String id =
cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
//number corresponding to the id
String name =
cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
//lets check if this guy even has a number saved
if(Integer.parseInt(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER)))
> 0){
//Query here
//Get the phone numbers!
Cursor pCur =
cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID
+ "=?",
new String[]{id},null);
while(pCur.moveToNext()){
ar.add((pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER))));
}
Log.d("String Report", ar.get(5));
pCur.close();
}
However this gives array out of bounds error at the Log.d method. For some
reason only one value is getting stored insidei.e. I only get ar.get(0) as
a valid output. What mistake am i making??
I am trying to query the default phone content provider's Phone Numbers
and storing the values thus obtained into an ArrayList ar = new
ArrayList(); Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,
null, null, null, null);
if (cur.getCount() > 0){
while (cur.getCount() > 0){
while(cur.moveToNext()){
//unique id
String id =
cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
//number corresponding to the id
String name =
cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
//lets check if this guy even has a number saved
if(Integer.parseInt(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER)))
> 0){
//Query here
//Get the phone numbers!
Cursor pCur =
cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID
+ "=?",
new String[]{id},null);
while(pCur.moveToNext()){
ar.add((pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER))));
}
Log.d("String Report", ar.get(5));
pCur.close();
}
However this gives array out of bounds error at the Log.d method. For some
reason only one value is getting stored insidei.e. I only get ar.get(0) as
a valid output. What mistake am i making??
Android: how to measure time to come out of standby from power button press
Android: how to measure time to come out of standby from power button press
I want to find how long it is the android devices come out of standby from
the user pressing the power button. In other words, to find out the
wake-up speed. I want to measure the time from app level programmatically.
Any ideas?
I want to find how long it is the android devices come out of standby from
the user pressing the power button. In other words, to find out the
wake-up speed. I want to measure the time from app level programmatically.
Any ideas?
Style based on StaticResource previously defined is not found at runtime
Style based on StaticResource previously defined is not found at runtime
I'm using Telerik's RadControls for WPF with implicit styling. The
following style is defined in
Themes/Windows8/Telerik.Windows.Controls.RibbonView.xaml:
<Style TargetType="telerikRibbonView:RadRibbonView"
x:Key="RadRibbonViewStyle">
...
</Style>
My own styles and the Telerik default ones get merged like this:
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary
Source="Windows8/Telerik.Windows.Controls.RibbonView.xaml" />
<ResourceDictionary Source="MyTheme/TelerikCustomizations.xaml" />
</ResourceDictionary.MergedDictionaries>
And in TelerikCustomizations.xaml I define the following (empty, for
testing purposes) style:
<Style x:Key="MyThemeRadRibbonViewStyle" TargetType="{x:Type
telerik:RadRibbonView}" BasedOn="{StaticResource
ResourceKey=RadRibbonViewStyle}" />
Which results in the following exception at runtime:
'Provide value on 'System.Windows.Markup.StaticResourceHolder' threw an
exception.' Line number '4' and line position '42'. {"Cannot find resource
named 'RadRibbonViewStyle'. Resource names are case sensitive."}
Which led me to the following debugging statements in MyView.xaml.cs:
public ShellView()
{
var baseStyle = FindResource("RadRibbonViewStyle");
var inherited = FindResource("MyThemeRadRibbonViewStyle");
InitializeComponent();
}
Now the thing is: The exception is thrown on the second FindResource call.
With the exact same message. However the RadRibbonViewStyle is clearly
found in the first line of the constructor.
If it matters, the merged dictionary is actually merged in App.xaml a
second time.
I'm sure I'm missing something obvious, but I can't figure out what.
I'm using Telerik's RadControls for WPF with implicit styling. The
following style is defined in
Themes/Windows8/Telerik.Windows.Controls.RibbonView.xaml:
<Style TargetType="telerikRibbonView:RadRibbonView"
x:Key="RadRibbonViewStyle">
...
</Style>
My own styles and the Telerik default ones get merged like this:
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary
Source="Windows8/Telerik.Windows.Controls.RibbonView.xaml" />
<ResourceDictionary Source="MyTheme/TelerikCustomizations.xaml" />
</ResourceDictionary.MergedDictionaries>
And in TelerikCustomizations.xaml I define the following (empty, for
testing purposes) style:
<Style x:Key="MyThemeRadRibbonViewStyle" TargetType="{x:Type
telerik:RadRibbonView}" BasedOn="{StaticResource
ResourceKey=RadRibbonViewStyle}" />
Which results in the following exception at runtime:
'Provide value on 'System.Windows.Markup.StaticResourceHolder' threw an
exception.' Line number '4' and line position '42'. {"Cannot find resource
named 'RadRibbonViewStyle'. Resource names are case sensitive."}
Which led me to the following debugging statements in MyView.xaml.cs:
public ShellView()
{
var baseStyle = FindResource("RadRibbonViewStyle");
var inherited = FindResource("MyThemeRadRibbonViewStyle");
InitializeComponent();
}
Now the thing is: The exception is thrown on the second FindResource call.
With the exact same message. However the RadRibbonViewStyle is clearly
found in the first line of the constructor.
If it matters, the merged dictionary is actually merged in App.xaml a
second time.
I'm sure I'm missing something obvious, but I can't figure out what.
How to handle requireJs timeout error?
How to handle requireJs timeout error?
I'm writing a mobile hybrid app using require.js as my loading framework.
I have an issue with loading errors. What I'm trying to do is setup a
fallback solution when the device is offline and I can't download the
google maps API script that I need to display a map on the screen. All
that I get is
Uncaught Error: Load timeout for modules:
async!http://maps.googleapis.com/maps/api/js?sensor=true
but I'm not able to catch this error and provide an alternative
implementation. Here is my gmaps module definition
define('gmaps',
['async!http://maps.googleapis.com/maps/api/js?sensor=true'],function(){
return window.google.maps; // mappatura nel più corto gmaps
});
What can I do?
I'm writing a mobile hybrid app using require.js as my loading framework.
I have an issue with loading errors. What I'm trying to do is setup a
fallback solution when the device is offline and I can't download the
google maps API script that I need to display a map on the screen. All
that I get is
Uncaught Error: Load timeout for modules:
async!http://maps.googleapis.com/maps/api/js?sensor=true
but I'm not able to catch this error and provide an alternative
implementation. Here is my gmaps module definition
define('gmaps',
['async!http://maps.googleapis.com/maps/api/js?sensor=true'],function(){
return window.google.maps; // mappatura nel più corto gmaps
});
What can I do?
How to detect iPhone Silent Button Status in iOS6
How to detect iPhone Silent Button Status in iOS6
I have been using following code to detect the iPhone silent button status
but it sometimes worked but usually dont work. I have searched alot but
wont be able to figure out the solution yet.
I have been using following code to detect the iPhone silent button status
but it sometimes worked but usually dont work. I have searched alot but
wont be able to figure out the solution yet.
Monday, 19 August 2013
PyDev Interactive Python Shell in Eclipse
PyDev Interactive Python Shell in Eclipse
I've been using Wing IDE for python programming and I am trying to switch
to Eclipse, PyDev.
When I run my code in Wing IDE, after finishing the execution the console
goes right back to the interactive shell and I can continue on testing,
but I don't know how to do this in Eclipse. I'm not sure if I am
describing my problem properly so I'll use an example:
Let's say I had a simple source code that looked like this (e.g. test.py):
print("hello")
When I run this in Wing IDE by clicking that green arrow, the console
would look like this after execution:
Python 2.7.5 (default, May 15 2013, 22:43:36) [MSC v.1500 32 bit (Intel)]
Type "help", "copyright", "credits" or "license" for more information.
[evaluate untitled-1.py]
hello
>>>>
And I can keep doing whatever on the shell and it would know my code
(defined functions etc.). But when I do the same thing in Eclipse, the
console would simply look like this:
hello
and I have to click "Remove All Terminated Launches" button to go back to
the shell.
Can this be done in Eclipse?
I've been using Wing IDE for python programming and I am trying to switch
to Eclipse, PyDev.
When I run my code in Wing IDE, after finishing the execution the console
goes right back to the interactive shell and I can continue on testing,
but I don't know how to do this in Eclipse. I'm not sure if I am
describing my problem properly so I'll use an example:
Let's say I had a simple source code that looked like this (e.g. test.py):
print("hello")
When I run this in Wing IDE by clicking that green arrow, the console
would look like this after execution:
Python 2.7.5 (default, May 15 2013, 22:43:36) [MSC v.1500 32 bit (Intel)]
Type "help", "copyright", "credits" or "license" for more information.
[evaluate untitled-1.py]
hello
>>>>
And I can keep doing whatever on the shell and it would know my code
(defined functions etc.). But when I do the same thing in Eclipse, the
console would simply look like this:
hello
and I have to click "Remove All Terminated Launches" button to go back to
the shell.
Can this be done in Eclipse?
Converting latitude and longitude to country in R: Error in .checkNumericCoerce2double(obj) : non-finite coordinates
Converting latitude and longitude to country in R: Error in
.checkNumericCoerce2double(obj) : non-finite coordinates
I am currently working with data (N of 271,848) in R that looks as follows:
Observation Longitude Latitude
1 116.38800 39.928902
2 53.000000 32.000000
3 NA NA
4 NA NA
And I am using the function code derived in the following post: Convert
latitude and longitude coordinates to country name in R
When I run the code to generate the country values, coords2country(points)
, I get the following error:
"Error in .checkNumericCoerce2double(obj) : non-finite coordinates"
My best guess is that it has something to do with the function not knowing
what to do with missing values (NA). When I ran the code on a subset of
observations (excluding NA's/missing values), it worked just fine. I
proceeded to modify the function slightly (see last line below), but that
still produced the error I am referring to above. Could somebody please
help me do the following:
Modify the code to properly handle NA's (or missing values).
coords2country = function(points)
{
countriesSP <- getMap(resolution='low')
#countriesSP <- getMap(resolution='high') #you could use high res map
from rworldxtra if you were concerned about detail
# convert our list of points to a SpatialPoints object
#pointsSP = SpatialPoints(points, proj4string=CRS("+proj=longlat
+datum=wgs84"))
#! andy modified to make the CRS the same as rworldmap
#pointsSP = SpatialPoints(points, proj4string=CRS("+proj=longlat
+ellps=WGS84 +datum=WGS84 +no_defs"))
# new changes in worldmap means you have to use this new CRS (bogdan):
pointsSP = SpatialPoints(points, proj4string=CRS(" +proj=longlat
+ellps=WGS84 +datum=WGS84 +no_defs +towgs84=0,0,0"))
# use 'over' to get indices of the Polygons object containing each point
indices = over(pointsSP, countriesSP)
# return the ADMIN names of each country
indices$ADMIN
#indices$ISO3 # returns the ISO3 code
#The line below is what I thought could resolve the problem.
na.action = na.omit
}
.checkNumericCoerce2double(obj) : non-finite coordinates
I am currently working with data (N of 271,848) in R that looks as follows:
Observation Longitude Latitude
1 116.38800 39.928902
2 53.000000 32.000000
3 NA NA
4 NA NA
And I am using the function code derived in the following post: Convert
latitude and longitude coordinates to country name in R
When I run the code to generate the country values, coords2country(points)
, I get the following error:
"Error in .checkNumericCoerce2double(obj) : non-finite coordinates"
My best guess is that it has something to do with the function not knowing
what to do with missing values (NA). When I ran the code on a subset of
observations (excluding NA's/missing values), it worked just fine. I
proceeded to modify the function slightly (see last line below), but that
still produced the error I am referring to above. Could somebody please
help me do the following:
Modify the code to properly handle NA's (or missing values).
coords2country = function(points)
{
countriesSP <- getMap(resolution='low')
#countriesSP <- getMap(resolution='high') #you could use high res map
from rworldxtra if you were concerned about detail
# convert our list of points to a SpatialPoints object
#pointsSP = SpatialPoints(points, proj4string=CRS("+proj=longlat
+datum=wgs84"))
#! andy modified to make the CRS the same as rworldmap
#pointsSP = SpatialPoints(points, proj4string=CRS("+proj=longlat
+ellps=WGS84 +datum=WGS84 +no_defs"))
# new changes in worldmap means you have to use this new CRS (bogdan):
pointsSP = SpatialPoints(points, proj4string=CRS(" +proj=longlat
+ellps=WGS84 +datum=WGS84 +no_defs +towgs84=0,0,0"))
# use 'over' to get indices of the Polygons object containing each point
indices = over(pointsSP, countriesSP)
# return the ADMIN names of each country
indices$ADMIN
#indices$ISO3 # returns the ISO3 code
#The line below is what I thought could resolve the problem.
na.action = na.omit
}
php checking if file exists on an external domain always returns 403 or 404
php checking if file exists on an external domain always returns 403 or 404
ive been struggling with this for days now.
I have a subdomain mapped to a subfolder within the parent domain. i want
to use images images from its parent domain
i can link to the images fine by using a standard href in an image tag
linking to the file.
My problem is i need to runs some checks to see if the image exists and if
it does no to display an place holder image.
I have got all my code down onto a test page, the image tag displays the
image fine but any calls i do either using curl or get_headers returns 404
or 403 errors.
Both domains are on the same dedicated server under the same account and
they use the same credentials so its not a security issue (i checked with
my hosts)
SO why does the image display via html but i cant get the a 200 with php???
test page can be found at http://mobile.reelfilmlocations.co.uk/untitled.php
<?php
function remoteFileExists($url) {
//$url = str_replace(" ", '%20', $url);
$agent = 'User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US;
rv:1.8.1.15) Gecko/20080623 Firefox/2.0.0.15';
$curl = curl_init($url);
//don't fetch the actual page, we only want to check the connection is ok
curl_setopt($curl, CURLOPT_NOBODY, true);
curl_setopt($curl, CURLOPT_USERAGENT, $agent);
//do request
$result = curl_exec($curl);
echo('curl result: '.$result.'<br>');
$ret = false;
//if request did not fail
if ($result !== false) {
//if request was ok, check response code
$statusCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
echo('curl status: '.$statusCode.'<br>');
if ($statusCode == 200 ) {
$ret = true;
}
}
curl_close($curl);
return $ret;
}
function get_response_code($theURL) {
$headers = get_headers($theURL);
foreach ($headers as $key => $value){
echo "$key => $value\n";
}
return substr($headers[0], 9, 3);
}
$image1 =
'http://www.reelfilmlocations.co.uk/uploads/images/thumbs/no-image.jpg';
$image2 =
'http://www.reelfilmlocations.co.uk/uploads/images/thumbs/Boston%20Manor%20M4-9.jpg';
$image3 =
'http://www.reelfilmlocations.co.uk/uploads/images/thumbs/thisimagedoesnotexist.jpg';
?>
IMAGE 1: <?php echo($image1); ?> (this image does exist)<br /><br />
<?php echo(remoteFileExists($image1)); ?><br />
<?php echo(get_response_code($image1)); ?><br />
<img src='<?php echo($image1); ?>'/><br /><br />
IMAGE 2: <?php echo($image1); ?> (this image does exist)<br />
<br />
<?php echo(remoteFileExists($image2)); ?><br />
<?php echo(get_response_code($image2)); ?><br />
<img src='<?php echo($image2); ?>'/><br /><br />
IMAGE 2: <?php echo($image3); ?> (this image does not exist)<br />
<br />
<?php echo(remoteFileExists($image3)); ?><br />
<?php echo(get_response_code($image3)); ?><br />
<img src='<?php echo($image3); ?>'/><br />
ive been struggling with this for days now.
I have a subdomain mapped to a subfolder within the parent domain. i want
to use images images from its parent domain
i can link to the images fine by using a standard href in an image tag
linking to the file.
My problem is i need to runs some checks to see if the image exists and if
it does no to display an place holder image.
I have got all my code down onto a test page, the image tag displays the
image fine but any calls i do either using curl or get_headers returns 404
or 403 errors.
Both domains are on the same dedicated server under the same account and
they use the same credentials so its not a security issue (i checked with
my hosts)
SO why does the image display via html but i cant get the a 200 with php???
test page can be found at http://mobile.reelfilmlocations.co.uk/untitled.php
<?php
function remoteFileExists($url) {
//$url = str_replace(" ", '%20', $url);
$agent = 'User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US;
rv:1.8.1.15) Gecko/20080623 Firefox/2.0.0.15';
$curl = curl_init($url);
//don't fetch the actual page, we only want to check the connection is ok
curl_setopt($curl, CURLOPT_NOBODY, true);
curl_setopt($curl, CURLOPT_USERAGENT, $agent);
//do request
$result = curl_exec($curl);
echo('curl result: '.$result.'<br>');
$ret = false;
//if request did not fail
if ($result !== false) {
//if request was ok, check response code
$statusCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
echo('curl status: '.$statusCode.'<br>');
if ($statusCode == 200 ) {
$ret = true;
}
}
curl_close($curl);
return $ret;
}
function get_response_code($theURL) {
$headers = get_headers($theURL);
foreach ($headers as $key => $value){
echo "$key => $value\n";
}
return substr($headers[0], 9, 3);
}
$image1 =
'http://www.reelfilmlocations.co.uk/uploads/images/thumbs/no-image.jpg';
$image2 =
'http://www.reelfilmlocations.co.uk/uploads/images/thumbs/Boston%20Manor%20M4-9.jpg';
$image3 =
'http://www.reelfilmlocations.co.uk/uploads/images/thumbs/thisimagedoesnotexist.jpg';
?>
IMAGE 1: <?php echo($image1); ?> (this image does exist)<br /><br />
<?php echo(remoteFileExists($image1)); ?><br />
<?php echo(get_response_code($image1)); ?><br />
<img src='<?php echo($image1); ?>'/><br /><br />
IMAGE 2: <?php echo($image1); ?> (this image does exist)<br />
<br />
<?php echo(remoteFileExists($image2)); ?><br />
<?php echo(get_response_code($image2)); ?><br />
<img src='<?php echo($image2); ?>'/><br /><br />
IMAGE 2: <?php echo($image3); ?> (this image does not exist)<br />
<br />
<?php echo(remoteFileExists($image3)); ?><br />
<?php echo(get_response_code($image3)); ?><br />
<img src='<?php echo($image3); ?>'/><br />
Subscribe to:
Comments (Atom)