text
stringlengths 8
267k
| meta
dict |
---|---|
Q: no more postback after file download in asp.net After downloading a file from a webpage, I can't do anything on that page. It is like the page is not working anymore. When I click on other button, there is no post back.
Here are my codings.
filename= "test.txt"
Response.AppendHeader("content-disposition", "attachment; filename= " + fileName);
Response.WriteFile(Server.MapPath("~/" + fileName));
Response.End();
So I try to comment Response.End() but it is still not working.
What can be the possible problems?
UPDATE
Go to this link to see how I solved it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631110",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Twitter Bootstrap / Twipsy I like the idea of the Twipsy plugin that is bundled as part of Twitter Boostrap, but it doesn't seem to work correctly.
Here's a jsfiddle: http://jsfiddle.net/burlesona/DUPyR/
As you can see, using the default settings as prescribed by the docs, the tooltip appears when you hover over the tool-tipped anchor, but it doesn't go away when you move the mouse away.
I understand that the appearance of the tooltip relies on CSS, but on the Twitter docs page the tooltips are being added and removed from the DOM by the script, whereas in this example and in my own local tests the script adds the tip but never removes it.
Here's a link to the script: http://twitter.github.com/bootstrap/1.3.0/bootstrap-twipsy.js
Any ideas / suggestions? I'm pretty confused as to why this is behaving as it is.
Alternatively if anyone has a better suggestion for a clean, lightweight jQuery tooltip plugin, please let me know.
Thanks!
A: As you have noted, your code is not working because you have not added the CSS file to your resources.
Working example: http://jsfiddle.net/DUPyR/1/
Because in that CSS file there are two classes called
.fade {
-moz-transition: opacity 0.15s linear 0s;
opacity: 0;
}
.fade.in {
opacity: 1;
}
When you move mouse in, the Tool-tip gets prepended to body and it gets class="twipsy fade in" The in gets removed on the hide function of the tool-tip making it invisible (opacity=0).
Working example with minimal CSS: http://jsfiddle.net/DUPyR/3/
Please note that its not removing the element from DOM as in the original example. More investigation of the CSS will surely shed some light there.
If you ask me my favorite tool-tip plugin, I use Jörn Zaefferer's lightweight tooltip plugin (4kb compressed). It suits my purpose well.
Link here: http://bassistance.de/jquery-plugins/jquery-plugin-tooltip/
A: I am not sure why twipsy is not working, but tipsy works: http://jsfiddle.net/X6H2Y/
Tipsy is the original jQuery plugin which was modified by Twitter for these:
(Twipsy is) Based on the excellent jQuery.tipsy plugin written by Jason Frame;
twipsy is an updated version, which doesn't rely on images, uses css3
for animations, and data-attributes for title storage!
A: Or you can use "tooltip" like this:
<div rel="tooltip" href="#" data-toggle="tooltip" data-placement="top" data-original-title="hi">I'm here</div>
<script type='text/javascript'> $(window).load(function(){ $('div[rel=tooltip]').tooltip(); });</script>
rel: http://twitter.github.com/bootstrap/javascript.html#tooltips
A: Yeah, it seems to be removed as a separate plugin now (2.3.1 at the time of writing) but there is a ToolTip plugin that comes with the main bootstrap.js file so that should do you.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631111",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: How to set the brightness of the screen on WP7 How to set the brightness of the screen on WP7 to its maximum using silverlight/xna?
<Canvas x:Name="light" Background="White" Width="480" Height="800" />
I used this code .Have any other way?
A: You can't set the brightness from a 3rd party application. There's no public API for this.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631113",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Weird MEX-file behavior Something weird is happening. I created a MEX-file with MATLAB R2011, and I compiled it with Visual Studio 2010.
I'm able to use the MEX-file in the workspace correctly.
Then, I'm using the MEX-file inside a MATLAB m-file (calls the MEX-file several times). When I try to run it, MATLAB crashes and ask me close.
Trying to analyze the error, I put breakpoints, but when I put breakpoints in the m-file, everything is correct. Actually what I do to run all the m-file is put a breakpoint at the end of the function and runs ok, I also can finish the all m-file without errors.
But when I try to run it without the breakpoints, MATLAB crashes...
At first I thought that it could be the memory, but why it works correctly with breakpoints?
I would appreciate if you could give me a clue to solve this.
Thanks in advance
Jessica
A: I also think that it is a memory issue.
Maybe, when you launch your mex file through the debugger, the memory is not handled exactly the same or the issue takes place just after your function returns.
You should try to launch matlab with this environment to facilitate debugging.
Please note that memory corruption can make Matlab crash after the faulty Mex function.
This means that you're perhaps debugging the wrong function.
For further assistance, I would need to see your code ;)
A: Sound like memory issue to me as well. Some code would help, as mentioned by Laurent'.
If you can reproduce the crash, I suggest debugging the c code itself. Make sure you run the debug version of the mex file, set a breakpoint in your code, attach to Matlab process from Visual Studio (ALt+Ctrl+p), and call the mex file from Matlab.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631128",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: ScrollView over the tabhost I am creating a page that has tabhost (main) and each tabweight also has tabhost (child) but when I put tabhost (child) inside scrollview its scroll works fine but it start from below the tabweight not from top of the page. I also try
sView.fullScroll(ScrollView.FOCUS_UP);
But page always load from below the tabweight.
Its screenshot like this when open MyDiet tab.
But I want it open like this
Suggest me any idea.
Thanks In advance.
A: You should give a little bit top margin of the layout:-
like as:-
< LinearLayout android:layout_marginTop="5dp"
>
i think this will work. If still problem then you should send your xml code.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631129",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Compile error with inner class (bracket expected) I have an inner listener class in my program. The compiler signals an error at the first line below and says '{' expected. I can't figure out what's wrong. I revised all my brackets and there's no problem. Here's my inner class:
private class Listener implements Action Listener
{
public void ActionPerformed(ActionEvent e)
{
if(i==1 && field.equalsIgnoreCase("red"))
{
i++;
label.setText("Enter color number" + i);
field.setText("");
return;
}
if(i==2 && field.equalsIgnoreCase("white"))
{
i++;
label.setText("Enter color number" + i);
field.setText("");
return;
}
if(i==3 && field.equalsIgnoreCase("yellow"))
{
i++;
label.setText("Enter color number" + i);
field.setText("");
return;
}
if(i==4 && field.equalsIgnoreCase("green"))
{
i++;
label.setText("Enter color number" + i);
field.setText("");
return;
}
if(i==5 && field.equalsIgnoreCase("blue"))
{
field.setVisible(false);
label.setText("Congratulations - your memory is perfect");
return;
}
field.setVisible(false);
label.setText("Sorry - wrong color. Eat more antioxidants");
}
}
A: Action Listener
is one word
ActionListener
A: It should be implements ActionListener without the space between Action and Listener.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631138",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: spring aop not firing for annotation I am using an annotation on a method. and whenever that annoation is present I want to intercept it using aop. What am i missing.
<bean id="emailAdvice" class="com.merc.spring.aop.advice.MultiThreadEmailAdvice"/>
<aop:config>
<aop:aspect ref="emailAdvice">
<aop:around
method="fork"
pointcut="execution(* org.springframework.mail.javamail.JavaMailSenderImpl.send(..))"/>
</aop:aspect>
<aop:aspect ref="emailAdvice">
<aop:around method="sendEmailAdvice" pointcut="@annotation(sendMailAnnotation)" arg-names="sendMailAnnotation"/>
</aop:aspect>
</aop:config>
@SendMailAnnotation()
public void testAnnotationEmail() {
System.out.println("send an email");
}
@Aspect
public class MultiThreadEmailAdvice {
public void sendEmailAdvice(ProceedingJoinPoint pjp, SendMailAnnotation sendMailAnnotation) throws Throwable {
System.out.println("before method execution");
pjp.proceed();
System.out.println("after method execution");
System.out.println(sendMailAnnotation.from());
}
}
A: Try to change
@annotation(sendMailAnnotation)
To
@annotation(<package>.SendMailAnnotation).
in your bean definition.
Ex
<aop:around method="sendEmailAdvice" pointcut="@annotation(com.merc.spring.aop.advice.SendMailAnnotation)" arg-names="sendMailAnnotation"/>
A: It turned out that the service class that call the annotated method was not spring managed. Once making in spring managed, it worked fine
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631140",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to define a function by intervals in Mathematica? How can I define a function f(x) in Mathematica that gives 1 if x is in [-5, -4] or [1, 3] and 0 otherwise? It's probably something simple but I just can't figure it out!
A: The basic construction you want is Piecewise, in particular the function you were asking for can be written as
f[x_] := Piecewise[{{1, -5 <= x <= -3}, {1, 1 <= x <= 3}}, 0]
or
f[x_] := Piecewise[{{1, -5 <= x <= -3 || 1 <= x <= 3}}, 0]
Note that the final argument, 0 defines the default (or "else") value is not needed because the default default is 0.
Also note that although Piecewise and Which are very similar in form, Piecewise is for constructing functions, while Which is for programming. Piecewise will play nicer with integration, simplification etc..., it also has the proper left-brace mathematical notation, see the examples in the documentation.
Since the piecewise function you want is quite simple, it could also be constructed from step functions like Boole, UnitStep and UnitBox, e.g.
UnitBox[(x + 4)/2] + UnitBox[(x - 2)/2]
These are just special cases of Piecewise, as shown by PiecewiseExpand
In[19]:= f[x] == UnitBox[(x+4)/2] + UnitBox[(x-2)/2]//PiecewiseExpand//Simplify
Out[19]= True
Alternatively, you can use switching functions like HeavisideTheta or HeavisidePi, e.g.
HeavisidePi[(x + 4)/2] + HeavisidePi[(x - 2)/2]
which are nice, because if treating the function as a distribution, then its derivative will return the correct combination of Dirac delta functions.
For more discussion see the tutorial Piecewise Functions.
A: Although Simon's answer is the canonical and correct one, here are another two options:
f[x_] := 1 /; IntervalMemberQ[Interval[{-5, -3}, {1, 3}], x]
f[x_?NumericQ] := 0
or
f[x_] := If[-5 <= x <= -3 || 1 <= x <= 3, 1, 0]
Edit:
Note that the first option depends on the order that the definitions were entered (thanks Sjoerd for pointing this out). A similar solution that does not have this problem and will also work correctly when supplied an Interval as input is
f[x_] := 0 /; !IntervalMemberQ[Interval[{-5, -3}, {1, 3}], x]
f[x_] := 1 /; IntervalMemberQ[Interval[{-5, -3}, {1, 3}], x]
A: All is good and well but as a general rule of the thumb one should try always the simplest approach and keep away as possible from the sophisticated high level programming. In this particular situation I mean the following:
f[x_ /; -5 <= x <= -3] = 0 etc ... etc
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631142",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "21"
} |
Q: How to create optimized ruby? I read a tweet http://twitter.com/#!/bjschaefer/status/120519670515249152 saying about "Optimized ruby".
Wondering how to create it?
A: As always when optimizing
*
*Measure
*Tweak
*Validate
*Repeat
Nothing special with optimizing Ruby and there are no hidden one click "optimize" buttons.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631146",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Periodictask not being executed In my WP7 app I am using a periodic task.
Whe I use the code for debugging to launch the Periodic Task it runs as expected i.e.
ScheduledActionService.LaunchForTest(periodicTaskName, TimeSpan.FromSeconds(60));
However when I just add it to the action service it will not execute i.e.
ScheduledActionService.Add(periodicTask);
The code is never executed. Its the same issue as http://forums.create.msdn.com/forums/t/91617.aspx
I have downloaded several sample apps and its the same in all of them. As soon as I comment out the LaunchForTest code then the task is not run. Its the same in the emulator and on the phone. I have checked the Phone > Settings > Background tasks and my task is there and 'on'.
The only thing I do see is the following in the output window when running in debug via the emulator
The thread '<No Name>' (0xf25003e) has exited with code 0 (0x0).
When I am running the ScheduledActionService.LaunchForTest code then I see a similar message, but I also see that assemblies have been loaded etc - and the code is performed.
Any ideas? Its very frustrating. - Thanks!
A: Make sure to check background service details are added to WPAppManifest.xml file.
Below is the sample
<Tasks>
<DefaultTask Name="_default" NavigationPage="MainPage.xaml" />
<ExtendedTask Name="BackgroundTask">
<BackgroundServiceAgent Specifier="ScheduledTaskAgent" Name="Task_Name" Source="Assembly_Name" Type="Assembly_Name.ScheduledAgent" />
</ExtendedTask>
</Tasks>
A while ago i had same problem, it looks like when you add background agent project to your foreground project, it is missing update the manifest file.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631150",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Lua: getting the latest line in external txt file I am having a lua function to reading and writing a txt file, I need every time lua write in at a new line instead of replacing the previous write in. How do I do that? Do I need to read in and get the lines 1st every time before I write in?
Here is my code:
local function FileOutput(name)
local f = io.open(name, "w+")
local meta = {
__call = function(t, str) f:write(str .. '\n') end,
__gc = function() f:close() end
}
return setmetatable({}, meta)
end
function writeRec()
LOG("writing")
local testfile = FileOutput(getScriptDirectory()..'/textOutput.txt')
testfile('oh yes!')
testfile = nil
end
A: Have you tried a+ instead of w+?
http://www.lua.org/manual/5.1/manual.html#pdf-io.open
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631152",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: GWT-GIN Multiple Implementations? I have the following code
public class AppGinModule extends AbstractGinModule{
@Override
protected void configure() {
bind(ContactListView.class).to(ContactListViewImpl.class);
bind(ContactDetailView.class).to(ContactDetailViewImpl.class);
}
}
@GinModules(AppGinModule.class)
public interface AppInjector extends Ginjector{
ContactDetailView getContactDetailView();
ContactListView getContactListView();
}
In my entry point
AppInjector appInjector = GWT.create(AppGinModule.class);
appInjector.getContactDetailsView();
Here ContactDetailView is always bind with ContactsDetailViewImpl. But i want that to bind with ContactDetailViewImplX under some conditions.
How can i do that? Pls help me.
A: You can't declaratively tell Gin to inject one implementation sometimes and another at other times. You can do it with a Provider or a @Provides method though.
Provider Example:
public class MyProvider implements Provider<MyThing> {
private final UserInfo userInfo;
private final ThingFactory thingFactory;
@Inject
public MyProvider(UserInfo userInfo, ThingFactory thingFactory) {
this.userInfo = userInfo;
this.thingFactory = thingFactory;
}
public MyThing get() {
//Return a different implementation for different users
return thingFactory.getThingFor(userInfo);
}
}
public class MyModule extends AbstractGinModule {
@Override
protected void configure() {
//other bindings here...
bind(MyThing.class).toProvider(MyProvider.class);
}
}
@Provides Example:
public class MyModule extends AbstractGinModule {
@Override
protected void configure() {
//other bindings here...
}
@Provides
MyThing getMyThing(UserInfo userInfo, ThingFactory thingFactory) {
//Return a different implementation for different users
return thingFactory.getThingFor(userInfo);
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631153",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How to insert/update an RDF file using Jena? I want to insert a node in my RDF file. I know that there is SPARQL insert/update syntax, but how to do this using Jena. An example will be of great use.
A: Are you sure that you need to use SPARQL update? In Jena, nodes (resources or literals) aren't in the Model by themselves, but only by virtue of being part of a triple (i.e. Statement) in the model. If you have a Model object in your code, use one of the many variants of addStatement to add a given resource or literal into your graph.
Addendum
After your comment clarifying that you want to add to a file on disk, you could do as RobV says and amend the Model in memory, then write it out again. And this is really the correct way to do it. However, there is a quick-and-dirty workaround you might find helpful. If your file is in Turtle or N-Triples format, you can just append to the end of the file (which, obviously, you can't do in XML). So something along the lines of:
File f = new File( "where.your.file.is" );
FileOutputStream out = new FileOutputStream( f, true );
out.write( ":john :loves :jane.\n" );
out.close();
would work. It's not really recommended, because you run the risk of (a) not having the correct namespace prefixes in place, (b) introducing syntax errors (since you're not using a Jena writer), and (c) creating duplicate triples, but it's sometimes a useful trick in a tight spot. Obviously you can only add information using this technique, not update or delete existing triples.
Directly appending to the end of an N-triples file is a valid and useful technique when collecting large volumes of data from ongoing logging or monitoring applications.
A: try this
Model m = ModelFactory.createDefaultModel();
m.read("/Users/heshanjayasinghe/Documents/A-enigmaProject/jena_Enigma/src/jena_enigma/Enigma.RDF", "RDF/XML");
String NS="http://www.heshjayasinghe.webatu.com/Enigma.RDF#";
Resource r = m.createResource(NS+"user8");//like subject
Property p1 =m.createProperty(NS+"lname");
Property p2 =m.createProperty(NS+"email");
Property p3 =m.createProperty(NS+"fname");
Property p4 =m.createProperty(NS+"password");
r.addProperty(p1, "thathasara", XSDDatatype.XSDstring);
r.addProperty(p2, "[email protected]", XSDDatatype.XSDstring);
r.addProperty(p3, "nipun", XSDDatatype.XSDstring);
r.addProperty(p4, "t123", XSDDatatype.XSDstring);
// m.write(System.out,"thurtle");
m.write(new FileOutputStream("/Users/heshanjayasinghe/Documents/A-enigmaProject/jena_Enigma/src/jena_enigma/Enigma.RDF"), "RDF/XML");
A: Use ARQs (Jena's SPARQL processor library) UpdateFactory to create an update and then the UpdateExecutionFactory to create an UpdateProcessor which can evaluate the updates.
It's slightly more involved than this as you also need a dataset to evaluate the updates on. I honestly don't know how easy it is to create a dataset from a single model but can't imagine it being that difficult
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631158",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Using Response in the same PHP file I have a one single PHP file in which
first part: Server generates some output.
Second Part:uses the server generated output and submits the information.
what i have done:
File Name: abc.php
<?php
//first part
based on the information here server generates some output say:
111 success: id:104.123/12345678 |value:10000045
//second part
i will be using the output generated in the first part.
what i have done is something like this
$server_said = file_get_contents('http://http://abc.php');
//abc.php is the file name
if (preg_match_all('/104.123\:(\d*)/', $server_said, $matches))
//i want to display only 104.123/12345678 part
{
$input = $matches[1];
}
$xmlfile = '<?xml version="1.0" encoding="UTF-8"?>
<identifier identifierType="id">'.$input.'</identifier>';
?>
error: the intended result is not being displayed at $input, it is just staying as $input
How can i do that?
I am not sure about the code what i have written above might be wrong.
A: your regular expression fails, the correct one is:
if (preg_match_all('/\d+\.\d+\/\d+/', $server_said, $matches))
as well, when your output XML, u need to change your headers to what follows:
header('Content-type: text/xml');
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631163",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Dealing with display objects on the stage I think there are 2 different practices with dealing with display object on the stage.
*
*You draw all the objects on the stage and then manipulate the "visible" attribute to show or hide them.
*You use addChild and removeChild to manipulate the visiblity
How do you think what is the best method for this?
Chris
A: I think the visible property should be used, you don't have to keep track of the display object visibility, unlike removeChild, which will throw and exception if you call it in a DisplayObjectContainer that does not contain a child.
A: You use addChild and removeChild to manipulate the visiblity.
It has some advantages comparing with timeline movieClip
1. Effective drawing,
2. flexibility in handling,
3. Increased performance and
3. granularity of its application programming interface (API)
A: I think it chages under conditions, if you won't use movieClip again you can use removeChild, and as i know visibility change dont stop its timeline. If you dont need to track for childIndexs you can remove from stage.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631165",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: COCOS2D: how to animate falling bricks into a grid I'm trying in the beginning of the game to animate 41 bricks to fall into a grid that is 6x7 from the top of the screen but so far I've just been able to make the bricks to fall down at the same position. If I remove the animation part then all bricks appear on the grid. The bricks should fall down with a millisecond or two after the previous brick to create the effect of steps.
I know that the position is the issue but I don't know how to fix it.
-(void)AnimateBricksFalling
{
self.allowTouch = NO;
for(int i =0; i< GRID_WIDTH ; i++)
{
for(int j =0; j< GRID_HEIGHT ; j++)
{
Bricks * d = grid[i][j];
d.mySprite.position = ccp(168,1000); //the position is the issue, making all the bricks to fall down to the same position
CCMoveTo *move = [CCMoveTo actionWithDuration:0.5 position:ccp(168,91)]; //the position is the issue, making all the bricks to fall down to the same position
[d.mySprite runAction: move];
}
}
}
A: you can use a Delay for each brick, something like this
[d.mySprite runAction: [d.mySprite runAction: [Sequence actions:
[DelayTime actionWithDuration: waitTime],
[CCMoveTo actionWithDuration:0.5 position:ccp(168,91)],
nil]]];
And then create an randon time and set it to the waitTime variable.
Then each call will move one brick, then wait, and do it again.
Hope it helps!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631172",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Opening documents inside a website I want to know is there any flash viewer which i can embed on my website, for opening word, pdf files?
or is there anything else that i can put on my php website, that can view the document
A: You can embed Google's docs Viewer: https://docs.google.com/viewer
It can handle most Office files, as well as PDF. It's not an unbranded solution, but it's probably the best you'll find.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631174",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Using CSS3 instead of images to achieve desired results I am trying to use CSS3 instead of images to code the menu in http://www.cssmania.com/ .
My code so far (& the images+styles) can be found here:
http://sarahjanetrading.com/js/j
I tried using CSS3 to achieve the border shadow and the menu li a background to match the one in http://www.cssmania.com. But it just doesnt look the same. When I tried using images, it looked almost perfect. But I want to use CSS3 to achieve the result.
I tried inspecting the code on cssmania.com, but couldnt find the ones for the menu border to make it look the way it is, and the menu li background. I just want the code for these two functions.
Thanks
A: The main thing I see that stands out different is the background of the links. There's a subtle gradient on the original design, and that's missing from yours. It's also why the borders look different - the gradient is on the color, not the borders, but your eye is tricked.
Add this to the stylesheet:
#header-mania .header {
/* Keep everything *except* the original background */
background: #7fa445;
background: -moz-linear-gradient(top, #7fa445 0%, #6b9632 100%);
background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#7fa445), color-stop(100%,#6b9632));
background: -webkit-linear-gradient(top, #7fa445 0%,#6b9632 100%);
background: -o-linear-gradient(top, #7fa445 0%,#6b9632 100%);
background: -ms-linear-gradient(top, #7fa445 0%,#6b9632 100%);
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#7fa445', endColorstr='#6b9632',GradientType=0 );
background: linear-gradient(top, #7fa445 0%,#6b9632 100%);
}
That background's color might not be exact (I didn't feel like firing up PS just to match the colors), but you can adjust the colors easily using the Ultimate CSS Gradient Generator
A: As far as I'm concerned your version of the menu doesn't look too different, in fact if you inspect css mania's stylesheet files they're only using text-shadow declarations on the elements, everything else is achieved with images. Hope you find my comments helpful!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631176",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: dynamic programming algorithm during an interview This question was asked to me in an interview and it embarrassingly exposed my shortcomings on dynamic programming. I will appreciate if someone can help me crack this one. Also, it would be very helpful to me (and others) if you can explain your thinking process along the way as you devise the solution as i seem to be able to understand when i see a solution which uses dynamic programming paradigm but struggle to come up with my own.
Without further ado, here is the question i was asked.
Given an integer i and set X of k points x1, x2, ... xk on real line, select i points from set X so as to minimize the sum of the distance from every point in X to a point in i using Dynamic programming.
A: With most DP problems I try and find a kind of reduce-and-conquer relation. That is, a relation whereby I can cut away from the problem size with each step (like divide and conquer, but usually doesn't divide the problem, it just removes a small part). In this problem (like many others) we can make a very simple observation: Either the first point is in the set of i points, or it isn't.
Some notation: Let's say X = {x1, x2, ..., xk}, and denote the reduced set Xn = {xn, xn+1, ..., xk}.
So the observation is that either x1 is one of the i points, or it isn't. Let's call our i-set finding function MSD(i,Xk) (minimum sum of distances). We can express that cut-away observation as follows:
MSD(i,Xk) = Either MSD(i-1,Xk-1) U {x1} or MSD(i,Xk-1)
We can formalise the "either or" part by realising a simple way of checking which of those two options it actually is: We run through the set X and calculate the sum of the distances, and check which is actually the smaller. We note at this point, that that check has a running time of ki since we will naively run through each of the k points and grab the minimum distance from points in the set of size i.
We make two simple observations regarding base cases:
MSD(i,Xi) = Xi
MSD(0,Xn) = {}
The first is that when looking for i points in a set of size i we obviously just take the whole set.
The second is that when looking for no points in a set, we return the empty set. This inductively ensures that MSD returns sets of size i (it's true for the case where i=0 and by induction is true according to our definition of MSD above).
That's it. That will find the appropriate set.
Runtime complexity is upper bounded by O(ik * step) where step is our O(ik) check from above. This is because MSD will be run on parameters that range from 0-i and X1 - Xk, which is a total of ik possible arguments.
That leaves us with a runtime of O((ik)2).
The following part is based on my understanding of the OP's question. I'm not sure if the distance of every point in X from the i-sized subset is the sum of the distances of every point from every other point in the subset, or the sum of the distances of every point in X from the subset itself.
I.e. sigma of x in X of (sum of distances of x from every point in the subset) OR sigma of x in X of (distance of x from the subset which is the minimum distance from x to any point in the subset)
I assume the latter.
We can reduce the runtime by optimising the O(ik) check from above. We notice that the elements are actually sorted (albeit in reverse order in this current notation), since when we add them on we do so always from the right hand side. Assuming they're sorted to begin with, they will be once out of the MSD routine. If they weren't sorted to begin with we can sort them, which will only cost O(klogk) anyway.
Once sorted, checking the distance of each point from a point in the set will be k * logi since for each point we do a binary search. This yields a total running time of O(ik * klogi + klogk)
= O(k2 * ilogi).
Finally, we can express that as O(k3logk). Not the fastest solution, but a solution.
I'm sure there are even more optimisations, but that's my 2c.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631180",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "15"
} |
Q: Why is CDATA needed for html in jQuery AJAX response? I have an ajax function that returns an xml. In the xml there is one html table and some other xml elements. I tried a few ways to extract the html table for inserting into the page, but was told that I need to wrap the table with CDATA. Then I can use the $container.html(respose.find('table-data').text()) to make it work.
What I want to ask are:
*
*Is this the only way to do this?
*Why is CDATA needed? I thought xhtml should co-exists with xml nicely.
EDIT:
Here is my xml response, I have checked with Firebug and is valid:
<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
<response>
<data>
<li class="item x1">
<p class="l1"><b class="view">0 views</b></p>
</li>
<li class="item x2">
<p class="l1"><b class="view">0 views</b></p>
</li>
</data>
<total_count>101387</total_count>
<total_pages>4056</total_pages>
<pagesize>25</pagesize>
</response>
A: CDATA sections are commonly used for scripting language content and sample XML and HTML content.
Check for more details here http://msdn.microsoft.com/en-us/library/ms256076.aspx
Try with jQuery.parseXML
more details http://api.jquery.com/jQuery.parseXML/ and this Complete Code http://www.vagrantradio.com/2009/10/how-to-parse-xml-using-jquery-and-ajax.html
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631183",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Print tomcat version and path I have a requirement to print the base dirctory of tomcat in which it is installed using java.
my tomcat is installed in c:\apache-tomcat\.
In other words I want to print the catalina.home directorty using Java.
System.out.println("print tomcat directory");
A: System.out.println(System.getProperty("catalina.home"));
A: You may get server info using this url - http://localhost:8080/manager/text/serverinfo command - Manager Commands..
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631184",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Can TSizeGrip be used to move and resize components at runtime (within FireMonkey)? FireMonkey's predecessor advertised that it could be used to create CAD and GIS programs. I've been exploring FireMonkey and thinking about how to create a simple CAD program. A basic function is to move shapes around on the screen using the mouse. FireMonkey includes a TSizeGrip component, which I suspect may be applicable to moving shapes and providing nodes at corners and edges of a shape for a user to click on. However, the documentation for TSizeGrip hasn't been completed.
Can TSizeGrip be used to allow end-user movement of FireMonkey shapes? If so, how?
A: No.
TSizeGrip is provided specifically to act as a "grab handle" for resizing a form, not arbitrary FireMonkey controls or containers.
You can see this quite easily by creating a new FireMonkey HD application. Drop a TPanel on the form and then drop a TSizeGrip onto that panel.
Run the application and you will find that when you mouse over and click on the size grip and drag, the form is resized, not the panel. A size grip control would normally be anchored to the lower right of a form.
If you are wondering why you need a control with such apparently limited use when resizable forms can just be resized using their border, the answer is that it can sometimes be useful to have a form be resizable without having the full draggable border style. e.g. modal dialog boxes.
A: No - with one exception.
If you create a new component in which you use TPanel and TSizeGrip – TSizeGrip will control TPanel's size, not TForm's size.
A: If you put TPanel and TSizeGrip on a Form
the TSizeGrip controls the size of the form and NOT the panel
I've just tried it
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631186",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Why is Asp.Net MVC not searching for a view in my Shared directory? In my /Views/Shared/ folder I created an EntityNotFound.cshtml razor view. In one of my controller actions I have the following call:
return View(MVC.Shared.Views.EntityNotFound, "Company");
This causes the following exception:
System.InvalidOperationException: The view '~/Views/Shared/EntityNotFound.cshtml' or its master was not found or no view engine supports the searched locations. The following locations were searched:
~/Views/Company/Company.cshtml
~/Views/Company/Company.vbhtml
~/Views/Shared/Company.cshtml
~/Views/Shared/Company.vbhtml
I am confused, because it does not even seem to be attempting to search ~/Views/Shared/EntityNotFound.cshtml. Even if I replace MVC.Shared.Views.EntityNotFound with "EntityNotFound" I get the same error.
Why is Asp.Net MVC not even attempting to find my shared view?
A: Have a look at the list of overloads for View();
http://msdn.microsoft.com/en-us/library/system.web.mvc.controller.view.aspx
Specifically, when you pass View(string,string); it sees the second string as the name of the master view.
Whats probably happening, is that it can't find the "Company" master view, you'll not the exception messages says
... or its master was not found...
Which means that it is probably finding the NotFoundException.cshtml, but can't correctly find the Company.cshtml that it's looking for as the master.
A: The correct syntax should be this (don't pass path, MVC is a language by conventions)
return View("EntityNotFound");
Assuming "Company" is a param you wnat to pass to the view, try like this:
ViewBag.ErrorEntity = "Company";
return View("EntityNotFound");
And from the View
<p>Entity not found: @ViewBag.ErrorEntity</p>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631189",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Unit Testing highly interdependent code So I have some challenging code I would like to refactor. The challenge is that it depends on Database queries, EJB and Java serverFaces. Not simultaneously but close to it.
A good example would be a geocoder. Getting meaningful results depending on multiple queries to the DB depending on the data entered and stored. The code might also reference other helper classes and look them up via the JSF framework.
What are the best strategies for testing this sort of code? Should I try to separate out my code as much as possible? Should I use mocking instead? What has worked for other people?
A: Well, the short answer is "yes".
You're going to need, first of all, to factor the code sufficiently to construct unit tests at all. What you're describing is excessively complicated to apply the usual unit test methods, and what you would get in any case is more like a higher-level acceptance test.
Now, as far as that factoring goes, you have several possible approaches, and you will probably use them all.
*
*Test the data base queries themselves, using an external script.
*Construct an appropriate mock for the components directly accessing the DB, in order to see what happens against known results.
*Build unit tests using a JUnit like framework for units of functionality.
*Examine the state of the art to see if you can usefully test the output HTML against unit tests.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631190",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to insert a list of students details in to WP7 Mango database I have a list of students: List<student> std
How can I insert this list into a WP7 Mango database using LINQ To SQL?
Is there any mechanism present in LINQ To SQL for inserting the entire list to the database table without iterating one by one?
A: No, you have to insert the records one at a time.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631192",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Intellij IDEA - Webservices client from WSDL with certificates I am somewhat new to SSL/TLS and Java trust/keystores. I am attempting to generate a client to consume a web service from a IIS-hosted WSDL file. This worked fine before the service was configured to require certificates. I now receive a Wsdl url connection exception.
In an attempt to bypass this, I saved a local copy of the WSDL via IE (with the appropriate certs in place via the Certificates MMC snap-in). I then attempted to point IDEA to that location (file:/C:/projects/wsdl/wsdlname.wsdl).
This fails with the following error messages:
parsing WSDL...
[ERROR] sun.security.validator.ValidatorException: PKIX path building failed:
sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid
certification path to requested target unknown location
[ERROR] invalid entity name: "Auth" (in namespace: "******")
line 0 of unknown location
Note: I've starred out the namespace.
*
*Is there a way to configure IntelliJ IDEA to be able to present a valid certificate if I want to use the generation utility/wizard?
*Is there a potential issue with the web service that is causing even the local WSDL import to fail?
Thanks in advance.
A: It should help if you install the certificate into JVM that is used to run IDEA via keytool.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631195",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Javascript and function prototype assignment I've always assumed that the prototype of a function was shared among all the objects, in a sense by reference. So if you change the value of a property of the prototype, all objects that share that prototype have the values change for them as well. So for instance below it seems that instead of the property bar being shared between all objects, it is copied. Is this right? Are the properties of the prototype of the constructor simply copied to all the class objects as they are created, or are they shared by linkage?
function foo()
{
this.bar = 1;
}
function derived() { }
derived.prototype = new foo()
object1 = new derived()
object2 = new derived()
object1.bar = 2;
//but notice if I had said here derived.prototype.bar = 3, object1.bar would still equal 2 but object2.bar would equal 3
alert(object2.bar) // this prints 1;
A: For example, you have code:
function Animal() {
}
Animal.prototype.name="animal";
function Dog() {
}
Dog.prototype = new Animal
Dog.prototype.constructor=Dog;
Dog.prototype.name="dog";
object1 = new Animal();
object2 = new Dog();
As a result you have two object instances, that looked as (you can check this for example in Chrome devtools or FF firebug or...):
object1:
__proto__: (is ref into an Animal.prototype object)
constructor: function Animal()
name: "animal"
__proto__: Object (is ref into an Object.prototype object)
object2:
__proto__: (is ref into an Dog.prototype object)
constructor: function Dog()
name: "dog"
__proto__: (is ref into an Animal.prototype object)
constructor: function Animal()
name: "animal"
__proto__: (is ref into an Object.prototype object)
When you run next code (for example):
alert(object1.name); // displayed "animal"
alert(object2.name); // displayed "dog"
What happened? 1) Javascript looked for property name in object instance (in object1 or object2). 2) When not found, it looked up in object instance proto property (that is same as prototype of class function). 3) When not founct it looked in proto of proto and next and next while not found name property and others proto found. If as result of search property is found, then value is returned, if not found, then undefined returned.
What happened if you execute next code:
object2.name = "doggy";
As a result you have for object2:
object2:
name: "doggy"
__proto__: (is ref into an Dog.prototype object)
constructor: function Dog()
name: "dog"
__proto__: (is ref into an Animal.prototype object)
constructor: function Animal()
name: "animal"
__proto__: (is ref into an Object.prototype object)
Property is assigned directly into instance object, but prototype object remains unchanged. And when you execute:
alert(object1.name); // displayed "animal"
alert(object2.name); // displayed "doggy"
When you need to create|change shared property of class, you can use one from next algoritms:
1)
Animal.prototype.secondName="aaa";
alert(object1.secondName); // displayed "aaa"
alert(object2.secondName); // displayed "aaa"
Animal.prototype.secondName="bbb";
alert(object1.secondName); // displayed "bbb"
alert(object2.secondName); // displayed "bbb"
// but
Animal.prototype.secondName="ccc";
object1.secondName="ddd";
alert(object1.secondName); // displayed "ccc"
alert(object2.secondName); // displayed "ddd"
2)
Create property of type object in prototype of function class and assign values to properties of this object.
Animal.prototype.propObject={thirdName:"zzz"};
alert(object1.propObject.thirdName); // displayed "zzz"
alert(object2.propObject.thirdName); // displayed "zzz"
Animal.prototype.propObject.thirdName="yyy";
alert(object1.propObject.thirdName); // displayed "yyy"
alert(object2.propObject.thirdName); // displayed "yyy"
object1.propObject.thirdName="xxx";
alert(object1.propObject.thirdName); // displayed "xxx"
alert(object2.propObject.thirdName); // displayed "xxx"
object2.propObject.thirdName="www";
alert(object1.propObject.thirdName); // displayed "www"
alert(object2.propObject.thirdName); // displayed "www"
A: When you assign object1.bar = 2, you are creating an own property on object1, this property exist only in that object instance, and it has nothing to do with its prototype.
This property on object1 will shadow the value of the one existing on derived.prototype, this means that when you lookup object1.bar, it will find a value directly existing on that object.
On the other side, if you lookup object2.bar, this object doesn't have an own bar property, so the property lookup will search on the object this one inherits from (derived.prototype) and it will find the value 1.
Your object structure looks something like this:
object1
--------
| bar: 2 | -----------------
-------- | derived.prototype
| ----------
|------> | bar: 1 | -- foo.prototype
object2 (no own properties)| ---------- | ------------------
-------- | -> | constructor: foo |
| | ----------------- ------------------
-------- |
v
------------------
| Object.prototype |
------------------
|
v
null
Where the ---> lines denote the internal [[Prototype]] link that expresses inheritance.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631196",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Asterisk1.6 no such command originate I installed Asteisk1.6
I tried to use "originate" and I got the no such command error.
I typed "core show help" then no have "origiante" command in list
How can I solve this? or I missing something at the config.
Please tell me.
Thanks.
A: In the Asterisk console, type "manager show commands". You should see it in there. Also, try using "Originate" instead of "originate". It is case sensitive.
A: In this thread, within the comments, a fellow says that Originate wasn't added until 1.6.2.
How to Dial to Originate a Call from Within the Dialplan?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631198",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: SOAPHeaderElement required help to write Java code to create SOAPHeaderElement or Element object for the following structure using JAX-WS 2.2.5 (Metro)
Metro provides WSBindingProvider to create header within Header tag but, how to create a nested header is the question (putting user and password within Auth tag).
Any help would be appreciated.
value
value
Thank you
A: Create Auth class which have user and password as the attributes. Then add that auth object as the Header.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631200",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Android: Fetch image from gallery without user interaction I want to fetch a picture, if present, from the gallery without having user to select picture from the gallery. I want to do this programmatically. I have tried following approach:
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = new Activity().managedQuery( MediaStore.Images.Media.INTERNAL_CONTENT_URI, projection, null, null, null);
if (cursor != null) {
// HERE YOU WILL GET A NULLPOINTER IF CURSOR IS NULL
// THIS CAN BE, IF YOU USED OI FILE MANAGER FOR PICKING THE MEDIA
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
BitmapFactory.Options options = new BitmapFactory.Options();;
options.inSampleSize = 1;
Bitmap bm = BitmapFactory.decodeFile(
cursor.getString(column_index),options);
remoteView.setImageViewBitmap(R.id.image,bm);
I'am calling this piece of code from a worker thread and not main UI thread. Is this approach correct? if not then what can be a better approach to get an image from gallery without user interaction?
Thanks.
A: I think that there are two parts to this question: getting the image from the phone gallery and updating the UI.
It seems that your method is correct for getting the images from the gallery. Another method is detailed here: http://developer.android.com/guide/topics/data/data-storage.html#filesExternal.
The RuntimeException you're seeing is because you're trying to update the UI on a worker thread. The Android framework requires all UI changes happen on the UI thread. You'll have to call Activity.runOnUiThread() after running the query to update the UI.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631204",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Integrating a 1-10 voting system effectively without common pitfalls I'm planning on integrating a reasonable ranking/voting system into an existing application.
I'm familiar with how the traditional 5 star rating systems work and know the common pitfalls/problems associated with them therefore was wondering if there is other ways (I've heard of Wilsons, Bayesian etc. but not really sure on how to implement this with the below structure):
*
*I'm planning on allowing users to vote on content between 1 to 10 via the contents page.
*The score and total votes for that content will be displayed on the contents page.
*I will also be displaying/listing the Top 10 Content so I'd need the method to be fair/realistic and not make a vote of 10 with total votes of 1 to go straight to number 1.
I'm using PHP and MySQL, I have a table for the content (which has a content_id which I guess I can JOIN on).
I'm wondering if you can suggest a way/method which achieves the above, I'd appreciate if you can attach some example PHP code and example MySQL schema so I can better understand it, as I've google'd and may have found potential solutions such as Wilsons and Bayesian...yet they provide a lengthy article with confusing mathematical equations - and mention no way which achieves the above (ie. the score....and implenting the method in PHP/MySQL) or atleast due to there not being any example PHP/MySQL code me misunderstanding this.
Perhaps this is easier then I think - I don't know as I've never had the need to implement this sort of "more complex" ranking/voting functionality before - so I'd appreciate your responses.
A: You should start by watching this video on youtube : Building Web Reputation Systems.
To emphasize the point, let me direct you to XKCD.
As for DB structure, you need following parts:
*
*list of items ( with total_votes column )
*list of user, which have voted
*intersection table for the items-users ( with rating column, if you go with 5star thing )
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631207",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: AForge.NET -> AVIWriter Adding Images as Frames I want to make a video from images, and each image should stay for one second.
The AVIWriter has 25 frames rate, so i have to add one image 25 times to make it stay for one second.
I tried changing the frame-rate, but it is not working.
Can anyone suggest a workaround?
The following is the code for writing frames into video:
private void writeVideo()
{
// instantiate AVI writer, use WMV3 codec
AVIWriter writer = new AVIWriter("wmv3");
// create new AVI file and open it
writer.Open(fileName, 320, 240);
// create frame image
Bitmap image = new Bitmap(320, 240);
var cubit = new AForge.Imaging.Filters.ResizeBilinear(320, 240);
string[] files = Directory.GetFiles(imagesFolder);
writer.FrameRate = 25;
int index = 0;
int failed = 0;
foreach (var item in files)
{
index++;
try
{
image = Image.FromFile(item) as Bitmap;
//image = cubit.Apply(image);
for (int i = 0; i < 25; i++)
{
writer.AddFrame(image);
}
}
catch
{
failed++;
}
this.Text = index + " of " + files.Length + ". Failed: " + failed;
}
writer.Close();
}
A: Hello I had the same problem and saw this topic read it all and no comment for
http://www.aforgenet.com/framework/docs/html/bc8345f8-8e09-c1a4-4834-8330e5e85605.htm
There is a note like that "The property should be set befor opening new file to take effect."
A: The solution of Hakan is working, if you use this code:
AVIWriter videoWriter;
videoWriter = new AVIWriter("wmv3");
videoWriter.FrameRate = 1;
videoWriter.Open("test.avi", 320, 240);
videoWriter.AddFrame(bitmap1);
videoWriter.AddFrame(bitmap2);
videoWriter.AddFrame(bitmap3);
videoWriter.Close();
There is well one bitmap displayed per second.
(just for giving a directly working piece of code).
A: The default frame rate for AVIWriter is 25. As you have no option to specify dropped or otherwise skipped frames, why wouldn't you set AVIWriter::FrameRate property to 1 before you start populating your writer with frames?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631208",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: ASP.NET MVC - Can't bind array to view model I have a view model with a from that includes a set of checkboxes. I need the check boxes to map to an array when binding in the post back method of my controller.
Here's the view model.
@model TMDM.Models.TestSeriesCreateViewModel
@{
ViewBag.Title = "Create";
}
<h2>Create a Test Series</h2>
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
<div class="editor-label">
@Html.LabelFor(model => model.Title)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Title)
@Html.ValidationMessageFor(model => model.Title)
</div>
<h3>Which Test Collections are in this Test Series?</h3>
<div class="editor-field">
@{
var i = 0;
foreach (var testCollection in Model.TestCollections)
{
<input type="checkbox" id="ChosenTestCollectionIds[@i]" name="ChosenTestCollectionIds[@i]" value="@testCollection.Id" />
<span>@testCollection.Title</span>
<br />
i++;
}
}
</div>
<p>
<input type="submit" value="Save" class="medium green awesome" />
@Html.ActionLink("Cancel", "Index", "TestSeries", null, new { @class = "medium black awesome" })
</p>
</fieldset>
The form is rendering fine, I've checked the source and each output check box has a different number for their id and name fields.
<input type="checkbox" id="ChosenTestCollectionIds[0]" name="ChosenTestCollectionIds[0]" value="5" />
<input type="checkbox" id="ChosenTestCollectionIds[1]" name="ChosenTestCollectionIds[1]" value="6" />
//etc...
Here is the view model.
public class TestSeriesModel
{
public int Id { get; set; }
public string Title { get; set; }
}
public class TestSeriesCreateViewModel : TestSeriesModel
{
public List<ITestCollectionDataObject> TestCollections { get; set; }
public int[] ChosenTestCollectionIds { get; set; }
}
Problem I'm having is that when the form posts back the ChosenTestCollectionIds array comes back null. What am I doing wrong here?
ANSWER
I've worked out how to do it:
<input type="checkbox" id="[@i]" name="ChosenTestCollectionIds" value="@testCollection.Id" />
A: I always come back to Phil Haack's post about model binding a list. In addition, I always define my own index because my user's will alter the list on the client side then post back the changes.
http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx
A: <input type="checkbox" id="[@i]" name="ChosenTestCollectionIds" value="@testCollection.Id" />
A: Set the name of the input types to all be the same. You can also create a custom model binder if you are trying to bind a more complex model than just a list. Here is an excellent article on the different ways to bind to your models
Various Model Binding techniques
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631212",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "25"
} |
Q: pushViewController does not cause new controller to draw view Preface: I am not using *.xib files.
I instantiate a UINavigationController in a class that effectively serves as my 'rootViewController'. This 'rootViewController' also has two UITableViewController members that are drawn on different sections of the iPad screen. One of which is set as the root view for the navigation controller. Let's call it tableViewControllerA.
The problem is, when I invoke pushViewController on a valid UINavigationController, I see no effect:
[tableViewControllerA.navigationController pushViewController:tableViewControllerX animated:YES];
I've gathered from the posts I've searched today, that this push method should in turn cause the screen to redraw the top of stack controller.view. This is not what I'm seeing.
It seemed there was a disconnect in my implementation, and it was time to reference a working example in my environment (xcode 4.0). Assuming the canned templates would provide a working basis, I created a new navigation-based applications. I simply modified didFinishLaunchingWithOptions: as follows.
UIViewController *view1 = [[UIViewController alloc] init];
UIViewController *view2 = [[UIViewController alloc] init];
view1.title = @"view1";
view2.title = @"view2";
[self.navigationController pushViewController:view1 animated:YES];
[self.navigationController pushViewController:view2 animated:YES];
self.window.rootViewController = [[UINavigationController alloc] initWithRootViewController:view1];
[view1 release];
[view2 release];
I found similar results. When I launch the simulator the screen title reads the title of whatever the self.window.rootViewController is pointing at. With the code as is, the title of the resulting top screen reads "view1". When I initWithRootViewController:view2, the resulting top screen reads "view2".
So please tell me I'm stupid cuz xyz...
Thanks.
A: Here are some references and suggestions:
Simple tutorial for navigation based application:
http://humblecoder.blogspot.com/2009/04/iphone-tutorial-navigation-controller.html
Here is another one to create the step by step navigation controller and adding the views:
http://www.icodeblog.com/2008/08/03/iphone-programming-tutorial-transitioning-between-views/
and here a bit advance with navigation + tab bar controller:
http://developer.apple.com/library/ios/#featuredarticles/ViewControllerPGforiPhoneOS/CombiningToolbarandNavigationControllers/CombiningToolbarandNavigationControllers.html
A: Without seeing your code, I have 2 theories:
*
*Your syntax and calls are wrong when you do the push. Use this as a model:
-(void)Examplemethod {
AnotherClassViewController *viewController = [[[AnotherClassViewController alloc] initWithNibName:@"AnotherClassView" bundle:nil] autorelease];
[self.navigationController pushViewController:viewController animated:YES];
}
*You are never adding the navigation controller to the view hierarchy which never adds the view either. Take a look at this.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631213",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: facebox cancel event Im using facebox for delete data (conformation) from MySQL. i like to know how to use a cancel button in the window. when the user click cancel facebox have to unload.
Here is the code im using in facebox.
Are You Sure You Want To Delete This URL?
<?php
include ('../db.php');
$id = $_GET['id'];
if (isset($id))
{
$query = "DELETE * FROM posts WHERE post_id='$id'";
}?>
<br/>
<br/>
<?php
echo '<a href="index.php?del='.$id.'" class="button" >Yes</a>';
echo '<a href="#" class="button" >Cancel</a>';
?>
what is the code i have to use in cancel button? thanks in advance.
Link to facebox : http://defunkt.io/facebox/
A: jQuery(document).trigger('close.facebox');
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631215",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: jQuery - Find next select element What I am trying to do is populate data in a select element. I'm using the following code, where a user selects a SubjectCategory from one drop down, which then should populate the next select element's html. The handler itself is working just fine, it returns the correct html I need to place inside the select element.
Also, keep in mind that I eventually clone both of these select elements and will need to populate them accordingly.
The problem is that $elem is always returning null.
I'm guessing that it's a problem with this line of code, however not quite sure (keeping in mind that I'm also cloning these two select elements):
var $elem = $this.closest('div').prev().find('select');
$(".SubjectCategory").live("click", function () {
var $this = $(this);
var $elem = $this.closest('div').next().find('select');
var a = $this.val();
$.get("/userControls/BookSubjectHandler.ashx?category=" + a, {}, function (data) {
$elem.html(data);
});
});
<div class="singleField subjectField">
<label id="Category" class="fieldSml">Subject Matter</label>
<div class="bookDetails ddl"><select id="ddlSubjectMatter" class="fieldSml SubjectCategory"></select></div>
<label id="Subjects" class="fieldSml">Category</label>
<div class="bookDetails ddl" id="subjectMatter"><select id="ddlSubjects" class="fieldSml Subjects"></select></div>
</div>
A: Given that the source element has an id of ddlSubjectMatter and the target select element has an id of subjectMatter, it may be a lot simpler to capitalise the first letter of the second id (i.e. make SubjectMatter) then you get the second element by:
var elem = document.getElementById(this.id.replace(/^ddl/,''));
It makes the element relationship independent of the document layout.
Incidentally, it is invalid HTML to have select elements with no options, not that it is a big issue.
A: You're searching inside the <label>, not the next <div> as you want. next only gets one element after the current one.
Try this: It searches for the first div next to your parent element.
var $elem = $this.closest('div').nextAll('div').first().find('select');
A: Why are you creating an extraneous $this variable? Unless you've omitted code that requires it for a different scope, just call $(this). That might be causing the problem, too.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631219",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: find a regular expression for strings containing the substring aba over the alphabet {a, b}? (formal language theory) The questions asks to find a regular expression for strings containing the substring aba over the alphabet {a, b}.
Does this mean anything can precede/procede aba so that the regular expression would be:
(aUb)*(aba)*(aUb)*
or is the question simply looking for:
(aba)*
Note: U means union and * means 0 or more times.
A: Since * means 0 or more, ε is in the first language, while you do not want it (it doesn't contain aba). You are looking for (aUb)*aba(aUb)*.
A: A substring is defined as
noun
a string that is part of a longer string
Also note that the second expression is a subset of the first.
A: The former: any string that contains aba at least once.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631220",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How do I bind the width property of a WPF Datagrid column? In a loop which sets up my WPF DataGrid columns, I want to bind the column width to member 'i' in my 'WidthList' with the following code:
var bindingColumnWidth = new Binding(string.Format("WidthList[{0}]", i));
customBoundColumn.Width = bindingColumnWidth;
However, this gives me the error:
Cannot implicitly convert type 'System.Windows.Data.Binding' to 'System.Windows.Controls.DataGridLength'
How can I resolve this?
A: DataGridColumn has no SetBinding method, you should try this:
BindingOperations.SetBinding(customBoundColumn, DataGridColumn.WidthProperty, bindingColumnWidth);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631223",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Android: How to determine waiting threads? Want to create a unit test for android library project. I need to test if the given thread is waiting (synchronized object.wait() was called) or not. Is it possible to determine it?
A: A common way to write unit tests to see if a method is called is to create a mock object that overrides the method to check and sets a flag when it is called. For example:
public class MockYourClass extends YourClass {
public boolean mWaitWasCalled = false;
@Override
public void wait() {
mWaitWasCalled = true;
super.wait();
}
}
Substitute the use of your class for this mock and then check that assertTrue(mockClass.mWaitWasCalled)
Given a random object, there's no way to tell if a thread is waiting on it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631224",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Efficient domain filtering using regex in ruby I'm building a rack server app that has to filter domains that can access the data.
This is currently how i do that and it works fine:
authorized_domains = /domain1.com|domain2.com|domain3.com/
return [417, {"Content-Type" => "text/html"}, ["Expectation Failed"]] unless env['HTTP_REFERER'].match(authorized_domains)
The problem is that i would get probably half a million request a day
or even more, and on top of that i would have about 1000-3000 domains on the list.
Is this the most efficient filtering there is? doing a regex on the list of domains?
A: I think because of the amount of domains and hits per day the best way would be to store them in a table, add an index and then query it whenever needed. You can even keep the table in memory (depeding on the DBMS) so that the queries run faster.
A: Store the domains as a Set in a class constant so that it doesn't get instantiated on each request. Then get the domain.tld from the HTTP_REFERER and do a look-up in the set.
Something like
require 'rubygems'
require 'rack'
require 'set'
require 'URI'
class FontServer
DOMAINS = %w[domain1.com domain2.com domain3.com].to_set
def call(env)
uri = URI.parse(env['HTTP_REFERER'])
domain_tld = uri.host.split('.')[-2..-1].join('.')
return [417, {"Content-Type" => "text/html"}, ["Expectation Failed"]] unless DOMAINS.include? domain
end
end
@pguardiario argued that the above is slower than his regex solution. To benchmark is to know.
require 'rubygems'
require 'rack'
require 'set'
require 'URI'
require 'benchmark'
domains=[]
3000.times {|i| domains<<"domain#{i}.com"}
DOMAINS = domains.to_set
re = Regexp.new('^https?:\/\/(' + domains.join('|') + ')')
env = {'HTTP_REFERER' => 'http://domain4711.com/'}
Benchmark.bm do |benchmark|
puts "pguardiario regex"
benchmark.report do
100000.times do
env['HTTP_REFERER'] =~ re
end
end
# Parsing the URL with the URI gem and getting domain.tld
# About three times faster than the regex solution
puts "jonelf original"
benchmark.report do
100000.times do
uri = URI.parse(env['HTTP_REFERER'])
domain_tld = uri.host.split('.')[-2..-1].join('.')
DOMAINS.include? domain_tld
end
end
# Set::include? is really fast. If we only got a
# fast way to get the domain it would rock.
puts "Only the set look-up"
benchmark.report do
domain_tld="domain4711.com"
100000.times do
DOMAINS.include? domain_tld
end
end
# Gets the full host instead of just domain.tld
# so that it does the same as pguardiario did
# About 3.8 times faster than the regex on my machine.
puts "A tweaked solution"
benchmark.report do
100000.times do
DOMAINS.include? URI.parse(env['HTTP_REFERER']).host
end
end
end
user system total real
pguardiario regex
8.437000 0.000000 8.437000 ( 8.538086)
jonelf original
2.719000 0.000000 2.719000 ( 2.734375)
Only the set look-up
0.047000 0.000000 0.047000 ( 0.040039)
A tweaked solution
2.203000 0.000000 2.203000 ( 2.222656)
A: It's faster to add the ^https?:// because the regex doesn't have to look everywhere in the string, only in the beginning:
domains = ['domain1.com', 'domain2.com', 'domain3.com'] * 1000
env = {'HTTP_REFERER' => 'http://domain4.com/'}
re = Regexp.new('^https?:\/\/(' + domains.join('|') + ')')
500000.times do
env['HTTP_REFERER'] =~ re
end
Edit
Well there are benchmarks and there are benchmarks but @Jonas Elfstrom semms to take the cake :) Let's try to show why you shouldn't take all benchmarks seriously:
domains=[]
3000.times {|i| domains<<"domain#{i}.com"}
# let's assume the referrer is in the top 10 of whitelisted referrers.
# I'm not trying to introduce bias, I actually think that's reasonable.
env = {'HTTP_REFERER' => 'http://domain10.com/'}
Benchmark.bm do |benchmark|
puts "pguardiario regex"
benchmark.report do
re = Regexp.new('^https?:\/\/(' + domains.join('|') + ')')
100000.times do
env['HTTP_REFERER'] =~ re
end
end
puts "Only the set look-up"
benchmark.report do
DOMAINS = domains.to_set
domain_tld = "domain4711.com" # huh?
# Um, excuse me? You think you can get away with hardcoding that? lol :)
100000.times do
# how about if we parse on the fly like we would have to do in real life.
domain_tld = URI.parse(env['HTTP_REFERER']).host
DOMAINS.include? domain_tld
end
end
end
user system total real
pguardiario regex
0.203000 0.000000 0.203000 ( 0.200012)
Only the set look-up
2.371000 0.000000 2.371000 ( 2.386136)
Result: Sorry @Jonas, not even close.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631229",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to download a file from server using ftp and how to save that file in my local folder this is my code but this is not working whats a problem in this code.u have any another code.give me idea to download a file from server using ftp.i am trying this code in my localhost also in my own server.
$curl = curl_init();
$file = fopen("ftpfile/file.csv", 'w');
curl_setopt($curl, CURLOPT_URL, "ftp:http://www.address.com/file.csv"); #input
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_FILE, $file); #output
curl_setopt($curl, CURLOPT_USERPWD, "myusername:mypassword");
curl_exec($curl);
A: I'm guessing one of two things: the fopen call failed (and you're not checking if it succeeded by seeing if $file !== false), or the double-use of _returntransfer AND _file is not acting as you expect.
returntransfer tells curl to return the retrieved data in the exec call, instead of outputting it directly to the browser. I suspect that if you did $data = curl_exec($curl); file_put_contents('ftpfile/file.csv', $data) you'd end up with a properly populatd file. So... either remove the returntransfer option, or eliminate the whole _file business and output the file yourself using what the _exec call returns.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631234",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to play sound after calling recorder and than animation start and than play sound? I have to task to develop an application which plays sound after user blow candles and than the sound should play. For blowing candle I have used AVAudioRecorder that catch user blow and than its starts animation of stopped candles and than it should start to play the song but its not playing the song. I have stored song locally.(in my application)
for AVAudioRecorder
NSURL *url1 = [NSURL fileURLWithPath:@"/dev/null"];
NSDictionary *settings = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithFloat: 44100.0], AVSampleRateKey,
[NSNumber numberWithInt: kAudioFormatAppleLossless], AVFormatIDKey,
[NSNumber numberWithInt: 1], AVNumberOfChannelsKey,
[NSNumber numberWithInt: AVAudioQualityMax], AVEncoderAudioQualityKey,
nil];
NSError *error1;
recorder = [[AVAudioRecorder alloc] initWithURL:url1 settings:settings error:&error1];
animation images starts and after that song should be play.
imageView1.animationImages= [NSArray arrayWithObjects:
[UIImage imageNamed:@"can6.png"],
[UIImage imageNamed:@"can7.png"],
[UIImage imageNamed:@"can8.png"],
[UIImage imageNamed:@"can9.png"],
[UIImage imageNamed:@"can10.png"],nil];
[imageView1 setAnimationRepeatCount:1];
imageView1.animationDuration=0.7;
[imageView1 startAnimating];
[recorder stop];
player = [[AVAudioPlayer alloc]
initWithContentsOfURL:[NSURL fileURLWithPath:
[[NSBundle mainBundle] pathForResource:xyz song ofType:nil]]
error:nil];
NSLog(@"music play-%@",xyz song);
[player prepareToPlay];
[player play];
All codes are working properly only sound is not playing.
I get candle stop animation starts but I can't here the song. Although the above sound play code works in another view perfectly and its plays the song but it's not playing the song here. Please help me.
A: Check that the result of [[NSBundle mainBundle] pathForResource:xyz song ofType:nil] is not nil. I think the problem might be passing nil for type. For example, if your song is HappyBirthday.mp3, you should call
[[NSBundle mainBundle] pathForResource:@"HappyBirthday" ofType:@"mp3"];
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631235",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: PHP cheapest way how to check if remote image exist I want to check if a remote image exist.
Currently using CURL and based on its response to i can determine if the file exist.
However, this takes a fare bit amount of time depending on the image file size also.
Is there a safest and cheapest way of doing a check without doing it offline or using cache?
$ch = curl_init();
// set URL and other appropriate options
/*--Note: if in sabre proxy, please activate the last 4 lines--*/
$options = array( CURLOPT_URL => $img,
CURLOPT_HEADER => false, // get the header
CURLOPT_NOBODY => true, // body not required
CURLOPT_RETURNTRANSFER => false, // get response as a string from curl_exec, not echo it
CURLOPT_FRESH_CONNECT => false, // don't use a cached version of the url
CURLOPT_FAILONERROR => true,
CURLOPT_TIMEOUT => 5
);
curl_setopt_array($ch, $options);
if(!curl_exec($ch)) { return FALSE; }
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
return ($httpcode<400);
A: Perform a HEAD request and check the response code.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631236",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: ssl(certificate based authentication) complete working and understanding in wp7 I am trying to understand the concept of ssl in wp7.
I learnt that public key is installed in the phone.
And how the private key will synchronize with the public key?
Is there any code needed?
In my scenario is that i have a username and password.
and for client authentication i want this ssl communication.
How to implement this ssl concept for this scenario?
And i dont want to disturb user experience too.
A: Short anwer: you cannot add trusted certificates to the phone and you cannot make HTTPS connections to servers with untrusted certificates.
Long answer
You can install a custom certificate on the phone by emailing it to yourself and opening the attachment on the phone. However, you'll have to do it on the emulator everytime it starts and you can't ask users of your application to do it (you'll very likely be rejected from the marketplace).
A: Use the following bog:
WP7CertInstaller 1.0.0.0 Explained
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631238",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How would I convert regular expression to finite automata? How would I change the following regular expression to finite automata?
(abUb)(bUaaa)b*b((a*b)*Ub)*
note: U means union in this case
A: There are five top-level concatenated components of this regex. According to the algorithm recoverable from a part of Kleene's theorem, you can make NFA-Lambdas for these, then form the concatenation by connecting final states of one to initial states of the next.
When you see a union, that means you make two machines and combine them by making a new start state with two lambda transitions.
Kleene closure is a little more involved, but basically make the machine for the thing being repeated, then transform it by adding a new accepting start state and a loop to it from the old final states.
The base case is the machine for a single letter, which is two states, initial and final, with the appropriately labelled transition.
Work recursively from the simplest machines (innermost subexpressions) up to the whole thing, combining as necessary. Simplify the result as much as you like, possibly converting to a minimal DFA.
A: There is an application called Automatic Java Code Generator for Regular Expressions and Finite Automata, that automatically generates the NFA, DFA (including the transition table), and Java Code for a given regular expression or finite automata. It can be downloaded from this link: www.s-solutions.info You can always check if your solution is correct or not.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631239",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to check if a Document Library (SPDocumentLibrary) supports a particular ContentType I have a SharePoint 2010 site set up locally for debugging with the following topography:
Main (SPSite)
-> Toolbox (SPWeb)
-> MyTool (SPWeb)
I have created and deployed the following to Main:
*
*Custom Field "RequestedBy"
*Custom Field "OriginalRequestFileName"
*Custom Content Type "RequestContentType" that contains the above two fields in addition to OOB fields
*Custom List Definition "RequestListDefinition" based on the above ContentType
*VisualWebPart "MyFileUploaderWebPart" that has a custom EditorPart to allow the user to define which document library the file should be uploaded to.
I have created an instance of a list "My Request List" in MyTool that's based on my custom list definition "RequestListDefinition".
In the EditorPart I've got a drop-down list of document libraries.
private void PopulateDocumentLibraryList(DropDownList dropDownList)
{
SPWeb currentWebsite = SPContext.Current.Web;
SPListCollection lists = currentWebsite.GetListsOfType(SPBaseType.DocumentLibrary);
if (lists.Count > 0)
{
List<SPDocumentLibrary> docLibraries = lists.Cast<SPList>()
.Select(list => list as SPDocumentLibrary)
.Where(library => library != null && !library.IsCatalog && !library.IsSiteAssetsLibrary)
.ToList();
dropDownList.DataSource = docLibraries;
dropDownList.DataTextField = "Title";
dropDownList.DataValueField = "ID";
dropDownList.DataBind();
// Default the selected item to the first entry
dropDownList.SelectedIndex = 0;
}
}
I would like to restrict the list of document libraries to only those that are derived from my custom list definition that I've deployed. I thought of doing this by checking the supported content types and thus tried altering the Where clause to:
private void PopulateDocumentLibraryList(DropDownList dropDownList)
{
SPWeb currentWebsite = SPContext.Current.Web;
SPListCollection lists = currentWebsite.GetListsOfType(SPBaseType.DocumentLibrary);
if (lists.Count > 0)
{
SPContentType voucherRequestListContentType = currentWebsite.ContentTypes["VoucherRequestContentType"];
List<SPDocumentLibrary> docLibraries = lists.Cast<SPList>()
.Select(list => list as SPDocumentLibrary)
.Where(library => library != null && !library.IsCatalog && !library.IsSiteAssetsLibrary && library.IsContentTypeAllowed(voucherRequestListContentType))
.ToList();
dropDownList.DataSource = docLibraries;
dropDownList.DataTextField = "Title";
dropDownList.DataValueField = "ID";
dropDownList.DataBind();
// Default the selected item to the first entry
dropDownList.SelectedIndex = 0;
}
}
It bombs out with the following error though:
Server Error in '/' Application.
--------------------------------------------------------------------------------
Value cannot be null.
Parameter name: ct
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.ArgumentNullException: Value cannot be null.
Parameter name: ct
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Stack Trace:
[ArgumentNullException: Value cannot be null.
Parameter name: ct]
Microsoft.SharePoint.SPList.IsContentTypeAllowed(SPContentType ct) +26981638
Dominos.OLO.WebParts.FileUploader.<>c__DisplayClass7.<PopulateDocumentLibraryList>b__4(SPDocumentLibrary library) +137
System.Linq.WhereEnumerableIterator`1.MoveNext() +269
System.Collections.Generic.List`1..ctor(IEnumerable`1 collection) +578
System.Linq.Enumerable.ToList(IEnumerable`1 source) +78
Dominos.OLO.WebParts.FileUploader.DocumentLibrarySelectorEditorPart.PopulateDocumentLibraryList(DropDownList dropDownList) +801
Dominos.OLO.WebParts.FileUploader.DocumentLibrarySelectorEditorPart.CreateChildControls() +154
System.Web.UI.Control.EnsureChildControls() +146
Dominos.OLO.WebParts.FileUploader.DocumentLibrarySelectorEditorPart.SyncChanges() +102
Microsoft.SharePoint.WebPartPages.ToolPane.OnSelectedWebPartChanged(Object sender, WebPartEventArgs e) +283
System.Web.UI.WebControls.WebParts.WebPartEventHandler.Invoke(Object sender, WebPartEventArgs e) +0
Microsoft.SharePoint.WebPartPages.SPWebPartManager.BeginWebPartEditing(WebPart webPart) +96
Microsoft.SharePoint.WebPartPages.SPWebPartManager.ShowToolPaneIfNecessary() +579
Microsoft.SharePoint.WebPartPages.SPWebPartManager.OnPageInitComplete(Object sender, EventArgs e) +296
System.EventHandler.Invoke(Object sender, EventArgs e) +0
System.Web.UI.Page.OnInitComplete(EventArgs e) +11056990
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1674
This suggests to me that it's failing to find the content type.
Another thought I had was to try and retrieve all lists that are of my custom list definition type "RequestListDefinition". However, SPWeb.GetListsOfType() takes an SPListTemplateType, which is an enum and thus doesn't contain my custom list definition. The documentation for SPListTemplateType (http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.splisttemplatetype.aspx) suggests using a method that accepts a string or an int instead of SPListTemplateType but I haven't seen any documentation for this.
Can someone please help me work out either:
*
*how I can get just those lists that are derived from my custom list definition; or
*how I can get a hold of my custom content type; or
*point me in the direction of a better solution for restricting the list of SPDocumentLibrary?
Thanks!!
A: Point 2:
The SPContentType should be retrieved via currentWebsite.AvailableContentTypes[name]. The ContentTypes property of a SPWeb does only return content types created on this particular web. However, AvailableContentTypes does return all content types available in the current site collection.
Update:
To check whether the list has your content type, you should use the content type collection on the list:
SPContentTypeId ctId = voucherRequestListContentType.Id;
// LINQ where clause:
.Where(library => (...) && library.ContentTypes[ctID] != null);
The method SPList.IsContentTypeAllowed checks if a given content type is supported on the list and not if the content type is part of the list. See the MSDN documentation SPList.IsContentTypeAllowed Method.
A: I found that IsApplicationList (SP 2013) was helpful in limiting to Document Libraries that were non-system libraries (i.e. IsApplicationList is true for _catalogs, SiteAssets, and SitePages, but not for Shared Documents).
In PowerShell, you can see this by running the following
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint")
Add-PsSnapin Microsoft.SharePoint.PowerShell
$site = Get-SPSite "http://sharePoint2013Url"
$webs = $site.AllWebs
foreach($web in $webs)
{
Write-Host "$($web.Url)"
foreach($list in $web.GetListsOfType([Microsoft.SharePoint.SPBaseType]::DocumentLibrary))
{
Write-Host "$($list.DefaultEditFormUrl) $($list.IsApplicationList)"
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631240",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Sybase ULtralite DB and iOS Core Data Is it possible to use Sybase ULtralite DB as the storage medium for Core Data instead of SQlite?
A: It is possible, although it might not be worth the effort:
Atomic Store Programming Topics
A: You can do it using either the Atomic store or the new Incremental Store. As @sosborn suggested though, there is very little point and it is not worth the effort. If you are dealing with syncing with a server you are better off transferring the data in an intermediate format like JSON.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631241",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Iphone sdk save drawings without whole context I want to capture screen of my view from my iPhone app. I have white background view and on that I draw a lines on that view's layer using this method .
- (void)draw {
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSaveGState(context);
if (self.fillColor) {
[self.fillColor setFill];
[self.path fill];
}
if (self.strokeColor) {
[self.strokeColor setStroke];
[self.path stroke];
}
CGContextRestoreGState(context);
}
- (void)drawRect:(CGRect)rect {
// Drawing code.
for (<Drawable> d in drawables) {
[d draw];
}
[delegate drawTemporary];
}
I have use delegate methods to draw lines on layer.
This is the project link from where I get help for this.
https://github.com/search?q=dudel&type=Everything&repo=&langOverride=&start_value=1
Now when I use the following context methods to save the drawing only I successfully save it without that white background.
drawImage.image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
But When I use the following method of Bezier Pathe I cannot save the drawing without its white background,It saves the whole screen i.e. that drawing and its background.
UIGraphicsBeginImageContext(self.view.bounds.size);
[dudelView.layer renderInContext:UIGraphicsGetCurrentContext()];
//UIImage *finishedPic = UIGraphicsGetImageFromCurrentImageContext();
So can anybody help me how can I save the drawing only here in this app.
A: (You've tagged this as MapKit related, but make no mention of MapKit.)
Why don't you just split your drawing sequence into three chunks?
*
*Draw your paths into an image context and get a UIImage, as you described.
*Draw a background color.
*Draw the UIImage.
Then you can use the UIImage for your "screenshot" as well.
I should also note that if the only thing you don't want in your captured UIImage is the background color, you are better off creating a UIImageView, setting its background color (-setBackgroundColor:), and setting its image to be your UIImage.
UIImageView internally has a number of optimizations that allow it to display graphics with much higher performance than you can get with a custom -drawRect: implementation.
A: Why don't you just save the drawables array? Those are all the drawings without the underlying image :)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631243",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Is this a normal occurrence in backbone.js? I seem to be writing something like this when rendering views...
_.each @model.nestedcollection.models, (nestedmodel) ->
and I feel at some point i'll probably need to write something like...
_.each @model.nestedcollection.models, (nestedmodel) ->
_.each nestedmodel.nestedcollection.models, (nestednestedmodel) ->
#pass into new view
at times.
Is this normal or should I be dealing with this in a better way?
A: This is normal. The backbone docs provide a list of underscore methods for iteration. You will see _.each at the top of the list. You should get to know these methods (if you haven't already) and use the most appropriate one. Your second example may be a good use case for using _.each as your outer iterator and a more specific type of iterator (like select, detect, reject, or reduce) as your inner iterator. Choose the appropriate iterator function depending on your intention.
A: one thing to note, other than what's already been said, is that the functions listed in the backbone documentation are directly available on the backbone collections.
you don't have to call _.each @model.nestedcollection.models, (model) ->, you can instead, call @model.nestedcollection.each (model) -> ... or whatever the right coffeescript syntax for that, is.
functionally the same, since it delegates to underscore's each method, but a little easier to type and read since it's directly on the collection.
A: update
I prefer Derick's specific answer for handling your question. My suggestion is too vague.
I'm not familiar with backbone beyond reviewing the docs.
sorta OOP:
You could create an object that automatically iterates over it's composed internal models and renders them. This way any combination of them would automatically iterate over their internal models and render them.
sorta Functional:
Alternatively you could pass in a rendering function to all your nested models and have them each use it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631247",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to pass in a SelectList and use associative select to get name from id? Given the following code how can I select a list item in my view to get the name via an id? I just want to get the name value from the list via a local @id variable that maps to the lists id range.
This really has nothing to do with dropdowns...perhaps selectlist is the wrong container for associative look up dictionaries?
-- Controller
ViewBag.TypeId = new SelectList(db.TypeIds, "TypeId", "Name");
-- View
@* ??? Get the name by a local @id *@
<div>ViewBag.TypeId.SelectItemNameById(@id)</div> @* Bad psuedo code here... *@
A: I will use Jquery with an ajax call on the onChange of your dropdownlist.
$(document).ready(function () {
$("#MyDrop").change(function () { GetValue("#MyDrop"); });
});
function GetValue(objSource) {
var url = '/Home/Index/GetValue/';
$.getJSON(url, { id: $(objSource).val() }, function (data) {
//with data returned fill your fields
});
});
}
From the controller
public ActionResult GetValue(string id)
{
int intId = 0;
int.TryParse(id, out intId);
var myData = //Get the value from Id
return Json(myData, JsonRequestBehavior.AllowGet);
}
Remeber to use AllowGet if you don't do a Post call from your ajax (like in my example)
UPDATE to reflect the comments
To achive what you need use a Dictionary passed via ViewBag.
Then from your view you access the (Dictionary)ViewBag.MyDictionary.
Or whatever collection you prefer.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631248",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to copy/update resources, frameworks or plugins to the (Mac OS X) "app bundle" with Qt Creator or qmake I've been reading for a couple days on how to copy/update external resources, plugins or frameworks to my App's Mac Bundle using Qt creator or qmake.
Right now I have found two main solutions. One is to use qmake together with some commands on the ".pro" file. The other one is to do a "Custom Deployment Step" script.
I was hoping to use the second option cause I already had a small make script that did what I wanted. The problem is that Qt Creator offers so little variables to work with that the script lost its usefulness. For instance, my script uses the "Target App Path" as a parameter so it can do all its work from there. But please correct me if I'm wrong, Qt Creator only offers %{buildDir} and %{sourceDir} variables...
The other option is using qmake. These are the things that I have tried so far on my ".pro" file:
1) Using the INSTALL command. I did a small test where I tried copying some files this way:
MediaFiles.path = test/media
MediaFiles.files = media/*
INSTALL += MediaFiles
And basically nothing happend. I was hopping to find the same "media" folder on the "test" folder but nothing. Don't know if I'm doing something wrong.
Please note that the "media" folder is beside the "test" folder and the ".pro" file. (They all have the same hierarchy position.)
2) Then I tried QMAKE_BUNDLE_DATA:
MediaFiles.path = Contents/MacOS
MediaFiles.files = media/*
QMAKE_BUNDLE_DATA += MediaFiles
But this gave me the following error:
usage: cp [-R [-H | -L | -P]] [-fi | -n] [-apvX] source_file target_file
cp [-R [-H | -L | -P]] [-fi | -n] [-apvX] source_file ... target_directory
make: *** [PathToApp] Error 64
None of the solutions seem to be pleasing so far. If I wanted to do a good custom make script I will need to hardcode every target path separately. In my case I have 8 different target path depending on some "CONFIG" variables.
I'm sure the qmake solution are the official way of doing this. If someone can point me out the solution to the Error 64 would be cool.
Some further question:
Do I have to do a qmake every time I want to update my bundle?
Can I execute my make script with the qmake?
A: QMAKE_BUNDLE_DATA started working flawlessly after putting the command on the end of the .pro script.
mac{
MediaFiles.files = media
MediaFiles.path = Contents/MacOS
QMAKE_BUNDLE_DATA += MediaFiles
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631249",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: previous button jquery I have these two elements in my page:
<input type='button' value="undo" style="display:none" onClick = "undoFunction()"/>
<input type='checkbox' onClick = "ajaxFunction()"/>
I want when ever I click checkbox, undo button appears. I have used jquery but something is wrong. it doesn't work.
this is my whole function:
function ajaxFunction(){
$(document).ready(function(){
$("form input:checkbox").click(function () {
var hrefAdd = ($(this).nextAll('a').attr("href"));
var word = savequery();
var ajaxRequest; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
var queryString ="?Word=" + word + "&Link_Add=" + hrefAdd ;
ajaxRequest.open("GET","ajax_request.php" + queryString , true);
$(this).prev('input[type="button"]').show();
$(this).css("display","none");
ajaxRequest.send(null);
});
});
}
A: It should be like:
$(this).prev('input[type="button"]').show()
The = instead of :
And a small "better practice" note:
Better approach would be to define your event handlers in non-obtrusive way (in case of jQuery in a domready callback:
$(function() {
$('input[type="checkbox"]').click(function() {
$(this).prev('input[type="button"]').show();
});
});
Same with the click event button input.
UPDATE:
Your whole JS code (of course wrapped in <script type="text/javascript"></script> tags) should look similar to this (as I've written in comment to your original question - you don't need to wrap a domready callback in another function)
$(document).ready(function(){
$("form input:checkbox").click(function () {
var hrefAdd = ($(this).nextAll('a').attr("href"));
var word = savequery();
var data = {"Word": word, "Link_Add": hrefAdd};
$.get('ajax_request.php', data);
$(this).prev('input[type="button"]').show();
$(this).css("display","none");
});
});
I've omitted e.g. a success callback from an ajax call since you don't have one in your original code, but you can find all in Jquery.get docs.
UPDATE 2:
Ok, here's complete page which does what you want (except that it may spit out an 404 error after ajax call depending, whether ajax_request.php exists or not). Does this work for you?
<html>
<head><title>test</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<script type="text/javascript" encoding="utf-8">
$(function() {
$("form input:checkbox").click(function () {
var hrefAdd = ($(this).nextAll('a').attr("href"));
var word = savequery();
var data = {"Word": word, "Link_Add": hrefAdd};
$.get('ajax_request.php', data);
$(this).prev('input[type="button"]').show();
$(this).css("display","none");
});
});
// just a mock function to make a call to it in checkbox click callback work
var savequery = function() {
return "foo";
}
</script>
<form action="" method="get">
<input type="button" value="undo" style="display:none"/>
<input type="checkbox" />
<a href="http://example.com/#foo">test link to fill hrefAdd</a>
</form>
</body>
</html>
A: This seems to work for me.
<input type='button' value="undo" style="display:none" />
<input type='checkbox' class='cb_button' />
<script type='text/javascript'>
$(document).ready( function() {
$(".cb_button").click( function() {
$(this).prev(":button").show();
});
});
</script>
The document.ready function is like a load for the page. Inside of there, we are saying, find the all the checkboxes with class 'cb_button', and set it so their click event does this function.
In the function, it tells it to get the particular checkboxes's prior sibling which has type='button.
If you want to toggle, you can check to see if it's checked with the .attr('checked'):
if ($(this).attr('checked')) {
$(this).prev(":button").show()
} else {
$(this).prev(":button").hide()
}
Hope this helps.
A: Please show us your complete code, the answer posted by akloboucnik seems to be correct. You can check it running here
http://jsfiddle.net/tDDV2/
check your JS logs and see if you can figure out the issue
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631256",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: cannot debug Thrust CUDA in Visual Studio I've compiled a simple CUDA project in VS10 (and it works), but strangely I cannot put a breakpoint or step-over some parts of the code, namely those involving Thrust call, not even host-side thrust. Having been through nvcc, with the debug keys specified: -D_NEXUS_DEBUG -g and -G0, the parts in question are invisible to F10 and breakpoints.
For example, in the function below, the step debug jumps only on the starred (easy) lines:
int thrust_test() {
thrust::host_vector<int> h_vec(1000);
thrust::generate(h_vec.begin(), h_vec.end(), rand);
*h_vec[0] = 1002;
thrust::device_vector<int> d_vec = h_vec;
*int h_res=-1;
h_res = thrust::reduce(h_vec.begin(), h_vec.end(), int(0), thrust::maximum<int>());
*int d_res=-1;
d_res = thrust::reduce(d_vec.begin(), d_vec.end(), int(0), thrust::maximum<int>());
*int prod=-1;
*prod = h_res*d_res;
return 0;
}
I can step in the Disassembly window and then go back to Source and Thrust source gets picked-up. But something is broken clearly.
Question 2: why in the build log below all the warnings are printed twice?
------ Configuration: Debug x64 ------
Compiling CUDA source file ..\..\..\src\cudamain.cu...
"C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v4.0\bin\nvcc.exe" -gencode=arch=compute_13,code=\"sm_13,compute_13\" --use-local-env --cl-version 2010 -ccbin "C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\bin\x86_amd64" -I"C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v4.0\include" -G0 --keep-dir "x64\Debug" -maxrregcount=0 --machine 64 --compile -D_NEXUS_DEBUG -g -Xcompiler "/EHsc /nologo /Od /Zi /MDd " -o "x64\Debug\cudamain.cu.obj" "cudamain.cu"
cudamain.cu(21): warning : variable "prod" was set but never used
C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v4.0\include\thrust/functional.h(759): warning : type qualifier on return type is meaningless
C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v4.0\include\thrust/functional.h(759): warning : type qualifier on return type is meaningless
cudamain.cu(21): warning : variable "prod" was set but never used
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631258",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: reading a plist file in Cocoa I have a plist that looks as below. Whats the preferred method to read a plist into and how do I read this into an array ? I can create a NSMutableDictionary, load the contents of this plist, load the keys into an Array and then use a for loop to read the top 2 keys - SomeData and MoreData. But I am unable to parse all the other keys (Key1, Key2 and Key3). How would I go about doing this ? Pasted code below that goes through the top 2 keys. (SomeData and MoreData). Thanks.
Plist:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN"
"http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>SomeData</key>
<array>
<dict>
<key>Key1</key>
<false/>
<key>Key2</key>
<dict>
<key>Key3</key>
<integer>0</integer>
</dict>
</dict>
</array>
<key> MoreData</key>
</dict>
</plist>
Code:
-(IBAction)modifyPlist:(id)sender{
NSLog(@"Listing Keys");
NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithContentsOfFile:@"/Users/sureshb/Documents/myprogs/plistMod/com.test.plist"];
NSArray *keys = [dict allKeys];
for (NSString *key in keys){
NSLog(@"%@",key);
}
}
A: If I'm not mistaken you can access those values in next way:
NSArray *someData = [dict objectForKey:@"SomeData"];
BOOL key1 = [[[someData objectAtIndex:0] valueForKey:@"Key1"] boolValue];
int key2 = [[[[someData objectAtIndex:0] objectForKey:@"Key2"] objectForKey:@"Key3"] intValue];
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631261",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Rake error: Stack level too deep I know this is a common question, but I just started a project with the new Rails 3.1.0 and Ruby 1.9.2 p290
On my first migrations I had already this error and I am not sure why.
Aurelien$ rake db:migrate --trace
/Users/Aurelien/.rvm/gems/ruby-1.9.2-p290@rails3/gems/rake-0.9.2/lib/rake/version.rb:4: warning: already initialized constant MAJOR
/Users/Aurelien/.rvm/gems/ruby-1.9.2-p290@rails3/gems/rake-0.9.2/lib/rake/version.rb:5: warning: already initialized constant MINOR
/Users/Aurelien/.rvm/gems/ruby-1.9.2-p290@rails3/gems/rake-0.9.2/lib/rake/version.rb:6: warning: already initialized constant BUILD
/Users/Aurelien/.rvm/gems/ruby-1.9.2-p290@rails3/gems/rake-0.9.2/lib/rake/version.rb:3: warning: already initialized constant NUMBERS
/Users/Aurelien/.rvm/gems/ruby-1.9.2-p290@rails3/gems/rake-0.9.2/lib/rake/version.rb:9: warning: already initialized constant VERSION
/Users/Aurelien/.rvm/gems/ruby-1.9.2-p290@rails3/gems/rake-0.9.2/lib/rake.rb:26: warning: already initialized constant RAKEVERSION
/Users/Aurelien/.rvm/gems/ruby-1.9.2-p290@rails3/gems/rake-0.9.2/lib/rake/early_time.rb:17: warning: already initialized constant EARLY
/Users/Aurelien/.rvm/gems/ruby-1.9.2-p290@rails3/gems/rake-0.9.2/lib/rake/alt_system.rb:32: warning: already initialized constant WINDOWS
/Users/Aurelien/.rvm/gems/ruby-1.9.2-p290@rails3/gems/rake-0.9.2/lib/rake/application.rb:28: warning: already initialized constant DEFAULT_RAKEFILES
WARNING: Possible conflict with Rake extension: String#ext already exists
WARNING: Possible conflict with Rake extension: String#pathmap already exists
/Users/Aurelien/.rvm/gems/ruby-1.9.2-p290@rails3/gems/rake-0.9.2/lib/rake/task_arguments.rb:73: warning: already initialized constant EMPTY_TASK_ARGS
/Users/Aurelien/.rvm/gems/ruby-1.9.2-p290@rails3/gems/rake-0.9.2/lib/rake/invocation_chain.rb:49: warning: already initialized constant EMPTY
/Users/Aurelien/.rvm/gems/ruby-1.9.2-p290@rails3/gems/rake-0.9.2/lib/rake/file_utils.rb:10: warning: already initialized constant RUBY
/Users/Aurelien/.rvm/gems/ruby-1.9.2-p290@rails3/gems/rake-0.9.2/lib/rake/file_utils.rb:84: warning: already initialized constant LN_SUPPORTED
/Users/Aurelien/.rvm/gems/ruby-1.9.2-p290@rails3/gems/rake-0.9.2/lib/rake/dsl_definition.rb:143: warning: already initialized constant Commands
/Users/Aurelien/.rvm/gems/ruby-1.9.2-p290@rails3/gems/rake-0.9.2/lib/rake/file_list.rb:44: warning: already initialized constant ARRAY_METHODS
/Users/Aurelien/.rvm/gems/ruby-1.9.2-p290@rails3/gems/rake-0.9.2/lib/rake/file_list.rb:47: warning: already initialized constant MUST_DEFINE
/Users/Aurelien/.rvm/gems/ruby-1.9.2-p290@rails3/gems/rake-0.9.2/lib/rake/file_list.rb:51: warning: already initialized constant MUST_NOT_DEFINE
/Users/Aurelien/.rvm/gems/ruby-1.9.2-p290@rails3/gems/rake-0.9.2/lib/rake/file_list.rb:55: warning: already initialized constant SPECIAL_RETURN
/Users/Aurelien/.rvm/gems/ruby-1.9.2-p290@rails3/gems/rake-0.9.2/lib/rake/file_list.rb:61: warning: already initialized constant DELEGATING_METHODS
/Users/Aurelien/.rvm/gems/ruby-1.9.2-p290@rails3/gems/rake-0.9.2/lib/rake/file_list.rb:364: warning: already initialized constant DEFAULT_IGNORE_PATTERNS
/Users/Aurelien/.rvm/gems/ruby-1.9.2-p290@rails3/gems/rake-0.9.2/lib/rake/file_list.rb:370: warning: already initialized constant DEFAULT_IGNORE_PROCS
/Users/Aurelien/.rvm/gems/ruby-1.9.2-p290@rails3/gems/rake-0.9.2/lib/rake.rb:64: warning: already initialized constant FileList
/Users/Aurelien/.rvm/gems/ruby-1.9.2-p290@rails3/gems/rake-0.9.2/lib/rake.rb:65: warning: already initialized constant RakeFileUtils
** Invoke db:migrate (first_time)
** Invoke environment (first_time)
** Execute environment
rake aborted!
stack level too deep
/Users/Aurelien/.rvm/gems/ruby-1.9.2-p290@rails3/gems/rake-0.9.2/lib/rake/task.rb:162
I also removed the gems and re-tyring with db:reset
source 'http://rubygems.org'
gem 'rails', '3.1.0'
# Bundle edge Rails instead:
# gem 'rails', :git => 'git://github.com/rails/rails.git'
gem 'sqlite3'
#gem "rspec-rails", :group => [:test, :development]
group :test do
#gem "factory_girl_rails"
#gem "capybara"
#gem "guard-rspec"
#gem "spork", "> 0.9.0.rc"
#gem "guard-spork"
end
The rake commands work with bundle exec, but it would be nice to avoid using it.
Thank you in advance for tips and answers.
Aurelien
A: You should specifically add Rake version >= 0.9.2 in your Gemfile!
There was a bug with some Rails 3 versions where you would see strange errors like this when you use an older Rake version.
In your Gemfile:
gem 'rake' , '>= 0.9.2'
I'd also recommend you create a new gemset specifically for your application, e.g.
rvm gemset create yourproject
rvm gemset use yourproject
or:
rvm gemset use yourproject --default
for the new gemset, you might have to add "gem install rake" manually, then run "bundle install"
Using a separate gemset in addition to using your Gemfile is the best way to keep your gem versions in your project stable, and decoupled from other projects.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631263",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: creating directory using PHP I need to create a directory using php with write permission...currently am using the following code
$folder_name = $this->input->post('foldername', true);
$path = '/home/temp/workspace/My_folder/documents/'.$folder_name;
mkdir($path,'0222');
But this is not working...
A: Does your application (Apache probably) have the right to write in that directory? Does the directory exist?
try this maybe:
$path = '/home/temp/workspace/My_folder/documents/'.$folder_name;
mkdir($path, 0222, $recursive=true);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631264",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Redirect subdomain to subdirectory - trailing slash I want to redirect [abc].apps.example.com to the following apps.example.com/[abc] but still showing the using the [abc].apps.example.com in the url.
[abc] an be anything eg.
calendar.apps.example.com
books.apps.example.com
etc
With a bit of digging around and tweaking, I have the following setup but doesn't work when an ending slash is missing:
RewriteEngine On
RewriteBase /
# Fix missing trailing slashes.
RewriteCond %{HTTP_HOST} !^www\.apps\.example\.com$ [NC]
RewriteCond %{HTTP_HOST} ^(www\.)?([^\.]+)\.apps\.example\.com$ [NC]
RewriteCond %{DOCUMENT_ROOT}/%2%{REQUEST_URI}/ -d
RewriteRule [^/]$ %{REQUEST_URI}/ [R=301,L]
# Rewrite sub domains.
RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteCond %{HTTP_HOST} !^www\.apps\.example\.com$ [NC]
RewriteCond %{HTTP_HOST} ^(www\.)?([^\.]+)\.apps\.example\.com$ [NC]
RewriteRule ^.*$ /%2/$0 [QSA,L]
When the following is entered:
calendar.apps.example.com/showcalendar/
it's redirected correctly to: apps.example.com/calendar/showcalendar/
But for when a trailing slash is missing
calendar.apps.example.com/showcalendar
I get a 404 error saying /calendar/calendar/showcalendar/ not found.
Please, if you know what's wrong with the above code or have a better solution do let me know.
Cheers,
Doggy
A: try the following rewrite rule for adding trailing slashes.
# add trailing slash
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^.*[^/]$ /$0/ [L,R=301]
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631268",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Array splitting ending / beginning I'm looking to split an array into two, one containing the beginning and one containing the ending. If their is an odd number of array items I want the first to contain the extra one.
$array = array('1','2','3','4','5','6','7');
$beg = array('1','2','3','4');
$end = array('5','6','7');
A: $array = array('1','2','3','4','5','6','7');
$count=count($array);
$num=$count/2;
if($count % 2 != 0)
{
$num++;
}
print_r($array1=array_slice($array,0,$num));
print_r($array2=array_slice($array,$num));
A: array_chunk anybody?
list($beginning, $ending) = array_chunk($array, ceil(count($array)/2));
working codepad example
A: Hello you can try array slice
You will find examples here
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631274",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Hibernate Automatic Versioning I have developed a customer maintenance application. Users can alter the customer details via web interface. I want to handle the following scenario:
*
*User 1 loads customer1 details.
*User 2 loads customer1 details.
*User 1 changes and saves customer1's name.
*User 2 only changes and saves customer1's age.
In the scenario above, finally database holds customer1's old name and the new age because User 2 overwrites User 1's update. I'm using Hibernate. I had heard that Hibernate Automatic Versioning supports this. If any one know how to handle this please advise me.
A: You just need to add a field annotated with @Version:
public class Customer {
@Id
private Long id;
@Version
private Long version;
// rest of the fields, etc.
}
Read this article for more information.
A: one solution, when second request tends to update details first check if it is updated after details loaded, if so then raise exception and allow user to change after loading details again, you can use modification time stamp to compare
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631280",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: Pointer to Pointer with argv Based on my understanding of pointer to pointer to an array of characters,
% ./pointer one two
argv
+----+ +----+
| . | ---> | . | ---> "./pointer\0"
+----+ +----+
| . | ---> "one\0"
+----+
| . | ---> "two\0"
+----+
From the code:
int main(int argc, char **argv) {
printf("Value of argv[1]: %s", argv[1]);
}
My question is, Why is argv[1] acceptable? Why is it not something like (*argv)[1]?
My understanding steps:
*
*Take argv, dereference it.
*It should return the address of the array of pointers to characters.
*Using pointer arithmetics to access elements of the array.
A: Indexing a pointer as an array implicitly dereferences it. p[0] is *p, p[1] is *(p + 1), etc.
A: It's more convenient to think of [] as an operator for pointers rather than arrays; it's used with both, but since arrays decay to pointers array indexing still makes sense if it's looked at this way. So essentially it offsets, then dereferences, a pointer.
So with argv[1], what you've really got is *(argv + 1) expressed with more convenient syntax. This gives you the second char * in the block of memory pointed at by argv, since char * is the type argv points to, and [1] offsets argv by sizeof(char *) bytes then dereferences the result.
(*argv)[1] would dereference argv first with * to get the first pointer to char, then offset that by 1 * sizeof(char) bytes, then dereferences that to get a char. This gives the second character in the first string of the group of strings pointed at by argv, which is obviously not the same thing as argv[1].
So think of an indexed array variable as a pointer being operated on by an "offset then dereference a pointer" operator.
A: Because argv is a pointer to pointer to char, it follows that argv[1] is a pointer to char. The printf() format %s expects a pointer to char argument and prints the null-terminated array of characters that the argument points to. Since argv[1] is not a null pointer, there is no problem.
(*argv)[1] is also valid C, but (*argv) is equivalent to argv[0] and is a pointer to char, so (*argv)[1] is the second character of argv[0], which is / in your example.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631282",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "29"
} |
Q: How to push a view controller onto navigation stack AFTER executing popToRootViewController I am trying to push a new view controller onto a navigation stack only after I pop the stack to rootviewcontroller
//Select the tab I want to go to
self.tabBarController.selectedIndex = FEEDPAGE_INDEX;
//Retrieve the navcon in the feed page
UINavigationController *navcon = (UINavigationController*)[self.tabBarController.viewControllers objectAtIndex:FEEDTAB_INDEX];
//Pop to root view controller here
[navcon popToRootViewControllerAnimated:YES];
//Push a new root view controller onto stack
QuestionAnswerViewController *x = [[QuestionAnswerViewController alloc]init];
[navcon pushViewController:x animated:YES];
The push didn't work i.e. no new page was displayed. It seemed that the popToRootViewController causes this to happen (not sure exactly). Any advise on how I can pop and then push a new page?
A: QuestionAnswerViewController *x = [[QuestionAnswerViewController alloc]init];
UINavigationController *navcon = (UINavigationController*)[self.tabBarController.viewControllers objectAtIndex:FEEDTAB_INDEX];
NSArray *arr = [navcon viewControllers];
NSArray *newStack = [NSArray arrayWithObjects:[arr objectAtIndex:0], x, nil];
[navcon setViewControllers:newStack];
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631283",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: CakePhp: Form validation on several fields? I've some conditions to a form to be valid that has to be on several fields instead one, how to do this.
Some example for a registration:
enterprise or firstName+lastName filled
mobile phone number OR static phone number filled
How to do this? Is there an implemented way or I've to do it myself every time?
Thank you
A: I am not sure if I understand the question correctly but you can create your own validation rule and then apply it for the desired fields (not really the other way around). See here
Otherwise Cakephp has a lot of pre-built validation rules here is an example:
var $validate = array(
'title' => array(
'titleRule1' => array (
'rule' => array('minLength', 1),
'required' => true,
'allowEmpty' => false,
'last' => true,
'message' => 'Please enter a title.'
),
'titleRule2' => array(
'rule' => array('between', 1, 100),
'message' => 'Your title must be between 1 and 100 characters long.'
)
),
'description' => array(
'rule' => array('minLength', 1),
'required' => true,
'allowEmpty' => false,
'last' => true,
'message' => 'Please write a description.'
)
);
A: Write your own validation rules. Cake Book: Custom validation rules
Attach a rule to the enterprise field what checks if it is filled or the first, last names are filled. Attach another rule to the name fields to check if the names or the enterprise fields are filled. Similar to the phone fields. You are in the model so you can reach all passed fields in $this->data
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631284",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: how to store multiple DataTables into single DataSet in c#? I have the code below which has multiple DataTables with results and I need to pass a single DataSet with all DataTable values.
MySqlCommand cmd = new MySqlCommand(getLikeInfo, con);
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
MySqlCommand cmd1 = new MySqlCommand(getKnowInfo, con);
MySqlDataAdapter da1 = new MySqlDataAdapter(cmd1);
DataTable dt1 = new DataTable();
da1.Fill(dt1);
MySqlCommand cmd2 = new MySqlCommand(getHotelInfo, con);
MySqlDataAdapter da2 = new MySqlDataAdapter(cmd2);
DataTable dt2 = new DataTable();
da2.Fill(dt2);
MySqlCommand cmd3 = new MySqlCommand(getRoomInfo, con);
MySqlDataAdapter da3 = new MySqlDataAdapter(cmd3);
DataTable dt3 = new DataTable();
da3.Fill(dt3);
MySqlCommand cmd4 = new MySqlCommand(getFoodInfo, con);
MySqlDataAdapter da4 = new MySqlDataAdapter(cmd4);
DataTable dt4 = new DataTable();
da4.Fill(dt4);
How can I do that?
A: DataSet ds = new DataSet();
ds.Tables.Add(dt);
ds.Tables.Add(dt1);
...
If you want your tables named in the DataSet you can create your tables from the DataSet
DataSet ds = new DataSet();
DataTable t1 = ds.Tables.Add("t1"); // Create
DataTable t1Again = ds.Tables["t1"]; // fetch by name
You can also set the TableName property of the tables if you use the first approach.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631286",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: Replacing specific Unicode characters in strings read from Excel I am attempting to replace some undesirable characters in a string retrieved from an Excel spreadsheet. The reason being that our Oracle database is using the WE8ISO8859P1 character set, which does not define several characters that Excel "helpfully" inserts for you in text (curly quotes, em and en dashes, etc.) Since I have no control over the database or how the Excel spreadsheets are created I need to replace the characters with something else.
I retrieve the cell contents into a string thus:
string s = xlRange.get_Range("A1", Missing.Value).Value2.ToString().Trim();
Viewing the string in Visual Studio's Text Visualiser shows the text to be complete and correctly retrieved. Next I try and replace one of the undesirable characters (in this case the right-hand curly quote symbol):
s = Regex.Replace(s, "\u0094", "\u0022");
But it does nothing (Text Visualiser shows it still to be there). To try and verify that the character I want to replace is actually in there, I tried:
bool a = s.Contains("\u0094");
but it returns false. However:
bool b = s.Contains("”");
returns true.
My (somewhat lacking) understanding of strings in .NET is that they're encoded in UTF-16, whereas Excel would probably be using ANSI. So does that mean I need to change the encoding of the text as it comes out of Excel? Or am I doing something else wrong here? Any advice would be greatly appreciated. I have read and re-read all articles I can find about Unicode and encoding but am still none the wiser.
A: Yes strings in .Net are UTF-16.
You're doing it right; perhaps your hex-math is incorrect.
The character you tested for isn't "\u0094" (Not sure that's what you meant). The following worked for me:
((int)"”"[0]).ToString("X") returns "201D"
"”" == "\u201D" returns true
"\u0094" == "" (right hand side is the empty string) returns false
A lot of UTF-16 characters will seem as an empty string by the text visualizer but they can either be an undisplayable character or part of a surrogate (i.e. Some characters may need to be typed "\UXXXXXXXX" while others you can do with (four digits) "\uXXXX".). My knowledge of this domain is very limited.
References - Jon Skeet's articles on:
*
*Strings
*Unicode
A: You can use NVARCHAR and NTEXT instead of VARCHAR and TEXT for the columns that need to accomodate those characters.
That wayyou don't have to convert the whole database, and you are future proof, because the columns will be Unicode.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631288",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: How to destroy my application? My application is always showing in Task Manager when I exit from my application. How do I destroy it? I used the onDestroy() method, but still it is running. I am using alarm manager and some database operations; is that the problem?
A: Android does not destroy applications unless it needs to. See this answer for more details: Is quitting an application frowned upon?
A: System.exit(0) will do the job. However, it is not at all recommended. Android does some caching, and saving state, so as to relaunch your appp quicker, the next time you launch it.. so you do not want to be messing around with that.
A: Its not a problem. thats how android works, terminating Application is done by os. But if you want to kill it then you may have to kill the process.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631289",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: how to determine is_home in wordpress if query a category? I need to query a category in home page. in index.php file I used this script
$all_featured_posts = query_posts(array('category_name'=>'featured-programs'));
Then in the header.php file I need to change the title
<title>
<?php
if ( is_home() ) {
echo 'My site name' ;
} elseif (is_404()) {
echo '404 Not Found';
} elseif (is_category()) {
echo ' Category' . wp_title('',0).' | My site name' ;
}
?>
The problem is when I query a category in the index file then the is_home return false ( Tried with is_front_page() also ) Then it alway show the title with the name of the category which I query.
How I can fix it? Thanks you!
A: I might be wrong, but I think because you use query_posts(), all your is_* functions change their values. And, well, because you do query a category, is_home() should return false.
What you can do to solve it, is use new WP_Query(), and get all the posts from it. This way, you will not be affecting the original WP_Query, and thus the is_* functions.
The code should look like this:
$query = new WP_Query('category_name=featured-programs');
while ( $query->have_posts() ) : $query->the_post();
echo '<li>';
the_title();
echo '</li>';
endwhile;
// Reset Post Data
wp_reset_postdata();
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631296",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: BigNum Class String Constructor Error So i am implementing a BigNum Class to deal with large integers and am currently trying to fix my string constructor class. I have to be able to read Strings such as "-345231563567" in an array with the numbers being read in backwards (i.e. 765365132543). The first part of the code attached checks the first character to see if it is positive or negative and sets positive to true or false. The next part of the code checks for leading zeros in the number that may occur as well as if the number is zero itself. the last part is what is loading the number into the array and for some reason i can not get the code to work. any help with a solution is much appreciated.
BigNum::BigNum(const char strin[])
{
size_t size = strlen(strin);
positive = true;
used=0;
if(strin[0] == '+')
{
positive = true;
used++;
}
else if(strin[0] == '-')
{
positive = false;
used++;
}
else
{
positive = true;
}
// While loop that trims off the leading zeros
while (used < size)
{
if (strin[used] != '0')
{
break;
}
used++;
}
// For the case of the number having all zeros
if(used == size)
{
positive = true;
digits = new size_t[1];
capacity = 1;
digits[0] = 0;
used = 1;
}
// Reads in the digits of the number in reverse order
else
{
int index = 0;
digits = new size_t[DEFAULT_CAPACITY];
capacity = size - used;
while(used < size)
{
digits[index] = strin[size - 1] - '0';
index++;
size--;
}
used = index + 1;
}
}
The BigNum.h can be found here
http://csel.cs.colorado.edu/%7Eekwhite/CSCI2270Fall2011/hw2/revised/BigNum.h
and the Test file i am trying to use can be found here. I fail test 7
http://csel.cs.colorado.edu/%7Eekwhite/CSCI2270Fall2011/hw2/revised/TestBigNum.cxx
A: Seems like you allocate DEFAULT_CAPACITY bytes which you have defined as 20 and continue to put 22 digits in it.
A: I just tried to run your code and there seems to be a problem with the digit= line. It is a pointer that you are setting equal to a value. Might that be your problem?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631297",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Stop Background Music Playing when Song Download in iPhone I am downloading song with asihttp request
My problem is when i click on url to download song, song start playing in my view
How do i stop this, I dont want song should play when downloading
Please Help
A: obj.tagvalue=[sender tag];
NSString * tmp =[NSString stringWithString:[obj.ringArray objectAtIndex:obj.tagvalue]];
NSString *filename=[RingUrlArray objectAtIndex:obj.tagvalue];
NSLog(@"%@",filename);
NSURL *url=[NSURL URLWithString:tmp];
NSLog(@"url %@",url);
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:@"Song"];
if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath])
[[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:nil];
NSString *filePath =[NSString stringWithFormat:@"%@/%@.mp3",dataPath,filename];
NSLog(@"%@",filePath);
[request setDownloadDestinationPath:filePath];
[request startAsynchronous];
UIAlertView *v=[[UIAlertView alloc] initWithTitle:@"Download Message " message:@"Your download has been started" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
[v show];
[v release];
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631302",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to create three buttons in UINavigationbar in iPhone programmatically? I'm developing a small application. I need to create three buttons in a subclass. One button is add, another one is search and the last one is back. I also create left and right buttons. But I can't create search button in the center of the navigation bar. How can I create it? My code is:
- (void)viewDidLoad
{
[super viewDidLoad];
UIBarButtonItem *flipButton = [[UIBarButtonItem alloc] initWithTitle:@"Flip"
style:UIBarButtonItemStyleBordered
target:self
action:@selector(flipView)];
self.navigationItem.rightBarButtonItem = flipButton;
[flipButton release];
UIBarButtonItem *flipButtons = [[UIBarButtonItem alloc]
initWithTitle:@"Add"
style:UIBarButtonItemStyleBordered
target:self
action:@selector(addbuttonview)];
self.navigationItem.leftBarButtonItem = flipButtons;
[flipButtons release];
}
How to create a middle button in the navigation bar? Please help me.
A: Below is the code to use segment control in navigation bar programatically
NSArray* arr = [[NSArray alloc] initWithObjects:[UIImage imageNamed:@"Log_Button.png"], [UIImage imageNamed:@"Chart_Button.png"], nil];
segmentedControl = [[UISegmentedControl alloc] initWithItems:arr];
[segmentedControl addTarget:self action:@selector(action) forControlEvents:UIControlEventValueChanged];
[segmentedControl setSegmentedControlStyle:UISegmentedControlStyleBar];
[arr release];
UIBarButtonItem *rb = [[UIBarButtonItem alloc] initWithCustomView:segmentedControl];
[self.navigationItem setRightBarButtonItem:rb];
[rb release];
A: UIButton *btnBack = [UIButton buttonWithType:UIButtonTypeCustom];
btnBack.frame = CGRectMake(10, 4, 100, 50);
[btnBack setImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"button_back" ofType:@"png"]] forState:UIControlStateNormal];
[btnBack addTarget:self action:@selector(btnBackPressed:) forControlEvents:UIControlEventTouchUpInside];
[self.navigationController.navigationBar addSubview:btnBack];
UIButton *btnHome = [UIButton buttonWithType:UIButtonTypeCustom];
btnHome.frame = CGRectMake(115, 4, 38, 30);
[btnHome setImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"header_icon_home" ofType:@"png"]] forState:UIControlStateNormal];
[btnHome addTarget:self action:@selector(btnHomePressed:) forControlEvents:UIControlEventTouchUpInside];
[self.navigationController.navigationBar addSubview:btnHome];
UIButton *searchBtn=[UIButton buttonWithType:UIButtonTypeCustom];
searchBtn.frame=CGRectMake(175, 2, 60, 40);
[searchBtn addTarget:self action:@selector(seachbtnPressed:) forControlEvents:UIControlEventTouchDown];
[searchBtn setImage:[UIImage imageNamed:@"Search.jpg"] forState:0];
[self.navigationController.navigationBar addSubview:searchBtn];
take three UIButtons and Add to navigationBar.set Frames Images As Per Ur Design.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631305",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Correct use of JSON for a simple restaurant menu description I would like to know whether this JSON script example I made is well formatted and whether it does make sense to put the information like this.
{"menu": {
"drinks": [
{"coke": "20"},
{"pepsi": "20"},
{"water": "20"}
],
"junk-food": [
{"hamburger": "40"},
{"fries": "20"},
{"pizza": "20"}
]
}}
I already validated the script with http://jsonlint.com/ but still I would like to a little more since I'm very new.
For some context on the use of the script, I'm going to parse the script with Python.
It is meant to organize elements of a GUI that will look more or less like this:
On the second window, a listbox similar to the first one will appear with the corresponding item and respective price.
*
*Is it correct JSON?
*Does this structure make sense?
A: The JSON is correct. The structure doesn't have much semantic meaning though. I changed the structure so that it has more meaning and will be more manageable when attributes are added.
{"menu": {
"items": [
{
"name":"coke",
"qty": 20,
"category":"drinks",
"sizes":["small","large"]
},
{
"name":"pepsi",
"qty": 20,
"category":"drinks",
"sizes":["small","large"]
},
{
"name":"water",
"qty": 20,
"category":"drinks",
"sizes":["small","large"]
},
{
"name":"hamburger",
"qty": 40,
"category":"junk food",
"sizes":["small","large"]
},
{
"name":"fries",
"qty": 20,
"category":"junk food",
"sizes":["small","large"]
},
{
"name":"pizza",
"qty": 20,
"category":"junk food",
"sizes":["small","large"]
}
]
}}
to save space you could do something like this too,
{"menu": {
"items": [
{
"name":"coke",
"qty": 20,
"category":0,
"sizes":["small","large"]
},
{
"name":"pepsi",
"qty": 20,
"category":0,
"sizes":["small","large"]
},
{
"name":"water",
"qty": 20,
"category":0,
"sizes":["small","large"]
},
{
"name":"hamburger",
"qty": 40,
"category":1,
"sizes":["small","large"]
},
{
"name":"fries",
"qty": 20,
"category":1,
"sizes":["small","large"]
},
{
"name":"pizza",
"qty": 20,
"category":1,
"sizes":["small","large"]
}
],
"categories":[
"drinks",
"junk food"
]
}}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631307",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Invalid usage of aggregate function Mean() and Type: String My Code is
DataTable dtNew = new DataTable();
object o2 = dtAll.Compute("MIN(Price)", string.Empty);
object o1 = dtAll.Compute("AVG(Price)",string.Empty);
Min returns minimum.. thats work fine. but avg generates error
"Invalid usage of aggregate function Mean() and Type: String."
Datatype of Price Column in sql server is decimal.
A: It appears that your issue is the data in the Price column. My hunch is that the column is storing the Price as text; therefore, when you call Min(Price) works perfectly fine because MIN is defined for strings but when you cal AVG doesn't like it because it doesn't know how to calculate the average of a bunch of strings.
In conclusion, make sure that the data type of the Price column is a number and your code should work fine as there's no problem with it.
EDIT
Demonstrating my point:
DataTable t = new DataTable();
t.Columns.Add("Price");
t.Columns["Price"].DataType=typeof(string);
for (int i = 0; i < 10; i++)
{
DataRow r = t.NewRow();
r.ItemArray=new object[]{i};
t.Rows.Add(r);
}
object min = t.Compute("MIN(Price)",string.Empty);
Console.WriteLine("Min: " +min); //PRINTS Min: 0
try
{
object avg = t.Compute("AVG(Price)", string.Empty);
Console.WriteLine("AVG: "+avg);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
Prints:
Min: 0
Invalid usage of aggregate function Mean() and Type: String.
Forcing the data type to be int as so:
t.Columns["Price"].DataType=typeof(int);
Now prints:
Min: 0
AVG: 4
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631311",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How do I make my app run in background on the iPhone? How can I create an iPhone app that runs in the background and receives data from a web service and produces push notifications?
A: For iOS app running in the background, you need to specify it in the info.plist.
required background modes = app plays audio,
web services are possible to use with iOS which one you like REST or SOAP?
For push notification you need external server or service.
A: As apple documentation application will run in background maximum 10 min after that application will not run in background expect audio,GPS like some other
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631314",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: ASIHTTPRequest giving me problems I have a code that sends POST data to a PHP website. Code:
request = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:@"http://www.example.com/Testing/Testing.php"]];
[request setPostValue:targettype forKey:@"targettype"];
[request setPostValue:targetmethod forKey:@"targetmethod"];
[request setPostValue:sourceurl forKey:@"sourceurl"];
[request setPostValue:filepath forKey:@"filepath"];
[request setDelegate:self];
[request startAsynchronous];
This is working perfectly. Once this data is sent and the PHP script outputs some data, the script creates a .txt file. Once the iPhone reads the contents of the .txt file, I want to run ASIHTTPRequest to a different PHP script that is supposed to delete this .txt file. From a PHP end, everything seems to be working, and the data is being received perfectly by the iPhone. However, once the data is received, I have a if...then statement that checks for the data and then once the data is present, I want to call ASIHTTPRequest to delete the .txt. This is the code I used to POST the data to the new PHP location:
{...
imageView.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString: string]]];
[self deletefile];
}
-(void) deletefile {
request = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:@"http://www.prajoth.com/Testing/Testing.php"]];
[request setPostValue:@"hey" forKey:@"targettype"];
[request setPostValue:@"hey" forKey:@"targetmethod"];
[request setPostValue:@"hey" forKey:@"sourceurl"];
[request setPostValue:filepath forKey:@"filepath"];
[request setDelegate:self];
[request startAsynchronous];
}
This is for some reason, throwing up a EXC_BAD_ACCESS. The console does not show any error message though. Please help!
A: Based on the code you've pasted, it's going to be difficult to figure this out. Where exactly is your app throwing the exception? It could be perhaps one of your global variables doesn't exist any more (filepath, for example), but then again it could also be something elsewhere in your code. EXC_BAD_ACCESS messages, as you can probably guess, occur when you try to access an object that's no longer in memory, so maybe you are releasing something earlier on which you now rely on?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631318",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: How to convert an Integer param in JAXB? I am creating a SOAP service using JAX-WS and JAXB. There is a count param. How can I using a costomize DataTypeConvert to convert it? I want to convert an Integer(not a POJO) param object by my costomisze DataTypeConvert. Because if the SOAP message contain "count" tag, this value will be set to 0, but if the SOAP message without "count" tag, this value will be set to null. I want make set this param to null in both two scenarios. If the Integer field in a POJO, I can use @XmlJavaTypeAdapter to convert it. But @XmlJavaTypeAdapter can't use on an Integer param which driectly in the method.
@WebMethod
public Team getTeamByCondition(@WebParam(name = "Name") String name,
@WebParam(name = "Condition") String condition,
@WebParam(name = "Count") Integer count) {
}
If there anyone can tell me how JAX-WS convert params?
A: You can create a wrapper class for your count with JAXB.
@XmlType
class Count {
@XmlValue
Integer count;
}
An alternative...
If you want to use a wrapper class take a look at XmlAdapter. They have pretty good samples there. Basically you annotate your Integer with @XmlJavaTypeAdapter. The annotation should point to an adapter you create. You still need to create a wrapper class like the above but your adapter can map any Integer you have defined to this wrapper class.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631323",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Appended row in table view of mobile application must retain permanently (titanium) I am using titanium for developing Android application. I am using following code for displaying data and using table view.When I click on comment_btn a new row get appended in table view.it works fine.But when I click back button or go to another window and again come back to same window where I added my new row that newly added row is not retain.I also tried
insertRowAfter but it gives me same result.I used following code:
for (var i=0;i<5;i++)
{
var row = Ti.UI.createTableViewRow({height:'auto',className:"row"});
var comments = Ti.UI.createLabel(
{
text:'new comment',
height:'auto',
font:{fontSize:12, fontFamily:'Helvetica Neue'},
color:'#000',
width:'auto',
textAlign:'left',
top:10,
left:40,
});row.add(comments);
}
comment_table.setData(data);
commnet.add(comment_table);
var comment_btn = Titanium.UI.createButton(
{
title:'comment',
height:60,
width:60,
bottom:-5,
left:-2,
});
comment.add(comment_btn);
var comment_box = Titanium.UI.createTextArea({
borderRadius:5,
backgroundColor:'#EEE',
editable: true,
height:30,
width:200,
top:10,
font:{fontSize:15,fontFamily:'Marker Felt'},
color:'#000',
keyboardType:Titanium.UI.KEYBOARD_DEFAULT,
returnKeyType:Titanium.UI.RETURNKEY_DEFAULT,
borderRadius:5,
});
comment.add(comment_box);
comment_btn.addEventListener('click', function()
{
comment_table.appendRow({title:comment_box.value});
//comment_table.insertRowAfter(3,{'title':comment_box.value});
}
A: *
*The Object must be of type Row for: comment_table.appendRow(ROW_TYPE_OBJECT).
*If you are going back(Assuming pressing back button) then current window gets closed hence
all children of that window say views, buttons, table will be removed.
*Assume current window with Tableview as widnow1, Now you opens window2, And If you are
transiting from window2 to window1 then you can see table with new appended row in
window1.
Solution:
*
*Create a global array(data[]) which holds the rows and rows which you are going to
append.
*When loading current window1,check if data is null.
*If data is not null then load your tableview from global array data
tableview.setData(data), else load fresh rows.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631325",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How can I tell if I'm at the last result when using WHILE so that I can omit a comma from my output? I know I can do what I need to do by getting a total records count and if I'm at the last record, don't display a comma but there has to be a better way.
I'm trying to build an SQL statement programatically using values from MySQL.
The code:
$fql="SELECT ";
$result = mysql_query("SELECT field FROM fb_aa_fields WHERE fql_table = '$query'", $conn);
while ($row = mysql_fetch_array($result)){
$get_field = "".$row{'field'}."";
$fql = $fql."$get_field, ";
}
$fql = $fql."FROM ".$query." WHERE owner=".$get_uid."";
It outputs this:
SELECT aid, can_upload, cover_object_id, cover_pid, created, description, edit_link, link, location, modified, modified_major, name, object_id, owner, photo_count, size, type, video_count, visible, FROM album WHERE owner=522862206
The problem is the last comma between "visible" and "FROM". How would you suggest is the best way to make that comma go away?
A: It's less of a pain to detect whether you're at the first element than the last. You could do like
$i = 0;
while($row =...) {
if ($i++) $fql .= ',';
$fql .= $row['field'];
}
Or, possibly better, defer tacking on fields to the string til the end. There's a built-in function called implode, that you can use to insert the commas between them.
$fields = array();
while($row =...) {
$fields[] = $row['field'];
}
$fql .= implode(',', $fields);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631326",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: number of elements in Tuple<...> Just wondering if there's an easy way to know how many elements are contained in a Tuple class
eg.
var a = new Tuple<int,int>(1,2);
but how many elements are there? Perhaps we don't care if we try to cast via the as keyword
var a1 = a as Tuple<int>
if(a1!=null)
var a2 = a as Tuple<int,int>
if(a2!=null)
Just after a little feedback. Are many people using Tuple?
A: var a = new Tuple<int, int>(1, 2);
var aType = a.GetType();
var numberOfGenericParameters = aType.GetGenericArguments().Length;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631327",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: java application distribution with extension api I am planning to write some java application & planning to distribute in free & commercial versions.Basically my idea is to get some money from out of it from corporate users.
I would like provide extension API which other user can write some jar & include in the product.
Please help me with the following questions.
1) If I distribute as JAR anyone can see my code even if I do obfuscation.I think there are some paid de-obfuscators..making exe or JNI an option but it's not an effective solution.
Microsoft products don't have this problem. Any advice?
2)If I make open source, I won't get much gain because,business don't usually go for support until unless its huge product like IBM websphere or RAD. Any inputs to avoid this?
A: Perhaps you should consider a dual license scheme: release your source code under the GPL, and the companies that don't want to comply with the therms of the GPL would need to purchase a commercial license.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631330",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: integrating boost with numerical recipes 3 code i get a bunch of errors when i use both nr3.h and boost library.
I use ubuntu 10.04 with libboost1.40 and code from http://www.nr.com/ (3rd edition)
try.cc:
#include "nr3.h"
#include <boost/algorithm/string/predicate.hpp>
int main(void) {
return 0;
}
i compile the code "g++ try.cc" and i get errors. if i comment out either the nr3.h line or the < boost ... > line, the code compiles fine.
here are the errors:
In file included from /usr/include/boost/assert.hpp:36,
from /usr/include/boost/range/iterator_range.hpp:31,
from /usr/include/boost/range/as_literal.hpp:22,
from /usr/include/boost/algorithm/string/predicate.hpp:19,
from boostnrexample.cc:2:
/usr/include/assert.h: In function ‘void __assert_fail(const char*, const char*, unsigned int, const char*)’:
/usr/include/assert.h:73: error: expected primary-expression before ‘,’ token
/usr/include/assert.h: At global scope:
/usr/include/assert.h:73: error: declaration does not declare anything
/usr/include/assert.h: In function ‘void __assert_perror_fail(int, const char*, unsigned int, const char*)’:
/usr/include/assert.h:79: error: expected primary-expression before ‘,’ token
/usr/include/assert.h: At global scope:
/usr/include/assert.h:79: error: declaration does not declare anything
/usr/include/assert.h: In function ‘void __assert(const char*, const char*, int)’:
/usr/include/assert.h:85: error: expected primary-expression before ‘,’ token
/usr/include/assert.h: At global scope:
/usr/include/assert.h:85: error: declaration does not declare anything
In file included from /usr/include/c++/4.4/x86_64-linux-gnu/bits/messages_members.h:37,
from /usr/include/c++/4.4/bits/locale_facets_nonio.h:1905,
from /usr/include/c++/4.4/locale:43,
from /usr/include/boost/algorithm/string/compare.hpp:15,
from /usr/include/boost/algorithm/string/predicate.hpp:22,
from boostnrexample.cc:2:
/usr/include/libintl.h: In function ‘char* gettext(const char*)’:
/usr/include/libintl.h:41: error: expected primary-expression before ‘,’ token
/usr/include/libintl.h: At global scope:
/usr/include/libintl.h:41: error: declaration does not declare anything
/usr/include/libintl.h: In function ‘char* dgettext(const char*, const char*)’:
/usr/include/libintl.h:46: error: expected primary-expression before ‘,’ token
/usr/include/libintl.h: At global scope:
/usr/include/libintl.h:46: error: declaration does not declare anything
/usr/include/libintl.h: In function ‘char* __dgettext(const char*, const char*)’:
/usr/include/libintl.h:48: error: expected primary-expression before ‘,’ token
/usr/include/libintl.h: At global scope:
/usr/include/libintl.h:48: error: declaration does not declare anything
/usr/include/libintl.h: In function ‘char* dcgettext(const char*, const char*, int)’:
/usr/include/libintl.h:54: error: expected primary-expression before ‘,’ token
/usr/include/libintl.h: At global scope:
/usr/include/libintl.h:54: error: declaration does not declare anything
/usr/include/libintl.h: In function ‘char* __dcgettext(const char*, const char*, int)’:
/usr/include/libintl.h:57: error: expected primary-expression before ‘,’ token
/usr/include/libintl.h: At global scope:
/usr/include/libintl.h:57: error: declaration does not declare anything
/usr/include/libintl.h: In function ‘char* ngettext(const char*, const char*, long unsigned int)’:
/usr/include/libintl.h:64: error: expected primary-expression before ‘,’ token
/usr/include/libintl.h: At global scope:
/usr/include/libintl.h:64: error: declaration does not declare anything
/usr/include/libintl.h: In function ‘char* dngettext(const char*, const char*, const char*, long unsigned int)’:
/usr/include/libintl.h:70: error: expected primary-expression before ‘,’ token
/usr/include/libintl.h: At global scope:
/usr/include/libintl.h:70: error: declaration does not declare anything
/usr/include/libintl.h: In function ‘char* dcngettext(const char*, const char*, const char*, long unsigned int, int)’:
/usr/include/libintl.h:77: error: expected primary-expression before ‘,’ token
/usr/include/libintl.h: At global scope:
/usr/include/libintl.h:77: error: declaration does not declare anything
/usr/include/libintl.h: In function ‘char* textdomain(const char*)’:
/usr/include/libintl.h:83: error: expected primary-expression before ‘,’ token
/usr/include/libintl.h: In function ‘char* bindtextdomain(const char*, const char*)’:
/usr/include/libintl.h:88: error: expected primary-expression before ‘,’ token
/usr/include/libintl.h: In function ‘char* bind_textdomain_codeset(const char*, const char*)’:
/usr/include/libintl.h:93: error: expected primary-expression before ‘,’ token
Update:
i also posted it at nr.com forum (http://www.nr.com/forum/showthread.php?t=2148). and got a response that the problem is that nr3.h made a define macro for throw(). i'm still not sure what could be a robust solution.
A: A quick fix is to go into nr3.h and change the C++ keyword abusing macro "throw" to an inoffensive none C++ keyword such as "toss".
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631334",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Fastest way to draw a bitmap? I'm working on a timelapse application and that requires drawing new frame every 30ms. Frames are stored in isolated storage (they are 640x480).
I tried loading them into MemoryStream first, and then convert to BitmapImage and assign as a Source for the Image control. But it's too long - it takes about 55ms. I measured and it's not reading from isolated storage, it's actually loading image into Image control that take the longest.
Is there any way to draw images faster on windows phone with silverlight or should I consider doing so with XNA?
A: Take a look at the WriteableBitmap class and the open source library WritableBitmapEx. The Blit method within WriteableBitmapEx will copy one bitmap into another. Not sure if it's fast enough for what you need, but it is very fast for what I'm doing with it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631338",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: jquery ui dialog - open when page loads if browser is ie I have a jQuery UI dialogue but need it to open as soon as the page is loaded if the browser is ie (Internet Explorer). I have made the dialogue, but cannot seem to find anywhere in the API Documentation to open a dialogue on load.
A: Just attach a normal $(window).load() handler but wrap it in a conditional comment:
<!--[if IE]>
<div id="ie-dialog">...</div>
<script type="text/javascript">
$(window).load(function() {
$('#ie-dialog').dialog();
});
</script>
<![endif]-->
You could also wait until the DOM is ready if you need it:
<!--[if IE]>
<div id="ie-dialog">...</div>
<script type="text/javascript">
$(document).ready(function() {
$('#ie-dialog').dialog();
});
</script>
<![endif]-->
A: $(function() {
if(jQuery.browser.msie) {
$("#dialog").dialog();
}
});
You can find more in documentation for jQuery.browser
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631339",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: JQuery script not working on divs fetched after page load So I have the jquery code here:
$(document).ready(function(){
$("div.post.photo").hover(function () {
$(this).children("div.show").slideToggle("fast");
});
});
It effects the html code here:
<div class="post photo">
<img src="source" />
<div class="show">
<div class="caption">
Caption
</div>
</div>
</div>
However as you scroll down the page, more div's are fetched via another script (not written by me), but the above jquery script doesn't affect them.
Thoughts?
A: You'll need to use jQuery's .live() handler - http://api.jquery.com/live/
"Attach a handler to the event for all elements which match the current selector, now and in the future."
eg.
$("div.post.photo").live('hover', function() {
$(this).children("div.show").slideToggle("fast");
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631341",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: In Cocoa-Touch Framework, is there any modal view in iPad like this? Is there any model view like this on the iPad?
A: Yes, there is:
UIModalPresentationFormSheet
The width and height of the presented view are smaller than those of the screen and the view is centered on the screen. If the device is in a landscape orientation and the keyboard is visible, the position of the view is adjusted upward so that the view remains visible. All uncovered areas are dimmed to prevent the user from interacting with them.
For example:
UIViewController *viewController = [[UIViewController alloc] init];
viewController.modalPresentationStyle = UIModalPresentationFormSheet;
[self presentModalViewController:viewController animated:YES];
viewController.view.superview.frame = CGRectMake(0, 0, 540, 500); // this is important to do this after presentModalView
viewController.view.superview.center = self.view.superview.center;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631342",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Mouse Over Movie Clip is Buggy...It has text boxes on top that cancel the effect can I bypass this? So I have a movieclip in my flash that has an event listener that calls it to pull up when the mouse is over and go down when the mouse is out. Kinda like a menu. But this object that I am accessing has text over it. The problem is it works until the the mouse that hits the text over it. Then it drops down.
I will paste my code if it helps...The code below is in the main timeline in scene 1.
//FeedBox Tween Stuff----------------------
var feedup:Tween = new Tween(FeedBox, "y", Strong.easeOut, 560, 290, 2, true);
var feeddown:Tween = new Tween(FeedBox, "y", Strong.easeOut, 290, 560, 2, true);
FeedBox.addEventListener(MouseEvent.MOUSE_OVER, mouseyOnFeed);
FeedBox.addEventListener(MouseEvent.MOUSE_OUT, mouseyOutBox);
function mouseyOnFeed(e:Event){
feedup.start();
}
function mouseyOutBox(e:Event){
feeddown.start();
}
Now the FeedBox has text over it in a text box that is generated from my twitter. This actionscript is actually in the library object.
var myXMLLoader:URLLoader = new URLLoader();
myXMLLoader.load(new URLRequest("http://twitter.com/statuses/user_timeline.xml?screen_name=allencoded"));
myXMLLoader.addEventListener(Event.COMPLETE, processXML);
function processXML(e:Event):void{
var myXML:XML = new XML(e.target.data);
tweet1.text = myXML.status[0].text;
tweet2.text = myXML.status[1].text;
tweet3.text = myXML.status[2].text;
tweet4.text = myXML.status[3].text;
}
A: Set the mouseChildren property of your movie clip false. Then the children (text in this case) will not interact with mouse.
FeedBox.mouseChildren = false;
A: Disable mouse events for children.
FeedBox.mouseChildren = false;
A: Seems like feedbox is not the children. You have to remove text from event loop,
textfield.mouseenabled = false;
In your cases its like
tweet1.mouseenabled = false;
tweet2.mouseenabled = false;
tweet3.mouseenabled = false;
tweet4.mouseenabled = false;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631348",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Using htaccess to redirect host urls but not when they contain paths or parameters What I would like to do is use htaccess to redirect (301, Permanent Redirect) simple host only urls to another domain but only when the url contains no path or parameters.
For example:
http://www.mydomain.com should redirect to http://www.myotherdomain.com and
http://mydomain.com should redirect to http://myotherdomain.com
(which I have found plenty of examples for)
but a url like:
http://www.mydomain.com/someimage.jpg or http://mydomain.com/js/coolJsScript.js should not be redirected at all.
Any help would be greatly appreciated!
Thanks!
A: I think this rule will match incoming URLs without any path:
RewriteRule ^$ http://othersite.com/ [L,R=301]
You haven't stated exactly what you are trying to do here, but there might be an alternative, which is to check to see if a file exists, and redirect to your other site if it doesn't exist. This test would be something like
# Check if file exists
RewriteCond %{REQUEST_URI} -f
# it exists, so stop processing
RewriteRule .* - [L]
# Redirect everything else
RewriteRule (.*) http://othersite.com/$1 [L,R=301]
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631349",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Can I register more than one BroadcastReceiver for an Activity in an Android Programming? I implemented a sample application which Shows the Phone Information, Battery Information of an Android application. I created two different Class files for two activities.
There is no issue in getting the phone related information. There is an issue in getting the Battery related information on my phone. The following are the some of the expected Actions that I want to register.
Intent.ACTION_BATTERY_CHANGED
Intent.ACTION_UMS_CONNECTED
Intent.ACTION_UMS_DISCONNECTED
Intent.ACTION_POWER_CONNECTED
Intent.ACTION_POWER_DISCONNECTED
Case 1 - I registered multiple BroadcastReceivers for each of the action given above.
Result - Only ACTION_BATTERY_CHANGED action data is coming up fine. But the other actions related data is not coming up fine.
Case 2 - I registered only one BroadcastReceiver for ACTION_BATTERY_CHANGED. In the implementation of onReceive(Context context, Intent intent) method I am checking for the other actions (ACTION_UMS_CONNECTED, ACTION_UMS_DISCONNECTED, ACTION_POWER_CONNECTED, ACTION_POWER_DISCONNECTED)
Result - Still the same issue the other actions related information is not coming up fine.
I tested with my Android Phone which has Android 2.1 update-1 version.
A:
Can I register more than one BroadcastReceiver for an Activity in an Android Programming?
AFAIK, yes. Moreover, you do not necessarily need multiple BroadcastReceiver objects for your scenario -- you could create a single IntentFilter that lists all your desired actions (see the addAction() method).
Rest of all are error data
That sentence does not parse in English, sorry.
Result - Still the same issue the other actions related information is not coming up fine.
If you do not register a receiver for a given broadcast action, you will not receive broadcasts for that action.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631352",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to get the 'reactor' when the twisted application is started by twistd? My application uses the 'twisted.web.client.Agent' to get web content. But the Agent class requires a 'reactor' instance to initiate. If I start my application using the 'twistd', there will be no 'reactor.run()' at all. So how can I get the 'reactor' instance?
A: I wish there were a better answer, but the way to get the current, active reactor in a Twisted application is:
from twisted.internet import reactor
The important thing is to not do this all over the place, but once near the "top" of your application code, so that you can easily replace the reactor for testing purposes or to modify its behavior in other ways (for example, you could potentially change connectTCP to go through a proxy). That is why Agent takes a reactor parameter rather than importing the current one itself.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631353",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: OpenLayers Refresh Strategy Problems I'm developing an application, part of which uses OpenLayers (calling a Geoserver-served WMS) displaying some frequently updated data (a vessel track - or more specifically, a series of points).
I would like to have this vessel track updated at a set interval - OpenLayers.Strategy.Refresh seems like the most approparite way to do this. I modified the wms.html example (OpenLayers 2.11) slightly to try this, ie:
underway = new OpenLayers.Layer.WMS("Underway Data",
"http://ubuntu-geospatial-server:8080/geoserver/underway/wms",
{'layers': 'underway:ss2011_v03', transparent: true, format: 'image/gif'},
{isBaseLayer: false},
{strategies : [new OpenLayers.Strategy.Refresh({interval: 6000})]}
);
map.addLayers([layer, underway]);
From what I can tell, this should work as-is (ie refresh the underway layer every 6 seconds), however nothing happens. The underlying WMS is getting updated - if I refresh the map manually, the updated data will appear.
I'm sure I'm missing something fairly obvious, any help would be much appreciated. I'm not getting any errors in Firebug or anything, it's just not doing anything.
A: Well, it turns out that you can't do a refresh strategy on a WMS service, as far as I can tell. So I converted my code to use WFS instead, and it works as expected. The code:
underway = new OpenLayers.Layer.Vector("WFS", {
strategies: [new OpenLayers.Strategy.BBOX(), new OpenLayers.Strategy.Refresh({interval: 4000, force: true})],
protocol: new OpenLayers.Protocol.WFS({
url: "http://ubuntu-geospatial-server:8080/geoserver/wfs",
featureType: "ss2011_v03",
featureNS: "http://csiro.au/underway",
geometryName: "position"
});
Note that I also need a BBOX strategy. Another gotcha that I found was that I needed to manually specify the geometryName, otherwise it would default to "the_geom", which doesn't exist for my layer.
A: I'm pretty sure you need to add a new OpenLayers.Strategy.Static() strategy for it to work.
And you need to activate your Refresh strategy which means you have to stick it in a separate variable.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631357",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: display default as first option in select box without changing order Is it possible to have a default option displayed in select box without changing the order of the other options?
<select>
<option>
1
</option>
<option>
2
</option>
<option>
3
</option>
<option>
4
</option>
<option>
5
</option>
</select>
*
*Default 1 is displayed:
2. I want 3 displayed as default without changing order of option list:
A: try something like
$("select").val($("select option[value='fb']").val());
http://jsfiddle.net/qu5fF/
or if you are using jquery 1.6 or higher use prop
$("select option[value='fb']").prop("selected",true);
http://jsfiddle.net/qu5fF/1/
for jquery version lower then 1.6 you can use .attr
$("select option[value='fb']").attr("selected","selected");
http://jsfiddle.net/qu5fF/3/
A: You can add the element at the 0 index.
<script type="text/javascript">
var elem = document.getElementById('<%= DropDown.ClientID %>');
var myNewOption = new Option(val.Name, val.ID);
elem .options[elem .options.length] = myNewOption;
</script>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631360",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Uninstalling Sync Framework without breaking Visual Studio Not strictly programming-related, but I do not know where else to post this question: Is Sync Framework a truly indispensable component of Visual Studio 2010?
From what I read about the Sync Framework, it is a tool that helps developers "synchronize data across multiple data stores," (Quoted text literally taken from Wikipedia's article on Sync Framework) a task that does not seem to be central to Windows, .NET Framework or Visual Studio.
Since none of my programming activities involves anything remotely resembling such a thing as "synchronizing data across multiple data stores," I thought it would be best to uninstall Sync Framework, especially taking into account the fact I am running out of disk space on my Windows dev box. However, when I tried to uninstall Sync Framework, a warning appeared that Visual Studio depends on it, and thus might not work correctly if I uninstall it.
So, without further ado: May I uninstall Sync Framework without breaking Visual Studio 2010?
A: The Visual Studio project item Local Database Cache uses Sync Framework.
If you're not going to use that project item, then I guess you can ignore the warning.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631368",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: compiler optimizes away a final field added to a serialized class This is a strange one, am wondering if this is by design or a compiler bug. Am using Sun Java 6 on a PC, but also seen with Sun Java 5 on a linux box.
Suppose I have a file on disk containing a serialized class. I then add a final field to the class and declare and initialize the field in one statement:
public final int newField = 2;
If I read in an object that was serialized before this field was added, this new field is given a default value of 0, which is correct. However, the compiler replaces occurrences of the field by the constant "2". OTOH, if I instead initialize the new field inside of a constructor:
Data (int d) {
this.oldField = d;
this.newField = 2;
}
then the field does not get optimized away and everything works as expected.
More explicitly, here is my Main class:
import java.io.*;
public class Main {
public static void main(String[] args) {
try {
FileInputStream fis = new FileInputStream ("Data.txt");
ObjectInputStream ois = new ObjectInputStream (fis);
Data d = (Data)ois.readObject();
ois.close();
fis.close();
d.print();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
and here is the Data class:
import java.io.*;
public class Data implements Serializable {
private static final long serialVersionUID = 1;
private int oldField;
private final int newField = 2;
Data(int d) {
this.oldField= d;
}
public void print() { {
System.out.println(this.oldField + " " + this.newField);
}
}
So my Data.txt file has a serialized instance of the original class with just "oldField = 1". So the expected output of running this is
1 0
but instead I get
1 2
whereas if I move the initialization into the constructor the output is correct.
Is this expected behaviour? My feeling is that the compiler should not be optimizing away fields in serialized classes, precisely for this reason. Perhaps that is asking too much. Thanks!
A: This is by design. If a variable is declared as final, has a primitive type and an initializer which is a constant expressions, then it is a "constant variable". This alters the semantics of initialization among other things. Specifically, the expression value is evaluated at compile time, and then embedded into the code.
Refer to JLS 4.12.4 for details.
When you put the initialization into the constructor, the variable is no longer a "constant variable" and normal initialization occurs.
By the way, I would have thought that a final variable having a different value than what the initializer said was a bad thing, not a good thing. To me, that would be highly unintuitive. At any rate, relying on this kind of behaviour does not strike me as good practice.
A: It's not clear why you think this is a problem. The compiler is doing exactly what it should do. The class definition says that the final field's value is 2, and that is exactly what you're getting.
The underlying reason is that when the final variable's value is declared in the initializer, the compiler knows its value immediately, so it is able to substitute the actual value as a literal wherever you use the variable. When you initialized it in constructor code, it couldn't see the value so easily so it doesn't do that optimization. It is still free to do so if it can.
In the language of the JLS #4.12.4, this is a 'constant variable', and JLS #13.1 says 'References to fields that are constant variables (§4.12.4) are resolved at compile time to the constant value that is denoted', which is exactly what is happening here.
My feeling is that the compiler should not be optimizing away fields
in serialized classes
Why should the compiler have different rules for serialized classes?
A: The usage of final variable always provokes compiler optimization. Its doing what it supposed to do.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631374",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Irrlicht - Using SMesh, SMeshBuffer and SceneManager->AddOctreeSceneNode(...) I need to draw a very large number of 3d lines. If I use driver->draw3dLine(...), the performance drops very badly. I heard that using the Octree we can optimize the drawing by displaying only what we need to see but I'm confused as to how to use it to solve my problem.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631378",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Is it possible to use wsdl web service in iphone? Hello every one.....
I am using wsdl web service in my project.I don't know how to use it.But from the wsdl2objc i generate the wsdl into objective c form.And after that i implement it into my project.In my wsdl there are many methods like getCountryList,getCityList,getCompanyContact....etc.Now i have a problem...i mean i fetched getCityList but not all city is shown in my city list.
Now i don't know what is the problem in my code.
Please tell me some suggestions....if you understand my problem...My code is..
- (SoapRequest*) getScanCustomerCompanies: (id <SoapDelegate>) handler machineId: (NSString*) machineId loc: (NSString*) loc cat: (int) cat pausefollow:(int)pausefollow favorite:(int)favorite activeontop:(int)activeontop nationwide:(int)nationwide orderby:(int)orderby
{
return [self getScanCustomerCompanies: handler action: nil machineId: machineId loc: loc cat: cat pausefollow:pausefollow favorite:favorite activeontop:activeontop nationwide:nationwide orderby:orderby];
}
- (SoapRequest*) getScanCustomerCompanies: (id) _target action: (SEL) _action machineId: (NSString*) machineId loc: (NSString*) loc cat: (int) cat pausefollow:(int)pausefollow favorite:(int)favorite activeontop:(int)activeontop nationwide:(int)nationwide orderby:(int)orderby
{
NSMutableArray* _params = [NSMutableArray array];
[_params addObject: [[[SoapParameter alloc] initWithValue: machineId forName: @"machineId"] autorelease]];
[_params addObject: [[[SoapParameter alloc] initWithValue: loc forName: @"loc"] autorelease]];
[_params addObject: [[[SoapParameter alloc] initWithValue: [NSNumber numberWithInt: cat] forName: @"cat"] autorelease]];
[_params addObject: [[[SoapParameter alloc] initWithValue:[NSNumber numberWithInt:pausefollow] forName:@"pausefollow"]autorelease]];
[_params addObject: [[[SoapParameter alloc] initWithValue:[NSNumber numberWithInt:favorite] forName:@"favorite"]autorelease]];
[_params addObject: [[[SoapParameter alloc] initWithValue:[NSNumber numberWithInt:activeontop] forName:@"activeontop"]autorelease]];
[_params addObject: [[[SoapParameter alloc] initWithValue:[NSNumber numberWithInt:nationwide] forName:@"nationwide"]autorelease]];
[_params addObject: [[[SoapParameter alloc] initWithValue:[NSNumber numberWithInt:orderby] forName:@"orderby"]autorelease]];
NSString* _envelope = [Soap createEnvelope: @"getScanCustomerCompanies" forNamespace: self.namespace withParameters: _params withHeaders: self.headers];
SoapRequest* _request = [SoapRequest create: _target action: _action service: self soapAction: @"urn:abc#getScanCustomerCompanies" postData: _envelope deserializeTo: [[SDZscanCustomerCompanies alloc] autorelease]];
[_request send];
return _request;
}
Thanks.......
A: Yes, iOS can consume WebServices including WSDL style.
Nobody probably knows where is your problem because you have not posted any code yet.
EDIT:
Cudzc generator makes a class which is named according wsdl name and prefix that you specified on the web site. In this class I had to change namespace and url according to the soap standards.
- (id) init
{
if(self = [super init])
{
self.serviceUrl = @"https://isir.justice.cz:8443/isir_ws/services/IsirPub001";
self.namespace = @"urn:IsirPub001/types";
self.headers = nil;
self.logging = YES;
}
return self;
}
Basically I recommend you to take SOAPUI, test the service on your machine and compare to the request that is generating by your code.
A: You can try the tool available online here:
http://sudzc.com/
I always use this service whenever I have SOAP request to handle.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631386",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
} |
Q: How can I set up different shipping options for different countries in Magento ? I sell my product internationally. I want to set up different shipping options for different countries. I have setup the FEDEX on my magento already.
How to setup FedEx Int'l Economy or FedEx Int'l Priority based on country/location in Magento?
A: The easiest I recently found is: Go to Promotions>Shopping Cart Price Rules - Here you can setup conditions and your countries and what you want to offer them eg. free shipping. It works well.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631387",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: remove selected (highlighted elements) on keyup function I have these two functions:
var $mainEdit= $("#main-edit");
function getSelText()
{
var txt = '';
if (window.getSelection)
{
txt = window.getSelection();
}
else if (document.getSelection)
{
txt = document.getSelection();
}
else if (document.selection)
{
txt = document.selection.createRange().text;
}
else return;
return $("#clipboard").val(txt);
}
$mainEdit.mouseup(function(){
$("#clipboard").val("");
getSelText();
}).mousedown(function(){
$("#clipboard").val("");
getSelText();
});
What I want to do, is on the keyup event...the highlighted elements would be removed.
So if I had this html:
<span>a</span>
<span>b</span>
<span>c</span>
and highlighted a and b, on the keyup event, the first two spans would be removed.
A: Here's a cross-browser function for deleting selected content:
function deleteSelected() {
if (window.getSelection()) {
window.getSelection().deleteFromDocument();
} else if (document.selection) {
document.selection.clear();
}
}
Hooking it up to the keyup event:
$mainEdit.keyup(deleteSelected);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631390",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Can an HTML button be used to upload a file for use with the W3C File API? I have a thumbnail interface mockup, and I would like to add the ability to upload an image. According to my mockup, the interface looks like this:
The intent was that the user would click on the "Add Icon" button, and a file dialog would pop up, just like the one that pops up when a file input is clicked. I would like the use the W3C's File API to handle the file upload asynchronously, and display the thumbnail in the gray area above the button once the upload is complete.
So, I'd like to upload a file without using a file input HTML element. I tried working with a hidden file input element and calling its click event handler with Javascript when the "Add Icon" button is clicked, but the call didn't do anything. I think security might have some reason to do with this.
Has anyone had any luck using an HTML button to upload a file before?
A: The trick I always do is wrapping the hidden file input into a label tag and then putting my custom input elements in the label tag. By defenition clicking on anything inside the label tag should trigger the input inside. No JavaScript needed at all!
<label>
<div>
My custom file input
</div>
<input type="file" id="file"/>
</label>
CSS: input{visibility:hidden;} Please note that you can't use display:none because then the element will not render. Still you can make the element width:0; height:0; to hide input element completely.
Fiddle
Using HTML file API is a little different. Read this article at Mozilla Developer Network to leran more.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631394",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Event vs. while(true) loop Background is the following: A Windows Service which is supposed to perform an action once per day at a given time.
I have currently implemented this by creating a timer and added the ElapsedEventHandler. The event fires every t minutes and it is then checked that we are passed the configured time. If so the action is performed and if not nothing happens.
A colleague asked me if it was not easier just to have a while(true) loop containing a sleep() and then of course the same logic for checking if we are past the time for action.
Question:
Can one say anything about the "robustness" of an event vs. a while(loop)? I am thinking of the situation where the thread "dies" so the while(true) loop exits. Is this more "likely" to happen in the one scenario vs. the other?
A: I'd vote for neither.
If your service just sits idle for an entire day periodically waking up (and paging code in) to see if "it's time to run", then this is a task better suited for the Windows Task Scheduler. You can programatically install a task to run every day through the task scheduler. Then your code doesn't need to be running at all unless it's time to run. (Or if your service does need to run in the background anyway, the task in the scheduler can signal your service to wake up instead of timer logic).
A: Both will be equally robust if you use proper error handling.
If you don't use proper error handling they will be equally brittle.
while(true)
{
...
Thread.Sleep(1000);
}
will make your service slow when responding to the standard service events like OnStop.
Besides, where do you put your while loop? In a separate thread? You will get more manual management if you use a loop too.
To summarize: use a timer.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631395",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Multiple Queries in different table (Also posted here.)
So I have two tables, one is invalid table and the other is valid table.
valid table:
id
status
date
invalid table:
id
status
date
I have to produce a report with this output:
date on-time late total valid invalid1 invalid2 total rate
--------- ------- ---- ----- ----- -------- -------- ----- ----
9/10/2011 4 10 14 3 3 3 6
*
*date: common fields on the 2 tables, field to group by, how many records on that day has
*on-time: count of all the id on the valid table
*late: count of all the records(id) on the invalid table
*total: total of on-time and late
*valid: count of id on the valid table with the "valid" status
*invalid1: count of id on the invalid table with "invalid1" status
*invalid2: count of id on the invalid table with "invalid2" status
*total: total of valid, invalid1, invalid2
*rate: average of totals
It's basically multiple queries with different table. How can I achieve it?
A: Someting like this?
SELECT
*,
(result.total + result._total) / 2 AS rate
FROM (
SELECT
date,
SUM(CASE WHEN data.valid = 1 THEN 1 ELSE 0 END) AS ontime,
SUM(CASE WHEN data.valid = 0 THEN 1 ELSE 0 END) AS late,
COUNT(*) AS total,
SUM(CASE WHEN data.valid = 1 AND data.status = 'valid' THEN 1 ELSE 0 END) AS valid,
SUM(CASE WHEN data.valid = 0 AND data.status = 'invalid1' THEN 1 ELSE 0 END) AS invalid1,
SUM(CASE WHEN data.valid = 0 AND data.status = 'invalid2' THEN 1 ELSE 0 END) AS invalid2,
SUM(CASE WHEN data.status IN ('valid', 'invalid', 'invalid2') THEN 1 ELSE 0 END) AS _total
FROM (
SELECT
date,
status,
valid = 1
FROM
Valid
UNION ALL
SELECT
date,
status,
valid = 0
FROM
InValid ) AS data
GROUP BY
date) AS result
A: SELECT date, ontime, late, ontime+late total, valid, invalid1, invalid2, valid+invalid1+invalid2 total
FROM
(SELECT date,
COUNT(*) late,
COUNT(IIF(status = 'invalid1', 1, NULL)) invalid1,
COUNT(IIF(status = 'invalid2', 1, NULL)) invalid2,
FROM invalid
GROUP BY date
) JOIN (
SELECT date,
COUNT(*) ontime,
COUNT(IIF(status = 'valud', 1, NULL)) valid,
FROM valid
GROUP BY date
) USING (date)
A: First of all, it seems that you are holding exactly the same information in 2 tables - I would recommend merging those tables together and add an additional boolean column called valid to hold the info related to validity of the record.
The query on your existent DB structure might look something like this:
SELECT unioned.* FROM (
( SELECT v.date AS date, v.status AS status, v.id AS id, COUNT(id) AS valid, 0 AS invalid1, 0 AS invalid2 FROM valid v GROUP BY v.date)
UNION
( SELECT i1.date AS date, i1.status AS status, i1.id AS id, 0 AS valid, COUNT(i1.id) AS invalid1, 0 AS invalid2 FROM invalid1 i1 GROUP BY i1.date)
UNION
( SELECT i2.date AS date, i2.status AS status, i2.id AS id, 0 AS valid, 0 AS invalid1, COUNT(i.id) AS invalid2 FROM invalid1 i1 GROUP BY i1.date)
) AS unioned GROUP BY unioned.date
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631396",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Differentiate between the program setting a checkbox and the user clicking it I want to know if there is a way to differentiate between the user clicking a checkbox, in which case I would like the following event to trigger, and the program itself setting the checked state, in which case I would like it to do nothing.
private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
if (sList.SelectedIndex != -1)
{
if (checkBox1.Checked)
CList[sList.SelectedIndex]._object[1] += 8;
else
CList[sList.SelectedIndex]._object[1] -= 8;
}
}
I just can't seem to find much about this issue. Thanks for your time.
A: You could also handle the click event of the checkbox. I don't know if that event is fired before or after checkedchanged, but if it happens before you could set a boolean to true or something and read it in checkedchanged.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631403",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to get XML node value in XSLT if we have got XML path in PARAM I am using XSLT 1.0 and have below sample code:
In my XSLT, I have got a param which has my XML path
<xsl:param name="sitespath"/>
I know I can load it as document and then further get the values accordingly, like below
<xsl:variable name="siteInfoPath" select="document($sitespath)/sitedata/region/site/language"/>
The above siteInfoPath XSLT varaible is loading the document with /sitedata/region/site/language data, however now I want to take PublishDate, below is the XML sample format
<?xml version="1.0"?>
<sitedata>
<resources>
<WorldwideSites>Worldwide sites</WorldwideSites>
<PublishedDate>10/3/2011 9:12:35 AM</PublishedDate>
</resources>
<region code="global" title="Global">
<site defaultLanguage="en" id="tcm:0-233-1" url="/english" countryCode="" title="" order="1">
<language code="en" pubId="tcm:0-233-1" pubPath="\english" Culture="en-GB" ShortDate="dd MMM yy" ShortDateShortDay="ddd dd MMM yy" ShortDateTime="dd MMM yy, HH:mm" LongDate="d MMMM, yyyy" LongDateTime="d MMMM, yyyy, HH:mm" LongDateExtendedShortDay="ddd dd MMM, yyyy" LongDateExtended="dddd, d MMMM, yyyy" LongDateExtendedTime="dddd, d MMMM, yyyy, HH:mm" MonthYear="MMMM, yyyy" OmniturePrefix="ek global:en:" OmnitureReportSuite="emirnewglobalenglish,emirnewibems" OmnitureDevReportSuite="emirglobalendev" sifr="Y" localTitle="" url="/english" mobileRedirect="true" flightStatusAlert="true" GoLiveDate="20071110" targetHost="http://fly1.com" hpSearchF="Yes" hpHotelsCars="Yes" hpMYB="Yes" hpOLCI="Yes" hpFStatus="Yes" hpServicesF="Yes">English</language>
</site>
Do I need to use another variable and need to load document like this
<xsl:variable name="siteInfoDate" select="document($sitespath)/sitedata/resources/PublishedDate"/>
I don't want to load same xml again...please suggest!!
A: Dynamic Xpath evaluation in general requires using an extension function --both in XSLT 1.0 and in XSLT 2.0. This is not a good idea, because you may or maynot find such an extension and may end up needing to write your own. Also, the code's portability is ruined.
Do I need to use another variable and need to load document like this
<xsl:variable name="siteInfoDate" select="document($sitespath)/sitedata/resources/PublishedDate"/>
I don't want to load same xml again...please suggest!!
This is actually the best way to solve the problem.
It is a widespread misconception that issuing more than one calls to the document() function with the same URL loads and parses the same document more than once.
The W3C XSLT specification defines that the URL typically is loaded and parsed only once -- the function is stable, regardless how many times the document() function is called.
Therefore, there isn't any loss of efficiency.
To eliminate your fears, do (this will help you sleep well, but isn't at all necessary):
<xsl:variable name="vDoc" select="document($sitespath)"/>
<xsl:variable name="siteInfoDate"
select="$vDoc/sitedata/resources/PublishedDate"/>
<xsl:variable name="siteInfoPath"
select="$vDoc/sitedata/region/site/language"/>
Here you obtain the document using only one, single call to the document() function.
A: In general in XSL 1, you would have to use an extension function for this as there is not a direct way to accomplish this. This is somewhat dependent on the actual parser you are using, but here is an example that works with Xalan which supports optional EXSLT functions:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0" xmlns:dyn="http://exslt.org/dynamic">
<xsl:param name="sitespath">/sitedata/region/site/language</xsl:param>
<xsl:template match="/">
<xsl:message>
<xsl:value-of select="dyn:evaluate($sitespath)/@code"/>
</xsl:message>
</xsl:template>
</xsl:stylesheet>
The evaluate() function will dynamically evaluate a XPath string and the example above will simply print it out the value of attribute code under whatever XPath the value of sitespath evaluates to.
If you are not using Xalan, then what you need to do may be different. For example, for Saxon parser all you need to do is change the namespace dyn URI to http://saxon.sf.net/ for more recent versions, or to http://icl.com/saxon for older ones.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631404",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Subsets and Splits