Explain hash rocket in this context
I've just written this code, that works although I am not entirely sure why:
scope = scope.where(Sequel.qualify(:meeting_graphs, :id) => query.ids)
I am specifically talking about the hash rocket.
Previously the code was this, which makes perfect sense:
scope = scope.where(id: query.ids)
First thing I do not understand is why it does this not work when I
replace the hash rocket with a colon which I thought was the preferred
syntax:
scope = scope.where(Sequel.qualify(:meeting_graphs, :id): query.ids)
Sequel.qualify returns an object which also confuses me as I thought it
would return a symbol.
Can anyone explain?
Thursday, 3 October 2013
Wednesday, 2 October 2013
Determining whether iOS application was launched via Siri
Determining whether iOS application was launched via Siri
I've been looking forever, but haven't found … Do you know if there's a
way to determine whether my iOS app was launched thru Siri or thru a
regular icon click launch ?
I need to know because I want to automate a "startup" action only when my
app is launched from Siri, not from a regular "app icon click" launch …
I was thinking that maybe application:didFinishLaunchingWithOptions or
some other API would allow my app to know how it was launched, but that
doesn't seem to be the case (or I just missed it !?).
Any idea if there's some trick available that I couldn't use until Apple
publishes some official/public Siri API ?
Thanks for any insight,
I've been looking forever, but haven't found … Do you know if there's a
way to determine whether my iOS app was launched thru Siri or thru a
regular icon click launch ?
I need to know because I want to automate a "startup" action only when my
app is launched from Siri, not from a regular "app icon click" launch …
I was thinking that maybe application:didFinishLaunchingWithOptions or
some other API would allow my app to know how it was launched, but that
doesn't seem to be the case (or I just missed it !?).
Any idea if there's some trick available that I couldn't use until Apple
publishes some official/public Siri API ?
Thanks for any insight,
Help Factoring Quadrinomial
Help Factoring Quadrinomial
I know factoring questions are a dime a dozen but I can't seem to get this
one.
$-2x^3+2x^2+32x+40$
Factor to obtain the following equation:
$-2(x-5)(x+2)^2$
Do I have to use division (I'd prefer not to)? The way the question is
worded, it seems I should just be able to pull factors out. This is the
farthest I could make it:
$-2(x^3-x^2-16x-20)$
$-2[x^2(x-1)-4(4x+5)]$
$-2[(x^2-4)(x-1)(4x+5)]$
I know factoring questions are a dime a dozen but I can't seem to get this
one.
$-2x^3+2x^2+32x+40$
Factor to obtain the following equation:
$-2(x-5)(x+2)^2$
Do I have to use division (I'd prefer not to)? The way the question is
worded, it seems I should just be able to pull factors out. This is the
farthest I could make it:
$-2(x^3-x^2-16x-20)$
$-2[x^2(x-1)-4(4x+5)]$
$-2[(x^2-4)(x-1)(4x+5)]$
GitHub Windows Client - Where is the pull/push commands?
GitHub Windows Client - Where is the pull/push commands?
I've been using Github for mac for a while and was just about to help a
colleague to install it on Windows.
problem is. I cannot find any menu or any button to initiate "push" or
"pull" as I can on mac. Only way I see it is to open a shell and execute
"git pull" But then, what's the point of the UI?
Any help?
I've been using Github for mac for a while and was just about to help a
colleague to install it on Windows.
problem is. I cannot find any menu or any button to initiate "push" or
"pull" as I can on mac. Only way I see it is to open a shell and execute
"git pull" But then, what's the point of the UI?
Any help?
Google Translate Activity not working anymore
Google Translate Activity not working anymore
I wrote a program that invokes Google Translator android application via
Intent.ACTION_VIEW. The problem is that invoking the Google Translator App
does not work anymore, although it did once.
The code is identical to the code given here:
Returning Translated Text from Google Translate Activity
(yes, I tried to replace my code by that code, the Google Translator App
behaves as if it does not receive any data.)
Currently I cannot specify the text and the two languages. The best I can
do is to use ACTION_SEND, but it ignores the two languages:
Intent i = new Intent();
i.setAction(Intent.ACTION_SEND);
i.putExtra(Intent.EXTRA_TEXT, "What is going on?");
i.putExtra("key_text_input", "What time is it?");
i.putExtra("key_text_output", "");
i.putExtra("key_language_from", "en");
i.putExtra("key_language_to", "es");
i.putExtra("key_suggest_translation", "");
i.putExtra("key_from_floating_window", false);
i.setComponent(new ComponentName("com.google.android.apps.translate",
"com.google.android.apps.translate.translation.TranslateActivity"));
What actually when I ran this code happened was: the Google Translator
asked me if I want to translate from English and translated "What is going
on?" to French.
So: how do I pass the languages to the Google Translate App now?
I wrote a program that invokes Google Translator android application via
Intent.ACTION_VIEW. The problem is that invoking the Google Translator App
does not work anymore, although it did once.
The code is identical to the code given here:
Returning Translated Text from Google Translate Activity
(yes, I tried to replace my code by that code, the Google Translator App
behaves as if it does not receive any data.)
Currently I cannot specify the text and the two languages. The best I can
do is to use ACTION_SEND, but it ignores the two languages:
Intent i = new Intent();
i.setAction(Intent.ACTION_SEND);
i.putExtra(Intent.EXTRA_TEXT, "What is going on?");
i.putExtra("key_text_input", "What time is it?");
i.putExtra("key_text_output", "");
i.putExtra("key_language_from", "en");
i.putExtra("key_language_to", "es");
i.putExtra("key_suggest_translation", "");
i.putExtra("key_from_floating_window", false);
i.setComponent(new ComponentName("com.google.android.apps.translate",
"com.google.android.apps.translate.translation.TranslateActivity"));
What actually when I ran this code happened was: the Google Translator
asked me if I want to translate from English and translated "What is going
on?" to French.
So: how do I pass the languages to the Google Translate App now?
Tuesday, 1 October 2013
Rails nested forms STI autosave
Rails nested forms STI autosave
I have one class "Section" and many other classes "SectionText",
"SectionQuote" etc using STI, elements that compound a Post. (Post
has_many sections). I'm using a autosave custom method via Ajax for build
new sections nested on Post, but I think this isn't a better choice!
I need autosave the sections, when user click on another component. What's
the better way to solve this? Thanks...
I have one class "Section" and many other classes "SectionText",
"SectionQuote" etc using STI, elements that compound a Post. (Post
has_many sections). I'm using a autosave custom method via Ajax for build
new sections nested on Post, but I think this isn't a better choice!
I need autosave the sections, when user click on another component. What's
the better way to solve this? Thanks...
Copy Excel Row if Cell is equal to a value
Copy Excel Row if Cell is equal to a value
I'm trying to copy and paste into a different workbook and spread that
data over different sheets inside of the new workbook. I've got my VBA
working, but it only works about 25% of the time. I continually get an
error on "Run-time error '1004': Select method of Range class failed".
Here is the script:
Sub CopyData()
Dim i As Range
For Each i In Range("A1:A1000")
Windows("data_1.xls").Activate
Sheets("data_1").Activate
If i.Value = 502 Then
i.Select
ActiveCell.Rows("1:1").EntireRow.Select
Selection.Copy
Windows("DataOne.xls").Activate
Sheets("502").Range("A39").End(xlUp).Offset(1, 0).PasteSpecial
End If
If i.Value = 503 Then
........
End If
Next i
End Sub
The failure happens on i.Select every time. Do I need to bring Next i up
to the end of every End If?
I'm trying to copy and paste into a different workbook and spread that
data over different sheets inside of the new workbook. I've got my VBA
working, but it only works about 25% of the time. I continually get an
error on "Run-time error '1004': Select method of Range class failed".
Here is the script:
Sub CopyData()
Dim i As Range
For Each i In Range("A1:A1000")
Windows("data_1.xls").Activate
Sheets("data_1").Activate
If i.Value = 502 Then
i.Select
ActiveCell.Rows("1:1").EntireRow.Select
Selection.Copy
Windows("DataOne.xls").Activate
Sheets("502").Range("A39").End(xlUp).Offset(1, 0).PasteSpecial
End If
If i.Value = 503 Then
........
End If
Next i
End Sub
The failure happens on i.Select every time. Do I need to bring Next i up
to the end of every End If?
Maximizing a ratio of convex functions by minimizing a difference?
Maximizing a ratio of convex functions by minimizing a difference?
Given that $g(.),h(.)$ are convex real functions whose domain is the set
of all real matrices while the range is the set of real numbers:
Is maximizing the term $g(X)/h(X)$ w.r.t X the same as minimizing
$h(X)-\nu g(X)$ for some scalar $\nu$? Is this always valid- why or why
not? Otherwise, is the problem ill-posed, and if so why?
I was thinking there is a different trade-off between how much, $g(X)$ is
maximized while $h(X)$ is minimized in both the formulations.
Given that $g(.),h(.)$ are convex real functions whose domain is the set
of all real matrices while the range is the set of real numbers:
Is maximizing the term $g(X)/h(X)$ w.r.t X the same as minimizing
$h(X)-\nu g(X)$ for some scalar $\nu$? Is this always valid- why or why
not? Otherwise, is the problem ill-posed, and if so why?
I was thinking there is a different trade-off between how much, $g(X)$ is
maximized while $h(X)$ is minimized in both the formulations.
$p$-subgroup of $G$ with $p$ a prime.
$p$-subgroup of $G$ with $p$ a prime.
If $H$ is a $p$-subgroup of a finite group $G$ then $[N_G(H) : H] ¡Õ
[G:H]\operatorname{mod} p$.
Proof:
Let S be the set of left cosets of H in G. H acts on S by left
translation, $h ¡¤ aH = haH$, then $|S| = [G : H]$. So $xH¡ôS_0 ⇐¢¡
hxH=xH ¢£h¡ôH ⇐¢¡ x^{−1}hxH=H ¢£h¡ôH ⇐¢¡
x^{−1}Hx=H ⇐¢¡ x¡ô N_G(H)$ $|S_0| = [N_G(H) : H]$ By the fact
that $ |H|=p^n$ and H acts on S we have $|S|¡Õ|S_0|$ mod p. So
$[G:H]¡Õ[N_G(H):H]$ modp.
Is it correct my proof?.
And If p divides $[G : H]$ then $N_G(H) ¡Á H $
Proof:
$0¡Õ[G:H]¡Õ[N_G(H):H]¡Ã1$. So $[N_G(H) : H] ¡Ã 1$, thus $ N_G(H) ¡Á H$ .
Is it correct?
Please help!!! T_T
If $H$ is a $p$-subgroup of a finite group $G$ then $[N_G(H) : H] ¡Õ
[G:H]\operatorname{mod} p$.
Proof:
Let S be the set of left cosets of H in G. H acts on S by left
translation, $h ¡¤ aH = haH$, then $|S| = [G : H]$. So $xH¡ôS_0 ⇐¢¡
hxH=xH ¢£h¡ôH ⇐¢¡ x^{−1}hxH=H ¢£h¡ôH ⇐¢¡
x^{−1}Hx=H ⇐¢¡ x¡ô N_G(H)$ $|S_0| = [N_G(H) : H]$ By the fact
that $ |H|=p^n$ and H acts on S we have $|S|¡Õ|S_0|$ mod p. So
$[G:H]¡Õ[N_G(H):H]$ modp.
Is it correct my proof?.
And If p divides $[G : H]$ then $N_G(H) ¡Á H $
Proof:
$0¡Õ[G:H]¡Õ[N_G(H):H]¡Ã1$. So $[N_G(H) : H] ¡Ã 1$, thus $ N_G(H) ¡Á H$ .
Is it correct?
Please help!!! T_T
Monday, 30 September 2013
Should I ask a question which I learned its answer while asking it=?iso-8859-1?Q?=3F_=96_meta.stackoverflow.com?=
Should I ask a question which I learned its answer while asking it? –
meta.stackoverflow.com
This happen quite a lot for me lately. I encounter a problem in my code, I
want to ask it here and while I type the question, I have an idea which
prove useful. I think that this question might ...
meta.stackoverflow.com
This happen quite a lot for me lately. I encounter a problem in my code, I
want to ask it here and while I type the question, I have an idea which
prove useful. I think that this question might ...
Prove that $\sum_{n=1}^{\infty}\frac{(-1)^n}{n}\left\lfloor\frac{\log(n)}{\log(2)}\right\rfloor=\gamma$
Prove that
$\sum_{n=1}^{\infty}\frac{(-1)^n}{n}\left\lfloor\frac{\log(n)}{\log(2)}\right\rfloor=\gamma$
pProve that/p blockquote
p$$\sum_{n=1}^{\infty}\frac{(-1)^n}{n}\left\lfloor\frac{\log(n)}{\log(2)}\right\rfloor=\gamma$$/p
/blockquote pCan we find a known value for
$\sum_{n=1}^{\infty}\frac{(-1)^n}{n}\left\lfloor\frac{\log(n)}{\log(k)}\right\rfloor$
for any $k\in\mathbb{N}?$/p
$\sum_{n=1}^{\infty}\frac{(-1)^n}{n}\left\lfloor\frac{\log(n)}{\log(2)}\right\rfloor=\gamma$
pProve that/p blockquote
p$$\sum_{n=1}^{\infty}\frac{(-1)^n}{n}\left\lfloor\frac{\log(n)}{\log(2)}\right\rfloor=\gamma$$/p
/blockquote pCan we find a known value for
$\sum_{n=1}^{\infty}\frac{(-1)^n}{n}\left\lfloor\frac{\log(n)}{\log(k)}\right\rfloor$
for any $k\in\mathbb{N}?$/p
jQuery alert if new cookie is created?
jQuery alert if new cookie is created?
I'm forced to work with iframes from external domains, to know what's
happening in them I need to do cross domain calls to my site which
sometimes create cookies without the pagereloading or any noticeable
actions happening in it.
Right now I'm working with a form that is hosted in an external server, on
submit the server makes a call to my site saving a cookie to let me know
the form has been submitted, I need to know the instant the new cookie is
created so I show a message in my site.
Is there a way to listen for new cookies and show an alert if a new cookie
is created?
I'm forced to work with iframes from external domains, to know what's
happening in them I need to do cross domain calls to my site which
sometimes create cookies without the pagereloading or any noticeable
actions happening in it.
Right now I'm working with a form that is hosted in an external server, on
submit the server makes a call to my site saving a cookie to let me know
the form has been submitted, I need to know the instant the new cookie is
created so I show a message in my site.
Is there a way to listen for new cookies and show an alert if a new cookie
is created?
Best practices for actors lookup from actors
Best practices for actors lookup from actors
I am using akka 2.2.x. in cluster mode. My question is related to actors
lookup.
I have two kind of actors:
processor. It accepts text and processes it somehow
result collector. Acceps messages from processor and summarize the results.
Processor actor needs to send message to result collector. So, I need to
have ActorRef inside processor.
The queston is - how to pass/lookup this ActorRef to processor.
I have 3 different solutions for now:
Lookup ActorRef to processor in creation time and pass ActorRef as
contructor parameter. Looks possibly wrong because it does not handle
actor restart process and does not fit into cluster environment.
Lookup in preStart with context.actorSelection("../result-collector").
After this I have the object of ActorSelection and can send messages with
!. In this solution I am aware of performance degradation because of
lookup in cluster before every call. Or am I wrong here?
Lookup in preStart with context.actorSelection("../result-collector") and
call resolveOne to obtain ActorRef. Looks ok, but may not handle akka
cluster changes.
Thanks!
I am using akka 2.2.x. in cluster mode. My question is related to actors
lookup.
I have two kind of actors:
processor. It accepts text and processes it somehow
result collector. Acceps messages from processor and summarize the results.
Processor actor needs to send message to result collector. So, I need to
have ActorRef inside processor.
The queston is - how to pass/lookup this ActorRef to processor.
I have 3 different solutions for now:
Lookup ActorRef to processor in creation time and pass ActorRef as
contructor parameter. Looks possibly wrong because it does not handle
actor restart process and does not fit into cluster environment.
Lookup in preStart with context.actorSelection("../result-collector").
After this I have the object of ActorSelection and can send messages with
!. In this solution I am aware of performance degradation because of
lookup in cluster before every call. Or am I wrong here?
Lookup in preStart with context.actorSelection("../result-collector") and
call resolveOne to obtain ActorRef. Looks ok, but may not handle akka
cluster changes.
Thanks!
Sunday, 29 September 2013
Concurrent Dictionary multiple writes
Concurrent Dictionary multiple writes
Im wondering, does C# ConcurrentDictionary support multiple simultaneous
writes? Or do all writes serialize? I know it is optimized for reading but
what about writting? Can i expect good performance with multiple threads
constantly writting to the dictionary?
Im wondering, does C# ConcurrentDictionary support multiple simultaneous
writes? Or do all writes serialize? I know it is optimized for reading but
what about writting? Can i expect good performance with multiple threads
constantly writting to the dictionary?
Ruby, stack level too deep (SystemStackError)
Ruby, stack level too deep (SystemStackError)
I have the following code:
class BookPrice
attr_accessor :price
def initialize(price)
@price = price
end
def price_in_cents
Integer(price*100 + 0.5)
end
end
b = BookPrice.new(2.20)
puts b.price_in_cents
This all works well and produces 220. But when I replace the second line
attr_accessor :price with:
def price
@price = price
end
I get stack level too deep (SystemStackError) error. What's going on? I
know I can replace Integer(price*100 + 0.5) with @price instead of the
method call price, but I want to keep it the way it is for OOP reasons.
How can I make this code work the way it is without attr_accessor?
I have the following code:
class BookPrice
attr_accessor :price
def initialize(price)
@price = price
end
def price_in_cents
Integer(price*100 + 0.5)
end
end
b = BookPrice.new(2.20)
puts b.price_in_cents
This all works well and produces 220. But when I replace the second line
attr_accessor :price with:
def price
@price = price
end
I get stack level too deep (SystemStackError) error. What's going on? I
know I can replace Integer(price*100 + 0.5) with @price instead of the
method call price, but I want to keep it the way it is for OOP reasons.
How can I make this code work the way it is without attr_accessor?
Type-unsafe behavior of Casbah
Type-unsafe behavior of Casbah
I have an id which is Long. But if I getAs[String], it blindly returns
Some(0) instead of None. It checks the presence of the key and not the
type.
scala> collection
res26: com.mongodb.DBObject = { "_id" : { "$oid" :
"520f8bf544ae41ec63d02eec"} , "date_about" : "2013-08-17T20:13:00.365Z" ,
"date_created" : "2013-08-17T20:13:00.365Z" , "date_modified" :
"2013-09-07T18:03:20.101Z" , "id" : 0 , "node_type" : "meta-folder" ,
"parent_id" : 0 , "title" : "my stuff, renamed by ajax, wow" , "version" :
2}
scala> collection.getAs[String]("id")
res27: Option[String] = Some(0)
scala> collection.getAs[Long]("id")
res28: Option[Long] = Some(0) //get-ing this is an
java.lang.ClassCastException
scala> collection.getAs[Long]("id").get
res29: Long = 0
Is this not unexpected behavior; should I not have got a Option[String] =
None? How do i get the expected behavior? I sbt-ed "org.mongodb" %%
"casbah" % "2.6.2"
I have an id which is Long. But if I getAs[String], it blindly returns
Some(0) instead of None. It checks the presence of the key and not the
type.
scala> collection
res26: com.mongodb.DBObject = { "_id" : { "$oid" :
"520f8bf544ae41ec63d02eec"} , "date_about" : "2013-08-17T20:13:00.365Z" ,
"date_created" : "2013-08-17T20:13:00.365Z" , "date_modified" :
"2013-09-07T18:03:20.101Z" , "id" : 0 , "node_type" : "meta-folder" ,
"parent_id" : 0 , "title" : "my stuff, renamed by ajax, wow" , "version" :
2}
scala> collection.getAs[String]("id")
res27: Option[String] = Some(0)
scala> collection.getAs[Long]("id")
res28: Option[Long] = Some(0) //get-ing this is an
java.lang.ClassCastException
scala> collection.getAs[Long]("id").get
res29: Long = 0
Is this not unexpected behavior; should I not have got a Option[String] =
None? How do i get the expected behavior? I sbt-ed "org.mongodb" %%
"casbah" % "2.6.2"
NSString boundingRectWithSize cutting height short with CoreText Framesetter ? iOS
NSString boundingRectWithSize cutting height short with CoreText
Framesetter ? iOS
I have a custom UIView which is drawing an NSString via CoreText :
- (NSMutableAttributedString *)getAttributedString : (NSString
*)displayText {
string = [[NSMutableAttributedString alloc]
initWithString:displayText];
helvetica = CTFontCreateWithName(CFSTR("Helvetica"), 20.0, NULL);
[string addAttribute:(id)kCTFontAttributeName
value:(__bridge id)helvetica
range:NSMakeRange(0, [string length])];
return string;
}
- (void)drawRect:(CGRect)rect
{
CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString(
(__bridge
CFAttributedStringRef)string);
// left column form
leftColumnPath = CGPathCreateMutable();
CGPathAddRect(leftColumnPath, NULL,
CGRectMake(0, 0,
self.bounds.size.width,
self.bounds.size.height));
// left column frame
textleftFrame = CTFramesetterCreateFrame(framesetter,
CFRangeMake(0, 0),
leftColumnPath, NULL);
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
// right column form
rightColumnPath = CGPathCreateMutable();
CGPathAddRect(rightColumnPath, NULL,
CGRectMake(self.bounds.size.width/2.0, 0,
self.bounds.size.width/2.0,
self.bounds.size.height));
NSInteger rightColumStart =
CTFrameGetVisibleStringRange(textleftFrame).length;
// right column frame
textrightFrame = CTFramesetterCreateFrame(framesetter,
CFRangeMake(rightColumStart, 0),
rightColumnPath,
NULL);
}
// flip the coordinate system
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetTextMatrix(context, CGAffineTransformIdentity);
CGContextTranslateCTM(context, 0, self.bounds.size.height);
CGContextScaleCTM(context, 1.0, -1.0);
// draw
CTFrameDraw(textleftFrame, context);
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
CTFrameDraw(textrightFrame, context);
}
// cleanup
CFRelease(textleftFrame);
CGPathRelease(leftColumnPath);
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
CFRelease(textrightFrame);
CGPathRelease(rightColumnPath);
}
CFRelease(framesetter);
CFRelease(helvetica);
CFRelease(helveticaBold);
}
In another class I am then trying to use boundingRectWithSize to calculate
how long the view will be to display the text (I then later set a
UIScrollView to match this) :
NSMutableAttributedString * attributedString = [textView
getAttributedString:text];
// Code here for iOS 7.0 - sizeWithFont is deprecated.
CGRect textBoxSize = [attributedString
boundingRectWithSize:CGSizeMake(315.f, CGFLOAT_MAX) options:
(NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading)
context:nil];
textView.frame = CGRectMake(textView.frame.origin.x, pictureSpace,
textBoxSize.size.width, textBoxSize.size.height);
The getAttributedString method is above. The problem is that textView is
slightly too short in height and therefore cuts off the last line of so of
text. Can anyone suggest what is wrong ?
Also, on a side note, why does the size in boundingRectWithSize have to be
315 (i.e slightly shorter than the screen width) rather than 320 in order
to work ? At 320 the textView ends up slightly too wide for the screen.
Thanks !
Framesetter ? iOS
I have a custom UIView which is drawing an NSString via CoreText :
- (NSMutableAttributedString *)getAttributedString : (NSString
*)displayText {
string = [[NSMutableAttributedString alloc]
initWithString:displayText];
helvetica = CTFontCreateWithName(CFSTR("Helvetica"), 20.0, NULL);
[string addAttribute:(id)kCTFontAttributeName
value:(__bridge id)helvetica
range:NSMakeRange(0, [string length])];
return string;
}
- (void)drawRect:(CGRect)rect
{
CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString(
(__bridge
CFAttributedStringRef)string);
// left column form
leftColumnPath = CGPathCreateMutable();
CGPathAddRect(leftColumnPath, NULL,
CGRectMake(0, 0,
self.bounds.size.width,
self.bounds.size.height));
// left column frame
textleftFrame = CTFramesetterCreateFrame(framesetter,
CFRangeMake(0, 0),
leftColumnPath, NULL);
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
// right column form
rightColumnPath = CGPathCreateMutable();
CGPathAddRect(rightColumnPath, NULL,
CGRectMake(self.bounds.size.width/2.0, 0,
self.bounds.size.width/2.0,
self.bounds.size.height));
NSInteger rightColumStart =
CTFrameGetVisibleStringRange(textleftFrame).length;
// right column frame
textrightFrame = CTFramesetterCreateFrame(framesetter,
CFRangeMake(rightColumStart, 0),
rightColumnPath,
NULL);
}
// flip the coordinate system
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetTextMatrix(context, CGAffineTransformIdentity);
CGContextTranslateCTM(context, 0, self.bounds.size.height);
CGContextScaleCTM(context, 1.0, -1.0);
// draw
CTFrameDraw(textleftFrame, context);
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
CTFrameDraw(textrightFrame, context);
}
// cleanup
CFRelease(textleftFrame);
CGPathRelease(leftColumnPath);
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
CFRelease(textrightFrame);
CGPathRelease(rightColumnPath);
}
CFRelease(framesetter);
CFRelease(helvetica);
CFRelease(helveticaBold);
}
In another class I am then trying to use boundingRectWithSize to calculate
how long the view will be to display the text (I then later set a
UIScrollView to match this) :
NSMutableAttributedString * attributedString = [textView
getAttributedString:text];
// Code here for iOS 7.0 - sizeWithFont is deprecated.
CGRect textBoxSize = [attributedString
boundingRectWithSize:CGSizeMake(315.f, CGFLOAT_MAX) options:
(NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading)
context:nil];
textView.frame = CGRectMake(textView.frame.origin.x, pictureSpace,
textBoxSize.size.width, textBoxSize.size.height);
The getAttributedString method is above. The problem is that textView is
slightly too short in height and therefore cuts off the last line of so of
text. Can anyone suggest what is wrong ?
Also, on a side note, why does the size in boundingRectWithSize have to be
315 (i.e slightly shorter than the screen width) rather than 320 in order
to work ? At 320 the textView ends up slightly too wide for the screen.
Thanks !
Saturday, 28 September 2013
Favicon for static HTML page
Favicon for static HTML page
I'm trying to upload a simple favicon to my HTML page. I've been browsing
the web for answers and I'm being told to "upload the image to my server."
My files are uploaded to GoDaddy, and I'm not exactly sure how to do this.
Basically, how do I get my website to have the /favicon.ico extension?
I'm trying to upload a simple favicon to my HTML page. I've been browsing
the web for answers and I'm being told to "upload the image to my server."
My files are uploaded to GoDaddy, and I'm not exactly sure how to do this.
Basically, how do I get my website to have the /favicon.ico extension?
Android: Relate 2 spinner/ variable to string-array
Android: Relate 2 spinner/ variable to string-array
I want to do a 2 spinner activity that the second spinner depends on the
first one, similar than the state/city example. I populate the spinners
with the string arrays, so heres my
strings.xml
<string-array name="Jornadas">
<item >1</item>
<item >2</item>
<item >3</item>
<item >4</item>
<item >5</item>
</string-array>
<string-array name="partidosj1">
<item >c11</item>
<item >c12</item>
<item >c15</item>
<item >c13</item>
</string-array>
<string-array name="partidosj2">
<item >c1</item>
<item >c2</item>
<item >c5</item>
<item >c3</item>
</string-array>
//and so on....
Heres my oncreate
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Spinner jornadas = (Spinner) findViewById(R.id.spinner1);
Spinner partidos = (Spinner) findViewById(R.id.spinner2);
ArrayAdapter adapter1 = ArrayAdapter.createFromResource(this,
R.array.Jornadas, android.R.layout.simple_spinner_item);
adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
jornadas.setAdapter(adapter1);
jornadas.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
@Override
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
String a= "partidosj "+pos;
}
});
ArrayAdapter adapter2 = ArrayAdapter.createFromResource(this,R.array.a,
android.R.layout.simple_spinner_item);
//Do whatever
}}
So the string "a" has the same name that the string array that I want to
populate the second spinner but I cannot refer It on the array adapter
because it has to be a int variable. Is there any way to convert the "a"
variable into a correct string-array resource?
Much appreciated!
I want to do a 2 spinner activity that the second spinner depends on the
first one, similar than the state/city example. I populate the spinners
with the string arrays, so heres my
strings.xml
<string-array name="Jornadas">
<item >1</item>
<item >2</item>
<item >3</item>
<item >4</item>
<item >5</item>
</string-array>
<string-array name="partidosj1">
<item >c11</item>
<item >c12</item>
<item >c15</item>
<item >c13</item>
</string-array>
<string-array name="partidosj2">
<item >c1</item>
<item >c2</item>
<item >c5</item>
<item >c3</item>
</string-array>
//and so on....
Heres my oncreate
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Spinner jornadas = (Spinner) findViewById(R.id.spinner1);
Spinner partidos = (Spinner) findViewById(R.id.spinner2);
ArrayAdapter adapter1 = ArrayAdapter.createFromResource(this,
R.array.Jornadas, android.R.layout.simple_spinner_item);
adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
jornadas.setAdapter(adapter1);
jornadas.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
@Override
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
String a= "partidosj "+pos;
}
});
ArrayAdapter adapter2 = ArrayAdapter.createFromResource(this,R.array.a,
android.R.layout.simple_spinner_item);
//Do whatever
}}
So the string "a" has the same name that the string array that I want to
populate the second spinner but I cannot refer It on the array adapter
because it has to be a int variable. Is there any way to convert the "a"
variable into a correct string-array resource?
Much appreciated!
Can a Kafka High Level Consumer be assigned to a specific Partition?
Can a Kafka High Level Consumer be assigned to a specific Partition?
Given the fact that a Consumer in Kafka can be configured to receive
messages only from one partition, I haven't seen a configuration approach
for this.
How do I tell a Kafka broker:
That I'm a CONSUMER A with this ID, under this GROUP L, subscribing to
TOPIC X, willing to get the stream of PARTITION A?
And then, start another CONSUMER B, under GROUP L, which subscribes to
TOPIC X, willing to get the stream of PARTITION B?
In other words, as in the scenario described by Kafka,
How do I start a consumer subscribing to a wall feed of a specific user?
Can I start a consumer when a user logs in, consumer his/her partition
form the topic and send the feed to the client?
Given the fact that a Consumer in Kafka can be configured to receive
messages only from one partition, I haven't seen a configuration approach
for this.
How do I tell a Kafka broker:
That I'm a CONSUMER A with this ID, under this GROUP L, subscribing to
TOPIC X, willing to get the stream of PARTITION A?
And then, start another CONSUMER B, under GROUP L, which subscribes to
TOPIC X, willing to get the stream of PARTITION B?
In other words, as in the scenario described by Kafka,
How do I start a consumer subscribing to a wall feed of a specific user?
Can I start a consumer when a user logs in, consumer his/her partition
form the topic and send the feed to the client?
Status Bar Text Color iOS 7
Status Bar Text Color iOS 7
pI am unable to change the text colour in the status bar in iOS 7 SDK.
Currently its black and i want it to be white for all my view controllers
in a storyboard. /p pI have seen few questions on StackOverflow like a
href=http://stackoverflow.com/questions/17678881/how-to-change-status-bar-text-color-in-ios-7THIS/a,
a
href=http://stackoverflow.com/questions/19063365/how-to-change-status-bar-background-color-and-text-color-in-ios-7THIS/a
and a
href=http://stackoverflow.com/questions/18897362/changing-the-status-bar-text-color-in-splash-screen-ios-7THIS/a
but they didn't of much help. Also may be due to the fact that i am unable
to find UIViewControllerBasedStatusBarAppearance to YES in my plist
file./p pCan any one tell me the right way to set the status bar text
colour to white for all view controllers in the storyboard? Thanks in
advance!/p
pI am unable to change the text colour in the status bar in iOS 7 SDK.
Currently its black and i want it to be white for all my view controllers
in a storyboard. /p pI have seen few questions on StackOverflow like a
href=http://stackoverflow.com/questions/17678881/how-to-change-status-bar-text-color-in-ios-7THIS/a,
a
href=http://stackoverflow.com/questions/19063365/how-to-change-status-bar-background-color-and-text-color-in-ios-7THIS/a
and a
href=http://stackoverflow.com/questions/18897362/changing-the-status-bar-text-color-in-splash-screen-ios-7THIS/a
but they didn't of much help. Also may be due to the fact that i am unable
to find UIViewControllerBasedStatusBarAppearance to YES in my plist
file./p pCan any one tell me the right way to set the status bar text
colour to white for all view controllers in the storyboard? Thanks in
advance!/p
Friday, 27 September 2013
Where Does Razor Code Go?
Where Does Razor Code Go?
When I create a Web Forms project, my code behind is compiled into a DLL,
which is processed by an IIS server. When I use Javascript, it's
interpreted by the browser and I can find it using things like the Chrome
Developer Tools or by inspecting the source.
However, when I create an ASP.NET Web Page using Razor syntax, I can't
find the code anywhere. Since it doesn't need to be compiled, it's not put
into a DLL and I can't locate any trace of it using Chrome's inspect
tools.
So, where does Razor code go?
When I create a Web Forms project, my code behind is compiled into a DLL,
which is processed by an IIS server. When I use Javascript, it's
interpreted by the browser and I can find it using things like the Chrome
Developer Tools or by inspecting the source.
However, when I create an ASP.NET Web Page using Razor syntax, I can't
find the code anywhere. Since it doesn't need to be compiled, it's not put
into a DLL and I can't locate any trace of it using Chrome's inspect
tools.
So, where does Razor code go?
Getting data from database into a php array
Getting data from database into a php array
i've been having an error for about 2 days now i'd appreaciate if someone
could help me.
I want to make a query that selects all payments in a month and save them
in an array, i wanna graph this so i also need the days where no payments
were done. this is my code and i think my problem is when i try to catch
them in an array. When i call my function from my main page all my website
goes down.
function getDailyGraph($membership, $selectedMonth){
$sql = "SELECT rate_amount AS payment, DAY(date) AS day FROM
payments WHERE membership_id = ".$membership.
" AND MONTH(date) = ".$selectedMonth." ORDER BY day";
$query = $db->query($sql);
$days = array();
for ($i=1; $i <= 31 ; $i++) {
$payment = mysql_fetch_array($query);
# code...
if ($i == $payment['dia']) {
# code...
$days[] = $payment['payment'];
}else{
$days[] = 0;
}
}
return $days;
}
i've been having an error for about 2 days now i'd appreaciate if someone
could help me.
I want to make a query that selects all payments in a month and save them
in an array, i wanna graph this so i also need the days where no payments
were done. this is my code and i think my problem is when i try to catch
them in an array. When i call my function from my main page all my website
goes down.
function getDailyGraph($membership, $selectedMonth){
$sql = "SELECT rate_amount AS payment, DAY(date) AS day FROM
payments WHERE membership_id = ".$membership.
" AND MONTH(date) = ".$selectedMonth." ORDER BY day";
$query = $db->query($sql);
$days = array();
for ($i=1; $i <= 31 ; $i++) {
$payment = mysql_fetch_array($query);
# code...
if ($i == $payment['dia']) {
# code...
$days[] = $payment['payment'];
}else{
$days[] = 0;
}
}
return $days;
}
Tell me what are the deprecated things in Java 7 [on hold]
Tell me what are the deprecated things in Java 7 [on hold]
I want to know the deprecated things in java 7. Also the alternatves usage
of those deprecated things.
I want to know the deprecated things in java 7. Also the alternatves usage
of those deprecated things.
Can't persist an entity with two foreign keys pointing to same table
Can't persist an entity with two foreign keys pointing to same table
I have three database-tables mapped as three entities:
Employee
Room
EmployeeToRoom
public class Employee implements Serializable {
@Id
@Column(name = "\"id_emp\"")
private Integer id_emp;
@Column(name = "\"name\"")
private String name;
@Column(name = "\"surname\"")
private String surname;
...
}
public class Room implements Serializable {
@Id
@Column(name = "\"id_room\"")
private Integer id_room;
@ManyToOne
@JoinColumn(name = "\"id_roomtype\"")
private RoomType type;
@ManyToOne
@JoinColumn(name = "\"id_floor\"")
private Floor floor;
...
}
public class EmployeeToRoom implements Serializable {
@Id
@SequenceGenerator(name = "etr_seq", sequenceName = "etr_seq",
allocationSize = 1, initialValue = 1)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "etr_seq")
@Column(name = "\"id\"")
private Integer id;
@ManyToOne
@JoinColumn(name = "\"id_room\"")
private Room room;
@ManyToOne
@JoinColumn(name = "\"id_emp\"")
private Employee employee;
/* Who created/updated record in DB */
@ManyToOne
@JoinColumn(name = "\"who\"")
private Employee who;
/* When was record created/updated */
@Column(name = "\"when\"")
private Timestamp when;
private static final long serialVersionUID = -2059394677268317393L;
...
}
So I'd like to store info which employee works in which room (and also who
and when created database record).
I created Managed Bean with listener:
@ManagedBean
@ViewScoped
public class EmployeeToRoomBean implements Serializable {
private static final long serialVersionUID = 1L;
final javax.persistence.EntityManager em = EntityManager.getEm();
private Logger log = LoggerFactory.getLogger(EmployeeToRoomBean.class);
private EmployeeToRoomDaoJPA ETRdao = new EmployeeToRoomDaoJPA();
...
public void updateListener() {
TimeStampMaker tsm = new TimeStampMaker();
...
/* Some issues */
...
EmployeeToRoom etrToadd = new EmployeeToRoom();
etrToadd.setRoom(getEditedRoom());
etrToadd.setEmployee(employee);
etrToadd.setWho(UserLogin.getUser().getEmployee());
etrToadd.setWhen(tsm.getTimestampAsObject());
ETRdao.create(etrToadd);
}
}
If I try to make logger output with set values (setRoom(), setEmployee(),
setWho(), setWhen()) everything is OK - not null values.
And finnaly I have:
public class EmployeeToRoomDaoJPA implements EmployeeToRoomDao,
Serializable {
private static final long serialVersionUID = 1L;
private Logger log =
LoggerFactory.getLogger(EmployeeToRoomDaoJPA.class);
...
@Override
public void create(EmployeeToRoom entity) {
EntityTransaction tx = em.getTransaction();
try {
tx.begin();
this.log.info("Creating new EmployeeToRoom entity:");
this.log.info("Room: " + entity.getRoom().getId_room());
this.log.info("Employee: " +
entity.getEmployee().getId_emp());
this.log.info("Who: " + entity.getWho().getId_emp());
this.log.info("When: " + entity.getWhen().toString());
em.persist(entity);
tx.commit();
this.log.info("done inserting obj " + entity.getId());
} catch (PersistenceException pe) {
if (tx != null) {
tx.begin();
tx.rollback();
}
throw pe;
}
}
}
And there's my problem. I just receive an PersistenceException with
message that query violated not-null constraint of column Who in
EmployeeToRoom entity.
But... I added logger output immediatly after beginning a transaction.
There's not null value in entity.getWho().getId_emp().
I can't solve this problem for several days. As you can see I have two
foreign keys in EmployeeToRoom entity/table to Employee entity/table -
property Employee and property Who. Can it be my problem? Or everything
else is wrong?
Many thanks for any advices.
(Postgres DBMS, Apache Tomcat, Hibernate, JSF2/Mojarra)
I have three database-tables mapped as three entities:
Employee
Room
EmployeeToRoom
public class Employee implements Serializable {
@Id
@Column(name = "\"id_emp\"")
private Integer id_emp;
@Column(name = "\"name\"")
private String name;
@Column(name = "\"surname\"")
private String surname;
...
}
public class Room implements Serializable {
@Id
@Column(name = "\"id_room\"")
private Integer id_room;
@ManyToOne
@JoinColumn(name = "\"id_roomtype\"")
private RoomType type;
@ManyToOne
@JoinColumn(name = "\"id_floor\"")
private Floor floor;
...
}
public class EmployeeToRoom implements Serializable {
@Id
@SequenceGenerator(name = "etr_seq", sequenceName = "etr_seq",
allocationSize = 1, initialValue = 1)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "etr_seq")
@Column(name = "\"id\"")
private Integer id;
@ManyToOne
@JoinColumn(name = "\"id_room\"")
private Room room;
@ManyToOne
@JoinColumn(name = "\"id_emp\"")
private Employee employee;
/* Who created/updated record in DB */
@ManyToOne
@JoinColumn(name = "\"who\"")
private Employee who;
/* When was record created/updated */
@Column(name = "\"when\"")
private Timestamp when;
private static final long serialVersionUID = -2059394677268317393L;
...
}
So I'd like to store info which employee works in which room (and also who
and when created database record).
I created Managed Bean with listener:
@ManagedBean
@ViewScoped
public class EmployeeToRoomBean implements Serializable {
private static final long serialVersionUID = 1L;
final javax.persistence.EntityManager em = EntityManager.getEm();
private Logger log = LoggerFactory.getLogger(EmployeeToRoomBean.class);
private EmployeeToRoomDaoJPA ETRdao = new EmployeeToRoomDaoJPA();
...
public void updateListener() {
TimeStampMaker tsm = new TimeStampMaker();
...
/* Some issues */
...
EmployeeToRoom etrToadd = new EmployeeToRoom();
etrToadd.setRoom(getEditedRoom());
etrToadd.setEmployee(employee);
etrToadd.setWho(UserLogin.getUser().getEmployee());
etrToadd.setWhen(tsm.getTimestampAsObject());
ETRdao.create(etrToadd);
}
}
If I try to make logger output with set values (setRoom(), setEmployee(),
setWho(), setWhen()) everything is OK - not null values.
And finnaly I have:
public class EmployeeToRoomDaoJPA implements EmployeeToRoomDao,
Serializable {
private static final long serialVersionUID = 1L;
private Logger log =
LoggerFactory.getLogger(EmployeeToRoomDaoJPA.class);
...
@Override
public void create(EmployeeToRoom entity) {
EntityTransaction tx = em.getTransaction();
try {
tx.begin();
this.log.info("Creating new EmployeeToRoom entity:");
this.log.info("Room: " + entity.getRoom().getId_room());
this.log.info("Employee: " +
entity.getEmployee().getId_emp());
this.log.info("Who: " + entity.getWho().getId_emp());
this.log.info("When: " + entity.getWhen().toString());
em.persist(entity);
tx.commit();
this.log.info("done inserting obj " + entity.getId());
} catch (PersistenceException pe) {
if (tx != null) {
tx.begin();
tx.rollback();
}
throw pe;
}
}
}
And there's my problem. I just receive an PersistenceException with
message that query violated not-null constraint of column Who in
EmployeeToRoom entity.
But... I added logger output immediatly after beginning a transaction.
There's not null value in entity.getWho().getId_emp().
I can't solve this problem for several days. As you can see I have two
foreign keys in EmployeeToRoom entity/table to Employee entity/table -
property Employee and property Who. Can it be my problem? Or everything
else is wrong?
Many thanks for any advices.
(Postgres DBMS, Apache Tomcat, Hibernate, JSF2/Mojarra)
Check if instance of class is annotated with atribute
Check if instance of class is annotated with atribute
I have a class (Application) that has multiple properties of the type of
another custom class (Employment). I would like to validate that
Employment class conditionally based on whether the property of the
Application class is marked with [Required].
From what I've found, I think I should be utilizing the IValidatableObject
interface for Employment. The problem is that I'm not sure how to use
reflection (or something else maybe) to check if this instance of the
class is annotated with the [Required] attribute to determine whether to
validate it or not.
Maybe this isn't even possible. I initially set up two classes for the
Employment class: Employment and EmploymentRequired. Only the latter had
the validation attributes on its properties. It works, but I'd like to
just have one class to use if possible.
public class Application
{
[Required]
public Employment Employer1 { get; set; }
public Employment Employer2 { get; set; }
}
public class Employment : IValidatableObject
{
[Required]
public string EmployerName { get; set; }
[Required]
public string JobTitle { get; set; }
public string Phone { get; set; }
public IEnumerable<ValidationResult> Validate(ValidationContext
validationContext)
{
var results = new List<ValidationResult>();
var t = this.GetType();
//var pi = t.GetProperty("Id");
//var isRequired = Attribute.IsDefined(pi, typeof(RequiredAttribute));
//how can I get the attributes of this property in Application class?
if (isRequired)
{
Validator.TryValidateProperty(this.EmployerName,
new ValidationContext(this, null, null) { MemberName =
"EmployerName" }, results);
Validator.TryValidateProperty(this.JobTitle,
new ValidationContext(this, null, null) { MemberName =
"JobTitle" }, results);
}
return results;
}
}
I have a class (Application) that has multiple properties of the type of
another custom class (Employment). I would like to validate that
Employment class conditionally based on whether the property of the
Application class is marked with [Required].
From what I've found, I think I should be utilizing the IValidatableObject
interface for Employment. The problem is that I'm not sure how to use
reflection (or something else maybe) to check if this instance of the
class is annotated with the [Required] attribute to determine whether to
validate it or not.
Maybe this isn't even possible. I initially set up two classes for the
Employment class: Employment and EmploymentRequired. Only the latter had
the validation attributes on its properties. It works, but I'd like to
just have one class to use if possible.
public class Application
{
[Required]
public Employment Employer1 { get; set; }
public Employment Employer2 { get; set; }
}
public class Employment : IValidatableObject
{
[Required]
public string EmployerName { get; set; }
[Required]
public string JobTitle { get; set; }
public string Phone { get; set; }
public IEnumerable<ValidationResult> Validate(ValidationContext
validationContext)
{
var results = new List<ValidationResult>();
var t = this.GetType();
//var pi = t.GetProperty("Id");
//var isRequired = Attribute.IsDefined(pi, typeof(RequiredAttribute));
//how can I get the attributes of this property in Application class?
if (isRequired)
{
Validator.TryValidateProperty(this.EmployerName,
new ValidationContext(this, null, null) { MemberName =
"EmployerName" }, results);
Validator.TryValidateProperty(this.JobTitle,
new ValidationContext(this, null, null) { MemberName =
"JobTitle" }, results);
}
return results;
}
}
CSS: How to create colsgroup like semantic-ui way
CSS: How to create colsgroup like semantic-ui way
the jsbin is here: http://jsbin.com/uMEjOV/1/edit
Hi, in semantic UI, (http://semantic-ui.com) we could create:
<div class="ui three column grid">
<div class="column">1</div>
<div class="column">2</div>
<div class="column">3</div>
</div>
i try to create my own without semantic-ui famework:
<div class="colsgroup">
<div class="column">col 1</div>
<div class="column">col 2</div>
<div class="column">col 3</div>
<!-- but i need extra class="close" to make it work -->
<div class="close"></div>
</div>
I want clear model just like semantic-ui way. Yes, i want to remove <div
class="close"></div> (the style of .close is float: none; clear: both;)
How to do it to be as clear as semantic-ui way?
the jsbin is here: http://jsbin.com/uMEjOV/1/edit
Hi, in semantic UI, (http://semantic-ui.com) we could create:
<div class="ui three column grid">
<div class="column">1</div>
<div class="column">2</div>
<div class="column">3</div>
</div>
i try to create my own without semantic-ui famework:
<div class="colsgroup">
<div class="column">col 1</div>
<div class="column">col 2</div>
<div class="column">col 3</div>
<!-- but i need extra class="close" to make it work -->
<div class="close"></div>
</div>
I want clear model just like semantic-ui way. Yes, i want to remove <div
class="close"></div> (the style of .close is float: none; clear: both;)
How to do it to be as clear as semantic-ui way?
iterating dicts out of a dict of matched-length lists
iterating dicts out of a dict of matched-length lists
I have this structure:
d = {
"a": [1, 2, 3],
"b": [4, 5, 6],
"c": [7, 8, 9],
}
The lengths of the lists are guaranteed to match. I want an iterator I can
for-loop over that will serve up a dict for each column in the lists, sort
of like a zip turned back into a dict with the original key names each
time, like this:
>>> for i in iDictOfListsToDicts(d):
... print i
{"a": 1, "b": 4, "c": 7}
{"a": 2, "b": 5, "c": 8}
{"a": 3, "b": 6, "c": 9}
I'm sure I could hack something in a generator function, but I feel like
I'm missing a tight little combo of maybe two things, perhaps from
collections and/or itertools. I'd like decent efficiency and readability
if possible.
I've been toying with things that begin like this:
map(iter, d.values())
Obviously that just gives me a list of iterators of values with no related
keys, though, and I still can't for-loop over that list and get what I
want.
I have this structure:
d = {
"a": [1, 2, 3],
"b": [4, 5, 6],
"c": [7, 8, 9],
}
The lengths of the lists are guaranteed to match. I want an iterator I can
for-loop over that will serve up a dict for each column in the lists, sort
of like a zip turned back into a dict with the original key names each
time, like this:
>>> for i in iDictOfListsToDicts(d):
... print i
{"a": 1, "b": 4, "c": 7}
{"a": 2, "b": 5, "c": 8}
{"a": 3, "b": 6, "c": 9}
I'm sure I could hack something in a generator function, but I feel like
I'm missing a tight little combo of maybe two things, perhaps from
collections and/or itertools. I'd like decent efficiency and readability
if possible.
I've been toying with things that begin like this:
map(iter, d.values())
Obviously that just gives me a list of iterators of values with no related
keys, though, and I still can't for-loop over that list and get what I
want.
Thursday, 26 September 2013
Android - Appending text lines. Help choose the right control
Android - Appending text lines. Help choose the right control
Folks,
In my social networking application, single-line messages come from
various users. As the message comes in, I need to display them in our UI
as a single line that shows the time, the user, and the message line. All
3 fields need to be colored differently.
I tried to use TextView but am running into a problem. As I need various
colors, I thought of using SpannableString but the problem is that
TextView.Append does not support SpannableString as a parameter.
The other thought I had was to build html style text as each line comes in.
I am wondering if I am overlooking something. Perhaps there is a better
user control or a better way to achieve my objective.
Thank you in advance for your help.
Regards,
Peter
Folks,
In my social networking application, single-line messages come from
various users. As the message comes in, I need to display them in our UI
as a single line that shows the time, the user, and the message line. All
3 fields need to be colored differently.
I tried to use TextView but am running into a problem. As I need various
colors, I thought of using SpannableString but the problem is that
TextView.Append does not support SpannableString as a parameter.
The other thought I had was to build html style text as each line comes in.
I am wondering if I am overlooking something. Perhaps there is a better
user control or a better way to achieve my objective.
Thank you in advance for your help.
Regards,
Peter
Wednesday, 25 September 2013
Python lazy boolean evaluation gone wrong?
Python lazy boolean evaluation gone wrong?
Why this works:
s = 'xyz'
i = 0
while i < len(s) and s[i] not in 'aeiou':
print(s[i])
i += 1
x
y
z
... but this does not?
s = 'xyz'
i = 0
while s[i] not in 'aeiou' and i < len(s):
print(s[i])
i += 1
x
y
z
Traceback (most recent call last):
File "<pyshell#135>", line 1, in <module>
while s[i] not in 'aeiou' and i <= len(s):
IndexError: string index out of range
I'm confused, what am I missing here?
Why this works:
s = 'xyz'
i = 0
while i < len(s) and s[i] not in 'aeiou':
print(s[i])
i += 1
x
y
z
... but this does not?
s = 'xyz'
i = 0
while s[i] not in 'aeiou' and i < len(s):
print(s[i])
i += 1
x
y
z
Traceback (most recent call last):
File "<pyshell#135>", line 1, in <module>
while s[i] not in 'aeiou' and i <= len(s):
IndexError: string index out of range
I'm confused, what am I missing here?
Thursday, 19 September 2013
jQuery media query that works on both resize AND load?
jQuery media query that works on both resize AND load?
I have a responsive site, and I am trying to run certain jQuery functions
only when the screen is at or below 480px wide. I can only get it to
partially work. If you load the page with your browser < 480px wide, it
works. But if you load the page > 480px wide, and then resize it to <480,
it doesn't work. I need it to work in both circumstances, turning off and
on as you resize accordingly. What am I doing wrong? Here is what I have
that works only if you load the page at <=480.
jQuery(document).ready(function($){
if ( $("div#wrapper").css("overflow") === "visible") {
// mobile js goes here
}
});
I have also tried it this way, but once I resize it starts looping
everything I put in the "mobile js goes here" part and crashes the
browser???
$(window).resize(function(){
if ( $("div#wrapper").css("overflow") === "visible") {
// mobile js goes here
}
});
I have a responsive site, and I am trying to run certain jQuery functions
only when the screen is at or below 480px wide. I can only get it to
partially work. If you load the page with your browser < 480px wide, it
works. But if you load the page > 480px wide, and then resize it to <480,
it doesn't work. I need it to work in both circumstances, turning off and
on as you resize accordingly. What am I doing wrong? Here is what I have
that works only if you load the page at <=480.
jQuery(document).ready(function($){
if ( $("div#wrapper").css("overflow") === "visible") {
// mobile js goes here
}
});
I have also tried it this way, but once I resize it starts looping
everything I put in the "mobile js goes here" part and crashes the
browser???
$(window).resize(function(){
if ( $("div#wrapper").css("overflow") === "visible") {
// mobile js goes here
}
});
Handling array and creating list of required elements in perl
Handling array and creating list of required elements in perl
I have the code below:
This code gathers non required files like "KS""PUBLIC" and stores in hash
and in grep checks for it and throws out and give only required files like
A0, A1, B0, B1 to @MYFILES.
use warnings;
use strict;
my @myfiles = ("public", "A0", "A1", "B1", "B0", "KS");
my %goods = map { $_ => 1 } qw(public KS);
my @MYFILES = grep { not exists $bads{$_} } @myfiles;
Now, instead I want that from array @myfiles hash stores only required
files but on the basis of pattern matching and then store it in hash and
then give it to @MYFILES then how to do? ANy suggestion?
Here is what I mean like greping required field on the basis of alphabet
and digit and then storing in hash and then using that hash to provide
values to @MYFILES. That hash should include only A0, A1, B0, B1.
Thanks,
I have the code below:
This code gathers non required files like "KS""PUBLIC" and stores in hash
and in grep checks for it and throws out and give only required files like
A0, A1, B0, B1 to @MYFILES.
use warnings;
use strict;
my @myfiles = ("public", "A0", "A1", "B1", "B0", "KS");
my %goods = map { $_ => 1 } qw(public KS);
my @MYFILES = grep { not exists $bads{$_} } @myfiles;
Now, instead I want that from array @myfiles hash stores only required
files but on the basis of pattern matching and then store it in hash and
then give it to @MYFILES then how to do? ANy suggestion?
Here is what I mean like greping required field on the basis of alphabet
and digit and then storing in hash and then using that hash to provide
values to @MYFILES. That hash should include only A0, A1, B0, B1.
Thanks,
R programming - improving a minimal spanning tree plot using {ape}
R programming - improving a minimal spanning tree plot using {ape}
I tried the following codes to plot minimal spanning tree:
library(ape)
mstree <-mst(distmat) #distmat is a distance matrix
plot(mstree, x1 = xycoordinates[,1], x2 = xycoordinates[,2])
if I command the above lines, I do get a minimal spanning tree diagram
according to the distance matrix I specified, yet the graph looks bit
boring because everything is black....if I want to change the colour of
the tree "branches" into blue (i.e. from being black), how can I do that?
Thank you,
I tried the following codes to plot minimal spanning tree:
library(ape)
mstree <-mst(distmat) #distmat is a distance matrix
plot(mstree, x1 = xycoordinates[,1], x2 = xycoordinates[,2])
if I command the above lines, I do get a minimal spanning tree diagram
according to the distance matrix I specified, yet the graph looks bit
boring because everything is black....if I want to change the colour of
the tree "branches" into blue (i.e. from being black), how can I do that?
Thank you,
Extracting block of data from a file
Extracting block of data from a file
I have a problem, which surely can be solved with an awk one-liner.
I want to split an existing data file, which consists of blocks of data
into separate files. The datafile has the following form:
1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3
And i want to store every single block of data in a separate file, named -
for example - "1.dat", ".dat", "3.dat",... The problem is, that each block
doesn't have a specific line number, they are just delimited by two "new
lines".
Thanks in advance, Jürgen
I have a problem, which surely can be solved with an awk one-liner.
I want to split an existing data file, which consists of blocks of data
into separate files. The datafile has the following form:
1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3
And i want to store every single block of data in a separate file, named -
for example - "1.dat", ".dat", "3.dat",... The problem is, that each block
doesn't have a specific line number, they are just delimited by two "new
lines".
Thanks in advance, Jürgen
how to save data locally in HTML5 web page so that we do not need to fetch from server again and again?
how to save data locally in HTML5 web page so that we do not need to fetch
from server again and again?
I want to make an app through HTML5 through which user can visit and store
data for offline, could any one give me references for that?
from server again and again?
I want to make an app through HTML5 through which user can visit and store
data for offline, could any one give me references for that?
Define shebang and encoding in python
Define shebang and encoding in python
Is there a difference between
(a) defining the encoding with the shebang
#!/usr/bin/env python -*- coding: utf-8 -*-
(b) defining the shebang and the encoding on separate lines?
#!/usr/bin/env python
#-*- coding: utf-8 -*-
Is there a difference between
(a) defining the encoding with the shebang
#!/usr/bin/env python -*- coding: utf-8 -*-
(b) defining the shebang and the encoding on separate lines?
#!/usr/bin/env python
#-*- coding: utf-8 -*-
load html files by its names in alphabetical order with include php
load html files by its names in alphabetical order with include php
I got this code on my site
<div id="tips-wrap">
<?php
include('news/games/02GA.html');
?>
</div>
<div id="tips-wrap">
<?php
include('news/games/03GA.html');
?>
</div>
it works pretty well, but I want to chage it, so it can load the files by
its names in alphabetical order with the last first, but I need it to
cycle with the new news
something like this:
<div id="tips-wrap">
<?php
include('news/003.html');
?>
</div>
<div id="tips-wrap">
<?php
include('news/002.html');
?>
</div>
so when we update the site with 050.html the code loads it in the first
slot of the page. I dont know if this is possible, I´m new with php
I got this code on my site
<div id="tips-wrap">
<?php
include('news/games/02GA.html');
?>
</div>
<div id="tips-wrap">
<?php
include('news/games/03GA.html');
?>
</div>
it works pretty well, but I want to chage it, so it can load the files by
its names in alphabetical order with the last first, but I need it to
cycle with the new news
something like this:
<div id="tips-wrap">
<?php
include('news/003.html');
?>
</div>
<div id="tips-wrap">
<?php
include('news/002.html');
?>
</div>
so when we update the site with 050.html the code loads it in the first
slot of the page. I dont know if this is possible, I´m new with php
Wednesday, 18 September 2013
From php file call another php file by giving it also a parameter
From php file call another php file by giving it also a parameter
I will explain with a simple example:
myphp1.php:
$html = get_html("myphp2.php", "parameter1"); //pseudocode
myphp2.php
<html>
<head>
</head>
<body>
<?php
echo $_POST["parameter1"];
?>
</body>
</html>
So basically the $html will hold the myphp2.php html output. Can I do that?
I will explain with a simple example:
myphp1.php:
$html = get_html("myphp2.php", "parameter1"); //pseudocode
myphp2.php
<html>
<head>
</head>
<body>
<?php
echo $_POST["parameter1"];
?>
</body>
</html>
So basically the $html will hold the myphp2.php html output. Can I do that?
GDAL for Java on Windows, native library error
GDAL for Java on Windows, native library error
I know it's probably fairly simple, but I'm having some issues grasping
all the different packages I need just to install GDAL and read
georeferenced rasters.
So I have already had OSGEO4W installed so that there exists a folderpath
as follows: C:\OsGeo4W\lib\gdal.jar as well as
C:\OsGeo4W\apps\swigwin\swig.exe
I also have the version from http://vbkto.dyndns.org/sdk/ so that I have a
folderpath as follows: C:\ProjectsJava\gdal\bin\gdal\java\ with a gdal.jar
and a bunch of dll's. This is what is originally linked in my project's
libraries.
After googling the problem, I've also added a -Djava.library.path to point
to the above gdal folderpath in the project's VM options (not entirely
sure what I did but didn't make a difference anyways).
Also from random googled answers I've added environment variables to
windows point to this and that related to GDAL or SWIG that did nothing
(so removed them for now). So I only have a PATH that points to the
gdal/bin folder and a GDAL_DATA that points to the gdal/bin/gdal-data
folder. If it makes any difference I have installed successfully GDAL
bindings for Python and there are some of it's environment variables left
over in PATH and GDAL_DATA as well to similar but different folders.
Basically the code fails to even run a gdal.Open(in_path), giving the
following error which hasn't changed no matter what I did differently:
Native library load failed.
java.lang.UnsatisfiedLinkError:
C:\ProjectsJava\gdal\bin\gdal\jave\gdaljni.dll: Can't find dependent
libraries
java.lang.UnsatisfiedLinkError:
org.gdal.gdal.gdalJNI.Open__SWIG_1(Ljava/lang/String;)J'
at org.gdal.gdal.gdalJNI.Open__SWIG_1(Native Method)
at org.gdal.gdal.gdal.Open(gdal.java:563)
at ...
Now I know I probably screwed up getting GDAL right, but to be honest the
labyrinthical instructions lost me well early on. All the odd packages to
adapt C++ code to Java and instructions meant for Unix/Linux have got me
all mixed up now.
I know it's probably fairly simple, but I'm having some issues grasping
all the different packages I need just to install GDAL and read
georeferenced rasters.
So I have already had OSGEO4W installed so that there exists a folderpath
as follows: C:\OsGeo4W\lib\gdal.jar as well as
C:\OsGeo4W\apps\swigwin\swig.exe
I also have the version from http://vbkto.dyndns.org/sdk/ so that I have a
folderpath as follows: C:\ProjectsJava\gdal\bin\gdal\java\ with a gdal.jar
and a bunch of dll's. This is what is originally linked in my project's
libraries.
After googling the problem, I've also added a -Djava.library.path to point
to the above gdal folderpath in the project's VM options (not entirely
sure what I did but didn't make a difference anyways).
Also from random googled answers I've added environment variables to
windows point to this and that related to GDAL or SWIG that did nothing
(so removed them for now). So I only have a PATH that points to the
gdal/bin folder and a GDAL_DATA that points to the gdal/bin/gdal-data
folder. If it makes any difference I have installed successfully GDAL
bindings for Python and there are some of it's environment variables left
over in PATH and GDAL_DATA as well to similar but different folders.
Basically the code fails to even run a gdal.Open(in_path), giving the
following error which hasn't changed no matter what I did differently:
Native library load failed.
java.lang.UnsatisfiedLinkError:
C:\ProjectsJava\gdal\bin\gdal\jave\gdaljni.dll: Can't find dependent
libraries
java.lang.UnsatisfiedLinkError:
org.gdal.gdal.gdalJNI.Open__SWIG_1(Ljava/lang/String;)J'
at org.gdal.gdal.gdalJNI.Open__SWIG_1(Native Method)
at org.gdal.gdal.gdal.Open(gdal.java:563)
at ...
Now I know I probably screwed up getting GDAL right, but to be honest the
labyrinthical instructions lost me well early on. All the odd packages to
adapt C++ code to Java and instructions meant for Unix/Linux have got me
all mixed up now.
Want to get day of a week as a string, But giving wrong day
Want to get day of a week as a string, But giving wrong day
I tried to get the day as a string by using the following code. But it
returns wrong string. Can I fix it with this code.
private String getDayOfWeek(int value){
String day = "";
switch(value){
case 1:
day="Sunday";
break;
case 2:
day="Monday";
break;
case 3:
day="Tuesday";
break;
case 4:
day="Wednesday";
break;
case 5:
day="Thursday";
break;
case 6:
day="Friday";
break;
case 7:
day="Saturday";
break;
}
return day;
I implements it as
Calendar c = Calendar.getInstance();
String dayOfWeek = getDayOfWeek(Calendar.DAY_OF_WEEK);
System.out.println(dayOfWeek);
Thanks in Advance
I tried to get the day as a string by using the following code. But it
returns wrong string. Can I fix it with this code.
private String getDayOfWeek(int value){
String day = "";
switch(value){
case 1:
day="Sunday";
break;
case 2:
day="Monday";
break;
case 3:
day="Tuesday";
break;
case 4:
day="Wednesday";
break;
case 5:
day="Thursday";
break;
case 6:
day="Friday";
break;
case 7:
day="Saturday";
break;
}
return day;
I implements it as
Calendar c = Calendar.getInstance();
String dayOfWeek = getDayOfWeek(Calendar.DAY_OF_WEEK);
System.out.println(dayOfWeek);
Thanks in Advance
ArrayList initializing
ArrayList initializing
Hey guys I just have a quick question about initializing an arraylist
This is just a small piece of code I'm doing
public class OrderManager {
ArrayList<Order>orders = new ArrayList<Order>();
public OrderManager() {
}
public OrderManager(ArrayList<Order> orders) {
orders = new ArrayList<Order>();
}
using a variable orders, and then declaring orders = new correct? Or is
this going to be two different instances and when I try to add things to
it its not going to work?
Or since OrderManager is going to take an arraylist does it even make sense?
I haven't tested it yet, I just started writing this code and have ran
into this problem before where I couldn't add to the list properly and
believe it was because of a error similar to this just checking to try and
get it right to start with.
Hey guys I just have a quick question about initializing an arraylist
This is just a small piece of code I'm doing
public class OrderManager {
ArrayList<Order>orders = new ArrayList<Order>();
public OrderManager() {
}
public OrderManager(ArrayList<Order> orders) {
orders = new ArrayList<Order>();
}
using a variable orders, and then declaring orders = new correct? Or is
this going to be two different instances and when I try to add things to
it its not going to work?
Or since OrderManager is going to take an arraylist does it even make sense?
I haven't tested it yet, I just started writing this code and have ran
into this problem before where I couldn't add to the list properly and
believe it was because of a error similar to this just checking to try and
get it right to start with.
SLF4J: No Binder, and then Multiple Bindings, trying to Bind to L4J
SLF4J: No Binder, and then Multiple Bindings, trying to Bind to L4J
I have a strange double error with SLF4J.
I'm trying to get SLF4J to bind to L4J.
In Eclipse, when I run a Maven Clean and then a Maven Install, I get this
in the Maven Install output:
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further
details.
Later on, when running the jUnit tests for the project, one of the tests
calls a method that logs a message (I haven't cleaned it up to not log
yet).
But instead of logging, I get this message:
SLF4J: Class path contains multiple SLF4J bindings.
SLF4J: Found binding in
[jar:file:/C:/Users/JDunn/.m2/repository/ch/qos/logback/logback-classic/0.9.30/logback-classic-0.9.30.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: Found binding in
[jar:file:/C:/Users/JDunn/.m2/repository/org/slf4j/slf4j-log4j13/1.0.1/slf4j-log4j13-1.0.1.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: See http://www.slf4j.org/codes.html#multiple_bindings for an
explanation.
So it seems that SLF4J first can't load a Binder, and then it finds
multiple Bindings!
In my pom.xml, I have only one relevant dependency:
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j13</artifactId>
<version>1.0.1</version>
</dependency>
To resolve the issue, I tried deleting the first binding from my
repository, namely this one:
C:/Users/JDunn/.m2/repository/ch/qos/logback/logback-classic/0.9.30/logback-classic-0.9.30.jar
I ran another Maven Clean, Maven Install and got a strange error when it
tried to run the tests:
Failed to execute goal
org.apache.maven.plugins:maven-surefire-plugin:2.14:test (default-test) on
project sonar-score-plugin: Execution default-test of goal
org.apache.maven.plugins:maven-surefire-plugin:2.14:test failed: There was
an error in the forked process
I then ran Maven Clean, Maven Install again, and got the original
"Multiple Bindings" error again, and found that the directory I had
deleted was there again as if I hadn't deleted it.
I don't know what else I can do to get rid of the "Multiple Bindings" error.
Note: I found a similar question, but I don't have the same cause that
could be effecting this error.
I have a strange double error with SLF4J.
I'm trying to get SLF4J to bind to L4J.
In Eclipse, when I run a Maven Clean and then a Maven Install, I get this
in the Maven Install output:
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further
details.
Later on, when running the jUnit tests for the project, one of the tests
calls a method that logs a message (I haven't cleaned it up to not log
yet).
But instead of logging, I get this message:
SLF4J: Class path contains multiple SLF4J bindings.
SLF4J: Found binding in
[jar:file:/C:/Users/JDunn/.m2/repository/ch/qos/logback/logback-classic/0.9.30/logback-classic-0.9.30.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: Found binding in
[jar:file:/C:/Users/JDunn/.m2/repository/org/slf4j/slf4j-log4j13/1.0.1/slf4j-log4j13-1.0.1.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: See http://www.slf4j.org/codes.html#multiple_bindings for an
explanation.
So it seems that SLF4J first can't load a Binder, and then it finds
multiple Bindings!
In my pom.xml, I have only one relevant dependency:
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j13</artifactId>
<version>1.0.1</version>
</dependency>
To resolve the issue, I tried deleting the first binding from my
repository, namely this one:
C:/Users/JDunn/.m2/repository/ch/qos/logback/logback-classic/0.9.30/logback-classic-0.9.30.jar
I ran another Maven Clean, Maven Install and got a strange error when it
tried to run the tests:
Failed to execute goal
org.apache.maven.plugins:maven-surefire-plugin:2.14:test (default-test) on
project sonar-score-plugin: Execution default-test of goal
org.apache.maven.plugins:maven-surefire-plugin:2.14:test failed: There was
an error in the forked process
I then ran Maven Clean, Maven Install again, and got the original
"Multiple Bindings" error again, and found that the directory I had
deleted was there again as if I hadn't deleted it.
I don't know what else I can do to get rid of the "Multiple Bindings" error.
Note: I found a similar question, but I don't have the same cause that
could be effecting this error.
PHP Download file with header
PHP Download file with header
I know it's something easy, but I can't seem to find the solution. I want
to download a pdf from a folder. The pdf is in a folder named forms. My
script is in a different folder.
When I try to download the file with the following code:
header('Content-Disposition: attachment; filename="forms/form1976.pdf"');
The filename becomes: forms-form1976.pdf. That's not right, the filename
should be: form1976.pdf. How do I enter the the correct folder first?
I know it's something easy, but I can't seem to find the solution. I want
to download a pdf from a folder. The pdf is in a folder named forms. My
script is in a different folder.
When I try to download the file with the following code:
header('Content-Disposition: attachment; filename="forms/form1976.pdf"');
The filename becomes: forms-form1976.pdf. That's not right, the filename
should be: form1976.pdf. How do I enter the the correct folder first?
API 18 deprecations
API 18 deprecations
Can anybody provide a list of deprications made in Jelly Bean 4.3 (API 18) ?
I had an app on API 16 and I wanted my app to be upgraded to API 18, so
please tell me what changes I have to make in my code.
Thanks in advance...
Can anybody provide a list of deprications made in Jelly Bean 4.3 (API 18) ?
I had an app on API 16 and I wanted my app to be upgraded to API 18, so
please tell me what changes I have to make in my code.
Thanks in advance...
How to list all background pids in bash
How to list all background pids in bash
Either I am not able to phrase my search correctly or the answer is not
easy to find!, but I am trying to figure out how to list all of my
background task PIDs. For example:
So far I have found that to list the last PID we use:
$!
But now I want to list the PID of the task before that (if one exists),
but I can't find how to do that. Utlimatly I want to list all my
background task PIDs.
I know we can also find last job ID with:
%% (last job in list)
%1 (first job in list)
%2 (second job in list)
But the same does not seem to work for process id?
Thanks all :)
Either I am not able to phrase my search correctly or the answer is not
easy to find!, but I am trying to figure out how to list all of my
background task PIDs. For example:
So far I have found that to list the last PID we use:
$!
But now I want to list the PID of the task before that (if one exists),
but I can't find how to do that. Utlimatly I want to list all my
background task PIDs.
I know we can also find last job ID with:
%% (last job in list)
%1 (first job in list)
%2 (second job in list)
But the same does not seem to work for process id?
Thanks all :)
Tuesday, 17 September 2013
java.lang.UnsupportedOperationException shown when trying to Assert some values
java.lang.UnsupportedOperationException shown when trying to Assert some
values
I am using the below code to assert text in my test script. But its giving
UnsupportedOperationException error every time it hits this code.
public static void verifyEquals(Object actual, Object expected) {
try {
Assert.assertEquals(actual, expected);
} catch(Throwable e) {
addVerificationFailure(e);
}
}
public static List<Throwable> getVerificationFailures() {
List verificationFailures =
verificationFailuresMap.get(Reporter.getCurrentTestResult());
return verificationFailures == null ? new ArrayList() :
verificationFailures;
}
private static void addVerificationFailure(Throwable e) {
StackTraceElement[] error = e.getStackTrace();
List<StackTraceElement> errors = Arrays.asList(error);
verificationFailuresMap.put(Reporter.getCurrentTestResult(), errors);
List verificationFailures = getVerificationFailures();
verificationFailuresMap.put(Reporter.getCurrentTestResult(),
verificationFailures);
verificationFailures.add(e);
}
Can anyone help me on this?
values
I am using the below code to assert text in my test script. But its giving
UnsupportedOperationException error every time it hits this code.
public static void verifyEquals(Object actual, Object expected) {
try {
Assert.assertEquals(actual, expected);
} catch(Throwable e) {
addVerificationFailure(e);
}
}
public static List<Throwable> getVerificationFailures() {
List verificationFailures =
verificationFailuresMap.get(Reporter.getCurrentTestResult());
return verificationFailures == null ? new ArrayList() :
verificationFailures;
}
private static void addVerificationFailure(Throwable e) {
StackTraceElement[] error = e.getStackTrace();
List<StackTraceElement> errors = Arrays.asList(error);
verificationFailuresMap.put(Reporter.getCurrentTestResult(), errors);
List verificationFailures = getVerificationFailures();
verificationFailuresMap.put(Reporter.getCurrentTestResult(),
verificationFailures);
verificationFailures.add(e);
}
Can anyone help me on this?
CSS fluid layout for inputs
CSS fluid layout for inputs
I am currently making a website and the sign up page requires:
- first name
- last name
- username
- email
- password
- retype password
I need the first name and last name inputs to be side by side and small
while the others below them are approximately twice the width. Like this:
Name
+-----------+ +-----------+
| first | | last |
+-----------+ +-----------+
Email
+----------------------------+
| |
+----------------------------+
I am extremely opposed to using px and absolutely need to use % for the
widths.
I cannot make the small inputs 50% and the large ones 100% because the
space in between the two small ones is not accounted for, you know?
I'm talking about this space:
Name
+-----------+ +-----------+
| first |<-->| last |
+-----------+ +-----------+
So that is why I can't use 50% for small ones and 100% for large ones!
Any help is greatly appreciated!
I am currently making a website and the sign up page requires:
- first name
- last name
- username
- password
- retype password
I need the first name and last name inputs to be side by side and small
while the others below them are approximately twice the width. Like this:
Name
+-----------+ +-----------+
| first | | last |
+-----------+ +-----------+
+----------------------------+
| |
+----------------------------+
I am extremely opposed to using px and absolutely need to use % for the
widths.
I cannot make the small inputs 50% and the large ones 100% because the
space in between the two small ones is not accounted for, you know?
I'm talking about this space:
Name
+-----------+ +-----------+
| first |<-->| last |
+-----------+ +-----------+
So that is why I can't use 50% for small ones and 100% for large ones!
Any help is greatly appreciated!
expected identifier or ( before for=?iso-8859-1?Q?(=92_before_=91for=92?=
expected identifier or '(' before 'for'
/** @file alloc.c */
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#define NEW_BLOCK_SIZE 1024
#define ARRAY_SIZE 31
typedef struct _metadata_mem
{
size_t size;
void * addr ;
struct _metadata_mem * next_free ;
struct _metadata_mem * pre_free;
char * unit ;
} metadata_mem;
#define SIZE_OF_MATEDATA sizeof(metadata_mem)
metadata_mem * array_of_block[31] ;
int i;
for(i=0; i<31; i++){
array_of_block[i]=NULL;
}
int index(size_t size){
int count=0;
while((int)size>=2){
size/=2;
count++;
}
return count ;
}
I received the following error and it starts in the for loop:
gcc alloc.c -O3 -Wextra -Wall -Werror -Wno-unused-result
-Wno-unused-parameter -o alloc.so -shared -fPIC
alloc.c:30:2: error: expected identifier or '(' before 'for'
alloc.c:30:12: error: expected '=', ',', ';', 'asm' or '__attribute__'
before '<' token
alloc.c:30:26: error: expected '=', ',', ';', 'asm' or '__attribute__'
before '++' token
alloc.c:35:5: error: conflicting types for 'index'
make: *** [alloc.so] Error 1
I have no idea what's wrong with the for loop. It seems OK. Am I not
supposed to initialized the array_of_block in the global context ?
Thanks a lot.
/** @file alloc.c */
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#define NEW_BLOCK_SIZE 1024
#define ARRAY_SIZE 31
typedef struct _metadata_mem
{
size_t size;
void * addr ;
struct _metadata_mem * next_free ;
struct _metadata_mem * pre_free;
char * unit ;
} metadata_mem;
#define SIZE_OF_MATEDATA sizeof(metadata_mem)
metadata_mem * array_of_block[31] ;
int i;
for(i=0; i<31; i++){
array_of_block[i]=NULL;
}
int index(size_t size){
int count=0;
while((int)size>=2){
size/=2;
count++;
}
return count ;
}
I received the following error and it starts in the for loop:
gcc alloc.c -O3 -Wextra -Wall -Werror -Wno-unused-result
-Wno-unused-parameter -o alloc.so -shared -fPIC
alloc.c:30:2: error: expected identifier or '(' before 'for'
alloc.c:30:12: error: expected '=', ',', ';', 'asm' or '__attribute__'
before '<' token
alloc.c:30:26: error: expected '=', ',', ';', 'asm' or '__attribute__'
before '++' token
alloc.c:35:5: error: conflicting types for 'index'
make: *** [alloc.so] Error 1
I have no idea what's wrong with the for loop. It seems OK. Am I not
supposed to initialized the array_of_block in the global context ?
Thanks a lot.
Keeping the latest erlang but running riak's make devrel
Keeping the latest erlang but running riak's make devrel
I'm reading this tutorial:
http://docs.basho.com/riak/1.1.4/tutorials/fast-track/Building-a-Development-Environment/
I installed riak from the .deb package in ubuntu. If I run riak start it
will say "node is already running!" the second time I do it. I downloaded
the riak source. The tutorial wants me to do make devrel. It gives me a
long erlang error. if I try to compile riak from source it will complain I
have the latest version of erlang. I tried to alias
erl=/usr/lib/riak/erts-5.9.1/bin/erl to use the older version bundled with
riak but it still gives same error. I tried to remove the vsn requirements
from the rebar.config.
Is there a way to run multiple nodes using riak start after installing
riak from the .deb package? Is there a way to compile riak without
removing the latest version of erlang?
I'm reading this tutorial:
http://docs.basho.com/riak/1.1.4/tutorials/fast-track/Building-a-Development-Environment/
I installed riak from the .deb package in ubuntu. If I run riak start it
will say "node is already running!" the second time I do it. I downloaded
the riak source. The tutorial wants me to do make devrel. It gives me a
long erlang error. if I try to compile riak from source it will complain I
have the latest version of erlang. I tried to alias
erl=/usr/lib/riak/erts-5.9.1/bin/erl to use the older version bundled with
riak but it still gives same error. I tried to remove the vsn requirements
from the rebar.config.
Is there a way to run multiple nodes using riak start after installing
riak from the .deb package? Is there a way to compile riak without
removing the latest version of erlang?
Include an image into a "mailto" mail?
Include an image into a "mailto" mail?
The title might not be clear - I'm creating an app in Unity and I want it
to start the device's default mail client to create a new mail. I can
easily do that with mailto. What I don't know how to do is include an
image in the mail being composed. In any way: as an attachment, as a part
of the mail body or whatever. But it's a local image, so I can't just put
a link to it in the mail.
Is it even possible? If so, how?
The title might not be clear - I'm creating an app in Unity and I want it
to start the device's default mail client to create a new mail. I can
easily do that with mailto. What I don't know how to do is include an
image in the mail being composed. In any way: as an attachment, as a part
of the mail body or whatever. But it's a local image, so I can't just put
a link to it in the mail.
Is it even possible? If so, how?
How do I include a variable in jquery .html
How do I include a variable in jquery .html
Trying to include a variable in my jquery:
var width = $(this).width();
$("#dynamic").html(".dropdown-bottom:before{left:'width'px;}");
How do I indicate that width is a variable in the .html?
Trying to include a variable in my jquery:
var width = $(this).width();
$("#dynamic").html(".dropdown-bottom:before{left:'width'px;}");
How do I indicate that width is a variable in the .html?
Sunday, 15 September 2013
what does "Message: ERROR:wrong token." means when using MFMessageComposeViewController to send sms in iOS?
This summary is not available. Please
click here to view the post.
Set ImagePickerController delegate
Set ImagePickerController delegate
I am not sure how to initialize the UIImagePickerController. I cannot set
the delegate. I would like to use
pickerController.delegate = self;
but this yields a warning: "Sending 'MyViewController *const_strong' to
parameter of incompatible type 'id'"
I declared my class to be a delegate (UIImagePickerControllerDelegate) and
added this:
UIImagePickerController *pickerController;
Can anyone help please?
I am not sure how to initialize the UIImagePickerController. I cannot set
the delegate. I would like to use
pickerController.delegate = self;
but this yields a warning: "Sending 'MyViewController *const_strong' to
parameter of incompatible type 'id'"
I declared my class to be a delegate (UIImagePickerControllerDelegate) and
added this:
UIImagePickerController *pickerController;
Can anyone help please?
Android Tab Menu not working
Android Tab Menu not working
I'm trying to make a MenuTab with android but I have a lot of problems.
Here's my code
tabHost = (TabHost) A.findViewById(R.id.tabHost);
tabHost.setup();
TabSpec spec1 = tabHost.newTabSpec("tab_news");
spec1.setIndicator(
"", //Load news titlte
A.getResources().getDrawable(R.drawable.icon_menu_news) //Load icon
);
spec1.setContent(R.id.tab_news);
tabHost.addTab(spec1);
First question, why if I put "title" inside indicator I don't see the image?
Well now I want to create a new activity when this tab is selected.
TabSpec firstTabSpec = tabHost.newTabSpec("tid1");
firstTabSpec.setIndicator("First Tab Name").setContent(new
Intent(A,Test.class));
This example doesn't work... I get this error
09-15 23:19:26.861: E/AndroidRuntime(14938): java.lang.RuntimeException:
Unable to start activity
ComponentInfo{com.workactivity/com.workactivity.MainActivity}:
java.lang.IllegalStateException: Did you forget to call 'public void
setup(LocalActivityManager activityGroup)'?
I try to google about setup but I get no matchs...
I follow this tutorial:
http://www.androidpeople.com/android-tabhost-tutorial-part-1 And this one:
http://android-pro.blogspot.com.es/2010/08/tabbed-applications-in-android.html
Thanks for all :)
I'm trying to make a MenuTab with android but I have a lot of problems.
Here's my code
tabHost = (TabHost) A.findViewById(R.id.tabHost);
tabHost.setup();
TabSpec spec1 = tabHost.newTabSpec("tab_news");
spec1.setIndicator(
"", //Load news titlte
A.getResources().getDrawable(R.drawable.icon_menu_news) //Load icon
);
spec1.setContent(R.id.tab_news);
tabHost.addTab(spec1);
First question, why if I put "title" inside indicator I don't see the image?
Well now I want to create a new activity when this tab is selected.
TabSpec firstTabSpec = tabHost.newTabSpec("tid1");
firstTabSpec.setIndicator("First Tab Name").setContent(new
Intent(A,Test.class));
This example doesn't work... I get this error
09-15 23:19:26.861: E/AndroidRuntime(14938): java.lang.RuntimeException:
Unable to start activity
ComponentInfo{com.workactivity/com.workactivity.MainActivity}:
java.lang.IllegalStateException: Did you forget to call 'public void
setup(LocalActivityManager activityGroup)'?
I try to google about setup but I get no matchs...
I follow this tutorial:
http://www.androidpeople.com/android-tabhost-tutorial-part-1 And this one:
http://android-pro.blogspot.com.es/2010/08/tabbed-applications-in-android.html
Thanks for all :)
Convert string to binary in python
Convert string to binary in python
I am in need of a way to get the binary representation of a string in
python. e.g.
st = "hello world"
toBinary(st)
Is there a module of some neat way of doing this?
I am in need of a way to get the binary representation of a string in
python. e.g.
st = "hello world"
toBinary(st)
Is there a module of some neat way of doing this?
ios6 / NSJSONSerialization / and json array data without key/value pair
ios6 / NSJSONSerialization / and json array data without key/value pair
I'm using a JSON datasource but without key/value pair, and the data is
like this:
[["user1",1,1,1,1],
["user2",1,1,1,1]]
If I try to decode this with NSJSONSerialization I get an NSArray with 1
entry like this:
jsonArray : (
(
"user1",
1,
1,
1,
1
),
(
user2,
1,
1,
1,
1
)
)
Any idea how I can get this more usable?
I'm using a JSON datasource but without key/value pair, and the data is
like this:
[["user1",1,1,1,1],
["user2",1,1,1,1]]
If I try to decode this with NSJSONSerialization I get an NSArray with 1
entry like this:
jsonArray : (
(
"user1",
1,
1,
1,
1
),
(
user2,
1,
1,
1,
1
)
)
Any idea how I can get this more usable?
MAC 10.4.8 mod_wsgi istall
MAC 10.4.8 mod_wsgi istall
Is there a good tutorial on how to install apache and python and run a
hello world server app? This is needed on a MAC environment 10.4.8 or
higher.
Is there a good tutorial on how to install apache and python and run a
hello world server app? This is needed on a MAC environment 10.4.8 or
higher.
How to fire custom events in Actionscript-3?
How to fire custom events in Actionscript-3?
I would like to add event listeners to my custom events similar to
stage.addEventListener(Keyboard.KEY_DOWN, myFunction);
My class is not inheriting and the event is LOADED like KEY_DOWN. When my
data is loaded I want to fire this event so every function that is
subscribed to this event can be notified about it:
public class MyClass
{
public static const LOADED: String = "Loaded";
public function addEventListener(eventType: String, handler:
Function):void
{
;
}
public function fireLoadedEvent(param: LoadedEvent):void
{
;
}
}
I would probably implement what I use in Flash to add event listeners but
in MyClass. I'm not sure how to store the listeners and how to call them
all with the parameters I want to pass to them. Is there something easier
and more common to use ?
I would like to add event listeners to my custom events similar to
stage.addEventListener(Keyboard.KEY_DOWN, myFunction);
My class is not inheriting and the event is LOADED like KEY_DOWN. When my
data is loaded I want to fire this event so every function that is
subscribed to this event can be notified about it:
public class MyClass
{
public static const LOADED: String = "Loaded";
public function addEventListener(eventType: String, handler:
Function):void
{
;
}
public function fireLoadedEvent(param: LoadedEvent):void
{
;
}
}
I would probably implement what I use in Flash to add event listeners but
in MyClass. I'm not sure how to store the listeners and how to call them
all with the parameters I want to pass to them. Is there something easier
and more common to use ?
Saturday, 14 September 2013
Pros and cons of using mysql_pconnect in php
Pros and cons of using mysql_pconnect in php
I want to know that when I should use mysql_pconnect instead of
mysql_connect.
I want to know that when I should use mysql_pconnect instead of
mysql_connect.
Change text color of a hyperlink
Change text color of a hyperlink
I'm making a navigation menu bar. I want it so that one of the href links
can change colors "horizontally", if you know what I mean. Here's an
example:
See how the "Create a Free Account" hyperlink switches from one color to
another? That's what I'm referring to.
If this question sounds a little vague, I'll try to re-word it.
I'm making a navigation menu bar. I want it so that one of the href links
can change colors "horizontally", if you know what I mean. Here's an
example:
See how the "Create a Free Account" hyperlink switches from one color to
another? That's what I'm referring to.
If this question sounds a little vague, I'll try to re-word it.
Single line output by using emmet-mode in Emacs
Single line output by using emmet-mode in Emacs
I'm using emmet-mode in Emacs24. https://github.com/smihica/emmet-mode
I want to output some tags in single line like:
<script src=""></script>
But this mode output in two lines like:
<script src="">
</script>
Is there setting for it?
I'm using emmet-mode in Emacs24. https://github.com/smihica/emmet-mode
I want to output some tags in single line like:
<script src=""></script>
But this mode output in two lines like:
<script src="">
</script>
Is there setting for it?
toy/doc undefined method 'available?'
toy/doc undefined method 'available?'
I'm attempting to build local Ruby documentation as suggested here:
https://github.com/toy/doc
However when I use the default Rakefile I get the following:
[Documentation]$ rake build
configuring and updating: 100.0%
rake aborted!
undefined method `available?' for Gem:Module
/Users/snowcrash/.rvm/gems/ruby-2.0.0-p195/gems/sdoc-0.2.20/lib/sdoc/json_backend.rb:9:in
`<top (required)>'
Any suggestions?
I'm attempting to build local Ruby documentation as suggested here:
https://github.com/toy/doc
However when I use the default Rakefile I get the following:
[Documentation]$ rake build
configuring and updating: 100.0%
rake aborted!
undefined method `available?' for Gem:Module
/Users/snowcrash/.rvm/gems/ruby-2.0.0-p195/gems/sdoc-0.2.20/lib/sdoc/json_backend.rb:9:in
`<top (required)>'
Any suggestions?
Perl. Just a bunch of lists?
Perl. Just a bunch of lists?
A colleague of mine mentioned that a simple way to grasp Perl is to, in
general, think in terms of lists. Basically, take the approach that almost
everything in perl is a list. Is this really a good way to look at Perl?
If so, why?
A colleague of mine mentioned that a simple way to grasp Perl is to, in
general, think in terms of lists. Basically, take the approach that almost
everything in perl is a list. Is this really a good way to look at Perl?
If so, why?
[NSURL initFileURLWithPath:]: nil string parameter'
[NSURL initFileURLWithPath:]: nil string parameter'
I want to pre populate coredata by following "this" tutorial but I had
this error "[NSURL initFileURLWithPath:]: nil string parameter" but I am
struggled to find where's the error from. I believe the error only occur
when I try to implement the core data.
I had Words.xcdatamodeld (With an entity"Words") and Words.h/m
#import "Words.h"
@implementation Words
@dynamic eng;
@dynamic kor;
@dynamic img;
@dynamic definition;
@dynamic mnemonic;
@dynamic exampleKor;
@dynamic exampleEng;
@dynamic audio;
@dynamic pronun;
@end
AppDelegate:
- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{
NSManagedObjectContext *context = [self managedObjectContext];
Words *word = [NSEntityDescription
insertNewObjectForEntityForName:@"Words"
inManagedObjectContext:context];
word.eng = @"ExampleWord";
word.kor = @"ExampleWord";
word.definition = @"ExampleWord";
word.mnemonic = @"ExampleWord";
word.img = @"ExampleWord";
word.pronun = @"ExampleWord";
word.exampleKor = @"ExampleWord";
word.exampleEng = @"ExampleWord";
word.audio = @"ExampleWord";
NSError *error;
if (![context save:&error]) {
NSLog(@"Whoops, couldn't save: %@", [error localizedDescription]);
}
// Test listing all FailedBankInfos from the store
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Words"
inManagedObjectContext:context];
[fetchRequest setEntity:entity];
NSArray *fetchedObjects = [context executeFetchRequest:fetchRequest
error:&error];
for (Words *info in fetchedObjects) {
NSLog(@"Kor: %@", info.kor);
NSLog(@"Eng: %@", info.eng);
}
// Override point for customization after application launch.
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen]
bounds]];
self.viewController = [[ViewController alloc] init];
UINavigationController *navController = [[UINavigationController alloc]
initWithRootViewController: self.viewController];
self.viewController.title = @"Categories";
self.window.rootViewController = navController;
[self.window makeKeyAndVisible];
}
ViewConroller
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription
entityForName:@"Words"
inManagedObjectContext:managedObjectContext];
[fetchRequest setEntity:entity];
NSError *error;
self.wordsArray = [managedObjectContext executeFetchRequest:fetchRequest
error:&error];
self.title = @"Words 1";
I want to pre populate coredata by following "this" tutorial but I had
this error "[NSURL initFileURLWithPath:]: nil string parameter" but I am
struggled to find where's the error from. I believe the error only occur
when I try to implement the core data.
I had Words.xcdatamodeld (With an entity"Words") and Words.h/m
#import "Words.h"
@implementation Words
@dynamic eng;
@dynamic kor;
@dynamic img;
@dynamic definition;
@dynamic mnemonic;
@dynamic exampleKor;
@dynamic exampleEng;
@dynamic audio;
@dynamic pronun;
@end
AppDelegate:
- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{
NSManagedObjectContext *context = [self managedObjectContext];
Words *word = [NSEntityDescription
insertNewObjectForEntityForName:@"Words"
inManagedObjectContext:context];
word.eng = @"ExampleWord";
word.kor = @"ExampleWord";
word.definition = @"ExampleWord";
word.mnemonic = @"ExampleWord";
word.img = @"ExampleWord";
word.pronun = @"ExampleWord";
word.exampleKor = @"ExampleWord";
word.exampleEng = @"ExampleWord";
word.audio = @"ExampleWord";
NSError *error;
if (![context save:&error]) {
NSLog(@"Whoops, couldn't save: %@", [error localizedDescription]);
}
// Test listing all FailedBankInfos from the store
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Words"
inManagedObjectContext:context];
[fetchRequest setEntity:entity];
NSArray *fetchedObjects = [context executeFetchRequest:fetchRequest
error:&error];
for (Words *info in fetchedObjects) {
NSLog(@"Kor: %@", info.kor);
NSLog(@"Eng: %@", info.eng);
}
// Override point for customization after application launch.
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen]
bounds]];
self.viewController = [[ViewController alloc] init];
UINavigationController *navController = [[UINavigationController alloc]
initWithRootViewController: self.viewController];
self.viewController.title = @"Categories";
self.window.rootViewController = navController;
[self.window makeKeyAndVisible];
}
ViewConroller
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription
entityForName:@"Words"
inManagedObjectContext:managedObjectContext];
[fetchRequest setEntity:entity];
NSError *error;
self.wordsArray = [managedObjectContext executeFetchRequest:fetchRequest
error:&error];
self.title = @"Words 1";
Lose row data while using SqlDataReader.ReadAsync() with sql query with output inserted
Lose row data while using SqlDataReader.ReadAsync() with sql query with
output inserted
I have such piece of code and after execution I get N rows in my database
table and N-1 rows data are returned from method. Can't understand what
I'm doing wrong and find any examples of similar problem. Does I lose data
because of sql query, or I did a mistake in a code? Please, help.
private String sqlCommandSample = "insert into [dbo].[SomeTable] " +
"(Title, Descript) " +
"output inserted.Title " +
"select Item.value('title[1]', 'nvarchar(max)'),
Item.value('description[1]', 'nvarchar(max)') " +
"from @Xml.nodes('nodes/node') as Result(Item) " +
"where not exists (select * from
[dbo].[SomeTable] " +
"where ([Title] = Item.value('Title[1]',
'nvarchar(200)')))";
public async Task<List<String>> FillTableAsync(String
sqlCommandString, GetArticleLink getArticleLink)
{
using (var sqlConnection = new SqlConnection(ConnectionString))
{
await sqlConnection.OpenAsync();
using (var sqlCommand = new SqlCommand(sqlCommandString,
sqlConnection))
{
using (var sqlReader = await sqlCommand.ExecuteReaderAsync())
{
var listOfLinks = new List<String>();
if (await sqlReader.ReadAsync())
{
while (await sqlReader.ReadAsync())
{
listOfLinks.Add(await GetLink(sqlReader));
}
}
return listOfLinks;
}
}
}
}
private async Task<String> GetLink(DbDataReader reader)
{
return await reader.GetFieldValueAsync<String>(0);
}
output inserted
I have such piece of code and after execution I get N rows in my database
table and N-1 rows data are returned from method. Can't understand what
I'm doing wrong and find any examples of similar problem. Does I lose data
because of sql query, or I did a mistake in a code? Please, help.
private String sqlCommandSample = "insert into [dbo].[SomeTable] " +
"(Title, Descript) " +
"output inserted.Title " +
"select Item.value('title[1]', 'nvarchar(max)'),
Item.value('description[1]', 'nvarchar(max)') " +
"from @Xml.nodes('nodes/node') as Result(Item) " +
"where not exists (select * from
[dbo].[SomeTable] " +
"where ([Title] = Item.value('Title[1]',
'nvarchar(200)')))";
public async Task<List<String>> FillTableAsync(String
sqlCommandString, GetArticleLink getArticleLink)
{
using (var sqlConnection = new SqlConnection(ConnectionString))
{
await sqlConnection.OpenAsync();
using (var sqlCommand = new SqlCommand(sqlCommandString,
sqlConnection))
{
using (var sqlReader = await sqlCommand.ExecuteReaderAsync())
{
var listOfLinks = new List<String>();
if (await sqlReader.ReadAsync())
{
while (await sqlReader.ReadAsync())
{
listOfLinks.Add(await GetLink(sqlReader));
}
}
return listOfLinks;
}
}
}
}
private async Task<String> GetLink(DbDataReader reader)
{
return await reader.GetFieldValueAsync<String>(0);
}
Shifting a 32 bit integer by 32 bits
Shifting a 32 bit integer by 32 bits
I'm slinging some C code and I need to bitshift a 32 bit int left 32 bits.
When I run this code with the parameter n = 0, the shifting doesn't
happen.
int x = 0xFFFFFFFF;
int y = x << (32 - n);
Why doesn't this work?
I'm slinging some C code and I need to bitshift a 32 bit int left 32 bits.
When I run this code with the parameter n = 0, the shifting doesn't
happen.
int x = 0xFFFFFFFF;
int y = x << (32 - n);
Why doesn't this work?
Friday, 13 September 2013
How to use Plugins for PopUp
How to use Plugins for PopUp
I try to search plugin jquery for create PopUp of comment. But i don't
know how use it and what is plugin that support for Popup. Any one can
help me to show simple code and explain
I try to search plugin jquery for create PopUp of comment. But i don't
know how use it and what is plugin that support for Popup. Any one can
help me to show simple code and explain
Is posible to enable primefaces button after validation?
Is posible to enable primefaces button after validation?
Is posible to enable primefaces button depending on the correct validation
of inputText and without using jquery or writing the validation on a java
class? I just looking for enable it in the xhtml on client side
Is posible to enable primefaces button depending on the correct validation
of inputText and without using jquery or writing the validation on a java
class? I just looking for enable it in the xhtml on client side
New to SML / NJ. Making a custom insert function
New to SML / NJ. Making a custom insert function
Define a function that, given a list L, an object x, and a positive
integer k, returns a copy of L with x inserted at the k-th position. For
example, if L is [a1, a2, a3] and k=2, then [a1, x, a2, a3] is returned.
If the length of L is less than k, insert at the end. For this kind of
problems, you are supposed not to use, for example, the length function.
Think about how the function computes the length. No 'if-then-else' or any
auxiliary function.
I've figured out how to make a function to find the length of a list
fun mylength ([]) = 0
| mylength (x::xs) = 1+ mylength(xs)
But, as the questions states, I can't use this as an auxiliary function in
the insert function. Also, i'm lost as to how to go about the insert
function? Any help or guidance would be appreciated!
Define a function that, given a list L, an object x, and a positive
integer k, returns a copy of L with x inserted at the k-th position. For
example, if L is [a1, a2, a3] and k=2, then [a1, x, a2, a3] is returned.
If the length of L is less than k, insert at the end. For this kind of
problems, you are supposed not to use, for example, the length function.
Think about how the function computes the length. No 'if-then-else' or any
auxiliary function.
I've figured out how to make a function to find the length of a list
fun mylength ([]) = 0
| mylength (x::xs) = 1+ mylength(xs)
But, as the questions states, I can't use this as an auxiliary function in
the insert function. Also, i'm lost as to how to go about the insert
function? Any help or guidance would be appreciated!
JEDIS: ClassCastException when returning Table from LUA
JEDIS: ClassCastException when returning Table from LUA
Hello I am calling a REDIS LUA script with Jedis
Why does this throw a ClassCastException?
Object zot = jedis.eval("return {1,2}");
java.lang.ClassCastException: java.lang.Long cannot be cast to [B
When I try it in redis-cli, it works
redis 127.0.0.1:6379> eval "return {1,2}" 0
1) (integer) 1
2) (integer) 2
Is this a bug, or do I need to know something? Thank you very much Peter
Hello I am calling a REDIS LUA script with Jedis
Why does this throw a ClassCastException?
Object zot = jedis.eval("return {1,2}");
java.lang.ClassCastException: java.lang.Long cannot be cast to [B
When I try it in redis-cli, it works
redis 127.0.0.1:6379> eval "return {1,2}" 0
1) (integer) 1
2) (integer) 2
Is this a bug, or do I need to know something? Thank you very much Peter
Shared Powerpoint file with an automatic VBA saving
Shared Powerpoint file with an automatic VBA saving
I'm trying to make a Powerpoint quiz for a company that will share it on
its network drive where everybody should have access to.
The idea is every employee could participate in quiz and after answering
all the questions, the score is saved to the last slide and all the scores
are listed for the current employee.
I already know how to make the quiz part of that but I have not found a
single tutorial how to do the saving thing –– add score to the last
slide's list and save the file.
Is this doable? Can the file in the network drive be updated, saved with
VBA, so that whoever opens the file next, will see all the scores on the
last slide?
I was first thinking of auto emailing the result but then figured it out
that it's not possible.
Does it matter if there's Windows and Mac users (don't know if there are
any mac users)?
thanks in advance
I'm trying to make a Powerpoint quiz for a company that will share it on
its network drive where everybody should have access to.
The idea is every employee could participate in quiz and after answering
all the questions, the score is saved to the last slide and all the scores
are listed for the current employee.
I already know how to make the quiz part of that but I have not found a
single tutorial how to do the saving thing –– add score to the last
slide's list and save the file.
Is this doable? Can the file in the network drive be updated, saved with
VBA, so that whoever opens the file next, will see all the scores on the
last slide?
I was first thinking of auto emailing the result but then figured it out
that it's not possible.
Does it matter if there's Windows and Mac users (don't know if there are
any mac users)?
thanks in advance
Thursday, 12 September 2013
Kill chrome process
Kill chrome process
I created a new project in Android. We use the following code:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.web);
webView = (WebView) findViewById(R.id.webView);
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl("http://t.co/YoHe3NKrJH");
He is opening Chrome.
I need to close it automatically after 10s.
I created a new project in Android. We use the following code:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.web);
webView = (WebView) findViewById(R.id.webView);
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl("http://t.co/YoHe3NKrJH");
He is opening Chrome.
I need to close it automatically after 10s.
Simplify sql query logic
Simplify sql query logic
I have the following query that is used in a stored procedure. I am trying
to simplify the logic in the CASE statement. Specifically I would like to
nest the Product inside the UserGroup
Thanks, Brad
SELECT
DCMNumber,
SUM(CONVERT(INT, CurrentlyAssigned)) AS PriorAssigned
FROM
dbo.cauAssignedClaim WITH(NOLOCK)
WHERE
RecordType = 'A' AND ([Status] <> 'DE' OR [Status] IS NULL)
AND DATEADD(dd, 0, DATEDIFF(dd, 0, EntryDate)) BETWEEN
CASE
WHEN Product IN('LTD', 'LTDCP') AND @UserGroup = '' OR @UserGroup =
'NONE'
THEN DATEADD(dd, 0, DATEDIFF(dd, 0, GETDATE()-30))
WHEN Product IN('STD', 'STDCP', 'SALCN', 'STAT', 'OFFOV') AND
@UserGroup = '' OR @UserGroup = 'NONE'
THEN DATEADD(dd, 0, DATEDIFF(dd, 0, GETDATE()-14))
WHEN Product IN('LTD', 'LTDCP') AND @UserGroup IN('SSAT', 'TCMS')
THEN DATEADD(dd, 0, DATEDIFF(dd, 0, GETDATE()-7))
WHEN Product IN('STD', 'STDCP', 'SALCN', 'STAT', 'OFFOV') AND
@UserGroup IN('Appeals', 'DMS', 'Life', 'WOP', 'IWOP')
THEN DATEADD(dd, 0, DATEDIFF(dd, 0, GETDATE()-7))
END
AND DATEADD(dd, 0, DATEDIFF(dd, 0, GETDATE()-1))
GROUP BY [Status], DCMNumber
I have the following query that is used in a stored procedure. I am trying
to simplify the logic in the CASE statement. Specifically I would like to
nest the Product inside the UserGroup
Thanks, Brad
SELECT
DCMNumber,
SUM(CONVERT(INT, CurrentlyAssigned)) AS PriorAssigned
FROM
dbo.cauAssignedClaim WITH(NOLOCK)
WHERE
RecordType = 'A' AND ([Status] <> 'DE' OR [Status] IS NULL)
AND DATEADD(dd, 0, DATEDIFF(dd, 0, EntryDate)) BETWEEN
CASE
WHEN Product IN('LTD', 'LTDCP') AND @UserGroup = '' OR @UserGroup =
'NONE'
THEN DATEADD(dd, 0, DATEDIFF(dd, 0, GETDATE()-30))
WHEN Product IN('STD', 'STDCP', 'SALCN', 'STAT', 'OFFOV') AND
@UserGroup = '' OR @UserGroup = 'NONE'
THEN DATEADD(dd, 0, DATEDIFF(dd, 0, GETDATE()-14))
WHEN Product IN('LTD', 'LTDCP') AND @UserGroup IN('SSAT', 'TCMS')
THEN DATEADD(dd, 0, DATEDIFF(dd, 0, GETDATE()-7))
WHEN Product IN('STD', 'STDCP', 'SALCN', 'STAT', 'OFFOV') AND
@UserGroup IN('Appeals', 'DMS', 'Life', 'WOP', 'IWOP')
THEN DATEADD(dd, 0, DATEDIFF(dd, 0, GETDATE()-7))
END
AND DATEADD(dd, 0, DATEDIFF(dd, 0, GETDATE()-1))
GROUP BY [Status], DCMNumber
How to filter a table by a relation to another table in MYSQL, with a concatenate column?
How to filter a table by a relation to another table in MYSQL, with a
concatenate column?
Using MYSQL, I have 2 table : Contacts and Categories
+------+---------+
| id | title |
+------+---------+
| 10 | Cat |
| 11 | John |
| 12 | Sam |
+------+---------+
and the categories
+------+------------+----------+
| id | id_contact | category |
+------+------------+----------+
| 1 | 10 | C# |
| 2 | 10 | WPF |
| 3 | 11 | PHP |
| 4 | 11 | JQuery |
| 5 | 12 | MySQL |
| 6 | 12 | MSSQL |
| 7 | 12 | PHP |
+------+------------+----------+
I want to select for all the contacts that have a category of PHP in this
case the selection result would be :
+------+---------+---------------------+
| id | title | categories |
+------+---------+---------------------+
| 11 | John | PHP , JQuery |
| 12 | Sam | MySQL , MSSQL , PHP |
+------+---------+---------------------+
with a column that contains all the categories concatenated and separated
by "," . please advice.
concatenate column?
Using MYSQL, I have 2 table : Contacts and Categories
+------+---------+
| id | title |
+------+---------+
| 10 | Cat |
| 11 | John |
| 12 | Sam |
+------+---------+
and the categories
+------+------------+----------+
| id | id_contact | category |
+------+------------+----------+
| 1 | 10 | C# |
| 2 | 10 | WPF |
| 3 | 11 | PHP |
| 4 | 11 | JQuery |
| 5 | 12 | MySQL |
| 6 | 12 | MSSQL |
| 7 | 12 | PHP |
+------+------------+----------+
I want to select for all the contacts that have a category of PHP in this
case the selection result would be :
+------+---------+---------------------+
| id | title | categories |
+------+---------+---------------------+
| 11 | John | PHP , JQuery |
| 12 | Sam | MySQL , MSSQL , PHP |
+------+---------+---------------------+
with a column that contains all the categories concatenated and separated
by "," . please advice.
EXT JS- TextField condition for Not a pattern
EXT JS- TextField condition for Not a pattern
i am new to EXT JS . Consider the declaration of a Textfield below
{
xtype: 'textfield'
,id:'lcfirstname'
,name: 'lcfirstname'
,maxLength: 100
,regex:/^\s*[a-zA-Z0-9-_]*$/
}
i can able to write pattern based on the pattern what and all can be typed
in text field. but i need to write pattern in the text field such that the
text field should not take those pattern
(i.e. not of regex like that anything is there in EXT JS?). the pattern
can include all the special symbols.
i am new to EXT JS . Consider the declaration of a Textfield below
{
xtype: 'textfield'
,id:'lcfirstname'
,name: 'lcfirstname'
,maxLength: 100
,regex:/^\s*[a-zA-Z0-9-_]*$/
}
i can able to write pattern based on the pattern what and all can be typed
in text field. but i need to write pattern in the text field such that the
text field should not take those pattern
(i.e. not of regex like that anything is there in EXT JS?). the pattern
can include all the special symbols.
Wednesday, 11 September 2013
Bring the child popup(light box) above the parent popup(fancy box)
Bring the child popup(light box) above the parent popup(fancy box)
I have a div with a name/id of div1 which consists of elements and buttons
that are got dynamically, When i press on one of the buttons in the div1 a
popup opens up (lightbox).
Now what i want is, i want to use a separate button to show the elements
inside the div1 in a new popup for which i've used fancy box.
And in the fancybox popup the elements/buttons present from the div1 are
shown, when i press one of the buttons in the fancybox popup, the new
popup(lightbox) appears behind the parent popup (fancybox).
What should i do to make the child popup (lightbox) appear over the parent
popup (fancy box) and not behind the parent popup .
I have a div with a name/id of div1 which consists of elements and buttons
that are got dynamically, When i press on one of the buttons in the div1 a
popup opens up (lightbox).
Now what i want is, i want to use a separate button to show the elements
inside the div1 in a new popup for which i've used fancy box.
And in the fancybox popup the elements/buttons present from the div1 are
shown, when i press one of the buttons in the fancybox popup, the new
popup(lightbox) appears behind the parent popup (fancybox).
What should i do to make the child popup (lightbox) appear over the parent
popup (fancy box) and not behind the parent popup .
ASP.Net MVC image not displaying
ASP.Net MVC image not displaying
I have a view with the following -
<img src= "@Url.Content(new Uri(image.Path).AbsoluteUri)" alt="@(new
Uri(image.Path).AbsoluteUri)" />
image.Path is a string
It renders the below html
<img alt="file:///C:/Users/Tom/MyAppApp_Data/uploads/myImage.jpg"
src="file:///C:/Users/Tom/MyAppApp_Data/uploads/myImage.jpg">
But the image is not displayed in the browser.
If I open FireBug and hover over the image element, the image will show in
the FireBug window.
If I take the above html and place in a test.html file and open the file
in a browser, the image is displayed.
However, if I hard code the above html into my view, it does not work!
I have a view with the following -
<img src= "@Url.Content(new Uri(image.Path).AbsoluteUri)" alt="@(new
Uri(image.Path).AbsoluteUri)" />
image.Path is a string
It renders the below html
<img alt="file:///C:/Users/Tom/MyAppApp_Data/uploads/myImage.jpg"
src="file:///C:/Users/Tom/MyAppApp_Data/uploads/myImage.jpg">
But the image is not displayed in the browser.
If I open FireBug and hover over the image element, the image will show in
the FireBug window.
If I take the above html and place in a test.html file and open the file
in a browser, the image is displayed.
However, if I hard code the above html into my view, it does not work!
Soundcloud API /resolve method 404 error
Soundcloud API /resolve method 404 error
Simple dimple one here- trying to use Soundcloud's resolve method to
retrieve a JSON feed of track data for a private set.
http://api.soundcloud.com/resolve.json?url=http://soundcloud.com/myUser/private-set
resolve returns a 401 unauthorized error, as it should
http://api.soundcloud.com/resolve.json?url=http://soundcloud.com/myUser/private-set&client_id=myClientID
resolve returns a '404' not found error. it should be 301 redirecting to
the authorized json feed for the track, such as
http://api.soundcloud.com/tracks/49931.json
I've created an App
I'm using the App's Client ID
I've enabled App access in the Set's edit menu
I'm formatting it as per the API docs
Am I missing something here?
Simple dimple one here- trying to use Soundcloud's resolve method to
retrieve a JSON feed of track data for a private set.
http://api.soundcloud.com/resolve.json?url=http://soundcloud.com/myUser/private-set
resolve returns a 401 unauthorized error, as it should
http://api.soundcloud.com/resolve.json?url=http://soundcloud.com/myUser/private-set&client_id=myClientID
resolve returns a '404' not found error. it should be 301 redirecting to
the authorized json feed for the track, such as
http://api.soundcloud.com/tracks/49931.json
I've created an App
I'm using the App's Client ID
I've enabled App access in the Set's edit menu
I'm formatting it as per the API docs
Am I missing something here?
new to android - not able to access global variable in protected static method
new to android - not able to access global variable in protected static
method
here is my code:
protected static Bitmap scaleImage() {
Bitmap nad = BitmapFactory.decodeFile(path);
return nad;
}
"path" is a global variable, and it gives me an error stating: cannot make
a static reference to a non-static field path... may be this is happening
because path is a string, and not a static.. but how else can I access
other variables in here? I tried looking through the documentation but
could not find anything.
method
here is my code:
protected static Bitmap scaleImage() {
Bitmap nad = BitmapFactory.decodeFile(path);
return nad;
}
"path" is a global variable, and it gives me an error stating: cannot make
a static reference to a non-static field path... may be this is happening
because path is a string, and not a static.. but how else can I access
other variables in here? I tried looking through the documentation but
could not find anything.
get specific keys from database
get specific keys from database
I'm trying to get some specific keys and values from the database. My
database entries look like so:
id | name | description | value
------------------------------------------
1 | lang | default language | en
2 | date | date format | YYYY-MM-DD
I want to echo only my name and value fields. I've tried using a nested
foreach loop, like so:
foreach($details as $key => $value)
{
foreach($value as $index => $row)
{
echo $index . " / " . $row . "<br />";
}
echo "<br />";
}
But that only echos:
id / 1
name / lang
description / default language
value / en
id / 2
name / date
description / date format
value / en
However, when I add an offset, like so: $index[1], I get this like a
instead of name, or e instead of description.
I've previously worked from while loops using mysql_fetch_array, but this
would give me a repeated element (say a <tr>) whereas I simply need to
extract the value of the field because this will be used to build a form
for the user to manage.
Would anyone have a suggestion or different approach for me to do
something of the sort ?
I'm trying to get some specific keys and values from the database. My
database entries look like so:
id | name | description | value
------------------------------------------
1 | lang | default language | en
2 | date | date format | YYYY-MM-DD
I want to echo only my name and value fields. I've tried using a nested
foreach loop, like so:
foreach($details as $key => $value)
{
foreach($value as $index => $row)
{
echo $index . " / " . $row . "<br />";
}
echo "<br />";
}
But that only echos:
id / 1
name / lang
description / default language
value / en
id / 2
name / date
description / date format
value / en
However, when I add an offset, like so: $index[1], I get this like a
instead of name, or e instead of description.
I've previously worked from while loops using mysql_fetch_array, but this
would give me a repeated element (say a <tr>) whereas I simply need to
extract the value of the field because this will be used to build a form
for the user to manage.
Would anyone have a suggestion or different approach for me to do
something of the sort ?
Using bootstrap-select
Using bootstrap-select
I am supposed to use bootstrap-select to give a user a choice of titles
e.g. Mr, Mrs or Ms.
Here's the select HTML:
<select name="adultSelect" class="selectpicker adultTitle_">
<option value="1">Mr</option>
<option value="2">Mrs</option>
<option value="3">Ms</option>
</select>
I want to assign the value to a variable in the backing bean when the user
clicks the form's submit button. For example, here's how I do the user's
surname:
<div>
<h:inputText value ="#{bean.surname}" label="Surname"></h:inputText>
</div>
From what I can see, the <select> tag doesn't have a value attribute
available to it.
The JS I have for the selectpicker looks like this:
$(".selectpicker").selectpicker({
style: "btn",
size: 3
});
I am supposed to use bootstrap-select to give a user a choice of titles
e.g. Mr, Mrs or Ms.
Here's the select HTML:
<select name="adultSelect" class="selectpicker adultTitle_">
<option value="1">Mr</option>
<option value="2">Mrs</option>
<option value="3">Ms</option>
</select>
I want to assign the value to a variable in the backing bean when the user
clicks the form's submit button. For example, here's how I do the user's
surname:
<div>
<h:inputText value ="#{bean.surname}" label="Surname"></h:inputText>
</div>
From what I can see, the <select> tag doesn't have a value attribute
available to it.
The JS I have for the selectpicker looks like this:
$(".selectpicker").selectpicker({
style: "btn",
size: 3
});
Tuesday, 10 September 2013
Xcode 4.5: SupportedInterfaceOrientation is not working
Xcode 4.5: SupportedInterfaceOrientation is not working
I am using iOS 5 and XCode 4.2. After coding I gave support for landscape
and portrait orientation. It is working correctly. But the orientation is
not supported when I used the code in XCode 4.5 iOS 6.
Do anyone know the reason?
I am using iOS 5 and XCode 4.2. After coding I gave support for landscape
and portrait orientation. It is working correctly. But the orientation is
not supported when I used the code in XCode 4.5 iOS 6.
Do anyone know the reason?
How to arrange data in array by month and year
How to arrange data in array by month and year
I am developing one website in php zend framework and sql server 2008.
I need to make one multidimensional array which stores the data by year
and month in this format :
Array(
[2012] => Array(
[11] => Array(
// data
)
[12] => Array(
// data
)
)
[2013] => Array(
[01] => Array(
// data
)
[02] => Array(
// data
)
[03] => Array(
// data
)
[04] => Array(
// data
)
)
)
But i am getting duplicates in my result array. Means i am getting 2012
data in 2013 also. My code is as follows :
// Database functions to get data
function select_cldata($month,$year)
{
global $db;
$select = "select ClientId,ClientName,Email,Request,'Order Placed'
as info from tbl_clrequest where MONTH(CreatedDate) = ".$month."
and YEAR(CreatedDate) = ".$year;
return $db->fetchAll($select);
}
function select_itemsdata($month,$year)
{
global $db;
$select = "select ItemId,ItemName,Desc,price,'Items delivered' as info1
from tbl_items where MONTH(ItemDate) = ".$month." and YEAR(ItemDate) =
".$year;
return $db->fetchAll($select);
}
// PHP Code
$test = new dbase();
$months = "2012-11,2012-12,2013-01,2013-02,2013-03,2013-04";
$mon_num = explode(",",$months);
$res = array();
$result = array();
foreach($mon_num as $mn)
{
$mm = explode("-",$mn);
$year = $mm[0];
$month = $mm[1];
$cl_data = $test->select_cldata($month,$year);
$dl_data = $test->select_itemsdata($month,$year);
$res[$month] =
array_merge($clients,$sr,$events,$ses,$docs,$event_change,$devents);
$result[$year] = $res;
}
echo "<pre>";
print_r($result);die;
Can anyone help me please ?
I am developing one website in php zend framework and sql server 2008.
I need to make one multidimensional array which stores the data by year
and month in this format :
Array(
[2012] => Array(
[11] => Array(
// data
)
[12] => Array(
// data
)
)
[2013] => Array(
[01] => Array(
// data
)
[02] => Array(
// data
)
[03] => Array(
// data
)
[04] => Array(
// data
)
)
)
But i am getting duplicates in my result array. Means i am getting 2012
data in 2013 also. My code is as follows :
// Database functions to get data
function select_cldata($month,$year)
{
global $db;
$select = "select ClientId,ClientName,Email,Request,'Order Placed'
as info from tbl_clrequest where MONTH(CreatedDate) = ".$month."
and YEAR(CreatedDate) = ".$year;
return $db->fetchAll($select);
}
function select_itemsdata($month,$year)
{
global $db;
$select = "select ItemId,ItemName,Desc,price,'Items delivered' as info1
from tbl_items where MONTH(ItemDate) = ".$month." and YEAR(ItemDate) =
".$year;
return $db->fetchAll($select);
}
// PHP Code
$test = new dbase();
$months = "2012-11,2012-12,2013-01,2013-02,2013-03,2013-04";
$mon_num = explode(",",$months);
$res = array();
$result = array();
foreach($mon_num as $mn)
{
$mm = explode("-",$mn);
$year = $mm[0];
$month = $mm[1];
$cl_data = $test->select_cldata($month,$year);
$dl_data = $test->select_itemsdata($month,$year);
$res[$month] =
array_merge($clients,$sr,$events,$ses,$docs,$event_change,$devents);
$result[$year] = $res;
}
echo "<pre>";
print_r($result);die;
Can anyone help me please ?
Stock exchange program in Objective-C
Stock exchange program in Objective-C
create a subclass of stock holding called ForeignStockHolding. Give
ForeginStockHolding an additional instance variable : conversationRate,
which will be float. ( the conversion rate is what you need to multiply
the local price by to get a price in canadian dollars . Assume the
purchase price and current price in local currency). override cost in
dollars and value in dollars to do the right thing. In Main(), add a few
instances of ForeignStockHodling to your array.
create a subclass of stock holding called ForeignStockHolding. Give
ForeginStockHolding an additional instance variable : conversationRate,
which will be float. ( the conversion rate is what you need to multiply
the local price by to get a price in canadian dollars . Assume the
purchase price and current price in local currency). override cost in
dollars and value in dollars to do the right thing. In Main(), add a few
instances of ForeignStockHodling to your array.
App engine dev server cross-group transactions with appengine-maven-plugin
App engine dev server cross-group transactions with appengine-maven-plugin
I am receiving an exception when I run JUnit tests on my App Engine project
java.lang.IllegalArgumentException: cross-group transaction need to be
explicitly specified
I am using Objectify (4.0b3), app engine and appengine-maven-plugin (1.8.4).
Objectify enables cross-group transactions if they are possible. However,
I read that they are disabled by default on the dev server. I would like
to enable them via my pom.xml
I have attempted to construct my pom.xml according to the documentation
<plugin>
<groupId>com.google.appengine</groupId>
<artifactId>appengine-maven-plugin</artifactId>
<version>${appengine.target.version}</version>
<configuration>
<useJava7>true</useJava7>
<address>127.0.0.1</address>
<port>8080</port>
<compileEncoding>utf-8</compileEncoding>
<jvmFlags>
<jvmFlag>-Ddatastore.default_high_rep_job_policy_unapplied_job_pct=20</jvmFlag>
</jvmFlags>
</configuration>
</plugin>
My IDE is Eclipse Kepler x64 (the Maven plugin came pre-installed but I
needed to point it to an external installation of Maven 3.1.0) and the
Google Plugin 4.3 (only the required packages). My java is
jdk-7u40-windows-x64.
The only version of the App Engine SDK available to this project is
downloaded through Maven (not installed with the eclipse plugin).
When I go to my project properties (after doing a Maven->Update Project) I
see:
Note that the image says "The selected SDK does not support HRD" and the
Use Specific SDK says "unknown version" at the end. I saw the same thing
with 1.8.3 on my old Eclipse install.
I don't want to install another version of the SDK because Maven will just
overwrite my project settings.
I'm a Java/Maven/App Engine newbie, so any help would be much appreciated.
Thanks.
Update 1:
As an interim solution, I decided to use the UI configuration with an
externally downloaded 1.8.4 SDK (just to test a build). However, the
moment you change the SDK in the UI, it creates a conflict with Maven
The App Engine SDK
'C:\Users\Steven.m2\repository\com\google\appengine\appengine-api-1.0-sdk\1.8.4\appengine-api-1.0-sdk-1.8.4.jar'
on the project's build path is not valid (SDK location
'C:\Users\Steven.m2\repository\com\google\appengine\appengine-api-1.0-sdk\1.8.4\appengine-api-1.0-sdk-1.8.4.jar'
is not a directory) projectname Unknown Google App Engine Problem
Even if the SDK is removed via the UI, its JARs removed from the
classpath, and the project cleaned and updated with Maven, the error will
persist.
I was curious and set the UI to point to the location defaulted in the
dropdown menu (I assume Maven had some hand in populating this) and I see:
And, as another experiment, I attempted to manually add the same directory:
None of this is really surprising though, since Maven is downloading Jars
and not the full SDK.
I am receiving an exception when I run JUnit tests on my App Engine project
java.lang.IllegalArgumentException: cross-group transaction need to be
explicitly specified
I am using Objectify (4.0b3), app engine and appengine-maven-plugin (1.8.4).
Objectify enables cross-group transactions if they are possible. However,
I read that they are disabled by default on the dev server. I would like
to enable them via my pom.xml
I have attempted to construct my pom.xml according to the documentation
<plugin>
<groupId>com.google.appengine</groupId>
<artifactId>appengine-maven-plugin</artifactId>
<version>${appengine.target.version}</version>
<configuration>
<useJava7>true</useJava7>
<address>127.0.0.1</address>
<port>8080</port>
<compileEncoding>utf-8</compileEncoding>
<jvmFlags>
<jvmFlag>-Ddatastore.default_high_rep_job_policy_unapplied_job_pct=20</jvmFlag>
</jvmFlags>
</configuration>
</plugin>
My IDE is Eclipse Kepler x64 (the Maven plugin came pre-installed but I
needed to point it to an external installation of Maven 3.1.0) and the
Google Plugin 4.3 (only the required packages). My java is
jdk-7u40-windows-x64.
The only version of the App Engine SDK available to this project is
downloaded through Maven (not installed with the eclipse plugin).
When I go to my project properties (after doing a Maven->Update Project) I
see:
Note that the image says "The selected SDK does not support HRD" and the
Use Specific SDK says "unknown version" at the end. I saw the same thing
with 1.8.3 on my old Eclipse install.
I don't want to install another version of the SDK because Maven will just
overwrite my project settings.
I'm a Java/Maven/App Engine newbie, so any help would be much appreciated.
Thanks.
Update 1:
As an interim solution, I decided to use the UI configuration with an
externally downloaded 1.8.4 SDK (just to test a build). However, the
moment you change the SDK in the UI, it creates a conflict with Maven
The App Engine SDK
'C:\Users\Steven.m2\repository\com\google\appengine\appengine-api-1.0-sdk\1.8.4\appengine-api-1.0-sdk-1.8.4.jar'
on the project's build path is not valid (SDK location
'C:\Users\Steven.m2\repository\com\google\appengine\appengine-api-1.0-sdk\1.8.4\appengine-api-1.0-sdk-1.8.4.jar'
is not a directory) projectname Unknown Google App Engine Problem
Even if the SDK is removed via the UI, its JARs removed from the
classpath, and the project cleaned and updated with Maven, the error will
persist.
I was curious and set the UI to point to the location defaulted in the
dropdown menu (I assume Maven had some hand in populating this) and I see:
And, as another experiment, I attempted to manually add the same directory:
None of this is really surprising though, since Maven is downloading Jars
and not the full SDK.
How can i upload multiple images to an html5 site?
How can i upload multiple images to an html5 site?
Ok so here is my situation. I have an html5 website that currently has no
images aside from the menu bar and flash. I need a way to upload dozens of
photos at a time without having to hand code them each.
Example
<img src="0532.jpg" alt="picture" width="1900" height="800">
^^^^^^ this is what I want to avoid.
Or at least manually inputting that for hundreds of images for a
portfolio. Is there some sort of Script, uploader that would allow me to
upload multiple images at a time?
Ok so here is my situation. I have an html5 website that currently has no
images aside from the menu bar and flash. I need a way to upload dozens of
photos at a time without having to hand code them each.
Example
<img src="0532.jpg" alt="picture" width="1900" height="800">
^^^^^^ this is what I want to avoid.
Or at least manually inputting that for hundreds of images for a
portfolio. Is there some sort of Script, uploader that would allow me to
upload multiple images at a time?
spring custome events:how to raise an event whenever a property values changed in spring bean
spring custome events:how to raise an event whenever a property values
changed in spring bean
Can you please help me how to write the code for following scenario:
I have a class called A
class A
{
private int a;
private String name;
private status;
//setters and getters
}
If(any property values changed) then raise an event (for suppose
PropertyChangeEvent) then execute the logic in class B...
class B
{
someLogic() {}
}
changed in spring bean
Can you please help me how to write the code for following scenario:
I have a class called A
class A
{
private int a;
private String name;
private status;
//setters and getters
}
If(any property values changed) then raise an event (for suppose
PropertyChangeEvent) then execute the logic in class B...
class B
{
someLogic() {}
}
Detecting jump gesture with Kinect [Algo]
Detecting jump gesture with Kinect [Algo]
I am trying to implement jump as well as ducking gestures of a user, and I
am using Kinect for skeleton tracking and extracting the joint positions.
I previously implemented a rudimentary algorithm taking the history of
past 10 values of a joint and checking if the joint moved upward/downward
greater than a threshold to deduce a jump/duck.
However, that doesn't seem to be the correct approach since the user:
- might duck a little before jumping
- when user jumps, also comes down and a duck is deduced.
- when the user ducks, also comes up, a jump is deduced
- the user when ducking might stay longer in air than when he ducks or
sits down.
What would be an appropriate algorithm to detect both of these jump/duck
gestures in a robust manner with Kinect joints being retrieved
instantaneously?
I am trying to implement jump as well as ducking gestures of a user, and I
am using Kinect for skeleton tracking and extracting the joint positions.
I previously implemented a rudimentary algorithm taking the history of
past 10 values of a joint and checking if the joint moved upward/downward
greater than a threshold to deduce a jump/duck.
However, that doesn't seem to be the correct approach since the user:
- might duck a little before jumping
- when user jumps, also comes down and a duck is deduced.
- when the user ducks, also comes up, a jump is deduced
- the user when ducking might stay longer in air than when he ducks or
sits down.
What would be an appropriate algorithm to detect both of these jump/duck
gestures in a robust manner with Kinect joints being retrieved
instantaneously?
XMPPFramework, NSManagedObjectContext is nil
XMPPFramework, NSManagedObjectContext is nil
I'm working with XMPPFramework on iOS. When I'm trying to fetch the data
from XMPPCoreDataStorage
XMPPMessageArchivingCoreDataStorage *storage =
[XMPPMessageArchivingCoreDataStorage sharedInstance];
NSManagedObjectContext *moc = [storage mainThreadManagedObjectContext];
NSEntityDescription *entityDescription = [NSEntityDescription
entityForName:@"XMPPMessageArchiving_Message_CoreDataObject"
inManagedObjectContext:moc];
NSFetchRequest *request = [[NSFetchRequest alloc]init];
[request setEntity:entityDescription];
NSError *error;
NSArray *messages = [moc executeFetchRequest:request error:&error];
the managed object context is nill
NSManagedObjectContext *moc = [storage mainThreadManagedObjectContext];
Any ideas?
I'm working with XMPPFramework on iOS. When I'm trying to fetch the data
from XMPPCoreDataStorage
XMPPMessageArchivingCoreDataStorage *storage =
[XMPPMessageArchivingCoreDataStorage sharedInstance];
NSManagedObjectContext *moc = [storage mainThreadManagedObjectContext];
NSEntityDescription *entityDescription = [NSEntityDescription
entityForName:@"XMPPMessageArchiving_Message_CoreDataObject"
inManagedObjectContext:moc];
NSFetchRequest *request = [[NSFetchRequest alloc]init];
[request setEntity:entityDescription];
NSError *error;
NSArray *messages = [moc executeFetchRequest:request error:&error];
the managed object context is nill
NSManagedObjectContext *moc = [storage mainThreadManagedObjectContext];
Any ideas?
Monday, 9 September 2013
Usage of ?? operator (null-coalescing operator)
Usage of ?? operator (null-coalescing operator)
I use ?? operator very heavily in my code. But today I just came across a
question.
Here the code which I use for ?? operator
private List<string> _names;
public List<string> Names
{
get { return _names ?? (_names = new List<string>()); }
}
But in some locations I have seen this code as well.
private List<string> _names;
public List<string> Names
{
get { return _names ?? new List<string>(); }
}
What is real difference between these codes. In one I am assigning _names
= new List() while in other I am just doing new List().
I use ?? operator very heavily in my code. But today I just came across a
question.
Here the code which I use for ?? operator
private List<string> _names;
public List<string> Names
{
get { return _names ?? (_names = new List<string>()); }
}
But in some locations I have seen this code as well.
private List<string> _names;
public List<string> Names
{
get { return _names ?? new List<string>(); }
}
What is real difference between these codes. In one I am assigning _names
= new List() while in other I am just doing new List().
Role of Library in linux
Role of Library in linux
/lib folder contains the list of shared library. I am not sure, whether
any other folder exist, which too contains library files. As we do
microcontroller programming, there will be only hex code generated after
compilation, but it does not contain any thing like library files folder.
Question:
1. Why does linux OS require library files?
2. Where are these library files used?
3. Has it also unshared library folder too (A.K.A static libraries)?
Regards
Learner
/lib folder contains the list of shared library. I am not sure, whether
any other folder exist, which too contains library files. As we do
microcontroller programming, there will be only hex code generated after
compilation, but it does not contain any thing like library files folder.
Question:
1. Why does linux OS require library files?
2. Where are these library files used?
3. Has it also unshared library folder too (A.K.A static libraries)?
Regards
Learner
How to create a custom setter method in MATLAB 2013b?
How to create a custom setter method in MATLAB 2013b?
Take the following class
classdef MyClass
properties (Access = public)
MyProperty;
end
methods
function this = MyClass()
% initialize the class
this.MyProperty = [];
this.LoadProperty(2,2);
end
function p = GetProperty(this)
p = this.MyProperty;
end
function this = LoadProperty(this, m, n)
% loads the property
this.MyProperty = zeros(m, n);
end
end
end
And then you call:
obj = MyClass();
obj.GetProperty()
It will return [] -- which is the first value assigned to MyProperty in
the constructor method.
The LoadProperty method is acting as a setter, but it does not set
anything. How can I create a setter for MyProperty? I am coming from C#
background and there it is very straightforward. -> SOLVED (see below)
I suspect that it is an issue with references and objects, as MATLAB
always send the object itself as the first parameter to every method of a
class, instead of sending only a reference as C# do.
Thank you in advance!
EDIT:
If I change the line this.LoadProperty(2,2); to this =
this.LoadProperty(2,2);, it works.
Now, is there a way to create a void-return method in MATLAB, which only
sets a class property, as it would be normally expected in C#, C++, Java,
etc?
Take the following class
classdef MyClass
properties (Access = public)
MyProperty;
end
methods
function this = MyClass()
% initialize the class
this.MyProperty = [];
this.LoadProperty(2,2);
end
function p = GetProperty(this)
p = this.MyProperty;
end
function this = LoadProperty(this, m, n)
% loads the property
this.MyProperty = zeros(m, n);
end
end
end
And then you call:
obj = MyClass();
obj.GetProperty()
It will return [] -- which is the first value assigned to MyProperty in
the constructor method.
The LoadProperty method is acting as a setter, but it does not set
anything. How can I create a setter for MyProperty? I am coming from C#
background and there it is very straightforward. -> SOLVED (see below)
I suspect that it is an issue with references and objects, as MATLAB
always send the object itself as the first parameter to every method of a
class, instead of sending only a reference as C# do.
Thank you in advance!
EDIT:
If I change the line this.LoadProperty(2,2); to this =
this.LoadProperty(2,2);, it works.
Now, is there a way to create a void-return method in MATLAB, which only
sets a class property, as it would be normally expected in C#, C++, Java,
etc?
Massive PHP array vs MySQL Database?
Massive PHP array vs MySQL Database?
Good afternoon,
I'm debating in my head whether I should use a massive, multidimensional
array or a database in MySQL. I'm developing for a client whom's business
has many products. In this multidimensional array I would include the
product title, description, image link and categories for each individual
product. My client has perhaps 1000+ products. I've researched other
similar questions and many of them say that an array is perhaps faster,
however none of them are dealing with an array of this scale. I personally
would much rather use an array, because my knowledge with MySQL is
extremely limited, but if it means sacrificing a significant amount of
speed then I would rather use the database. Which would you consider a
more appropriate option for my case?
Good afternoon,
I'm debating in my head whether I should use a massive, multidimensional
array or a database in MySQL. I'm developing for a client whom's business
has many products. In this multidimensional array I would include the
product title, description, image link and categories for each individual
product. My client has perhaps 1000+ products. I've researched other
similar questions and many of them say that an array is perhaps faster,
however none of them are dealing with an array of this scale. I personally
would much rather use an array, because my knowledge with MySQL is
extremely limited, but if it means sacrificing a significant amount of
speed then I would rather use the database. Which would you consider a
more appropriate option for my case?
Dynamically generated anchor does not post back when id is populated
Dynamically generated anchor does not post back when id is populated
Strange. It seems that whenever I populate the id property of a
dynamically generated htmlanchor the postback method stops working.
Dim ancAction As New HtmlAnchor
AddHandler ancAction.ServerClick, AddressOf HandleEditClick
ancAction.ID = "edit:" & x.xId
divAction.Controls.Add(ancAction)
HandleEditClick will fire when I comment out the line that populates the
id property.
Any help would be appreciated.
Strange. It seems that whenever I populate the id property of a
dynamically generated htmlanchor the postback method stops working.
Dim ancAction As New HtmlAnchor
AddHandler ancAction.ServerClick, AddressOf HandleEditClick
ancAction.ID = "edit:" & x.xId
divAction.Controls.Add(ancAction)
HandleEditClick will fire when I comment out the line that populates the
id property.
Any help would be appreciated.
TreeView like Functionality Android
TreeView like Functionality Android
I'm implementing TreeView for my app. I've searched the web, found one
ListView implementation TreeView which is too messy. Is it possible to
implement n level TreeView using ExpandableListView?
Please Share your Ideas or reference me to some examples.
Thanks in Advance.
I'm implementing TreeView for my app. I've searched the web, found one
ListView implementation TreeView which is too messy. Is it possible to
implement n level TreeView using ExpandableListView?
Please Share your Ideas or reference me to some examples.
Thanks in Advance.
Removing subquery of select statement used multiple times to optimize the performance
Removing subquery of select statement used multiple times to optimize the
performance
I have a following query, this query uses a subquery in the select clause
multiple times as
SELECT DISTINCT CAST(decCostFactor as decimal(9,4))
FROM tblsubteam WITH (NOLOCK)
WHERE intstore = st.intStore
AND strsubteam = SUBSTRING(tblDetail.strMiscText,12,4)
I want to remove this subquery. I tried using group by CAST(decCostFactor
as decimal(9,4)), but now it ask to include other columns as well in the
group by cluase.
Any help is really appreciated.
The main query is
DECLARE @Region int=10006
SELECT
st.strRegion,
st.intStore,
st.strStoreName,
tblSticker.intStickerNo ,
tblSticker.strTeamNo AS strTeam ,
tblSticker.dtmFixtureStartDate AS dtmStartDate ,
tblSticker.intAreaNo ,
SUBSTRING ( tblSticker.strMiscText , 8 , 30 ) AS strSection ,
tblDetail.intLineNum ,
tblDetail.strBarcode ,
tblDetail.intBarcodeLength ,
tblDetail.intBarcodeType ,
tblDetail.strBarcodeEntrySw AS strKeyBarcode ,
tblDetail.fltPrice AS fltPrice ,
tblDetail.fltQty AS fltQty ,
tblDetail.strPTCCode4 AS strKeyPrice ,
tblDetail.strPTCCode5 AS strKeyQty ,
SUBSTRING ( tblDetail.strMiscText , 1 , 1 ) AS strNOF ,
SUBSTRING ( tblDetail.strClientText , 1 , 30 ) AS strDesc ,
SUBSTRING ( tblDetail.strMiscText , 12 , 4 ) AS strSubTeam ,
SUBSTRING ( tblDetail.strMiscText , 16 , 25 ) AS strSubTeamDesc ,
SUBSTRING ( tblDetail.strClientText , 34 , 3 ) AS strSubDept ,
SUBSTRING ( tblDetail.strClientText , 37 , 3 ) AS strClass ,
SUBSTRING ( tblDetail.strClientText , 40 , 3 ) AS strSubClass ,
SUBSTRING ( tblDetail.strMiscText , 41 , 7 ) AS strCostFactor ,
SUBSTRING ( tblDetail.strMiscText , 41 , 1 ) AS strPerishableFlag ,
tblSubTeam.blnBreakoutCost,
fltPriceLb = tblDetail.fltClientMisc1,
fltCostLb = CASE
WHEN tblDetail.decCost > 0
THEN tblDetail.decCost
ELSE tblDetail.fltClientMisc1 *
( SELECT DISTINCT CAST(decCostFactor as decimal(6,4))
FROM tblsubteam WITH (NOLOCK)
WHERE intstore = st.intStore
AND strsubteam = SUBSTRING(tblDetail.strMiscText,12,4)
)
END,
strVendor = CASE WHEN tblDetail.strVendor IS NULL THEN 'NA' ELSE
tblDetail.strVendor END,
fltWeightSouth = CASE
WHEN tblDetail.fltClientMisc1 > 0
THEN (tblDetail.fltPrice / tblDetail.fltClientMisc1)
WHEN SUBSTRING(tblDetail.strMiscText,49,1) <> 'R'
AND tblDetail.fltClientMisc1 = 0
THEN cast(SUBSTRING(tblDetail.strClientText,43,6) as float)
ELSE 0
END,
fltCostSouth = ISNULL(CASE
WHEN SUBSTRING(tblDetail.strMiscText,50,1) = 'C'
THEN (tblDetail.fltPrice )
ELSE
-- To calculate cost for Subteam 3100 in the south region -
Thomas - 2/19/2008
CASE
WHEN (SUBSTRING(tblDetail.strMiscText,12,4) = '3100')
AND (Substring(tblDetail.strMiscText,1,1) <> 'N')
THEN fltprice *
( SELECT DISTINCT CAST(decCostFactor as decimal(6,4))
FROM tblsubteam WITH (NOLOCK)
WHERE intstore = st.intStore
AND strsubteam = SUBSTRING(tblDetail.strMiscText, 12, 4)
)
ELSE CASE
WHEN tblDetail.fltClientMisc1 > 0 and tblDetail.decCost > 0
-- modified by TA to remedy Extended Retail for weighted
items
THEN (tblDetail.fltPrice / tblDetail.fltClientMisc1) *
tblDetail.decCost
ELSE CASE
WHEN (Substring(tblDetail.strMiscText,1,1) = 'N')
Or (tblDetail.strBarcode = '00000000000000')
THEN CASE
WHEN (fltprice = 0 and tblDetail.decCost > 0)
THEN CASE
WHEN SUBSTRING(tblDetail.strClientText,43,6) <> ''
THEN CASE
WHEN CAST(SUBSTRING(tblDetail.strClientText,43,6) as
float) > 0
THEN
CAST(SUBSTRING(tblDetail.strClientText,43,6)
as float)*tblDetail.decCost
ELSE fltTotalUnits*tblDetail.decCost
END
ELSE 0 * tblDetail.decCost
END
ELSE CASE
WHEN (Substring(tblDetail.strMiscText,41,7)) = ''
THEN fltprice * 0
ELSE fltprice *
Cast(Substring(tblDetail.strMiscText,41,7)
as decimal(6,4))
END
END
ELSE CASE
WHEN (fltprice > 0 and tblDetail.decCost = 0)
THEN fltprice *
( SELECT DISTINCT CAST(decCostFactor as decimal(6,4))
FROM tblsubteam WITH (NOLOCK)
WHERE intstore = st.intStore
AND strsubteam = SUBSTRING(tblDetail.strMiscText,12,4)
)
ELSE CASE
WHEN (fltprice = 0 and tblDetail.decCost > 0)
THEN CASE
WHEN CAST(SUBSTRING(tblDetail.strClientText,43,6) as
float) > 0
THEN
CAST(SUBSTRING(tblDetail.strClientText,43,6)
as float) * tblDetail.decCost
ELSE tblDetail.decCost
END
ELSE tblDetail.decCost
END
END
END
END
END
END,0),
fltItemCost = ISNULL(CASE
WHEN ((((Substring(tblDetail.strMiscText,41,7) = '00.0000')
or (tblDetail.fltClientMisc1 = 0))
or (tblDetail.decCost = 0))
and Substring(tblDetail.strMiscText,1,1) <> 'N')
THEN CASE
WHEN (fltprice > 0 and tblDetail.decCost = 0)
THEN fltprice *
( SELECT DISTINCT CAST(decCostFactor as decimal(9,4))
FROM tblsubteam WITH (NOLOCK)
WHERE intstore = st.intStore
AND strsubteam = SUBSTRING(tblDetail.strMiscText,12,4)
)
ELSE CASE
WHEN (fltprice = 0 and tblDetail.decCost > 0)
THEN tblDetail.decCost
ELSE CASE
WHEN (Substring(tblDetail.strMiscText,41,7)) = ''
THEN fltprice * 0
ELSE fltprice *
Cast(Substring(tblDetail.strMiscText,41,7) as
decimal(9,4))
END
END
END
ELSE CASE
WHEN (Substring(tblDetail.strMiscText,1,1) = 'N')
Or (tblDetail.strBarcode = '00000000000000')
THEN fltprice * Cast(Substring(tblDetail.strMiscText,41,7)
as decimal(9,4))
ELSE CASE
WHEN (fltprice > 0 and tblDetail.decCost = 0)
THEN fltprice *
( SELECT DISTINCT CAST(decCostFactor as decimal(9,4))
FROM tblsubteam WITH (NOLOCK)
WHERE intstore = st.intStore
AND strsubteam = SUBSTRING(tblDetail.strMiscText,12,4)
)
ELSE CASE
WHEN (Substring(tblDetail.strMiscText,41,7)) = ''
THEN fltprice * 0
ELSE fltprice *
Cast(Substring(tblDetail.strMiscText,41,7) as
decimal(9,4))
END
END
END
END, 0),
strWeight = SUBSTRING(tblDetail.strClientText, 43, 6)
FROM
tblSticker WITH ( NOLOCK )
INNER JOIN tblDetail WITH ( NOLOCK )
ON tblSticker.intStore = tblDetail.intStore
AND tblSticker.intStickerNo = tblDetail.intStickerNo
AND tblSticker.dtmStickerDate = tblDetail.dtmStickerDate
LEFT OUTER JOIN tblsubteam
ON tblDetail.intStore = tblSubTeam.intStore
AND SUBSTRING ( tblDetail.strMiscText , 12 , 4 ) = tblSubTeam.strSubTeam
inner join tblStore st on st.intStore=tblDetail.intStore
--fix add join to store. Kevin 2/8/07
-- AND SUBSTRING ( tblDetail.strMiscText , 12 , 4 ) = tblSubTeam.strSubTeam
--fix fix move join to store outside of compound conditional. Eddie 9/2/11
WHERE
((@Region is not null and st.intRegion=@Region) or @Region is null)
AND st.intStore < 90000
AND ( tblSticker.intStickerNo NOT BETWEEN 334717100
AND 334717299 )
AND tblSticker.strRescanSW = 'N'
AND ( tblSticker.strEmptyStatus = ' '
OR tblSticker.strEmptyStatus = '*' )
ORDER BY st.strStoreName,
tblSticker.intStickerNo ,
tblDetail.intLineNum
performance
I have a following query, this query uses a subquery in the select clause
multiple times as
SELECT DISTINCT CAST(decCostFactor as decimal(9,4))
FROM tblsubteam WITH (NOLOCK)
WHERE intstore = st.intStore
AND strsubteam = SUBSTRING(tblDetail.strMiscText,12,4)
I want to remove this subquery. I tried using group by CAST(decCostFactor
as decimal(9,4)), but now it ask to include other columns as well in the
group by cluase.
Any help is really appreciated.
The main query is
DECLARE @Region int=10006
SELECT
st.strRegion,
st.intStore,
st.strStoreName,
tblSticker.intStickerNo ,
tblSticker.strTeamNo AS strTeam ,
tblSticker.dtmFixtureStartDate AS dtmStartDate ,
tblSticker.intAreaNo ,
SUBSTRING ( tblSticker.strMiscText , 8 , 30 ) AS strSection ,
tblDetail.intLineNum ,
tblDetail.strBarcode ,
tblDetail.intBarcodeLength ,
tblDetail.intBarcodeType ,
tblDetail.strBarcodeEntrySw AS strKeyBarcode ,
tblDetail.fltPrice AS fltPrice ,
tblDetail.fltQty AS fltQty ,
tblDetail.strPTCCode4 AS strKeyPrice ,
tblDetail.strPTCCode5 AS strKeyQty ,
SUBSTRING ( tblDetail.strMiscText , 1 , 1 ) AS strNOF ,
SUBSTRING ( tblDetail.strClientText , 1 , 30 ) AS strDesc ,
SUBSTRING ( tblDetail.strMiscText , 12 , 4 ) AS strSubTeam ,
SUBSTRING ( tblDetail.strMiscText , 16 , 25 ) AS strSubTeamDesc ,
SUBSTRING ( tblDetail.strClientText , 34 , 3 ) AS strSubDept ,
SUBSTRING ( tblDetail.strClientText , 37 , 3 ) AS strClass ,
SUBSTRING ( tblDetail.strClientText , 40 , 3 ) AS strSubClass ,
SUBSTRING ( tblDetail.strMiscText , 41 , 7 ) AS strCostFactor ,
SUBSTRING ( tblDetail.strMiscText , 41 , 1 ) AS strPerishableFlag ,
tblSubTeam.blnBreakoutCost,
fltPriceLb = tblDetail.fltClientMisc1,
fltCostLb = CASE
WHEN tblDetail.decCost > 0
THEN tblDetail.decCost
ELSE tblDetail.fltClientMisc1 *
( SELECT DISTINCT CAST(decCostFactor as decimal(6,4))
FROM tblsubteam WITH (NOLOCK)
WHERE intstore = st.intStore
AND strsubteam = SUBSTRING(tblDetail.strMiscText,12,4)
)
END,
strVendor = CASE WHEN tblDetail.strVendor IS NULL THEN 'NA' ELSE
tblDetail.strVendor END,
fltWeightSouth = CASE
WHEN tblDetail.fltClientMisc1 > 0
THEN (tblDetail.fltPrice / tblDetail.fltClientMisc1)
WHEN SUBSTRING(tblDetail.strMiscText,49,1) <> 'R'
AND tblDetail.fltClientMisc1 = 0
THEN cast(SUBSTRING(tblDetail.strClientText,43,6) as float)
ELSE 0
END,
fltCostSouth = ISNULL(CASE
WHEN SUBSTRING(tblDetail.strMiscText,50,1) = 'C'
THEN (tblDetail.fltPrice )
ELSE
-- To calculate cost for Subteam 3100 in the south region -
Thomas - 2/19/2008
CASE
WHEN (SUBSTRING(tblDetail.strMiscText,12,4) = '3100')
AND (Substring(tblDetail.strMiscText,1,1) <> 'N')
THEN fltprice *
( SELECT DISTINCT CAST(decCostFactor as decimal(6,4))
FROM tblsubteam WITH (NOLOCK)
WHERE intstore = st.intStore
AND strsubteam = SUBSTRING(tblDetail.strMiscText, 12, 4)
)
ELSE CASE
WHEN tblDetail.fltClientMisc1 > 0 and tblDetail.decCost > 0
-- modified by TA to remedy Extended Retail for weighted
items
THEN (tblDetail.fltPrice / tblDetail.fltClientMisc1) *
tblDetail.decCost
ELSE CASE
WHEN (Substring(tblDetail.strMiscText,1,1) = 'N')
Or (tblDetail.strBarcode = '00000000000000')
THEN CASE
WHEN (fltprice = 0 and tblDetail.decCost > 0)
THEN CASE
WHEN SUBSTRING(tblDetail.strClientText,43,6) <> ''
THEN CASE
WHEN CAST(SUBSTRING(tblDetail.strClientText,43,6) as
float) > 0
THEN
CAST(SUBSTRING(tblDetail.strClientText,43,6)
as float)*tblDetail.decCost
ELSE fltTotalUnits*tblDetail.decCost
END
ELSE 0 * tblDetail.decCost
END
ELSE CASE
WHEN (Substring(tblDetail.strMiscText,41,7)) = ''
THEN fltprice * 0
ELSE fltprice *
Cast(Substring(tblDetail.strMiscText,41,7)
as decimal(6,4))
END
END
ELSE CASE
WHEN (fltprice > 0 and tblDetail.decCost = 0)
THEN fltprice *
( SELECT DISTINCT CAST(decCostFactor as decimal(6,4))
FROM tblsubteam WITH (NOLOCK)
WHERE intstore = st.intStore
AND strsubteam = SUBSTRING(tblDetail.strMiscText,12,4)
)
ELSE CASE
WHEN (fltprice = 0 and tblDetail.decCost > 0)
THEN CASE
WHEN CAST(SUBSTRING(tblDetail.strClientText,43,6) as
float) > 0
THEN
CAST(SUBSTRING(tblDetail.strClientText,43,6)
as float) * tblDetail.decCost
ELSE tblDetail.decCost
END
ELSE tblDetail.decCost
END
END
END
END
END
END,0),
fltItemCost = ISNULL(CASE
WHEN ((((Substring(tblDetail.strMiscText,41,7) = '00.0000')
or (tblDetail.fltClientMisc1 = 0))
or (tblDetail.decCost = 0))
and Substring(tblDetail.strMiscText,1,1) <> 'N')
THEN CASE
WHEN (fltprice > 0 and tblDetail.decCost = 0)
THEN fltprice *
( SELECT DISTINCT CAST(decCostFactor as decimal(9,4))
FROM tblsubteam WITH (NOLOCK)
WHERE intstore = st.intStore
AND strsubteam = SUBSTRING(tblDetail.strMiscText,12,4)
)
ELSE CASE
WHEN (fltprice = 0 and tblDetail.decCost > 0)
THEN tblDetail.decCost
ELSE CASE
WHEN (Substring(tblDetail.strMiscText,41,7)) = ''
THEN fltprice * 0
ELSE fltprice *
Cast(Substring(tblDetail.strMiscText,41,7) as
decimal(9,4))
END
END
END
ELSE CASE
WHEN (Substring(tblDetail.strMiscText,1,1) = 'N')
Or (tblDetail.strBarcode = '00000000000000')
THEN fltprice * Cast(Substring(tblDetail.strMiscText,41,7)
as decimal(9,4))
ELSE CASE
WHEN (fltprice > 0 and tblDetail.decCost = 0)
THEN fltprice *
( SELECT DISTINCT CAST(decCostFactor as decimal(9,4))
FROM tblsubteam WITH (NOLOCK)
WHERE intstore = st.intStore
AND strsubteam = SUBSTRING(tblDetail.strMiscText,12,4)
)
ELSE CASE
WHEN (Substring(tblDetail.strMiscText,41,7)) = ''
THEN fltprice * 0
ELSE fltprice *
Cast(Substring(tblDetail.strMiscText,41,7) as
decimal(9,4))
END
END
END
END, 0),
strWeight = SUBSTRING(tblDetail.strClientText, 43, 6)
FROM
tblSticker WITH ( NOLOCK )
INNER JOIN tblDetail WITH ( NOLOCK )
ON tblSticker.intStore = tblDetail.intStore
AND tblSticker.intStickerNo = tblDetail.intStickerNo
AND tblSticker.dtmStickerDate = tblDetail.dtmStickerDate
LEFT OUTER JOIN tblsubteam
ON tblDetail.intStore = tblSubTeam.intStore
AND SUBSTRING ( tblDetail.strMiscText , 12 , 4 ) = tblSubTeam.strSubTeam
inner join tblStore st on st.intStore=tblDetail.intStore
--fix add join to store. Kevin 2/8/07
-- AND SUBSTRING ( tblDetail.strMiscText , 12 , 4 ) = tblSubTeam.strSubTeam
--fix fix move join to store outside of compound conditional. Eddie 9/2/11
WHERE
((@Region is not null and st.intRegion=@Region) or @Region is null)
AND st.intStore < 90000
AND ( tblSticker.intStickerNo NOT BETWEEN 334717100
AND 334717299 )
AND tblSticker.strRescanSW = 'N'
AND ( tblSticker.strEmptyStatus = ' '
OR tblSticker.strEmptyStatus = '*' )
ORDER BY st.strStoreName,
tblSticker.intStickerNo ,
tblDetail.intLineNum
Subscribe to:
Posts (Atom)